Java Servlet store users info into Java DB - java

I have write a java servlet to insert and display users info from database. I am inserting a photo to all users. The problem is when I want to display the byte array for the photos it displays just the first bytes e.g.: [B#43809cd3
private void doAddUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
InputStream inputStream = null;
Part filePart = request.getPart("image");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
String message = null;
try {
// Register JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:derby://127.0.0.1:1527/tutoriumDB", "db", "db");
// Execute SQL query
PreparedStatement st= conn.prepareStatement("insert into users(ID,NAME,LAT,LONG,IMAGE) values(?,?,?,?,?)");
st.setString(1, request.getParameter("id1"));
st.setString(2, request.getParameter("name"));
st.setString(3, request.getParameter("lat"));
st.setString(4, request.getParameter("long"));
if (inputStream != null) {
//st.setBlob(5, inputStream);
st.setBinaryStream(5, inputStream, (int)filePart.getSize());
}
int row = st.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
st.close();
conn.close();
try (PrintWriter out = response.getWriter()) {
out.println("Der Benutzer mit der ID: " +request.getParameter("id1")+" und Name: " +
request.getParameter("name")+" wurde eingefuegt");
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(TutServlet.class.getName()).log(Level.SEVERE, null, ex);
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/submit.jsp").forward(
request, response);
}
private void getAllUsers(HttpServletRequest request, HttpServletResponse response) throws IOException
{
try {
// Register JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:derby://127.0.0.1:1527/tutoriumDB", "db", "db");
// Execute SQL query
String sql = "SELECT * FROM users order by ID";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
byte[] imgData = null ;
ArrayList<String> users = new ArrayList<String>();
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double lat = rs.getDouble("lat");
double longit = rs.getDouble("long");
byte[] bytes = rs.getBytes("image");
users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +bytes);
}
stmt.close();
conn.close();
try (PrintWriter out = response.getWriter()) {
for (String s : users)
{
out.println(s);
}
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(TutServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
Result of getAllUser

Ok let me check i analize your code and saw the image, the image is correct because you are using
users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +bytes);
as you can see the var called bytes is this:
byte[] bytes = rs.getBytes("image");
why is it getting [B#43809cd3 ? because the method toString is not overriding in byte.
What could you do? if your byte is not null then iterate it and make your own like this:
byte[] bytes = new byte[2];
bytes[0] = 1;
bytes[1] = 127;
System.out.println(bytes);
StringBuilder byteAppender = new StringBuilder("");
if(null != bytes){
for(byte b: bytes){
byteAppender.append(b);
}
System.out.println("Ok bites are " +byteAppender);
}
So now you will put byteAppender instead of bytes so this will be:
users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +byteAppender );
So your coude could be like this:
private void getAllUsers(HttpServletRequest request, HttpServletResponse response) throws IOException
{
try {
// Register JDBC driver
Class.forName("org.apache.derby.jdbc.ClientDriver");
// Open a connection
Connection conn = DriverManager.getConnection("jdbc:derby://127.0.0.1:1527/tutoriumDB", "db", "db");
// Execute SQL query
String sql = "SELECT * FROM users order by ID";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
byte[] imgData = null ;
ArrayList<String> users = new ArrayList<String>();
StringBuilder byteAppender = new StringBuilder(""); //here is the String you will make
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
double lat = rs.getDouble("lat");
double longit = rs.getDouble("long");
byte[] bytes = rs.getBytes("image");
if(null != bytes){ //you ask the object is not null
for(byte b: bytes){ //you itarete it
byteAppender.append(b); //you add it
}
}
users.add(id + ", " + name+ ", " +lat+ ", " +longit+ ", " +byteAppender); //you put it
byteAppender.setLength(0); //you restart it
}
stmt.close();
conn.close();
try (PrintWriter out = response.getWriter()) {
for (String s : users)
{
out.println(s);
}
}
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(TutServlet.class.getName()).log(Level.SEVERE, null, ex);
}
}
Also you could read this: how to convert byte array to string and vice versa
Hope it help you.
Cya

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

ArrayIndexOutOfBounds: 0 when trying to add an image as a BLOB to an sqlite database in java

I am trying to insert an image as a blob to my sqlite database but I just can't get it to work as I am catching the error java.lang.ArrayIndexOutOfBoundsException: 0
I tried to do it with one try catch statement but again i couldn't figure it out. The url used to create the connection to the database is correct since I have been using the same url throught the other methods and were working fine. Any help would be greatly appreciated.
This is my code:
public Boolean insertIntoProducts(String name, String description, String filePath, Double price, int quantity) {
String url = "jdbc:sqlite:C:/Users/User/Desktop/MyDatabase.db";
Boolean success = false;
String sqlSelectID = "SELECT ID FROM Products ORDER BY ID DESC";
// Establishing a connection to the database
try {
// Initialising the image file
File image = new File(filePath);
FileInputStream fileInput = new FileInputStream(image);
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int i; (i = fileInput.read(buf)) != -1;) {
// read all the bytes and store them in the array. Stores the binary data of the
// image
byteArray.write(buf, 0, i);
// Closing the file input to prevent memory leaks
fileInput.close();
try (Connection conn = DriverManager.getConnection(url)){
Statement statement = conn.();
ResultSet result = statement.executeQuery(sqlSelectID);
int id = 0;
if (result.next()) {
id = result.getInt("ID");
}
String sql = "INSERT INTO Products(ID,Name,Description,Quantity,Price,Image,isAuthorised) "
+ "VALUES (" + id + ",'" + name + "','" + description + "'," + quantity + ",'" + price
+ "','?','0');";
PreparedStatement pstatement = conn.prepareStatement(sql);
pstatement.setBytes(1, byteArray.toByteArray());
// Creating a variable to check if the insertion was successful depending if a
// row was added to the table
int row = 0;
row = pstatement.executeUpdate();
if (row > 0) {
success = true;
}
} catch (SQLException e) {
System.out.println(e);
}
}
} catch (Exception e) {
System.out.println(e);
}
return success;
}
The error is in the line pstatement.setBytes(1, byteArray.toByteArray());
I have checked the length of the array and it has a correct length but I don't know what it is trying to access in order for this error to be created

How to update data in table?

I finished making an encryption program that encrypts text and tried to apply this program to encrypt a field in a database table. I have a problem that all the data field is encrypted by on value (last record)
public static void main(String[] args) throws IOException {
String v_url = "jdbc:oracle:thin:#192.168.2.154:1522:orcl2";
String v_username = "scott";
String v_password = "tiger";
Connection con = null;
try {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con = DriverManager.getConnection(v_url, v_username, v_password);
System.out
.println("Connection to Oracle database was Established");
String sql = "select JOB_NAME from job ";
Statement stmt = con.createStatement();
ResultSet srs = stmt.executeQuery(sql);
while (srs.next()) {
vname = srs.getString("job_name");
}
} catch (SQLException err) {
System.out.println(err.getMessage());
}
Scanner in = new Scanner(System.in);
System.out.println("Enter Your KeyText ");
String StrKey = in.nextLine();
// Print the Concatenated Data.
String ConcatenatedData = StrKey.concat(vname);
System.out.println("The plaintext Data is : " + ConcatenatedData);
// Convering the Concatenated data to Ascii data.
byte[] asciiText = null;
try {
// translating text String to 7 bit ASCII encoding
asciiText = ConcatenatedData.getBytes("US-ASCII");
// System.out.println(Arrays.toString(asciiText));
} catch (java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}
String binary = "";
for (byte b : asciiText) {
// binary = Integer.toBinaryString(b & 255 | 256).substring(1);
binary += Integer.toBinaryString(0x100 + (int) (b & 0xFF)).substring(1);
}
// System.out.println("Requested binary :" +binary);
String ReversedBinary = binary.replace('0', '2').replace('1', '0').replace('2', '1');
// System.out.println("Reveresd binary :" + ReversedBinary);
mainencdec decimalToBinary = new mainencdec();
String binary1 = decimalToBinary.convertBinaryStringToString(ReversedBinary);
try {
String sql_statment = "UPDATE job SET job_name =?";
PreparedStatement updatequery = con.prepareStatement(sql_statment);
updatequery.setString(1, binary1);
updatequery.executeQuery();
con.commit();
System.out.println("An existing user was updated successfully!");
} catch (SQLException err) {
System.out.println(err.getMessage());
}
}
the problem is that the data in job name field is encrypted by the same value as: JOB_NAME
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
323130,2'2$1'2&0&2#1
I want each value in this field encrypted according to its data

java.sql.SQLException: No suitable driver found for jdbc:oracle:thin

I currently have a web app that has certain classes able to connect to my database, but one other class cant.For whatever reason, I have started to get this exception for one of my classes. Here is what I have done:
I am working with Java 7 and have ojdbc7 in both my class path and lib folder
I have multiple classes who can connect to the url file, yet my other class cant and throws "java.sql.SQLException: No suitable driver found for jdbc:oracle:thin:#someurl"
My class is able to access the database AFTER I have connected to it in another class
I have a config.properties file that contains the URL, so I know the URL is not at fault and never changes
Here is my code where the program fails. I don't connect to the database until I call this method too:
public SimpleEntry<String, String> loadOrders(File file) {
SimpleEntry<String, String> response = new SimpleEntry<String, String>(
"", "");
PreparedStatement st = null;
ResultSet rs = null;
Connection con = null;
try {
Scanner scan = new Scanner(file);
String header = "";
String trailer = "";
int orderCtr = 0;
int valueCtr = 0;
String request = "";
ArrayList<HashMap<String, String>> orders =
new ArrayList<HashMap<String, String>>();
log.info("Scanning content");
// start to scan content
while (scan.hasNextLine()) {
String line = scan.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter("\t");
String type = sc.next();
// differentiates between header, trailer, and content
if (type.equals("H")) {
header = line;
} else if (type.equals("T")) {
trailer = line;
break;
} else {
// begin to enter in data appropriately from method's
// parameter
// key of map = column, value = data being inserted
HashMap<String, String> order = new HashMap<String, String>();
// Format:
/*
* CLIENT_CUSTOMER_ID, FIRST_NAME, LAST_NAME,___, ADDRESS1,
* ADDRESS2, CITY, STATE, POSTAL_CODE, PHONE, EMAIL_ADDRESS,
* STORE_NUMBER, DELIVERY_METHOD,___, REWARD_VALUE,___,___,
* CARD_ACTIVE_DATE, CARD_EXPIRED_DATE, REQUEST
*/
order.put("CLIENT_CUSTOMER_ID", sc.next());
String name = sc.next();
order.put("FIRST_NAME", name.substring(0, 1).toUpperCase()
+ name.substring(1).toLowerCase());
name = sc.next();
order.put("LAST_NAME", name.substring(0, 1).toUpperCase()
+ name.substring(1).toLowerCase());
sc.next();
order.put("ADDRESS1", sc.next());
order.put("ADDRESS2", sc.next());
order.put("CITY", sc.next());
order.put("STATE", sc.next());
order.put("POSTAL_CODE", sc.next());
order.put("PHONE", sc.next());
order.put("EMAIL_ADDRESS", sc.next());
order.put("STORE_NUMBER", sc.next());
order.put("DELIVERY_METHOD", sc.next());
sc.next();
// purpose of valueCtr -> count reward values for a total
String oVal = sc.next();
valueCtr += Integer.parseInt(oVal);
order.put("REWARD_VALUE", oVal);
sc.next();
sc.next();
order.put("CARD_ACTIVE_DATE", sc.next());
order.put("CARD_EXPIRED_DATE", sc.next());
// used later in program
request = sc.next();
order.put("REQUEST", request);
orders.add(order);
// count number of orders
orderCtr++;
}
sc.close();
}
scan.close();
log.info("Scanning complete");
// finds if the trailer contains the correct value and order amount
boolean ok = true;
if (!trailer.contains(Integer.toString(valueCtr))) {
ok = false;
}
if (!trailer.contains(Integer.toString(orderCtr))) {
ok = false;
}
// if the trailer doesnt, throw error
if (!ok) {
log.error("Error in loadOrders: Order Count
and/or total value of file \n does not match trailer amounts");
response = new SimpleEntry<String, String>("ERROR",
"Order Count and/or total value of file \n does
not match trailer amounts");
return response;
}
String className = "oracle.jdbc.driver.OracleDriver";
Class.forName(className);
con = DriverManager.getConnection(Env.getCardUrl(),
Env.getCardUser(), Env.getCardPass());
log.info("Starting insertion statement");
String query = "SELECT MAX(BATCH_ID) + 1 FROM INTEGRATION.OL_ORDER";
st = con.prepareStatement(query);
rs = st.executeQuery();
rs.next();
int batch = rs.getInt(1);
String insert = "INSERT INTO INTEGRATION.OL_ORDER ("
+ "BATCH_ID, "
+ "CLIENT_CUSTOMER_ID, "
+ "FIRST_NAME, "
+ "LAST_NAME, "
+ "ADDRESS1, "
+ "ADDRESS2, "
+ "CITY, "
+ "STATE, "
+ "POSTAL_CODE, "
+ "PHONE, "
+ "EMAIL_ADDRESS, "
+ "STORE_NUMBER, "
+ "DELIVERY_METHOD, "
+ "REWARD_VALUE, "
+ "CARD_ACTIVE_DATE, "
+ "CARD_EXPIRED_DATE, "
+ "REQUEST,"
+ "PASSPHRASE, "
+ "ITEM_CODE, "
+ "CONFIRMED_MAILADDR, "
+ "JET_CLIENT_ID) VALUES(?, ?, ?, ?, ?, ?, ?,
?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
st = con.prepareStatement(insert);
log.info("Insertion complete, reorganizing data");
// add batch
for (HashMap<String, String> o : orders) {
st.setInt(1, batch);
// first, last, address1, address2, city, state, postal, phone,
// storenum, delivery
// validation and formatting
ArrayList<String> content = validateContent(
o.get("FIRST_NAME"), o.get("LAST_NAME"),
o.get("ADDRESS1"), o.get("ADDRESS2"), o.get("CITY"),
o.get("STATE"), o.get("POSTAL_CODE"), o.get("PHONE"),
o.get("STORE_NUMBER"), o.get("DELIVERY_METHOD"));
st.setString(2, o.get("CLIENT_CUSTOMER_ID"));
st.setString(3, content.get(0));
st.setString(4, content.get(1));
st.setString(5, content.get(2));
st.setString(6, content.get(3));
st.setString(7, content.get(4));
st.setString(8, content.get(5));
st.setString(9, content.get(6));
st.setString(10, content.get(7));
st.setString(11, o.get("EMAIL_ADDRESS"));
st.setString(12, content.get(8));
st.setString(13, content.get(9));
st.setInt(14, Integer.parseInt(o.get("REWARD_VALUE")));
st.setDate(15, stringToDate(o.get("CARD_ACTIVE_DATE")));
st.setDate(16, stringToDate(o.get("CARD_EXPIRED_DATE")));
st.setString(17, o.get("REQUEST"));
st.setString(18, getRandom());
st.setString(19, "17331-000002");
st.setString(20, "0");
st.setInt(21, 97);
st.addBatch();
}
st.executeBatch();
log.info("Reorganization complete");
response = new SimpleEntry<String, String>(Integer.toString(batch),
request);
} catch (Exception e) {
StringWriter errors = new StringWriter();
e.printStackTrace(new PrintWriter(errors));
String temp = errors.toString();
log.fatal("Error inside loadOrders(): " + temp);
return null;
} finally {
Dir.close(rs, st, con);
}
return response;
}
My code for Dir.close:
public static void close(ResultSet rs, Statement ps, Connection conn) {
Logger logger =LogManager.getLogger("AE");
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
logger.error("The result set cannot be closed.", e);
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
logger.error("The statement cannot be closed.", e);
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
logger.error("The data source connection cannot be closed.", e);
}
}
}
As mentioned in my last comment, the JAR was on the webapp's class which meant the error couldn't be caused by a lack of drivers. Apparently when deploying my WAR file, tomcat was referencing an older WAR file or something with code that was not updated with the code I had posted above. After exporting my WAR file and renaming to an arbitrary name followed by deploying it under that name, I was not getting the error anymore. Something else to think about is the my messiness of code in the previous war file; I wasn't closing PreparedStatement, Result, and even the Connection variables correctly. Updating the war with a different name with the code posted above worked.

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.

Categories