Strange error in apache tomcat? - java

I am using apache tomcat with eclipse keplee .this is my jsp file which runs a java file which queries from tdb using sparql . jsp file :
<%# page import="check.test4query" %>
<% test4query demo = new test4query();
test4query dem = new test4query();
String[] id =new String[20];
String[] dat =new String[20];
int i;
demo.mai("SELECT ?x WHERE { ?y <TO:> 'hjcooljohny75#gmail.com' . ?y <SUB:> ?x} LIMIT 20 ");
for(i=0;i<20;i++)
{ id[i]=test4query.arr[i];
id[i] = id[i].substring(0, Math.min(id[i].length(), 30));
}
for(i=0;i<20;i++)
{ //id[i]=test4query.arr[i];
out.println("<tr>"+"&nbsp&nbsp&nbsp&nbsp"+id[i]+"<hr style='border-color:#E6E6E6;padding:0px;margin:0px'>"+"</tr>");
}
%>
this is my test4query :
public static String[] arr=new String[20];
public void mai (String s) {
//String s;
//load the dataset
//String query1;
//query1="hjcooljohny75#gmail.com";
//query1 = (String)(subjectentry.getText());
// s="SELECT ?x WHERE { ?y <TO:> '"+query1+"' . ?y <SUB:> ?x} LIMIT 20 ";
System.out.println(s);
String directory = "EMAILADDRESS" ;
Dataset ds = TDBFactory.createDataset(directory) ;
Model model = ds.getDefaultModel() ;
ds.begin(ReadWrite.READ) ;
QueryExecution qExec = QueryExecutionFactory.create(s, ds) ;
int i=0;
try{
ResultSet rs = qExec.execSelect() ;
String x=rs.toString();
while (rs.hasNext()) {
QuerySolution qs = rs.next();
String rds;
if(qs.get("x")!=null)
rds = qs.get("x").toString();
else rds="hi";
// String em = (String)rs.getString();
if(rds==null)
break;
//System.out.println(rds);
arr[i] = rds;
i++;
//for (int i =0; i < arr.length; i++){
}
} finally
{qExec.close() ;
ds.commit();
ds.end();
}
for( i=0;i<20;i++)
System.out.println(arr[i]);
//arr[0]="hi";
// return arr;
// try {
// ResultSetFormatter.out(rs) ;
// } finally { qExec.close() ; }
// Another query - same view of the data.
}
The problem is when I start the tomcat server it runs perfectly showing the results but after that if I refresh the page it shows error:
com.hp.hpl.jena.tdb.transaction.TDBTransactionException: Not in a transaction
com.hp.hpl.jena.tdb.transaction.DatasetGraphTransaction.get(DatasetGraphTransaction.java:106)
com.hp.hpl.jena.tdb.transaction.DatasetGraphTransaction.get(DatasetGraphTransaction.java:40)
com.hp.hpl.jena.sparql.core.DatasetGraphTrackActive.getDefaultGraph(DatasetGraphTrackActive.java:91)
com.hp.hpl.jena.sparql.core.DatasetImpl.getDefaultModel(DatasetImpl.java:103)
check.test4query.mai(test4query.java:59)
org.apache.jsp.grayscale.gmail_005flike_jsp._jspService(gmail_005flike_jsp.java:210)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:403)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:347)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
and this happens all the time but when I restart the server it shows correct ans for the first time and then error..I don't know what is the problem and how to correct it??

This is the wrong way round:
Model model = ds.getDefaultModel() ;
ds.begin(ReadWrite.READ) ;
Try instead:
ds.begin(ReadWrite.READ) ;
Model model = ds.getDefaultModel() ;

The problem is that you are leaking resources and not cleaning up after yourself
You start a transaction with your ds.begin(ReadWrite.READ) call but you don't ever close the transaction with a ds.end() call which is why subsequent calls fail with the error you see. You also fail to ever close your QueryExecution
You should use a try { } catch { } finally { } to ensure that you clean up relevant resources

Related

how to update multiple records with jdbc with oracle and spring boot

I am trying to update several records from spring jdbc but this is not working what am i doing wrong?
does not respond when I make a request, but the data in the array is arriving, try without array and the same thing happens.
I am sending an array of objects to be able to update but I get to the method cstmt.executeQuery(); it does not execute and it waits and does not go any further.
#PostMapping(path = "/updateEstadoPlanesServicios", produces = MediaType.APPLICATION_JSON)
public String updateEstadoPlanesServicios(#RequestBody String lista) {
ServiciosPlanesUpdateDTO[] fromJson = gson.fromJson(lista, ServiciosPlanesUpdateDTO[].class);
return gson.toJson(consultaPlanesComisionPortal.estadoPlanesServicios(fromJson));
}
#Transactional(rollbackFor = { Exception.class })
public replyDTO estadoPlanesServicios(ServiciosPlanesUpdateDTO[] list) {
System.out.println("data: "+list.toString());
replyDTO re = new replyDTO();
int count = 0;
try {
StringBuilder update = new StringBuilder();
update.append("UPDATE Detalleproductoservicio ");
update.append(" SET loginregistro = ?, estado = 'D', fechasys = sysdate ");
update.append(" WHERE codigo_Servicio = ? and codigo_planproductoservicio = ? and NIT = ?");
try (Connection conexion = obtenerConexion.obtenerConexion(0);
PreparedStatement cstmt = conexion.prepareStatement(update.toString())) {
conexion.setAutoCommit(false);
for(ServiciosPlanesUpdateDTO elements: list) {
//System.out.println(elements.toString());
System.out.println("1 element:"+elements.getLoginRegistro());
System.out.println("2 element:"+elements.getCodigoServicio());
System.out.println("3 element:"+elements.getCodigoPlanProductoServicio());
System.out.println("4 element:"+elements.getNit());
cstmt.setString(1, elements.getLoginRegistro().trim());
cstmt.setInt(2,Integer.parseInt( elements.getCodigoServicio().trim()));
cstmt.setString(3, elements.getCodigoPlanProductoServicio().trim());
cstmt.setString(4, elements.getNit().trim());
count = cstmt.executeUpdate();
//cstmt.execute();
//count++;
//cstmt.addBatch();
//cstmt.executeBatch();
//
}
conexion.commit();
if(count > 0) {
re.setMessage("Status ok,"
+"count: "+count);
re.setExitoso(true);
}else {
re.setExitoso(false);
re.setMessage("failed");
}
}
} catch (Exception e ) {
re.setExitoso(false);
re.setMessage(e.getMessage());
}
return re;
}
this is working I found the problem apparently the database conflicts when I have Oracle SQL Developer open and I make the request by postman this is a little weird but I closed Oracle Developer and it worked.

Problems finding correct table

i'm trying to scrape a site using Jaunt ( https://ravit.is.fi/hevoset/1 ) and I'm having problems finding the correct table element to parse this table (in red: https://i.imgur.com/JWNByHR.png )
From the html, I assumed the correct element would be < table border=\"0\" cellpadding=\"3\" cellspacing=\"1\">
but the table marked in green also uses the same element so what would be the way to "choose" the correct table? Been trying tons of things to no avail but as I am pretty new to java, html and coding in general, I'm most likely missing something obvious
Also, I tried putting the data from the other table to the xls table but everything went to same cell so what do you need to do so it would look like this: https://i.imgur.com/2TF4mO4.png ?
Thank you in advance
public class JauntTesti{
public static void main(String[] args){
int sivu = 1;
while (true) {
try{
UserAgent userAgent = new UserAgent();
if (sivu <= 1) {
userAgent.visit("https://ravit.is.fi/hevoset/" + sivu);
String title = userAgent.doc.findFirst("<title>").getChildText(); //hakee ekan löytyvän otsikon stringiin title
System.out.println("\n" + sivu);
Element body = userAgent.doc.findFirst("<body>");
Element strong = body.findEach("<strong>");
Element strong2 = userAgent.doc.findEach("<td>");
Element strong3 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(1);
Element strong4 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(1).getElement(1);
Element strong5 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(2).getElement(1);
Element strong6 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(3).getElement(1);
Element strong7 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(4).getElement(1);
Element strong8 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(5).getElement(1);
Element test1 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0);
Element test2 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(1).getElement(0);
Element test3 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(2).getElement(0);
Element test4 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(3).getElement(0);
Element test5 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(4).getElement(0);
Element test6 = strong2.getElement(0).getElement(0).getElement(1).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(0).getElement(5).getElement(0);
String nimi = strong3.innerText();
String laji = strong4.innerText();
String sukupuoli = strong5.innerText();
String ika = strong6.innerText();
String valmentaja = strong7.innerText();
String omistaja = strong8.innerText();
while (true) {
if (test4.innerHTML().equals("<strong>IKÄ:</strong> ")){
ika = strong6.innerText();
break;
}
ika = " ";
break;
}
while (true) {
if (test4.innerHTML().equals("<strong>VALMENTAJA:</strong> ")){
valmentaja = strong6.innerText();
break;
}
if (test5.innerHTML().equals("<strong>VALMENTAJA:</strong> ")){
valmentaja = strong7.innerText();
break;
}
valmentaja = "-1";
break;
}
while (true) {
if (test4.innerHTML().equals("<strong>OMISTAJA:</strong> ")){
omistaja = strong6.innerText();
break;
}
if (test5.innerHTML().equals("<strong>OMISTAJA:</strong> ")){
omistaja = strong7.innerText();
break;
}
if (test6.innerHTML().equals("<strong>OMISTAJA:</strong> ")){
omistaja = strong8.innerText();
break;
}
omistaja = "-1";
break;
}
Table taulukko2 = userAgent.doc.getTable("<table border=\"0\" cellpadding=\"3\" cellspacing=\"1\">");
Elements taul1 = taulukko2.getCol(0);
for(Element element : taul1) System.out.println(taul1.innerText());
ika = ika.replace(" v","");
//int ikav = Integer.parseInt(ika);
System.out.println("Nimi: " + nimi);
System.out.println("Laji: " + laji);
System.out.println("Sukupuoli: " + sukupuoli);
System.out.println("Ikä: " + ika);
System.out.println("Valmentaja: " + valmentaja);
System.out.println("Omistaja: " + omistaja);
try {
String filename = "C:/sheets/" + sivu + ".xls";
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
sheet.setColumnWidth(0, 5000);
sheet.setColumnWidth(1, 5000);
sheet.setColumnWidth(2, 3000);
sheet.setColumnWidth(3, 2000);
sheet.setColumnWidth(4, 4000);
sheet.setColumnWidth(5, 8000);
HSSFRow rowhead = sheet.createRow((short)0);
rowhead.createCell(0).setCellValue("NIMI");
rowhead.createCell(1).setCellValue("LAJI");
rowhead.createCell(2).setCellValue("SUKUPUOLI");
rowhead.createCell(3).setCellValue("IKÄ");
rowhead.createCell(4).setCellValue("VALMENTAJA");
rowhead.createCell(5).setCellValue("OMISTAJA");
//rowhead.createCell(6).setCellValue(taul1.innerText());
HSSFRow row = sheet.createRow((short)1);
row.createCell(0).setCellValue(nimi);
row.createCell(1).setCellValue(laji);
row.createCell(2).setCellValue(sukupuoli);
row.createCell(3).setCellValue(ika);
row.createCell(4).setCellValue(valmentaja);
row.createCell(5).setCellValue(omistaja);
FileOutputStream fileOut = new FileOutputStream(filename);
workbook.write(fileOut);
fileOut.close();
workbook.close();
} catch ( Exception ex ) {
System.out.println(ex);
}
sivu++;
} else {
break;
}
}
catch(JauntException e){
System.err.println(e);
}
}
}
}
With the univocity-html-parser, you can get all details from all tables. Not sure how you need to organize your data, but this should give you some guidance:
HtmlEntityList entityList = new HtmlEntityList();
HtmlEntitySettings person = entityList.configureEntity("person");
addFields(person, "NIMI", "LAJI", "SUKUPUOLI", "IKÄ", "VALMENTAJA", "OMISTAJA");
//not sure if you need the fields under "URAN TILASTOT", but here we go:
addFields(person, "STARTIT", "VOITOT", "2. SIJAT", "3. SIJAT", "VOITTOSUMMA");
//also not not sure if you need the fields under "Tilastot, kun kenkiä riisuttu pois", but here we go again:
addExactFields(person, "ȻȻ, ȻC tai CȻ", "ȻȻ", "ȻC", "CȻ", "ENNÄTYSAJAT", "RYHMÄLÄHTÖ", "TASOITUSAJO");
//I have no clue what the tables mean, so I'm calling them "table 1" and "table 2"
HtmlEntitySettings table1 = entityList.configureEntity("table1");
captureColumns(table1, "VUOSI", "STARTIT", "VOITOT", "2. SIJAT", "3. SIJAT", "VOITTOSUMMA", "RYHMÄ", "TASOITUS");
HtmlEntitySettings table2 = entityList.configureEntity("table2");
captureColumnsInLastTable(table2, "R", "PVM", "L", "R-NRO", "MATKA", "S", "KMA", "HYL", "KERR.", "PALK.", "OHJ.", "VALM.");
HtmlParser parser = new HtmlParser(entityList);
Results<HtmlParserResult> results = parser.parse(new UrlReaderProvider("https://ravit.is.fi/hevoset/1"));
printResult(results.get("person"));
printResult(results.get("table1"));
printResult(results.get("table2"));
Which uses the following methods:
private void addFields(HtmlEntitySettings entity, String... labels) {
for (String label : labels) {
entity.addField(label).match("td")
.withText(label)
.not().classes("heppatilastohead")
.matchNext("td").getText();
}
}
private void addExactFields(HtmlEntitySettings entity, String... labels) {
for (String label : labels) {
entity.addField(label).match("td").withExactText(label).matchNext("td").getText();
}
}
private void captureColumns(HtmlEntitySettings entity, String... headers) {
for (String header : headers) {
entity.addField(header)
.match("td")
.underHeader("td").withExactText(header)
.getText();
}
}
private void captureColumnsInLastTable(HtmlEntitySettings entity, String... headers) {
for (String header : headers) {
entity.addField(header)
.match("form")
.match("tr").not().at(2)
.match("td")
.underHeader("td").withExactText(header)
.getText();
}
}
private void printResult(HtmlParserResult result) {
System.out.println("\nValues of [" + result.getEntityName() + "]");
for (HtmlRecord record : result.iterateRecords()) {
System.out.println(record.fillFieldMap(new LinkedHashMap<String, String>()));
}
}
The output of this code is:
Values of [person]
{NIMI=Bernard Gazeau, LAJI=Lämminverinen, SUKUPUOLI=Ruuna, IKÄ=18 v, VALMENTAJA=Hannele Haapala, OMISTAJA=HaapalaHannele, Mouhijärvi, STARTIT=6, VOITOT=0, 2. SIJAT=0, 3. SIJAT=0, VOITTOSUMMA=680 €, ȻȻ, ȻC tai CȻ=0: 0-0-0, ȻȻ=0: 0-0-0, ȻC=0: 0-0-0, CȻ=0: 0-0-0, ENNÄTYSAJAT=null, RYHMÄLÄHTÖ=null, TASOITUSAJO=20,1 ke}
Values of [table1]
{VUOSI=2009, STARTIT=1, VOITOT=0, 2. SIJAT=0, 3. SIJAT=0, VOITTOSUMMA=140, RYHMÄ=null, TASOITUS=20,1 ke}
{VUOSI=2008, STARTIT=3, VOITOT=0, 2. SIJAT=0, 3. SIJAT=0, VOITTOSUMMA=420, RYHMÄ=null, TASOITUS=21,5 ke}
{VUOSI=2006, STARTIT=2, VOITOT=0, 2. SIJAT=0, 3. SIJAT=0, VOITTOSUMMA=120, RYHMÄ=null, TASOITUS=22,2 ke}
{VUOSI=YHT, STARTIT=6, VOITOT=0, 2. SIJAT=0, 3. SIJAT=0, VOITTOSUMMA=680, RYHMÄ=null, TASOITUS=20,1 ke}
Values of [table2]
{R=T, PVM=12.05.09, L=1, R-NRO=5, MATKA=2120, S=p, KMA=null, HYL=p, KERR.=0,0, PALK.=0, OHJ.=M Forss, VALM.=Haapala}
{R=TK, PVM=10.04.09, L=2, R-NRO=3, MATKA=2120, S=4, KMA=20,1, HYL=null, KERR.=25,6, PALK.=140, OHJ.=M Forss, VALM.=Haapala}
{R=TK, PVM=31.10.08, L=3, R-NRO=6, MATKA=2120, S=4, KMA=22,7, HYL=null, KERR.=104,2, PALK.=240, OHJ.=H Hell, VALM.=Haapala}
{R=T, PVM=04.03.08, L=2, R-NRO=10, MATKA=2100, S=8, KMA=21,5, HYL=null, KERR.=99,6, PALK.=100, OHJ.=H Hell, VALM.=Haapala}
{R=P, PVM=17.02.08, L=10, R-NRO=1, MATKA=2100, S=5, KMA=23,6, HYL=null, KERR.=96,1, PALK.=80, OHJ.=H Hell, VALM.=Haapala}
{R=T, PVM=15.01.08, L=KL1, R-NRO=3, MATKA=2120, S=kl, KMA=22,4, HYL=null, KERR.=0,0, PALK.=0, OHJ.=H Hell, VALM.=Haapala}
{R=T, PVM=18.12.07, L=KL1, R-NRO=1, MATKA=2120, S=kl hlo, KMA=25,2, HYL=hlo, KERR.=0,0, PALK.=0, OHJ.=H Hell, VALM.=Haapala}
{R=F, PVM=15.01.06, L=2, R-NRO=1, MATKA=2140, S=5, KMA=22,2, HYL=null, KERR.=21,4, PALK.=120, OHJ.=H Kamppuri, VALM.=Haapala}
{R=F, PVM=08.01.06, L=1, R-NRO=1, MATKA=2140, S=8, KMA=22,9, HYL=null, KERR.=4,0, PALK.=0, OHJ.=Ha Korpi, VALM.=Haapala}
Hope this can be useful to you.
Disclosure: I'm the author of this library. It's commercial closed source but it can save you a lot of development time.

Single thread writing to different database with different connection parameters

I am working on a project in which I have three tables in a different database with different schemas. So that means I have three different connection parameters for those three tables to connect using JDBC-
Let's suppose-
For Table1-
Username:- A
Password:- B
URL: C
Columns-
ID1 String
Account1 String
For Table2-
Username:- P
Password:- Q
URL:- R
Columns-
ID2 String
Account2 String
For Table3-
Username:- T
Password:- U
URL:- V
Columns-
ID3 String
Account3 String
And I am supposed to insert in all the three tables or any one of them using JDBC.
Below are the three use cases I have-
From the command prompt if suppose I am passing Table1 only, then I am suppose to insert only in Table1 columns by making connection to
Table1.
And if I am passing Table1, Table2 from the command prompt then I am suppose to insert in both Table1 and Table2 columns by making
connection to Table1 and Table2.
And if I am passing Table1, Table2 and Table3 then I am suppose to enter in all the three tables using there respective connection
parameter
I am not able to understand how to write code for the above particular scenario in such a cleaner way so that it can be extended in near future as well if I come up with four tables. I can have a one constant file which can store the SQL that needs to be executed for any of the three tables and some other constant thing as well.
public static void main(String[] args) {
}
class Task implements Runnable {
private Connection dbConnection = null;
private PreparedStatement preparedStatement = null;
public Task() {
}
#Override
public void run() {
dbConnection = getDbConnection();
//prepare the statement and execute it
}
}
private Connection getDBConnection() {
Connection dbConnection = null;
Class.forName(Constants.DRIVER_NAME);
dbConnection = DriverManager.getConnection( , , );
return dbConnection;
}
Can anyone provide some thoughts on this how should I proceed forward?
Note:-
Column in each table will differ a lot. Like in some tables, column can be 10 and in some other table, column can be 20.
Create databases.properties file with content like this:
# Table 1
table1.url: jdbc:mysql://localhost:3306/garden
table1.user: gardener
table1.password: shavel
table1.table: fruits
table1.column.id: fruitID
table1.column.color: fruitColor
table1.column.weight: fruitWeight
# ... More fruit columns here ...
# Table 2
table2.url: jdbc:mysql://otherhost:3306/forest
table2.user: forester
table2.password: axe
table2.table: trees
table2.column.id: treeID
table2.column.height: treeHeight
# ... More tree columns here ...
# ... More tables here ...
Then do something like this:
public static void main (String [] args)
{
Properties databasesProperties = new Properties ();
databasesProperties.load ("databases.properties");
for (String arg: args)
{
String url = databasesProperties.get (arg + ".url");
String user = databasesProperties.get (arg + ".user");
String password= databasesProperties.get (arg + ".password");
String table = databasesProperties.get (arg + ".table");
String columnPrefix = arg + ".column."
Map <String, String> columns = new HashMap <String, String> ();
for (String key: databasesProperties.stringPropertyNames ())
{
if (key.startsWith (columnPrefix))
columns.put (
key.substring (columnPrefix.length ()),
databasesProperties.get (key));
}
doInsert (url, user, password, table, columns);
}
}
Later you can always add more tables into your databases.properties file.
Save your Database properties in a class file DBPropery.java.
final class DBProperty
{
static String[] urls = {
"C",
"R",
"V"
}; //You can add more URLs here.
static String[] driver= {
"Driver1",
"Driver2",
"Driver3"
};//You can add more drivers string
static String[] table = {
"Table1",
"Table2",
"Table3"
};//You can add more table names here According to URLs mentioned in urls array.
static String[] user = {
"A",
"P",
"T"
};//You can add more user names here according to URls mentioned in urls array.
static String[] pwd = {
"B",
"Q",
"U"
};//You can add more Password here according to URls mentioned in urls array.
static String[] queries = {
"Query for Table1",
"Query for Table2",
"Query for Table3",
};//You can add more queries here for more tables according to URls mentioned in urls array.
static int[] columns ={
2,
2,
2
};//You can change the column numbers according to need . 0th index belongs to Table1 , 1 to table2....so on.
//If you add more tables , add corresponding columns count to next index.
static String[] columnValues ={
"1^John",
"34^Vicky",
"65^Ethen"
};//String at each index represents a row in corresponding table in table[] array. each column is seperated by delimiter "^".
}
Make all Changes in DBProperty.java file.
Then proceed with following class file
import java.sql.*;
import java.util.*;
class MultiTableInsert implements Runnable
{
Map<String,Integer> columnsInTable;
Map<String,String> tableDriver;
Map<String,String> rowForTable;
Map<String,String> queryForTable;
Map<String,String> urlForTable;
Map<String,String> userForTable;
Map<String,String> pwdForTable;
String[] tables ;
public MultiTableInsert(String... tables)//Loading all Database Settings here..
{
this.tables = tables;
columnsInTable = new LinkedHashMap<String,Integer>();
rowForTable = new LinkedHashMap<String,String>();
tableDriver = new LinkedHashMap<String,String>();
urlForTable = new LinkedHashMap<String,String>();
userForTable= new LinkedHashMap<String,String>();
pwdForTable = new LinkedHashMap<String,String>();
for (int i = 0 ; i < DBProperty.urls.length ; i++ )
{
try
{
tableDriver.put(DBProperty.table[i],DBProperty.driver[i]);
queryForTable.put(DBProperty.table[i],DBProperty.queries[i]);
columnsInTable.put(DBProperty.table[i],DBProperty.columns[i]);
rowForTable.put(DBProperty.table[i],DBProperty.columnValues[i]);
urlForTable.put(DBProperty.table[i],DBProperty.urls[i]);
userForTable.put(DBProperty.table[i],DBProperty.user[i]);
pwdForTable.put(DBProperty.table[i],DBProperty.pwd[i]);
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
#Override
public void run()
{
insertIntoTable(tables);
}
private void insertIntoTable(String... tables)
{
for (String tble : tables )
{
Connection con = null;
PreparedStatement pStmt = null;
try
{
Class.forName(tableDriver.get(tble));
con = DriverManager.getConnection(urlForTable.get(tble),userForTable.get(tble),pwdForTable.get(tble));
pStmt = con.prepareStatement(queryForTable.get(tble));
int columns = columnsInTable.get(tble);
String sRow = rowForTable.get(tble);
StringTokenizer tokenizer = new StringTokenizer(sRow,"^");
for (int i = 0; i < columns ; i++)
{
pStmt.setString(i+1,(String)tokenizer.nextElement());
}
pStmt.execute();
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
try
{
con.close();
}catch (Exception ex){}
try
{
pStmt.close();
}catch (Exception ex){}
}
}
}
public static void main(String[] args)
{
int length = args.length;
int THREAD_COUNTS = 10;//Number of threads you want to start.
switch (length)
{
case 0:
System.out.println("Usage: javac MultiTableInsert Table1/Table2/Table3 <Table1/Table2/Table3> <Table1/Table2/Table3>");
System.exit(0);
case 1:
for (int i = 0 ; i < THREAD_COUNTS ; i++)
{
MultiTableInsert mti = new MultiTableInsert(args[0]);
Thread th = new Thread(mti,"Thread"+i);//Create New Thread
th.start(); //Start Thread
}
break;
case 2:
for (int i = 0 ; i < THREAD_COUNTS ; i++)
{
MultiTableInsert mti = new MultiTableInsert(args[0],args[1]);//Create New Thread
Thread th = new Thread(mti,"Thread"+i); //Start Thread
th.start();
}
break;
default:
for (int i = 0 ; i < THREAD_COUNTS ; i++)
{
MultiTableInsert mti = new MultiTableInsert(args[0],args[1],args[2]);//Create New Thread
Thread th = new Thread(mti,"Thread"+i); //Start Thread
th.start();
}
break;
}
}
}

Java Bean not working as expected

OK, I have a JSP running the following script section.
<% irCollection mgrq = new irCollection();
mgrq.setMgrid("Chris Novish");
mgrq.populateCollection();
int pagenum;
if (request.getParameter("p") != null) {
String pagedatum=request.getParameter("p");
pagenum = Integer.parseInt(pagedatum);
} else { pagenum = 0; }
for (int i=0;i<10;i++) {
int rownum = pagenum * 10 + i;
InquireRecord currec = mgrq.getCurRecords(rownum);
out.println(currec.getID()); %>
irCollection has an ArrayList property that stores a several InquireRecord objects. It gets this data from a database using the mgrid as (set in line 2 there) as the matching term.
But I'm getting an IndexOutOfBounds exception on what appears here as line 11.
I've done some tests, and I'm pretty sure that it's because populateCollection() isn't getting things done. I have a getSize method that gives me a size of 0.
I made a test class in Eclipse to make sure all my methods were working:
package com.serco.inquire;
public class test {
public static void main (String[] args) {
String mgr = "Chris Novish";
irCollection bob = new irCollection();
bob.setMgrid(mgr);
bob.populateCollection();
InquireRecord fred = bob.getCurRecords(1);
System.out.println(fred.getID());
}
}
That test class produces exactly what I'd expect.
Other than the names of some of the local variables, I can't see what I'm doign different in the JSP.
So... tell me, what noobish mistake did I make?
for the sake of being thorough, here's the populateCollection() method:
public void populateCollection() {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String filename = "inquire.mdb";
String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
database+= filename.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection( database ,"","");
Statement s = con.createStatement();
s.execute ("SELECT * FROM inquiries WHERE manager = '" + mgrid + "'");
ResultSet rs = s.getResultSet();
int cur;
if (rs != null) {
while (rs.next()) {
cur = rs.getRow();
cur -- ;
int curID = rs.getInt("ID");
this.newIR.setID(curID);
String cursub = rs.getString("submitter");
this.newIR.setSubmitter(cursub);
this.iRecords.add(cur, this.newIR);
}
this.size = iRecords.size();
this.pages = this.size / 10;
int remain = this.size % 10;
if (remain > 0) { this.pages++; }
} else { System.out.println("no records."); }
}
catch (Throwable e) {
System.out.println(e);
}
}
Your IndexOutOfBounds exception is probably being caused by the value of rownum being passed to mgrq.getCurRecords().
Your test code proves nothing because there you're calling getCurRecords() with a constant which is probably always valid for your system and will never cause the exception.
My suggestion is to step through the code in your JSP with a debugger, or even simply to print out the value of your variables (especially pagedatum, pagenum and rownum) in your JSP code.
Is your JSP Snippet correct? It looks like you started the braces for the
for (int i=0;i<10;i++) {
but I dont see a end braces for that at all. Can you check if that is the case and if so, fix the code appropriately?

how to generate RSS for news sites programmatically in java/j2ee?

how to generate RSS for news sites programmatically? I dont know how to start..
I learned how to write RSS from this article:
http://www.petefreitag.com/item/465.cfm
You can also just go to an RSS feed you like and press "View Source". Then you should simply use your java application to reproduce an XML similar to the XML you see (Only with your data).
When you finish, use one of many RSS Validators to validate your RSS.
It's easier than it first looks...
This code shows how to query a database to generate arbitrary XML from a JSP, manually.
It's not RSS, but the idea might be helpful to you.
private String ExecQueryGetXml(java.sql.PreparedStatement stmt, String rowEltName) {
String result= "<none/>";
String item;
java.sql.ResultSet resultSet;
java.sql.ResultSetMetaData metaData ;
StringBuffer buf = new StringBuffer();
int i;
try {
resultSet = stmt.executeQuery();
metaData= resultSet.getMetaData();
int numberOfColumns = metaData.getColumnCount();
String[] columnNames = new String[numberOfColumns];
for( i = 0; i < numberOfColumns; i++)
columnNames[i] = metaData.getColumnLabel(i+1);
try {
// if ((root!=null) && (!root.equals("")))
// buf.append('<').append(root).append('>').append('\n');
// each row is an element, each field a sub-element
while ( resultSet.next() ) {
// open the row elt
buf.append(' ').append('<').append(rowEltName).append(">\n");
for( i= 0; i < numberOfColumns; i++) {
item = resultSet.getString(i+1);
if(item==null) continue;
buf.append(" <").append(columnNames[i]).append('>');
// check for CDATA required here?
buf.append(item);
buf.append("</").append(columnNames[i]).append(">\n");
}
buf.append("\n </").append(rowEltName).append(">\n");
}
// conditionally close the row elt
// if ((root!=null) && (!root.equals("")))
// buf.append("</").append(root).append(">\n");
result= buf.toString();
}
catch(Exception e1) {
System.err.print("\n\n----Exception (2): failed converting ResultSet to xml.\n");
System.err.print(e1);
result= "<error><message>Exception (2): " + e1.toString() + ". Failed converting ResultSet to xml.</message></error>\n";
}
}
catch(Exception e2) {
System.err.print("\n\n----Exception (3).\n");
System.err.print("\n\n----query failed, or getMetaData failed.\n");
System.err.print("\n\n---- Exc as string: \n" + e2);
System.err.print("\n\n---- Exc via helper: \n" +
dinoch.demo.ExceptionHelper.getStackTraceAsString(e2));
result= "<error><message>Exception (3): " + e2 + ". query failed, or getMetaData() failed.</message></error>\n";
}
return result;
}
How about using a framework like Rome or jrss

Categories

Resources