Creating an HTML table in Java - java

I have a problem in my code when I am creating a table in Java using HTML. This is my code:
for(int station : stations){
String rowcolor = null;
String stationnum = Integer.toString(station);
String lastDate = pollData(station); //CALL GET LAST
String status = determineStatus(station, lastDate); // CALL DETERMINE STATUS
switch(status){
case " ONLINE":
rowcolor = (" <tr bgcolor=\"#5FFF33\">");
break;
case " OFFLINE":
rowcolor = (" <tr bgcolor=\"red\">");
break;
case " DELAYED":
rowcolor = (" <tr bgcolor=\"yellow\">");
break;
}
out.write("<html>" +
"<body>" +
"<table border ='1'>" +
"<tr>" +
"<td>Station Number</td>" +
"<td>Station Name</td>" +
"<td>Status</td>" +
"<td>As of Date</td>" +
"</tr>");
out.write(rowcolor + "<td>");
out.write(stationnum);
out.write("</td><td>");
out.write(stationnname[id]);
out.write("</td><td>");
out.write(status);
out.write("</td><td>");
out.write(lastDate);
out.write("</table>" +
"</body>" +
"</html>");
id++;
out.close();
}
}catch (IOException e) {
System.err.println(e);
}
and this is the output:
When I remove the out.close(); part, the output is this:
As you can see, the image there is a problem in creating the table. Something is not right but I can’t find a way to fix it. Please help me; thanks in advance.

Look at what you're writing to the output buffer and where.
Inside your for loop, you are writing a complete HTML document (ie <html><body>...</body></html>) and an entire table with header row and one data row.
What I assume you want to do is keep writing table rows to the one table. To do so, write the aforementioned tags outside your for loop
out.write("<html><body><table border=\"1\"><thead>" +
"<tr><td>Station Number</td><td>Station Name</td>" +
"<td>Status</td><td>As of Date</td></tr></thead><tbody>");
for(int station : stations) {
// get data, determine rowcolor, etc
out.write(rowcolor + ... + "</tr>");
}
out.write("</tbody></table></body></html>");
out.close();

As Phil said,out.close(); is inside the for loop,you need to change it to outside the for loop,due to if it's inside loop,out will close for the first iterate,and will not work for other records
for(int station : stations){
}
out.close();

Related

Seperating ArrayList items to a regular keyword group

I started Java for plugin codding in minecraft. now I'm trying to add role names as prefix and show it in chat.
ArrayList<String> userRoles = new ArrayList<String>();
if(player.hasPermission("chat.rank.admin")){
userRoles.add("[Admin]");
} if(player.hasPermission("chat.rank.vip")) {
userRoles.add("[VIP]");
}
event.setFormat(userRoles<>(1) + " " + player.getDisplayName() + "§7: " + msg);
// In this line, the expected output is "[Admin] user: msg" or both [Admin] [VIP] user: msg"
// But it gives "([Admin],[VIP]) user: msg"
// I'm sure it has a simple solution but as I said, I'm new here. thanks from now
It seems like you are trying to create a list which only stores one value.
You might want to try creating a function that get the rank name of the player outside of your PlayerChatEvent listener.
Here's a demo code:
public String getPlayerRankName(Player p){
if (p.hasPermission("chat.rank.admin"))
return "[Admin]";
else if (p.hasPermission("chat.rank.vip"))
return "[VIP]";
else
return "";
}
And in your PlayerChatEvent event listener, call this function in your chat line:
event.setFormat(getPlayerRankName(event.getPlayer()) + " " + player.getDisplayName() + "§7: " + msg);

How to save information from JTable to a File?

Here is my case:
So far my group and I, managed to read information from an external file and place it in a JTable. But we need an update button. So we guess we should take all the information from JTable after editting something inside it, and replace it with the current information in the same file. So we kind of think we have to overwrite the old file.
So far we got this: (for int i... is a part of the code but can't get it inside the grey area :P)
for(int i = 0; i < model.getRowCount(); i++) {
p += model.getValueAt(i, 0) + " "
+ model.getValueAt(i, 1) + " "
+ (Integer) model.getValueAt(i, 2) + " "
+ model.getValueAt(i, 3) + " "
+ (Integer)model.getValueAt(i, 4) + " "
+ model.getValueAt(i, 5) + " "
+ model.getValueAt(i, 6) + " "
+ model.getValueAt(i, 7) + " "
+ (Integer)model.getValueAt(i, 8) + "\n";
}
// Update File
SaveMember sm = new SaveMember();
sm.update(p);
Inside our SaveMember.java we got:
public void update(String x) throws Exception {
File f = new File("Members/Members.txt");
PrintStream output = new PrintStream(f);
output.print(x);
So by now when we go and change the data and press the button update, it doesn't do anything at all, and doesn't replace the old data with the new.. Thanks for reading! :)
I'm not sure. If you have double checked that your code is executed at all (maybe you forgot to attach the ActionListener to your button - we all do that from time to time...) try flush the output stream and close the stream afterwards.
First check if your code in the for loop is executed at all. Set a breakpoint after the for loop and inspect the string p. If you are not familiar with debugging, print the string to the console with System.out.println(p).
If your code is NOT executed: Check why the method your code is in is not called. Perhaps you forgot to attach an action listener to your update button or the action listener has an early return under some circumstances.
If your code is executed: What do you do with the exception that is thrown by the method update? Make sure to log it with your logger or print it to the console (again via System.out.println(exc)). If you get a FileNotFoundException the path to the file is not correct.

Find element with given text using jsoup

I have a table like in this fiddle. I need to find data related to the row which contains given text.
For example, by providing 1707, I need to get all data in table row which contains 1707. So output should be as below.
Tuesday 2014-08-05 1707 33 43 47 52 image text
Currently I'm accessing data on html page as below.
Document doc;
try {
doc = Jsoup
.connect("url here").timeout(300000).userAgent("Mozilla").get();
Element table = doc.select("table#customers").first();
if (table != null) {
Iterator<Element> iterator = table.select("td").iterator();
while (iterator.hasNext()) {
System.out.println("Day : " + iterator.next().text());
System.out.println("Date : " + iterator.next().text());
System.out.println("Draw : " + iterator.next().text());
System.out.println("No1 : " + iterator.next().text());
System.out.println("No2 : " + iterator.next().text());
System.out.println("No3 : " + iterator.next().text());
System.out.println("No4 : " + iterator.next().text());
System.out.println("Symbol : " + iterator.next().text());
System.out.println("Non : " + iterator.next().text());
}
} else {
System.out
.println("No results were found according to search criteria.");
}
} catch (IOException e) {
e.printStackTrace();
}
}
The above code return all data on table. But I need to get data related to given text.
How could I achieve this?
As shown in jsoup documentation you can use the pseudo-selector :contains(text):
table.select("tr:contains(1707) td")
You can try it here

java result set only writing one line instead of all selected into .csv

I have a java function that is meant to take strings from jlist called "readyList" and pulling data from mysql workbench tables with the intent to write a line for each string in a .csv file. With the current code it sucessfully pulls the data one at a time like i intended but it only writes the last line instead of all the lines. I want to have all the lines written in the .csv file. Please help!
int[] selectedIx = readyList.getSelectedIndices();
for (int i = 0; i < selectedIx.length; i++) {
// while (i < selectedIx.length) {
Object sel = readyList.getModel().getElementAt(selectedIx[i]);
Statement s1 = DBConnect.connection.createStatement();
String selTable01 = "SELECT Sku As s, Qty As q, Orig_Retail As prce, Orig_Sku As orgsk, Store As strcd "
+ "FROM completed_lines WHERE Form_Name = '" + sel + "' AND Warranty = 'true'";
s1.execute(selTable01);
try (ResultSet rs01 = s1.getResultSet()) {
fWriter = new FileWriter("Exports/Transfers/" + /* frmNm.replace(":", "_") */"EBW_" + GtDates.fdate + ".csv", false);
writer = new BufferedWriter(fWriter);
String header = "slip_number,slip_type,out_store,in_store,item_number,quantity,price,comment,to_num";
writer.write(header);
writer.newLine();
while (rs01.next()) {
String strcode = rs01.getString("strcd");
String sku = rs01.getString("s");
String qty = rs01.getString("q");
String price = rs01.getString("prce");
String orgsku = rs01.getString("orgsk");
//System.out.println(frmNm.split("_")[1] + qty + "," + sku + "," + vendor + "," + desc1 + "," + reas + "," + descdmg + "," + orgR + "," + nwsku + "," + desc2 + "," + qtyI);
String line = ""+","+"out"+","+strcode+","+"RTV"+","+sku+","+qty+","+price+","+"EBW"+","+orgsku;
writer.write(line);
writer.newLine();
}
}
// JOptionPane.showMessageDialog(frame, "All Data from Selected Forms has been Exported");
}
// FormCompelted();
writer.close();
}
}
A few issues with this code. The reason you're only getting the last result is because of this line:
fWriter = new FileWriter("Exports/Transfers/" + /* frmNm.replace(":", "_") */"EBW_" + GtDates.fdate + ".csv", false);
This line is inside your loop. The false as the last parameter tells FileWriter not to append. In other words, a false means overwrite the file if it exists. Since this is in your loop, each result overwrites the file that the last result created. You should create the FileWriter outside of your loop, probably in a try with resources. That will allow you to remove your writer.close() call, which should have been in a finally block anyway.
Not related to your original question but something you should be aware of: You're creating a new Statement with each loop iteration. This can be an expensive operation. You should use a PreparedStatement instead. Create it outside your loop and then just set the parameter and execute it inside the loop. It also implements AutoCloseable, so you can create it in a try with resources too, probably the same one you create your FileWriter in.

After extracting data from html using a for loop, how do I insert one by one into a database?

I have extracted multiple data from an HTML using Jsoup and now I am trying to insert one by one into a derby db using JDBC on netbeans.
Here is my code:
public String nameOf() {
String nameStr = null;
String nameResults = "";
for(int j=100;j<=110;j++) {
refNum = j;
//System.out.println("Reference Number: " + refNum);
try {
//crawl and parse HTML from definition and causes page
Document docDandC = Jsoup.connect("http://www.abcd.edu/encylopedia/article/000" + refNum + ".htm").get();
// scrape name data
Elements name = docDandC.select("title");
nameStr = name.get(0).text();
//System.out.println(nameStr);
nameResults += nameStr + " ";
} catch (Exception e) {
//System.out.println("Reference number " + refNum + " does not exist.");
}
}
return nameResults;
So this method takes the names of diseases from 10 different HTMLs. What I am trying to do is to insert one name at a time to a derby db that I have created using JDBC. I have everything set up and all I have left to do is to insert each name in the corresponding name field of a table named DISEASE (which has fields: id, name, etc).
nameResults += nameStr + " ";
This part worries me as well since some diseases can have multiple words. Maybe I should use a list of some sort?
Please help! Thanks in advance.
Something like:
public List<String> nameOf() {
...
List<String> nameResults = new ArrayList<String>();
...
nameResults.add(nameStr);
...
return nameResults;

Categories