Index element using setter getter android - java

This is my jsoup parser to extract soap content
doc = Jsoup.parse(getxml,"", Parser.xmlParser());
Elements taux = doc.select("taux");
Elements devise = doc.select("devise");
Elements datecours = doc.select("dateCours");
Elements libelle = doc.select("libelle");
Elements quotite = doc.select("quotite");
Elements fixing = doc.select("fixing");

Maybe this will help you. After getting the elements from the web service, assuming that all of the strings contain a large string with separated values, do the following:
String[] deviseSeparated = devise.split(" ");
String[] datecourSeparated = datecour.split(" ");
String[] libelSeparated = libel.split(" ");
String[] quotSeparated = quot.split(" ");
String[] fixSeparated = fix.split(" ");
and after that, assuming that all of the arrays are the same size, just execute this for loop, to initiate the objects:
for (int i = 0; i < deviseSeparated.length; i++) {
PostList.add(new convertor_pst(deviseSeparated[i],datecourSeparated[i],libelSeparated[i],quotSeparated[i],fixSeparated[i]));
}
Is this what you are looking for?

Related

Parsing currency exchange data from https://uzmanpara.milliyet.com.tr/doviz-kurlari/

I prepare the program and I wrote this code with helping but the first 10 times it works then it gives me NULL values,
String url = "https://uzmanpara.milliyet.com.tr/doviz-kurlari/";
//Document doc = Jsoup.parse(url);
Document doc = null;
try {
doc = Jsoup.connect(url).timeout(6000).get();
} catch (IOException ex) {
Logger.getLogger(den3.class.getName()).log(Level.SEVERE, null, ex);
}
int i = 0;
String[] currencyStr = new String[11];
String[] buyStr = new String[11];
String[] sellStr = new String[11];
Elements elements = doc.select(".borsaMain > div:nth-child(2) > div:nth-child(1) > table.table-markets");
for (Element element : elements) {
Elements curreny = element.parent().select("td:nth-child(2)");
Elements buy = element.parent().select("td:nth-child(3)");
Elements sell = element.parent().select("td:nth-child(4)");
System.out.println(i);
currencyStr[i] = curreny.text();
buyStr[i] = buy.text();
sellStr[i] = sell.text();
System.out.println(String.format("%s [buy=%s, sell=%s]",
curreny.text(), buy.text(), sell.text()));
i++;
}
for(i = 0; i < 11; i++){
System.out.println("currency: " + currencyStr[i]);
System.out.println("buy: " + buyStr[i]);
System.out.println("sell: " + sellStr[i]);
}
here is the code, I guess it is a connection problem but I could not solve it I use Netbeans, Do I have to change the connection properties of Netbeans or should I have to add something more in the code
can you help me?
There's nothing wrong with the connection. Your query simply doesn't match the page structure.
Somewhere on your page, there's an element with class borsaMain, that has a direct child with class detL. And then somewhere in the descendants tree of detL, there is your table. You can write this as the following CSS element selector query:
.borsaMain > .detL table
There will be two tables in the result, but I suspect you are looking for the first one.
So basically, you want something like:
Element table = doc.selectFirst(".borsaMain > .detL table");
for (Element row : table.select("tr:has(td)")) {
// your existing loop code
}

finding the number of open closed html tags in a string

I trying to figure out the best way to find the number of valid HTML tags in a string.
The assumption is that the tag is valid only if it has an opening and closing tag
this is an example of a test case
INPUT
"html": "<html><head></head><body><div><div></div></div>"
Output
"validTags":3
If you need to parse HTML
Do not do it yourself. There is no need to reinvent the wheel. There is a plethora of libraries for parsing HTML. Use the proper tool for the proper job.
Concentrate your efforts on the rest of your project. Sure, you could implement your own function that parses a string, looks for < and >, and acts appropriately. But HTML might be slightly more complex than you imagine, or you might end up needing more HTML parsing than just counting tags.
Maybe in the future you'llwant to count <br/> and <br /> as well. Or you'll want to find the depth of the HTML tree.
Maybe your homemade code doesn't account for all possible combinations of escaping characters, nested tags, etc. How many correct tags are there in the string:
<a><b><c><d e><f g="<h></h>"><i j="<k>" l="</k>"></i></f></e d></b></c></ a >
In a comment, user dbl linked to a similar question with links to libraries: How to validate HTML from java ?
If you want to count open-closed tag pairs as a learning project
Here is a proposed algorithm in pseudocode, as a recursive function:
function count_tags(s):
tag, remainder = find_next_tag(s)
found, inside, after = find_closing_tag(tag, remainder)
if (found)
return 1 + count_tags(inside) + count_tags(after)
else
return count_tags(inside)
Examples
on the string hello <a>world<c></c></a><b></b>, we will get:
tag = "<a>"
remainder = "world<c></c></a><b></b>"
found = true
inside = "world<c></c>"
after = "<b></b>"
return 1 + count_tags("world<c></c>") + count_tags("<b></b>")
on the string <html><head></head>:
tag = "<html>"
remainder = "<head></head>"
found = false
inside = "<head></head>"
after = ""
return count_tags("<head></head>")
on the string <a><b></a></b>:
tag = "<a>"
remainder = "<b></a></b>"
found = true
inside = "<b>"
after = "</b>"
return 1 + count_tags("<b>") + count_tags("</b>")
I wrote a function that would do exactly this.
static int checkValidTags(String html,String[] openTags, String[] closeTags) {
//openTags and closeTags must have the same length;
//This function keeps track of all opening tags.
//and removes the opening and closing tags if the tag is closed correctly
//It can even detect when there are labels added to the tags.
HashMap<Character,Integer> open = new HashMap<>();
HashMap<Character,Integer> close = new HashMap<>();
//Use a start character, this is 1 because 0 would be a string terminator.
int startChar = 1;
for(int i = 0; i < openTags.length; i++) {
open.put((char)startChar, i);
close.put((char)(startChar+1), i);
html = html.replaceAll(openTags[i],""+ (char)startChar);
html = html.replaceAll(closeTags[i],""+(char)(startChar+1));
startChar+=2;
}
List<List<Integer>> startIndexes = new ArrayList<>();
int validLabels = 0;
for(int i = 0; i < openTags.length; i++) {
startIndexes.add(new ArrayList<>());
}
for(int i = 0; i < html.length(); i++) {
char c = html.charAt(i);
if(open.get(c)!=null) {
startIndexes.get(open.get(c)).add(0,i);
}
if(close.get(c)!=null&&!startIndexes.get(close.get(c)).isEmpty()) {
String closed = html.substring(startIndexes.get(close.get(c)).get(0),i);
for(int k = 0; k < startIndexes.size(); k++) {
if(!startIndexes.get(k).isEmpty()) {
int p = startIndexes.get(k).get(0);
if(p > startIndexes.get(close.get(c)).get(0)) {
startIndexes.get(k).remove(0);
}
}
}
startIndexes.get(close.get(c)).remove(0);
html.replace(closed, "");
validLabels++;
}
}
return validLabels;
}
And to use it in your example you would do like this:
String html = "<html><head></head><body><div><div></div></div>";
int validTags = checkValidTags(html,new String[] {
//Add here all the tags you are looking for.
//Remove the trailing '>' so it can detect extra tags appended to it
"<html","<head","<body","<div"
}, new String[]{
"</html>","</head>","</body>","</div>"
});
System.out.println(validTags);
Output:
3

how to convert list<objct> into string []

Is it possible to convert this type List<Jadval> into String[] wordList?
I read the words from database with like this :
public static List<Jadval> jadvalList = new ArrayList<Jadval>();
JadvalDB jadvalDB = new JadvalDB(GameActivity.this);
jadvalList = jadvalDB.getWords(myPos + 1);
and now i want to put jadvalList values into String[] wordList.
i use this code to set the values :
for (int i = 0; i < jadvalList.size(); i++) {
wordList[i] = (jadvalList.get(i).toString());
}
but I get the error that wordList is empty .
any idea?
You can use streams and complete it in one line like this:
String[] wordList = jadvalList.stream().map(a->a.toString()).toArray(String[]::new);

Comparing text extracted from two different loops in selenium and assert whether they are equal or not

Comparing text extracted from two different loops in selenium and assert whether they are equal or not. Following is the selenium code, I need to compare two strings as project_text and actualVal:
driver.findElement(By.xpath(OR.getProperty("projects"))).click();
Thread.sleep(5000);
System.out.println("Selecting from list");
Select project_dropdown = new Select(driver.findElement(By.xpath(OR.getProperty("client"))));
project_dropdown.selectByVisibleText("Marketo");
System.out.println("Verifying the selection of the list");
String part1=OR.getProperty("project_start");
String part2=OR.getProperty("project_end");
String assign_part1=OR.getProperty("assign_users_start");
String assign_part2=OR.getProperty("assign_users_end");
int i=1;
String project_text = null;
String assign_text = null;
while(isElementPresent(part1+i+part2)){
project_text = driver.findElement(By.xpath(part1+i+part2)).getText();
assign_text = driver.findElement(By.xpath(assign_part1+i+assign_part2)).getText();
if (assign_text.contains("aaaa"))
System.out.println(project_text);
i++;
}
System.out.println("Project_text = " + project_text);
driver.findElement(By.xpath(OR.getProperty("calender"))).click();
Thread.sleep(5000);
driver.findElement(By.xpath(OR.getProperty("date_link"))).click();
Thread.sleep(5000);
Select project_dropdown1 = new Select(driver.findElement(By.xpath(OR.getProperty("client_select"))));
project_dropdown1.selectByVisibleText("Marketo");
WebElement project_droplist= driver.findElement(By.xpath(OR.getProperty("project_select")));
List<WebElement> droplist_cotents = project_droplist.findElements(By.tagName("option"));
System.out.println(droplist_cotents.size());
//System.out.println(droplist_cotents.get(3).getText());
String actualVal=null;
for(int j=0;j<droplist_cotents.size();j++){
actualVal = droplist_cotents.get(j).getText();
System.out.println(actualVal);
}
System.out.println("actualVal = " + actualVal);
Assert.assertEquals(project_text, actualVal);
As i can see from your code, your project_text and actualVal are in the form of strings. The best way to compare values in them is to store them as string array's as you are looping through many values and you need to store them somewhere to assert. Here's how to store the values in an array and compare them -
int i = 0;
String[] project_text = new String[100];
String[] actualVal = new String[100];
while(isElementPresent(part1+i+part2)){
project_text[i] = driver.findElement(By.xpath(part1+i+part2)).getText();
assign_text = driver.findElement(By.xpath(assign_part1+i+assign_part2)).getText();
if (assign_text.contains("aaaa"))
System.out.println(project_text[i]);
i++;
}
for(int j=0;j<droplist_cotents.size();j++){
actualVal[j] = droplist_cotents.get(j).getText();
System.out.println(actualVal[j]);
}
for(int i = 0;i<project_text.length();i++)
Assert.assertEquals(project_text[i], actualVal[i]);
However if you don't know the size of the array, use ArrayList and work it out. Here's a sample.
Hope this helps.

String cannot be added to List using Object in Java

I am working on a JSF based Web Application where I read contents from a file(dumpfile) and then parse it using a logic and keep adding it to a list using an object and also set a string using the object. But I keep getting this error. I am confused where I am wrong. I am a beginner so can anyone be kind enough to help me?
List<DumpController> FinalDumpNotes;
public List<DumpController> initializeDumpNotes()
throws SocketException, IOException {
PostProcessedDump postProcessedDump = (PostProcessedDump) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("postProcessedDump");
List<DumpController> FinalNotes = new ArrayList<>();
if (postProcessedDump.getDumpNotes() == null) {
dumpNotes = new DumpNotes();
}
DumpListController dlcon = (DumpListController) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("dumpListController");
DumpInfo dumpinfo = dlcon.getSelectedDumpInfo();
String fileName = dumpinfo.getDate() + dumpinfo.getTime() + dumpinfo.getSeqNo() + dumpinfo.getType() + dumpinfo.getTape() + dumpinfo.getDescription() + ".txt";
if (checkFileExistsInWin(fileName)) {
postProcessedDump.setDumpnotescontent(getFileContentsFromWin(fileName));
String consolidateDumpnotes = getFileContentsFromWin(fileName);
String lines[];
String content = "";
lines = consolidateDumpnotes.split("\\r?\\n");
List<String> finallines = new ArrayList<>();
int k = 0;
for (int i = 0; i < lines.length; i++) {
if (!lines[i].equalsIgnoreCase("")) {
finallines.add(lines[i]);
k++;
}
}
for (int j = 0; j < finallines.size(); j++) {
if (finallines.get(j).startsWith("---------------------SAVED BY")) {
PostProcessedDump dump = new PostProcessedDump();
dump.setDumpMessage(content);
content = "";
FinalDumpNotes.add(dump);
} else {
content = content + finallines.get(j);
}
}
}
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("postProcessedDump", postProcessedDump);
return FinalDumpNotes;
}
I get the following error:
If you want to add instances of type PostProcessedDump to your List you should change it's type. Also, don't forget to initialize it. Something like,
List<PostProcessedDump> FinalDumpNotes = new ArrayList<>();
Also, Java naming convention is to start variable names with a lower case letter. FinalDumpNotes looks like a class, I would suggest something like
List<PostProcessedDump> processedList = new ArrayList<>();
Problems with your code:
List<DumpController> FinalDumpNotes;
You declare FinalDumpNotes to be a List of DumpController objects, but you never initialize it. In addition, your IDE is barfing on the following line of code:
FinalDumpNotes.add(dump);
because you are attempting to add a PostProcessedDump object to the List instead of a DumpController object.
For starters, you need to initialize your list like this:
List<DumpController> finalDumpNotes = new ArrayList<DumpController>();
Notice that I have made the variable name beginning with lower case, which is the convention (upper case is normally reserved for classes and interfaces).
I will leave it to you as a homework assignment to sort out the correct usage of this List.

Categories