Parsing SQLite with JSON, Client to Server - java

I have got a GUI client, that can receive data from a multithreaded server. I then want to be able to send data back to the server. From what I understand with Json, I can use it to send the SQLite statement and also a string. I'm not sure if what I'm trying to implement is the best way forward, but this is what I have got. On the client:
private void addDriverToTable() {
if (printWriter != null && bufferedReader != null) {
String driverRef = driverRefTextField.getText();
String driverNumber = numberTextField.getText();
String driverCode = codeTextField.getText();
String driverForename = forenameTextField.getText();
String driverSurname = surnameTextField.getText();
String driverDOB = dobTextField.getText();
String driverNationality = nationalityTextField.getText();
String driverURL = urlTextField.getText();
System.out.println("get, " + driverRef + "," + driverNumber + "," + driverCode + "," + driverForename + ","
+ driverSurname + "," + driverDOB + "," + driverNationality + "," + driverURL);
String insertDriver = "INSERT INTO drivers (driverRef, number, code, forename, surname, dob, nationality, url)" +
"VALUES (?,?,?,?,?,?,?,?)";
String addDriver = (driverRef + "," + driverNumber + "," + driverCode + "," + driverForename + "," +
driverSurname + "," + driverDOB + "," + driverNationality + "," + driverURL);
addDriverHashMap = new HashMap();
addDriverHashMap.put(insertDriver, addDriver);
Gson gson = new Gson();
JsonObject addDriverData;
addDriverData = gson.toJsonTree(addDriverHashMap).getAsJsonObject();
System.out.println(addDriverData);
String toSend = "add";
printWriter.println(toSend);
String toSendJson = String.valueOf(addDriverData);
printWriter.println(toSendJson);
String reply = null;
printWriter.println(addDriverData);
statusLabel.setText("Status: Adding Driver to database");
try {
reply = bufferedReader.readLine();
statusLabel.setText("Status: Received reply from server");
}catch (IOException ex){
statusLabel.setText("IOException " + ex);
}
statusLabel.setText("Adding Driver to database");
}else {
statusLabel.setText("You must connect to the server first");
}
}
On the client handler:
#Override
public void run() {
try{
threadSays("Waiting for data from client...");
String lineRead;
while ((lineRead = bufferedReader.readLine()) != null){
threadSays("Read data from client: \"" + lineRead + "\".");
if(command.matches("add")){
if(command.matches("INSERT")) {
JsonObject jsonReply = JsonParser.parseString(arrayRead[0]).getAsJsonObject();
addMyDrivers = new ArrayList<>(Arrays.asList(jsonReply));
insertDriver = (String) addMyDrivers.get(1);
addDriver = (String) addMyDrivers.get(2);
replyMessage = "Adding Driver to Database";
ThreadedServer.addDriver(insertDriver, addDriver);
}
}
printWriter.println(replyMessage);
}
}catch (IOException ex){
Logger.getLogger(ClientHandlerThread.class.getName()).log(Level.SEVERE, null, ex);
}finally {
try {
threadSays("We have lost connection to client " + connectionNumber + ".");
ThreadedServer.removeThread(this);
socket.close();
}catch (IOException ex){
Logger.getLogger(ClientHandlerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Finally on the server:
public static void addDriver(String insertDriver, String addDriver) {
try (Connection connection = ConnectionSQLite.getConnection()) {
try (PreparedStatement preparedStatement = connection.prepareStatement(insertDriver)) {
preparedStatement.setString(1, addDriver);
preparedStatement.setString(2, addDriver);
preparedStatement.setString(3, addDriver);
preparedStatement.setString(4, addDriver);
preparedStatement.setString(5, addDriver);
preparedStatement.setString(6, addDriver);
preparedStatement.setString(7, addDriver);
preparedStatement.setString(8, addDriver);
preparedStatement.execute();
}
} catch (SQLException ex) {
Logger.getLogger(SQLException.class.getName()).log(Level.SEVERE, null, ex);
}
}
The SQLite message appears on the server, I can't work out how to actually get it to then do the insert, the data I'm trying to insert. Any help would be greatly appreciated.

Related

Exception is not handled

When I open the view window, I enter the value of facultyCode and if I enter an existing value, then everything is fine, and if I enter a non-existent value, then the window freezes and nothing happens
CLIENT
#FXML
void initialize() {
showButton.setOnAction(actionEvent -> {
String input = null;
try {
socket = new Socket("127.0.0.1",3024);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String facultyCode = facultyCodeArea.getText();
String output = "SELECT * FROM Faculty WHERE facultyCode = " + facultyCode + ";";
try {
outputStream.writeUTF(output);
outputStream.flush();
input = inputStream.readUTF(); //if the input is incorrect, input is not assigned to
//anything
} catch (IOException e) {
e.printStackTrace();
}
String[] dataServer = input.split(" ");
String name = dataServer[0];
nameArea.setText(name);
String code = dataServer[1];
facultyCodeArea.setText(code);
String number = dataServer[2];
numberSubjectsArea.setText(number);
String main = dataServer[3];
mainSubjectArea.setText(main);
String dean = dataServer[4];
deanArea.setText(dean);
String language = dataServer[5];
languageStudyArea.setText(language);
});
}
SERVER
else if (isSelectQuery(input)) {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(input);
while (resultSet.next()) {
String name = resultSet.getString("name");
int codeFaculty = resultSet.getInt("facultyCode");
int numberSubject = resultSet.getInt("numberSubjects");
String mainSubject = resultSet.getString("mainSubject");
String dean = resultSet.getString("dean");
String languageStudy = resultSet.getString("languageStudy");
String output = name + " " +
codeFaculty + " " +
numberSubject + " " +
mainSubject + " " +
dean + " " +
languageStudy;
outputStream.writeUTF(output);
outputStream.flush();
}
}
I've tried closing the window if an exception occurs, I've also tried closing the window if input = null, but didn't help
SERVER
String output = "error";
else if (isSelectQuery(input)) {
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(input);
while (resultSet.next()) {
String name = resultSet.getString("name");
int codeFaculty = resultSet.getInt("facultyCode");
int numberSubject = resultSet.getInt("numberSubjects");
String mainSubject = resultSet.getString("mainSubject");
String dean = resultSet.getString("dean");
String languageStudy = resultSet.getString("languageStudy");
output = name + " " +
codeFaculty + " " +
numberSubject + " " +
mainSubject + " " +
dean + " " +
languageStudy;
}
outputStream.writeUTF(output);
outputStream.flush();
}
CLIENT
#FXML
void initialize() {
showButton.setOnAction(actionEvent -> {
String input = null;
try {
socket = new Socket("127.0.0.1",3024);
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new DataInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
String facultyCode = facultyCodeArea.getText();
String output = "SELECT * FROM Faculty WHERE facultyCode = " + facultyCode + ";";
try {
outputStream.writeUTF(output);
outputStream.flush();
input = inputStream.readUTF();
} catch (IOException e) {
e.printStackTrace();
}
String[] dataServer = input.split(" ");
if(!dataServer[0].equals("error")) {
String name = dataServer[0];
nameArea.setText(name);
String code = dataServer[1];
facultyCodeArea.setText(code);
String number = dataServer[2];
numberSubjectsArea.setText(number);
String main = dataServer[3];
mainSubjectArea.setText(main);
String dean = dataServer[4];
deanArea.setText(dean);
String language = dataServer[5];
languageStudyArea.setText(language);
}
else {
errorArea.setText("Not exist");
}
});
}
So I first assign output = error and if the request does not return anything, then I send it to the client, if on request something came, I assign values ​​and send it to the client. Next, I process the data on the client

Java JDBC MySQL exception: “Operation not allowed after ResultSet closed” with Web Page read [duplicate]

This question already has answers here:
Java JDBC MySQL exception: "Operation not allowed after ResultSet closed"
(2 answers)
Closed 5 years ago.
I am using the MySQL connector to get the URL to find values on the web pages.
I am getting the above message and I am not sure why. It inserts the first record from the rs1, but I am not sure why it is closing it.
Below is my code
String strSQL = "SELECT * FROM element_info;";
String sElementID = "";
String sSymbol = "";
URL urlChartLink;
URLConnection urlconn;
String sChartLink = "";
String sCurrentPrice = "";
String FindValue = "last_last";
try {
Class.forName(driver).newInstance();
Connection mysqlconn = DriverManager.getConnection(url + dbName, userName, password);
Statement st1 = mysqlconn.createStatement();
ResultSet rs1 = st1.executeQuery(strSQL);
while (rs1.next()) {
// Get all of the elements
// Retrieve the ElementID
sElementID = rs1.getString(1);
// Retrieve the Symbol
sSymbol = rs1.getString(2);
// Retrieve the Chartlink
sChartLink = rs1.getString(3);
if (sChartLink == "") {
break;
}
try {
urlChartLink = new URL(sChartLink);
urlconn = urlChartLink.openConnection();
urlconn.addRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
BufferedReader in = new BufferedReader(new InputStreamReader(urlconn.getInputStream(), "UTF-8"));
String currentLine;
while ((currentLine = in.readLine()) != null) {
// See if the value is on this record
int pos1 = currentLine.indexOf(FindValue);
int pos2 = currentLine.indexOf("</span>");
// pos1 = 66
if (pos1 > 0) {
pos1 = pos1 + 21;
pos2 = pos2 - 1;
// System.out.print("pos1 = " + pos1 + "\n");
// System.out.print("pos2 = " + pos2 + "\n");
sCurrentPrice = currentLine.substring(pos1, pos2);
// System.out.print("sCurrentPrice = " + sCurrentPrice + "\n");
// Import into the marketprices
strSQL = "INSERT INTO marketprices"
+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"
+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
int val = st1.executeUpdate(strSQL);
if (val == 1)
System.out.print("Successfully inserted from " + sChartLink + "\n");
break;
}
}
in.close();
} catch (IOException e) {
System.out.print("Error getting ChartLink website: " + e.getMessage() + "\n");
break;
}
}
} catch (Exception e) {
System.out.print("Error: " + e.getMessage() + "\n");
e.printStackTrace();
}
You are trying to write with a statement object that is already in use as you are still reading the existing resultset from that statement object. You need to create a new statement object for the update portion of your code:
strSQL = "INSERT INTO marketprices"+ "(ElementID,Symbol,PullDatetime,Price) VALUES (" + "'" + sElementID + "','"+ sSymbol + "','" + sToday + "','" + sCurrentPrice + "')";
Connection mysqlconn2 = DriverManager.getConnection(url + dbName, userName, password);
Statement st2 = mysqlconn.createStatement();
int val = st2.executeUpdate(strSQL);

statement.executeQuery returning resultset with no rows

My problem is that when I fire a query directly into Oracle, it returns me the rows with proper data. But when I try to fire the same query via Statement, its fetching me a resultset with no rows.
My code is as follows :
public void sendSMStoMobile() {
if (smsGatewayStatus.equals("STOPPED")) {
stringBuilder.append("The control is returning" + "\n");
jTextArea1.setText(stringBuilder.toString());
return;
}
DBCP dbcp = DBCP.getInstance(database_url, username, password);
Connection connection = null;
Statement statement = null;
try {
connection = dbcp.getConnection();
statement = connection.createStatement();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
} catch (InterruptedException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
System.out.println("Message : " + ex.getMessage());
}
ResultSet resultSet = null;
try {
sql = new StringBuffer();
sql.append("SELECT SMS_ID, MOBILE_NO, SMS_CONTENT ");
sql.append("FROM SMSDATA.SMS_DATA ");
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('LOANREPAY') " );
//sql.append("WHERE SENT_STATUS = 'N' AND Message_Code IN('SPECIAL') " );
sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("WHERE tranum <= (select max(tranum) -25 from smsgtway.sms_all_tran where SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT')) and SENT_STATUS = 'N' AND Message_Code IN('MEMDEP','MEMGRANT','SAMGRANT') " );
sql.append("ORDER BY SMS_ID desc ");
// sql.append("ORDER BY SENT_TIMSTAMP " );
// For Test
//sql.append("SELECT customer_Code,MOBILE_NO, SMS_CONTENT,SMS_ID " );
//sql.append("FROM MB_SMS_DTL ");
//sql.append("WHERE SENT_STATUS = 'N' ");
//sql.append("ORDER BY SMS_ID " );
// End Test
resultSet = statement.executeQuery(sql.toString());
System.out.println("Code comes here");
/* if(!resultSet.next()){
stringBuilder.append("No Data Found" +"\n");
jTextArea1.setText(stringBuilder.toString());
} */
if (!resultSet.next()) {
System.out.println("no data");
} else {
System.out.println("Data Found...");
do {
//statement(s)
} while (resultSet.next());
}
while (resultSet.next()) {
System.out.println("Data Found...");
String smsId = resultSet.getString(1);
String destMobileNo = resultSet.getString(2);
String message = resultSet.getString(3);
OutboundMessage sms = new OutboundMessage(destMobileNo, message);
System.out.println("Code comes here" + smsId);
//System.out.println("sms = " + sms);
try {
Service.getInstance().sendMessage(sms);
} catch (TimeoutException timeoutException) {
System.out.println("1");
stringBuilder.append("Exception : " + timeoutException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (GatewayException gatewayException) {
System.out.println("2");
stringBuilder.append("Exception : " + gatewayException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (IOException iOException) {
System.out.println("3");
stringBuilder.append("Exception : " + iOException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (InterruptedException interruptedException) {
System.out.println("4");
stringBuilder.append("Exception : " + interruptedException.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
} catch (java.lang.StringIndexOutOfBoundsException siobe) {
System.out.println("5");
stringBuilder.append("Exception : " + siobe.getMessage() + "\n");
jTextArea1.setText(stringBuilder.toString());
}
//Update Table After Send Message
String updateQuery = "UPDATE SMSDATA.SMS_DATA SET SENT_STATUS = 'Y', SENT_DATE = sysdate WHERE SMS_ID = " + smsId;
//String updateQuery = "UPDATE MB_SMS_DTL SET SENT_STATUS = 'Y' WHERE SMS_ID = " + tranNumber ;
//System.out.println("Update Query: " + updateQuery);
if (i < 10) {
System.out.print(smsId + ": Y, ");
}
if (i == 10) {
System.out.print(smsId + ": Y, " + "\n");
i = 0;
}
statement.executeUpdate(updateQuery);
connection.commit();
i = i + 1;
}
} catch (Exception e) {
System.out.println("Message: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
stringBuilder.append("Message: " + e.getMessage() + "\n");
stringBuilder.append("Cause: " + e.getCause() + "\n");
jTextArea1.setText(stringBuilder.toString());
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
Logger.getLogger(Send_SMS_Form.class.getName()).log(Level.SEVERE, null, ex);
}
}
dbcp.releaseConnection(connection);
//Service.getInstance().stopService();
}
}
When I call this function , "no data" is printed in Console . The sql is correct . When I run the sql in Toad , I have found 2 rows .
Please help me .

send a broadcast message to all items in list in java

I would like to send a broadcast message to all numbers returned from the select statement. It saves elements in the list but then it sends the same message to everyone. What am I doing wrong? Please see my method below.
public static List<Message> listAllMessages(Connection connection) {
List<Message> msg = new ArrayList<Message>();
String messages = ReturnTexts.getMessage(connection, "EMPTYMESSAGE");
String sql = "SELECT b.`productid` as productid, p.`productname` as productname, b.`msisdn` as msisdn , MAX(b.`amount`) as amount, b.`productcode` as productcode, a.`endDate` as enddate FROM "
+ TableNames.SAVEDBIDSTABLE
+ "b LEFT JOIN "
+ TableNames.PRODUCTTABLE1
+ " p ON b.`productcode`= p.`code` "
+ " JOIN "
+ TableNames.AUCTIONTABLE1
+ " a"
+ " ON b.`productcode`= a.`productcode` "
+ "GROUP BY msisdn, productcode ";
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
if (connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
// LOGGER.info(sql);
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
// statement = connection.createStatement();
resultSet = statement.executeQuery();
long productid = 0;
String productname = null;
String msisdn = null;
int amount = 0;
String productcode = null;
Date enddate = null;
while (resultSet.next()) {
productid = resultSet.getLong("productid");
productname = resultSet.getString("productname");
msisdn = resultSet.getString("msisdn");
amount = resultSet.getInt("amount");
productcode = resultSet.getString("productcode");
enddate = resultSet.getTimestamp("enddate");
msg.add(new Message(Long.valueOf(productid), productname,
msisdn, amount, productcode, String.valueOf(enddate)));
}
String messages = ReturnTexts
.getMessage(connection, "BROADCAST")
.replace("XXXX", productname)
// .replace("YYYY", String.valueOf(amount))
.replace("YYYY",
String.valueOf(maxBid(productcode, connection)))
.replace("ZZZZ", String.valueOf(enddate));
//LOGGER.info(messages.toString());
try {
for (Message obj : msg) {
obj.setMessage(messages);
String apiUrl = "url/sendsms.jsp";
getResponse(apiUrl + "?" + "user="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&password="
+ URLEncoder.encode("xxx", "UTF-8")
+ "&mobiles=" + obj.getMsisdn() + "&sms="
+ URLEncoder.encode(obj.getMessage(), "UTF-8"));
//bulkMessagesLog(obj.getMsisdn(), obj.getMessage(),obj.getProductcode(), connection);
bulkMessagesLog(productcode, msisdn, productname, connection);
//LOGGER.info(obj.getMsisdn() + " : " + obj.getProductcode()+ " : " + obj.getMessage());
}
} catch (UnsupportedEncodingException e) {
System.err
.println("UnsupportedEncodingException while trying to send SMS.");
e.getMessage();
}
} catch (SQLException e) {
LOGGER.error(e.getMessage());
} finally {
DBConnection.closeAllDBUsage(resultSet, statement, null);
}
return msg;
}
public static void bulkMessagesLog(String msisdn, String message,String productcode,
Connection connection) {
PreparedStatement statement = null;
String sql = "INSERT INTO " + TableNames.BULK_MESSAGESLOGTABLE
+ "(`msisdn`,`message`,`productcode`,`dateCreated`) VALUES(?,?,?,now()) ";
try {
if ( connection == null || connection.isClosed() )
connection = DBConnection.getConnection();
statement = DBConnection.isConnected(connection).prepareStatement(
sql);
statement.setString(1, msisdn);
statement.setString(2, message);
statement.setString(3, productcode);
//statement.addBatch();
statement.executeUpdate();
} catch (SQLException e) {
LOGGER.error(e.getMessage(), e);
} finally {
DBConnection.closeAllDBUsage(null, statement, connection);
}
}
You do iterate over the result set and build a list of messages in msg. Though you only create the text once, outside of the loop, so it's always the same with the (last) productname etc.
Should probably also be created in the loop.

java connection pool autocommit

I'm using for the first time the connection pool in java. The application that I'm writing is a web application deployed on oracle glassfish 3.1 and the resource connection pool is handled by it. I set the autocommit to false on my connection object, returned by the javax.sql.DataSource, but in the code the rollback command has no effect at all. All the previous operation of write are committed automatically. Is there any other settings in java code that I have to do to disable autocommit? Or there is some configuration settings that I have to do on glassfish?
The database that I'm using is Oracle 10g.
I post here a part of the code that is giving me problem:
private int importFile(String id, String fileName, String label,
String prosumerId, String districtCodes)
throws IOException,
SQLException {
logger.debug("Importing file [" + fileName + "]");
File f = new File(fileName);
BufferedReader br = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
String query = "insert into TB_SDK_USER_FILES values ("
+ id + ", '" + label + "', '"
+ fileName.substring(fileName.lastIndexOf("/") + 1) + "', 'active', "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "to_date('" + sdf.format(new Date(cal.getTimeInMillis())) + "', 'dd/mm/yyyy hh24:mi:ss'), "
+ "'" + prosumerId + "'"
+ ") ";
logger.debug("Executing query [" + query + "]");
dbl.openDBConnection();
int x = dbl.set(query);
if (x <= 0) {
dbl.rollback();
dbl.closeDBConnection();
logger.error("Insert in TB_SDK_USER_FILES failed, stopping execution ");
return -3;
}
PreparedStatement ps = null;
String line = new String();
try {
br = new BufferedReader(new FileReader(f));
query = "insert into TB_SDK_CONTENTS "
+ "(id, contentCode, cli, content, contentType, PROSUMERID, cld, email) "
+ "values (?,?,?,?,?,?,?,?)";
logger.debug("Executing query [" + query + "]");
ps = dbl.getPreparedStatement(query);
while ((line = br.readLine()) != null) {
String[] tmp = line.split("\t");
if (tmp.length < 4) {
logger.debug("Sono presenti erroneamente meno di 4 valori!!!!");
br.close();
f.delete();
dbl.rollback();
ps.close();
dbl.closeDBConnection();
return -2;
}
ps.setInt(1, new Integer(id).intValue());
String test = tmp[0].replace("*", "");
logger.debug("first column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- NumberFormatException");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
if (tmp[0].length() > 0) {
ps.setString(2, tmp[0].trim());
} else {
logger.error("The first column does not satisfy the format requested. Found [" + tmp[0] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -6;
}
test = tmp[1].replace("*", "").trim();
logger.debug("second column: test [" + test + "]");
try {
if (test.length() > 0) {
double testDouble = Double.parseDouble(test);
//int testInt = Integer.parseInt(test);
}
} catch (NumberFormatException nfe) {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
if (tmp[1].length() > 0) {
ps.setString(3, tmp[1].trim());
} else {
logger.error("The second column does not satisfy the format requested. Found [" + tmp[1] + "] -- length() <= 0");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -7;
}
logger.debug("third column: tmp[2] [" + tmp[2] + "]");
ps.setString(4, tmp[2]);
if ((tmp[3].length() > 0) && ((tmp[3].compareToIgnoreCase("TTS") == 0)
|| (tmp[3].compareToIgnoreCase("Audio") == 0))) {
ps.setString(5, tmp[3].trim());
logger.debug("fourth column: tmp[3] [" + tmp[3] + "]");
} else {
logger.error("The fourth column does not satisfy the format requested. Found [" + tmp[3] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -10;
}
ps.setString(6, prosumerId);
if (tmp.length > 4) {
tmp[4] = tmp[4].trim();
if ((tmp[4].length() > 0) && (tmp[4].length() <= 12) && (tmp[4].matches("^\\d*$"))) {
boolean ok = false;
logger.debug("Checking district codes...");
String[] codes = districtCodes.split(",");
for (int i = 0; i < codes.length; i++) {
if (tmp[4].startsWith(codes[i].trim())) {
ok = true;
logger.debug("District code found.");
break;
}
}
if (ok) {
ps.setString(7, tmp[4]);
logger.debug("fifth column: tmp[4] [" + tmp[4] + "]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else if (tmp[4].length() == 0) {
ps.setString(7, "-");
logger.debug("fifth column: tmp[4] [-]");
} else {
logger.error("The fifth column does not satisfy the format requested. Found [" + tmp[4] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -8;
}
} else {
ps.setString(7, "-");
}
if (tmp.length == 6) {
tmp[5] = tmp[5].trim();
if ((tmp[5].length() > 0) && (isValidEmailAddress(tmp[5]))) {
ps.setString(8, tmp[5]);
} else if (tmp[5].length() == 0) {
ps.setString(8, "-");
} else {
logger.error("The sixth column does not satisfy the format requested. Found [" + tmp[5] + "]");
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
f.delete();
return -9;
}
} else {
ps.setString(8, "-");
}
x = ps.executeUpdate();
if (x <= 0) {
dbl.rollback();
ps.close();
dbl.closeDBConnection();
br.close();
//f.delete();
logger.error("Insert in TB_SDK_CONTENTS failed, stopping execution ");
return -3;
}
}
br.close();
//f.delete();
ps.close();
dbl.commit();
dbl.closeDBConnection();
return 0;
} catch (Exception ex) {
logger.error("An exception occured during the import of file [" + fileName + "] for line [" + line + "]", ex);
dbl.rollback();
if (br != null) {
br.close();
}
if (ps != null) {
ps.close();
}
dbl.closeDBConnection();
//f.delete();
return -1;
}
}
On the other class that handle the DB operation:
public int set(String query) {
Statement statement = null;
int ris = -1;
try {
if (connection == null || !connection.isValid(1)) connect();
logger.debug("Opening statement");
statement = connection.createStatement();
ris = statement.executeUpdate(query);
} catch (SQLException ex) {
logger.error("ERROR in execution of [" + query + "] due to: ", ex);
ris = -1;
} finally {
try {
logger.debug("Closing statement");
if (statement != null) {
statement.close();
}
} catch (SQLException ex1) {
logger.error("ERROR cannot close statement.", ex1);
}
}
return ris;
}
The connection open:
public boolean connect() {
if (dataSource != null) {
try {
connection = dataSource.getConnection();
logger.info("Connection open to DB");
return true;
} catch (SQLException ex) {
logger.error("An error occured during request of connection to datasource, due to...", ex);
return false;
}
}
String url;
if (connectionString.length() > 0) {
url = connectionString;
} else {
url = "jdbc:oracle:thin:#" + host + ":" + port + ":" + sid;
}
try {
// create an OracleDataSource
OracleDataSource ods = new OracleDataSource();
// set connection properties
Properties prop = new Properties();
prop.put("user", user);
prop.put("password", pwd);
ods.setConnectionProperties(prop);
ods.setURL(url);
// get the connection
connection = ods.getConnection();
connection.setAutoCommit(false);
((OracleConnection) connection).setDefaultRowPrefetch(10);
logger.info("Connection open to DB");
return true;
} catch (Exception ex) {
logger.info("An exception occured in execution of [connect]. ");
if (dataSource == null) {
logger.error("[" + url + ", " + user + ", " + pwd + "] ERROR in execution of [connect] due to: ", ex);
}
return false;
}
}
dataSource getConnection():
public static Connection getConnection() throws SQLException {
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
return con;
}
The lookup for the data source is done in the Context Listener at context creation.
Edit:
I'm reading again the oracle tutorials about the usage of pooling connection and other links about it: every example the open and close of the connection to the pool is done in the same method. I thought that was just a need to be more simplest to explain all the steps, but I'm wondering if this is not also a need to satisfy the "transaction" at connection pool level. Can anyone confirm me this? Or give me a documentation link where this is well explained? Thank you very much!

Categories