I'm a bit confused with how to split my arraylist, loop thru the list, and pull out only specific info.
I have an arraylist of 20 URLs:
"http://xxxx.websitename.com:1234/aaa/bbb/ccc"
"http://yyyy.websitename.com:5678/aaa/bbb/ccc"
etc.....
And I want to be able to have the results pull only:
xxxx 1234
yyyy 5678
How do I get this started if I want the above as my result? I can find how to do it as a string, but no good example as an array list.
public class HealthCheck {
public static void main(String[] args) {
ArrayList arlURL = new ArrayList();
arlURL.add("http://xxxx.websitename.com:1234/aaa/bbb/ccc");
arlURL.add("http://yyyy.websitename.com:5678/aaa/bbb/ccc");
System.out.println(arlURL);
There is no way to get only the (sub)domain and port by only using the ArrayList implementation. You can only get the entries as you put them into the ArrayList.
Use the build in URL class to parse the URLs of the ArrayList:
URL aURL = new URL("http://xxxx.websitename.com:1234/aaa/bbb/ccc");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());
See http://docs.oracle.com/javase/tutorial/networking/urls/urlInfo.html
As you only want to have to subdomain you have to further split the aURL.getHost() string at the first dot (e.g., aURL.getHost().substring(0, aURL.getHost().indexOf(".")), be aware to first check that the string contains a dot before using this...).
Related
Here is my code:
// This is the bug - this works.
String[] lst = {"desk", "pencil"};
String lst0 = lst[0];
System.out.println("path: " + lst[0]);
System.out.println("result: " + root.getDirectory(lst0).getFileName());
// This is the bug - this doesn't work.
String[] ef = "desk/pencil".split("/");
String ef1 = ef[0];
System.out.println("path: " + ef1);
System.out.println("result (without getFileName): " + root.getDirectory(ef1));
But in the second case, the function isn't called properly, as ef[0] seems considered differently from lst[0] by the compiler despite both being strings. I assume this is becaue lst is a array that resulted from list splitting. Is there any way to fix/work around this?
I have a string, let's call it output, that's equals the following:
ltm data-group internal str_testclass {
records {
baz {
data "value 1"
}
foobar {
data "value 2"
}
topaz {}
}
type string
}
And I'm trying to extract the substring between the quotes for a given "record" name. So given foobar I want to extract value 2. The substring I want to extract will always come in the form I have prescribed above, after the "record" name, a whitespace, an open bracket, a new line, whitespace, the string data, and then the substring I want to capture is between the quotes from there. The one exception is when there is no value, which will always happen like I have prescribed above with topaz, in which case after the "record" name there will just be an open and closed bracket and I'd just like to get an empty string for this. How could I write a line of Java to capture this? So far I have ......
String myValue = output.replaceAll("(?:foobar\\s{\n\\s*data "([^\"]*)|()})","$1 $2");
But I'm not sure where to go from here.
Let's start extracting "records" structure with following regex ltm\s+data-group\s+internal\s+str_testclass\s*\{\s*records\s*\{\s*(?<records>([^\s}]+\s*\{\s*(data\s*"[^"]*")?\s*\}\s*)*)\}\s*type\s*string\s*\}
Then from "records" group, just find for sucessive match against [^\s}]+\s*\{\s*(?:data\s*"(?<data>[^"]*)")?\s*\}\s*. The "data" group contains what's you're looking for and will be null in "topaz" case.
Java strings:
"ltm\\s+data-group\\s+internal\\s+str_testclass\\s*\\{\\s*records\\s*\\{\\s*(?<records>([^\\s}]+\\s*\\{\\s*(data\\s*\"[^\"]*\")?\\s*\\}\\s*)*)\\}\\s*type\\s*string\\s*\\}"
"[^\\s}]+\\s*\\{\\s*(?:data\\s*\"(?<data>[^\"]*)\")?\\s*\\}\\s*"
Demo:
String input =
"ltm data-group internal str_testclass {\n" +
" records {\n" +
" baz {\n" +
" data \"value 1\"\n" +
" }\n" +
" foobar {\n" +
" data \"value 2\"\n" +
" }\n" +
" topaz {}\n" +
" empty { data \"\"}\n" +
" }\n" +
" type string\n" +
"}";
Pattern language = Pattern.compile("ltm\\s+data-group\\s+internal\\s+str_testclass\\s*\\{\\s*records\\s*\\{\\s*(?<records>([^\\s}]+\\s*\\{\\s*(data\\s*\"[^\"]*\")?\\s*\\}\\s*)*)\\}\\s*type\\s*string\\s*\\}");
Pattern record = Pattern.compile("(?<name>[^\\s}]+)\\s*\\{\\s*(?:data\\s*\"(?<data>[^\"]*)\")?\\s*\\}\\s*");
Matcher lgMatcher = language.matcher(input);
if (lgMatcher.matches()) {
String records = lgMatcher.group();
Matcher rdMatcher = record.matcher(records);
while (rdMatcher.find()) {
System.out.printf("%s:%s%n", rdMatcher.group("name"), rdMatcher.group("data"));
}
} else {
System.err.println("Language not recognized");
}
Output:
baz:value 1
foobar:value 2
topaz:null
empty:
Alernatives: As your parsing a custom language, you can give a try to write an ANTLR grammar or create Groovy DSL.
Your regex shouldn't even compile, because you are not escaping the " inside your regex String, so it is ending your String at the first " inside your regex.
Instead, try this regex:
String regex = key + "\\s\\{\\s*\\n\\s*data\\s*\"([^\"]*)\"";
You can check out how it works here on regex101.
Try something like this getRecord() method where key is the record 'name' you're searching for, e.g. foobar, and the input is the string you want to search through.
public static void main(String[] args) {
String input = "ltm data-group internal str_testclass { \n" +
" records { \n" +
" baz { \n" +
" data \"value 1\" \n" +
" } \n" +
" foobar { \n" +
" data \"value 2\" \n" +
" }\n" +
" topaz {}\n" +
" } \n" +
" type string \n" +
"}";
String bazValue = getRecord("baz", input);
String foobarValue = getRecord("foobar", input);
String topazValue = getRecord("topaz", input);
System.out.println("Record data value for 'baz' is '" + bazValue + "'");
System.out.println("Record data value for 'foobar' is '" + foobarValue + "'");
System.out.println("Record data value for 'topaz' is '" + topazValue + "'");
}
private static String getRecord(String key, String input) {
String regex = key + "\\s\\{\\s*\\n\\s*data\\s*\"([^\"]*)\"";
final Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
//if we find a record with data return it
return matcher.group(1);
} else {
//else see if the key exists with empty {}
final Pattern keyPattern = Pattern.compile(key);
Matcher keyMatcher = keyPattern.matcher(input);
if (keyMatcher.find()) {
//return empty string if key exists with empty {}
return "";
} else {
//else handle error, throw exception, etc.
System.err.println("Record not found for key: " + key);
throw new RuntimeException("Record not found for key: " + key);
}
}
}
Output:
Record data value for 'baz' is 'value 1'
Record data value for 'foobar' is 'value 2'
Record data value for 'topaz' is ''
You could try
(?:foobar\s{\s*data "(.*)")
I think the replaceAll() isn't necessary here. Would something like this work:
String var1 = "foobar";
String regex = '(?:' + var1 + '\s{\n\s*data "([^"]*)")';
You can then use this as your regex to pass into your pattern and matcher to find the substring.
You can simple transform this into a function so that you can pass variables into it for your search string:
public static void SearchString(String str)
{
String regex = '(?:' + str + '\s{\n\s*data "([^"]*)")';
}
I have a few test values in my database and i want to fetch them all in android.
This is my following JSON output of the values inside my Database:
[{"email_address":"rainier_gaari#hotmail.com","comment":"qwehgashdgaskdaweq","date_comment":"2014-06-21","time_comment":"08:28:00","password":"rainier1990"},
{"email_address":"rainier_gaari#hotmail.com","comment":"asfasdasdasd","date_comment":"2104-06-12","time_comment":"09:03:00","password":"rainier1990"}
{"email_address":"rainier_gaari#hotmail.com","comment":"asdsfafd","date_comment":"2014-06-22","time_comment":"04:44:00","password":"rainier1990"}]
But every time that I run this code: http://prntscr.com/3vhs5j , it only gives me the first line of the JSON output.: http://prntscr.com/3vi34b
How can I show all the rows( instead of 1 row)in android?
You can use a JSONObject provided by the android API. The JSONObject has a method called getJSONArray()
http://developer.android.com/reference/org/json/JSONObject.html#getJSONArray(java.lang.String)
your error there is that you are instantiating a JSONArray with your Object. you should try this:
JSONArray myArray =jsonObject.getJSONArray();
This is a snippet of code from one of my apps that worked very well to retrieve Json data.
success = jObject.getInt(TAG_SUCCESS);
vehicles = jObject.getJSONArray(Vehicle.TAG_VEHICLES);
if(success == 1) {
// loop through all the vehicles
for(int i = 0; i < vehicles.length(); i++) {
JSONObject obj = vehicles.getJSONObject(i);
// Get each element based on it's tag
String year = obj.getString(Vehicle.TAG_YEAR);
String model = obj.getString(Vehicle.TAG_MODEL);
String brand = obj.getString(Vehicle.TAG_BRAND);
String color = obj.getString(Vehicle.TAG_COLOR);
String license_plate = obj.getString(Vehicle.TAG_LICENSE);
String main_driver = obj.getString(Vehicle.TAG_DRIVER);
String policeNumber = obj.getString(Vehicle.TAG_POLICENUMBER);
String driversLicense = obj.getString(Vehicle.TAG_DRIVER_LICENSE);
String licenseState = obj.getString(Vehicle.TAG_LICENSE_STATE);
String driverBirthday = obj.getString(Vehicle.TAG_BIRTHDAY_MONTH) + "/" +
obj.getString(Vehicle.TAG_BIRTHDAY_DAY) + "/" +
obj.get(Vehicle.TAG_BIRTHDAY_YEAR);
String driverGender = obj.getString(Vehicle.TAG_DRIVER_GENDER);
ListRowGroup group = new ListRowGroup(brand + " " + year + " " + model, brand);
group.children.add(brand + " " + year + " " + model);
group.children.add(policeNumber);
group.children.add(model);
group.children.add(color);
group.children.add(license_plate);
group.children.add(main_driver);
group.children.add(driversLicense + " - " + licenseState);
group.children.add(driverBirthday + " - " + driverGender);
vehiclesGroup.append(i, group);
}
It would help if you put some of the code for getting the JSON in your question, to make it easier to reference, but, I don't see a loop, which is why it only gets the first line.
You may want to refer to this question: JSON Array iteration in Android/Java but basically use the length property of the JSONArray and loop through that many times.
I have a number of xml's that come in haphazardly that contain a Ocount, and Lnumber, as well as other data. I have created a class to get that data.
My problem is that how can I group xml's that have the same Lnumber(string), until it reaches the Ocount(int). (the xmls that have the same lnumber has the same Ocount). And eventually send out a email telling with xmls has been processed.
String readLine = FileHandler.checkListFile(sh.getShipmentHeader().getBillToCustomer());
if (!readLine.isEmpty())
{
int orderCount = 0;
int index = readLine.indexOf(";") + 1;
String customerName = readLine.substring(index, readLine.indexOf(";", index)).trim();
index = readLine.indexOf(";", index) + 1;
String to = readLine.substring(index, readLine.length()).trim();
if (!billMap.containsKey(sh.getShipmentHeader().getBillToCustomer()))
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), 1);
orderCount = 1;
}
else
{
billMap.put(sh.getShipmentHeader().getBillToCustomer(), ((int) billMap.get(sh.getShipmentHeader().getBillToCustomer())) + 1);
orderCount = (int) billMap.get(sh.getShipmentHeader().getBillToCustomer());
}
outboundMessage += sh.getShipmentHeader().getOrderNumber() + li ;
logger.info("On-Demand Outbound Export Info: " + orderCount + " processed out of " + sh.getShipmentHeader().getOrderCount() +
" for " + customerName);
if (orderCount == sh.getShipmentHeader().getOrderCount())
{
Email email = new Email();
billMap.remove(sh.getShipmentHeader().getBillToCustomer());
outboundMessage += li + "Total of #"+ sh.getShipmentHeader().getOrderCount() + " orders processed for "+ customerName + li ;
logger.info("On-Demand Email sent for " + customerName);
System.out.println(outboundMessage);
email.outboundEmail("TEST: Orders for " + customerName + " complete", outboundMessage, to);
outboundMessage = "";
email = null;
}}
I been working on this for days, where am I going wrong.
It seems like you are having difficulty obtaining information from xmls. I suggest using XStream [1]. It is capable of serialising objects to xml and back. By using XStream, you can get an Object from the xml and compare variables (Lnumber and Ocount) easily.
If you insist using this code, I suggest adding comments to notify us what you are doing, but if want an easier alternative to work with xml files using java, I highly suggest using XStream as a solution.
[1] http://x-stream.github.io/
I am facing some difficulties while assigning the values in an array list. My code is :
while (answer.hasMore()) {
SearchResult rslt = (SearchResult)answer.next();
Attributes attrs = rslt.getAttributes();
System.out.println();
if (attrs.get("department") != null && attrs.get("telephonenumber") != null) {
System.out.println(attrs.get("department") + " " + attrs.get("name") + " " +
attrs.get("Description") + " " + attrs.get("mail") + " " +
attrs.get("telephonenumber")+
attrs.get("samaccountname") + attrs.get("samaccountname") );
}
I want to assign the values of attrs.get("department") + attrs.get("description")+ attrs.get("name")+attrs.get("mail") each one to an array list.
I tried to define at the beginning:
String[] name = new String[100];
and in the while loop i tried to read the name attribute, I tried to do:
name = attrs.get("name");
But it did not work. Can anyone help.
In Java, an array and an ArrayList are quite different.
String[] name_array = new String[100];
creates a fixed-length array of Strings, but
ArrayList name_list = new ArrayList();
creates a variable-length ArrayList of objects (it will grow as you add more objects).
To add an object to an ArrayList, you can use its add() method.
name_list.add("Hello");
However, with an array you need to set the object at a specific index, e.g:
name_array[23] = "Hello";
You need to read a basic tutorial on the Java language and standard library.
You cannot directly assign strings to a array made of string "references". You need to index it first. But it would be much better to actually use a list (and maybe convert it to an array later). Check out List and ArrayList in the Java documentation.
As an example:
Attributes attrs = new Attributes();
List<String> attribValues = new ArrayList<String>();
System.out.println();
if (attrs.get("department") != null
&& attrs.get("telephonenumber") != null) {
System.out
.println(attrs.get("department") + " " + attrs.get("name")
+ " " + attrs.get("Description") + " "
+ attrs.get("mail") + " "
+ attrs.get("telephonenumber")
+ attrs.get("samaccountname")
+ attrs.get("samaccountname"));
attribValues.add(attrs.get("department"));
attribValues.add(attrs.get("telephonenumber"));
}
final String[] attribArray = attribValues.toArray(new String[attribValues.size()]);
First of all define your name as String not as an array of String like this:
String name;
And then read name as:
name = attrs.getString("name");
Now coming back to your issue of populating List, I am sure you will get ready-made answers here but I suggest you to do some reading on how to create and populate a List in Java.