iterate over a set and create a string containing HTML - java

I have the following code that is used in the Image gallery generating program Jalbum to generate all keywords used for the images in the gallery.
Set allKeywords = new HashSet();
for (AlbumObject ao : currentObjects) {
XmpManager mgr = ao.getXmpManager();
if (mgr != null) {
allKeywords.addAll(mgr.getKeywordSet());
}
}
//get the Iterator
Iterator itr = allKeywords.iterator();
while(itr.hasNext())
out.println(itr.next());
My question is when out.print:
out.println(itr.next());
how can I add html to each individual keyword? I basically want to outprint:
keyword
I am a newbie in this realm so please be gentle!

out.println("" + itr.next() + "");
If you want to call iterator.next() two times
out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + itr.next() + "\">"
+ (itr.hasNext() ? itr.next() : "") + "</a>");
For your requirement I hope mgr.getKeywordSet() returns string
String str = itr.next();
System.out.println("<a href=\"#\" class=\"label list2\""
+ " data-filter=\"" + "." + str + "\">" + str + "</a>");

Related

Checking if a button is disabled or not

my issue i am having is that selenium is saying that the next arrow button is enabled when it is disabled/grayed out. what i am trying to do is this
1 click next arrow button
2 sleep for 5 seconds
3 check if disabled
4 click next arrow button
5 check if disabled
( loop repeat steps 1 -5)
if button is disabled break do while loop
my code that is not working is below
PS_OBJ_CycleData.Nextbtn(driver).click();
Thread.sleep(5000);
WebElement element = driver.findElement(By.id("changeStartWeekGrid_next"));
if (element.isEnabled()) {
System.out.println("Good next arrow enabled");
} else {
System.out.println("next arrow disabled");
PS_OBJ_CycleData.Cancelbtn(driver).click();
break dowhileloop;
}
my console output is "Good next arrow enabled" instead of going to the else statment.
Button HTML is here
<div id="changeStartWeekGrid_next" class="paginationButton" disabled="disabled" data-xpal="xpath-selected">
<a tabindex="0" href="#" id="changeStartWeekGrid_next_link" onclick="var registry = require('dijit/registry'); registry.byId('changeStartWeekGrid').next(); return false;">
<span class="icon-pagination-next"></span>
</a>
</div>
As you can see the button is actually disabled there another way to check is button is really disabled? Any help would be appreciated.
this is an additional picture of the inspected element
The documentation for isEnabled.
Sadly, using the isEnabled method doesn't work in this case, as stated by the documentation:
This will generally return true for everything but disabled input elements.
A proper alternative is using JavaScript to check for the attribute's existence, and its value. You can inject JavaScript through the executeScript method of the webdriver classes. The first argument is the script, all following arguments are passed to the script, accessible as arguments[i], ...
For example:
Boolean disabled = driver.executeScript("return arguments[0].hasAttribute(\"disabled\");", element);
I In this case since i did not have an actual button I needed to find it attribute to see if it was disabled or not.
PS_OBJ_CycleData.Nextbtn(driver).click();
Thread.sleep(4000);
// check is arrow button is disabled
if (driver.findElement(By.id("changeStartWeekGrid_next")).getAttribute("disabled") != null) {
PS_OBJ_CycleData.Cancelbtn(driver).click();
break dowhileloop;
}
You can check it with this simple code:
Boolean isbutton;
isbutton=button1.isEnable()
Make sure you have the correct element. I've wasted hours trying to figure out why an element was enabled when it shouldn't have been, when I was actually looking at the wrong one! Inspecting the element in the browser did not help, because it wasn't the same element that the java code was looking at. The following code turned out to be helpful:
System.out.println("Actual element=" + describeElement(yourElement));
public static String describeElement(WebElement element) {
String result = "";
if (element == null ) {
log.error("Could not describe null Element");
return "null";
}
// Look for common attributes, such as id, name, value, title, placeholder, type, href, target, role, class,
String id = element.getAttribute("id");
String name = element.getAttribute("name");
String value = element.getAttribute("value");
String title = element.getAttribute("title");
String placeholder = element.getAttribute("placeholder");
String type = element.getAttribute("type");
String href = element.getAttribute("href");
String target = element.getAttribute("target");
String role = element.getAttribute("role");
String thisClass = element.getAttribute("class");
result = "WebElement [tag:" + element.getTagName() + " text:'" + limit(element.getText()) + "' id:'" + id + "' " +
(StringUtils.isEmpty(name) ? "" : (" name:'" + name + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" value:'" + value + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" title:'" + title + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" placeholder:'" + placeholder + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" type:'" + type + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" href:'" + href + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" target:'" + target + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" name:'" + name + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" role:'" + role + "' ")) +
(StringUtils.isEmpty(name) ? "" : (" class:'" + thisClass + "' ")) +
" isDisplayed: " + element.isDisplayed() +
" isEnabled: " + element.isEnabled() +
" isSelected: " + element.isSelected() + "]";
return result;
}

Univocity Parsers: Calling a function from here is not working: parserSettings.selectFields( *some_function* );

I am using a .csv file and would like to pass a string constructed by a function to: parserSettings.selectFields( function );
During testing, when the string returned by the function is pasted directly into: parserSettings.selectFields( string ); the parsing works fine, however, when the function is used instead, the parse doesn't work, and there is only output of whitespace.
Here is the function:
public String buildColList() {
//Parse the qty col names string, which is a comma separated string
String qtyString = getQtyString();
List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));
String colString = StringUtils.join(qtyCols.toArray(), "\"" + ", " + "\"");
String fullColString;
fullColString = "\"" + getString1() + "\"" + ", " + "\"" + getString2() + "\"" + ", " + "\"" + colString + "\"" + ", " + "\"" + getString4 + "\"";
return fullColString;
}
Here is how it is placed:
parserSettings.selectFields(buildColList());
Any help would be greatly appreciated, thanks.
You need to return an array from your buildColList method, as the parserSettings.selectFields() method won't split a single string. Your current implementation is selecting a single, big header instead of multiple columns. Change your method to do something like this:
public String[] buildColList() {
//Parse the qty col names string, which is a comma separated string
String qtyString = getQtyString();
List<String> qtyCols = Arrays.asList(qtyString.split("\\s*,\\s*"));
String colString = StringUtils.join(qtyCols.toArray(), "\"" + ", " + "\"");
String[] fullColString = new String[]{getString1(), getString2(), colString, getString4};
return fullColString;
}
And it should work. You might need to adjust my solution to fit your particular scenario as I didn't run this code. Also, I'm not sure why you were appending quotes around the column names, so I removed them.
Hope this helps.

Extracting Capture Group from Non-Capture Group in Java

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 "([^"]*)")';
}

JavaScript output to a String

Is it possible to fetch javascript output to a string in java. I am working with Selenium WebDriver and I expect all child nodes to be listed for which I want to make use of javascript. I am making use of JavascriptExecutor functionality. I want something like this;
JavascriptExecutor js = (JavascriptExecutor)LaunchBrowserTest.driver;
List<String> s = (List<String>)(js.executeScript(" var text = 'aa'; "
+ "var list = document.getElementById('jstree'); "
+ "var anchorlist = document.getElementsByTagName('a'); "
+ "for( i = 0; i < anchorlist.length; i++ ) "
+ "{ "
+ "text = text + anchorlist[i].innerHTML; "
+ "};"
+ "console.log(text);"));
System.out.println("String Array: " + s );
Is there any way I could expect the text outputted and captured into String 's' in java ?
After I get the list, I wanted them to be used in Selenium to click on the nodes as below
WebElement element = driver.findElement(By.linkText(s[i])); where i < s.length
The present output shows me String Array: []
Please suggest me changes/links to get the functionality working.
Answer:
JavascriptExecutor js = (JavascriptExecutor)LaunchBrowserTest.driver;
List<String> s = (List<String>)(js.executeScript(" var text = 'aa'; "
+ "var list = document.getElementById('jstree'); "
+ "var anchorlist = document.getElementsByTagName('a'); "
+ "for( i = 0; i < anchorlist.length; i++ ) "
+ "{ "
+ "text = text + anchorlist[i].innerHTML; "
+ "};"
+ "return text;"));
System.out.println("String Array: " + s );
If you look through the documentation of Selenium JavascriptExecutor and look for the executeScript() method, you will see that your Javascript has to return something in
order to catch it up in Java itself.
Here you can see what kind of data type you will get in Java if your JS script returns
anything.
I hope this helps you out, good luck.

getting session variables from session

I am getting the below error when I compile the below code
Enumeration e = bean.getSession().getAttributeNames();
while (e.hasMoreElements()) {
String name = (String)e.nextElement();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
Error:
found : java.util.Iterator
required: java.util.Enumeration
Enumeration e = bean.getSession().getAttributeNames();
You shouldn't be using an enumeration, it should be an Iterator. Then use the methods of the Iterator like hasNext() to check if there is a next item and next() to get the next item. Hope it helps :)
how about just using a for loop?
for (String name : bean.getSession().getAttributeNames() ) {
String value = session.getAttribute(name).toString();
System.out.println( name + " = " + value );
}
It looks like you're actually using a getAttributeNames() method that return an instance of java.util.Iterator. So as a quick fix, this should work:
Iterator it = bean.getSession().getAttributeNames();
while (it.hasNext()) {
String name = (String)it.next();
String value = session.getAttribute(name).toString();
System.out.println(name + " = " + value);
More help/info could be provided if we knew the actual types of the bean variable and/or the return value of bean.getSession().
I think the problem is in the first line. This works for me:
<%
Enumeration attrs = session.getAttributeNames(); //you will need to include java.util.Enumeration
while(attrs.hasMoreElements()){ //for each item in the session array
String id = attrs.nextElement().toString(); //the name of the attribute
out.print("'" + id + "': '" + session.getAttribute(id) + "'"); //print out the key/value pair
}
%>
As others pointed out though, you should be using an Iterator

Categories

Resources