I have this code which I want to use to verify file processing from database status table:
package com.file.verifier;
import java.io.IOException;
import java.nio.file.*;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
public class Application extends SqlUtils {
private static String folderPath = "D:\\EntityImportEversana";
public static void main(final String[] args) throws IOException, InterruptedException {
System.out.println("Running file verifier");
System.out.println("monitoring folder " + folderPath);
SqlUtils sql = new SqlUtils();
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get(folderPath);
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey key;
while ((key = watchService.take()) != null) {
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event kind:" + event.kind() + ". File affected: " + event.context() + ".");
if(event.kind().equals(StandardWatchEventKinds.ENTRY_DELETE)){
Instant start = Instant.now();
boolean flag = true;
while(flag) {
while ((key = watchService.take()) != null) {
HashMap<String, List> map = sql.checkFileImport();
List values = map.get(event.context()); // get values by file name
if(values.contains("Completed")){
// exit the monitoring while loop
flag = false;
}
}
Thread.sleep(1000);
}
Instant end = Instant.now();
System.out.println(Duration.between(start,end));
long seconds = TimeUnit.MILLISECONDS.toSeconds(Duration.between(start,end).getSeconds());
long minutes = TimeUnit.MILLISECONDS.toMinutes(Duration.between(start,end).getSeconds());
System.out.format("Execution time %d minutes %d seconds", minutes, seconds);
}
}
key.reset();
}
watchService.close();
}
}
SQL requests file:
package com.file.verifier;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;
public class SqlUtils {
String connectionUrl =
"jdbc:sqlserver://......";
protected HashMap<String, List> checkFileImport(){
ResultSet resultSet = null;
HashMap<String, List> map = new HashMap<>();
try (Connection connection = DriverManager.getConnection(connectionUrl);
Statement statement = connection.createStatement();) {
// Create and execute a SELECT SQL statement.
String selectSql = "SELECT * from integration.EntityImportRequests";
resultSet = statement.executeQuery(selectSql);
// Print results from select statement
while (resultSet.next()) {
map.put(resultSet.getString(3), Arrays.asList(resultSet.getString(5),
resultSet.getString(6),
resultSet.getString(7)));
}
}
catch (SQLException e) {
e.printStackTrace();
}
return map;
}
}
I use this code to detect the file import. How I can replace the while loop with something better? When there is a error status I would like to stop the execution and print and print the processing error.
Related
Here, You can see the program which fetch the Leaked Connection count from weblogic. But, I always get it as zero. I have set maximum connection count to 10 from my data source and I run some code which not closes the connection so, Connection Unavailable count is increases to 10 but Liked Connection count is still 0.
So, What to do to increase the count of it because there are liked connections are there by application.
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Hashtable;
import java.util.List;
import java.util.Properties;
import java.util.logging.Logger;
import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class Test {
private static final Logger logger = Logger.getLogger(Test.class.getName());
private static final String PROTOCOL = "admin.server.protocol";
private static final String HOST = "admin.server.host";
private static final String PORT = "admin.server.port";
private static final String USERNAME = "admin.server.username";
private static final String PASSWORD = "admin.server.password";
private static final String JNDI_ROOT = "jndi.root";
private static final String DATA_SOURCE = "DataSourceName";
private static final String DATASOURCE_ORACLEDS_JTA = "dataSource-OracleDS_jta";
private static MBeanServerConnection connection;
private static JMXConnector connector;
public static void main(String[] args) throws InterruptedException {
Test test = new Test();
System.out.println(test.isConnectionLeaked());
}
public List<String> getDataSourceNames(){
return Arrays.asList(DATA_SOURCE,DATASOURCE_ORACLEDS_JTA);
}
/*
* Initialize connection to the Domain Runtime MBean Server.
*/
public static void initConnection() throws IOException,
MalformedURLException {
logger.info("Inside initConnection");
InputStream is = ClassLoader.getSystemResourceAsStream("jmx.properties");
Properties props = new Properties();
props.load(is);
String protocol = (String) props.get(PROTOCOL);
Integer portInteger = Integer.valueOf((String) props.get(PORT));
int port = portInteger.intValue();
String jndiroot = (String) props.get(JNDI_ROOT);
String hostname = (String) props.get(HOST);
JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostname, port, jndiroot);
Hashtable<String, Object> h = new Hashtable<>();
h.put(Context.SECURITY_PRINCIPAL, (String) props.get(USERNAME));
h.put(Context.SECURITY_CREDENTIALS, (String) props.get(PASSWORD));
h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
h.put("jmx.remote.x.request.waiting.timeout", new Long(10000));
connector = JMXConnectorFactory.connect(serviceURL, h);
connection = connector.getMBeanServerConnection();
logger.info("End initConnection");
}
public boolean isConnectionLeaked() {
List<String> dataPoolNames = getDataSourceNames();
boolean isLeaked = false;
try {
initConnection();
ObjectName service = new ObjectName("com.bea:Name=DomainRuntimeService,"
+ "Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
ObjectName[] number_of_servers = (ObjectName[]) connection.getAttribute(service, "ServerRuntimes");
int length = (int) number_of_servers.length;
for (int i = 0; i < length; i++) {
logger.info("Server Instance=" + number_of_servers[i]);
String name = (String) connection.getAttribute(number_of_servers[i], "Name");
ObjectName[] number_of_dbpools = (ObjectName[]) connection.getAttribute(new ObjectName("com.bea:Name="
+ name + ",ServerRuntime=" + name + ",Location=" + name + ",Type=JDBCServiceRuntime"),
"JDBCDataSourceRuntimeMBeans");
int pool_length = (int) number_of_dbpools.length;
for (int x = 0; x < pool_length; x++) {
String poolName = (String) connection.getAttribute(number_of_dbpools[x], "Name");
logger.info("********* PoolName=" + poolName + " ******");
int leakedConnectionCount = (Integer) connection.getAttribute(number_of_dbpools[x],
"LeakedConnectionCount");
logger.info("leakedConnectionCount : " + leakedConnectionCount);
if (leakedConnectionCount > 0) { // Send email alert
isLeaked = true;
}
}
}
} catch (Exception e) {
logger.severe("Exception in isConnectionLeaked method");
logger.severe("Message = " + e.getMessage());
} finally {
try {
if (connector != null) {
logger.info("Connectors JMXConnector.");
connector.close();
}
} catch (IOException e) {
logger.severe(e.getMessage());
}
}
logger.info("End isConnectionLeaked. isLeaked = "+isLeaked);
return isLeaked;
}
}
The Inactive Connection Timeout is set to 0?
I want to upload txt file from java application(software) to restful web-service , Because inside txt file i have list of sql query to execute. So , I want to upload file into web-service first then execute query line by line to database.
I converted txt file into List object then again into string and passed it but could not get success.
Here is Webservice code
package com.java.webservice;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import com.sun.jersey.api.client.WebResource;
#Path("UploadFile")
public class UploadFile {
private List<String> storedQueries = new ArrayList<String>();
private Connection conn = null;
// private PreparedStatement pstm = null;
private Statement pstm = null;
private ResultSet rs = null;
private String q = "";
// #GET here defines, this method will method will process HTTP GET
// requests.
#GET
// #Path here defines method level path. Identifies the URI path that a
// resource class method will serve requests for.
#Path("/getTest")
// #Produces here defines the media type(s) that the methods
// of a resource class can produce.
#Produces(MediaType.APPLICATION_JSON)
// #PathParam injects the value of URI parameter that defined in #Path
// expression, into the method.
public Response getTest(#QueryParam("name") String name) {
// String name = "Lokendra Pun ,Java Engineer";
System.out.println("Your Name IS: " + name);
java.util.StringTokenizer st = new java.util.StringTokenizer(name, ",");
java.util.ArrayList newArrayList = new java.util.ArrayList();
while (st.hasMoreTokens()) {
// the trim() below may not always be desired or necessary
newArrayList.add(st.nextToken().trim());
}
// this if statement only necessary because a String created from
// ArrayList.toString() ends up as "[1, 2, 3, 4]" not, "1, 2, 3, 4"
if (newArrayList.size() == 1) {
// remove [] around item
int length = ((String) newArrayList.get(0)).length();
newArrayList.set(0, ((String) newArrayList.get(0)).substring(1, length - 1));
} else if (newArrayList.size() > 1) {
// remove '[' in first item and ']' in last
int lastIndex = newArrayList.size() - 1;
String oldString = (String) newArrayList.get(0);
String newString = oldString.substring(1, oldString.length());
newArrayList.set(0, newString);
oldString = (String) newArrayList.get(lastIndex);
newString = oldString.substring(0, oldString.length() - 1);
newArrayList.set(newArrayList.size() - 1, newString);
}
System.out.println("newArrayList->" + newArrayList.toString());
System.out.println("==================");
for (int i = 0; i < newArrayList.size(); i++) {
System.out.println("Name" + i + " :" + newArrayList.get(i));
}
System.out.println("==================");
return Response.status(200).entity(name).build();
}
/**
*
*
* method to get file name from remote server and process query into
* database
*
*
*
*/
#GET
#Produces(MediaType.APPLICATION_JSON)
#Path("/getUploadQuery")
public Response getUploadQuery(#QueryParam("file_name") String file_name,
#QueryParam("database_name") String database_name) {
System.out.println("I am inside getTeacher Method");
String list = null;
try {
conn = getConnection(database_name);
if (conn != null) {
try {
for (String line : Files.readAllLines(Paths.get(file_name))) {
storedQueries.add(line);
System.out.println(line);
}
for (int i = 0; i < storedQueries.size(); i++) {
System.out.println("Looping Query Length is: " + storedQueries.size());
System.out.println("Connection Object Inside Loop : " + conn);
pstm = conn.createStatement();
System.out.println("Looping Size now : " + i);
if (!storedQueries.get(i).equals("")) {
System.out.println("Query Before Executed is: " + storedQueries.get(i));
// pstm =
// conn.prepareStatement(storedQueries.get(i));
// pstm.executeUpdate();
pstm.addBatch(storedQueries.get(i));
pstm.executeBatch();
}
}
pstm.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
list = "true";
} else {
list = "false";
}
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(200).entity(list).build();
}
/**
*
* method to connect to remote server database according to db and school
* name
*
* #param database_name
* #return
*/
public Connection getConnection(String database_name) {
System.out.println("Database Name before Connection: " + database_name);
try {
Class.forName("com.mysql.jdbc.Driver");
// Setup the connection with the DB
conn = DriverManager.getConnection(
"jdbc:mysql://localhost/" + database_name + "?" + "user=root&password=java#android2016");
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
}
And here is code for service calling from java application
package WSserviceCall;
import javax.ws.rs.core.MediaType;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
public class TestMain {
public static final String BASE_URI = "http://localhost:8080/MovieGalaxyService";
public static final String PATH_TEST = "/UploadFile/getTest";
public static final String PATH_LOAD_FILE = "/UploadFile/getUploadQuery";
public static final String PATH_AGE = "/UploadFile/age/";
public static void main(String[] args) {
try {
// TODO Auto-generated method stub
List<String> storedQueries = new ArrayList<String>();
String currentDirectory = System.getProperty("user.dir");
String file_name = currentDirectory + "/databaseBackupScript.txt";
String name = "Lokendra Pun Param";
String age ="26";
try{
for (String line : Files.readAllLines(Paths.get(file_name))) {
storedQueries.add(line);
System.out.println(line);
}
}catch(Exception e){
e.printStackTrace();
}
// String names = ""+aa;
//System.out.println("Array Objec is: "+aa);
//System.out.println("String Objects is: "+aa.toString());
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource resource = client.resource(BASE_URI);
String param = storedQueries.toString();
String temp_uri = URLEncoder.encode(param, "UTF-8");
WebResource testResource = resource.path(PATH_TEST).
queryParam("name",temp_uri);
//WebResource testResource = resource.path(PATH_TEST);
// System.out.println("Client Response \n"
// + getClientResponse(testResource));
// System.out.println("Response \n" + getResponse(testResource) + "\n\n");
String testValue = getResponse(testResource);
System.out.println("Test Resource Value is : "+testValue);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(TestMain.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Returns client response.
* e.g :
* GET http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
* returned a response status of 200 OK
*
* #param service
* #return
*/
private static String getClientResponse(WebResource resource) {
return resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class).toString();
}
/**
* Returns the response as JSON data
* e.g : status : true or false
*
* #param service
* #return
*/
private static String getResponse(WebResource resource) {
return resource.accept(MediaType.APPLICATION_JSON).get(String.class);
}
}
In my application I am taking data from file and transferring to database. I have 400 000 records. First it transfers data fast up to 10 000 records after that it updating very slowly. Hw to increase the performance of transferring data to db?
is there any problem with gc?
This is my code:
package com.fileupload;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.swing.text.ZoneView;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.InputStream;
import java.util.Iterator;
import org.apache.poi.xssf.eventusermodel.XSSFReader;
import org.apache.poi.xssf.model.SharedStringsTable;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
public class SendDataToDb extends HttpServlet{
PreparedStatement ps = null;
HttpSession hs;
Connection con1;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
hs = request.getSession(false);
try {
Class.forName("com.mysql.jdbc.Driver");
con1 = DriverManager.getConnection("jdbc:mysql://localhost:3306/xlsx","root","Inf123#");
ps = con1.prepareStatement("INSERT INTO userdetails(ID, NAME, AGE, GENDER,ADDRESS, ZONEID, LOCATION) VALUES(?, ?, ?, ?, ?, ?, ?)");
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
try {
processOneSheet("C:/Users/Penchalaiah/Desktop/New folder/"+hs.getAttribute("filename1"));
System.out.println("clossing the connnection");
ps.close();
con1.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void processOneSheet(String filename) throws Exception {
OPCPackage pkg = OPCPackage.open(filename);
XSSFReader r = new XSSFReader( pkg );
SharedStringsTable sst = r.getSharedStringsTable();
XMLReader parser = fetchSheetParser(sst);
// To look up the Sheet Name / Sheet Order / rID,
// you need to process the core Workbook stream.
// Normally it's of the form rId# or rSheet#
InputStream sheet2 = r.getSheet("rId2");
InputSource sheetSource = new InputSource(sheet2);
parser.parse(sheetSource);
sheet2.close();
}
public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
ContentHandler handler = new SheetHandler(sst);
parser.setContentHandler(handler);
return parser;
}
/**
* See org.xml.sax.helpers.DefaultHandler javadocs
*/
private class SheetHandler extends DefaultHandler {
private SharedStringsTable sst;
private String lastContents;
private boolean nextIsString;
String id;
String names;
String age;
String gender;
String address;
int i = 1;
private SheetHandler(SharedStringsTable sst) {
this.sst = sst;
}
public void startElement(String uri, String localName, String name,
Attributes attributes) throws SAXException {
// c => cell
if(name.equals("c")) {
// Print the cell reference
// Figure out if the value is an index in the SST
String cellType = attributes.getValue("t");
if(cellType != null && cellType.equals("s")) {
nextIsString = true;
} else {
nextIsString = false;
}
}
// Clear contents cache
lastContents = "";
//System.out.println("===>"+lastContents+"<====");
}
public void endElement(String uri, String localName, String name)
throws SAXException {
// Process the last contents as required.
// Do now, as characters() may be called more than once
if(nextIsString) {
int idx = Integer.parseInt(lastContents);
lastContents = new XSSFRichTextString(sst.getEntryAt(idx)).toString();
nextIsString = false;
}
// v => contents of a cell
// Output after we've seen the string contents
if(name.equals("v")) {
System.out.print(lastContents+"\t");
if(i == 1){
id = lastContents;
System.out.print(lastContents+"("+i+")");
}
if(i == 2){
names = lastContents;
System.out.print(lastContents+"("+i+")");
}
if(i == 3){
age = lastContents;
System.out.print(lastContents+"("+i+")");
}
if(i == 4){
gender = lastContents;
System.out.print(lastContents+"("+i+")");
}
if(i == 5){
address = lastContents;
System.out.print(lastContents+"("+i+")");
insertInToDb(id, names, age, gender, address);
i = 0;
}
i++;
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
lastContents += new String(ch, start, length);
}
}
public void insertInToDb(String id,String names,String age, String gender,String address){
try {
ps.setString(1, id);
ps.setString(2, names);
ps.setString(3, age);
ps.setString(4, gender);
ps.setString(5, address);
ps.setString(6, (String)hs.getAttribute("zoneId1"));
ps.setString(7, (String)hs.getAttribute("location1"));
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Executing one batch operation for multiple records is much faster than executing each insert query for multiple records.
You can create a batch of 10000 or whatever you want and then execute the batch.
Connection con = null;
PreparedStatement pstm = null;
try {
Class.forName("driver class");
con = DriverManager.
getConnection("connectionUrlString","password");
con.setAutoCommit(false);
pstm = con.prepareStatement("your insert command );
pstm .setInt(1, 3000); //set all parameters
pst.addBatch();
int count[] = pst.executeBatch();
for(int i=1;i<=count.length;i++){
System.out.println("Query "+i+" has effected "+count[i]+" records");
}
con.commit();
pst.close();
con.close();
Im trying to make a little server for my homework.This is very simple project yet i cant insert some variables (which i took from the client ,in an object form ,through serialization ) into the database .
It shows no errors! That's what i find strange and also the client receive the response without problems.
my Server class is as the following :
package server;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import org.ietf.jgss.Oid;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class Server {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3333), 0);
server.createContext("/", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
ObjectInputStream ios = new ObjectInputStream(t.getRequestBody());
final String url = "jdbc:mysql://localhost/httpServer";
final String user = "root";
final String password = "";
try {
Send oin = (Send) ios.readObject();
String response = "Kjo eshte nje pergjigje nga serveri! \n"
+ "Clienti me id "
+ oin.getId()
+ " dhe me emer "
+ oin.getName()
+ " ka pasur "
+ oin.getAmount()
+ "$ ne llogarine e tij ,por me pas ka terhequr "
+ oin.getPaid()
+ "$ nga llogaria \n"
+ "Kjo terheqe eshte ruajtur ne database dhe tani gjendja e re eshte "
+ (oin.getAmount() - oin.getPaid()) + "$ \n";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
int id = oin.getId();
String emri = oin.getName();
int amount = oin.getAmount();
int paid = oin.getPaid();
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, user,
password);
try {
Statement s = con.createStatement();
s.executeUpdate("INSERT INTO person VALUES ('" + id
+ "','" + emri + "','" + amount + "','" + paid
+ "')");
} catch (SQLException s) {
System.out
.println("Tabel or column or data type is not found!");
}
} catch (Exception e) {
e.printStackTrace();
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
can you please help me ?
Or have any idea what the problem may is ?
Edit:
Maybe i am doing something wrong in the Client:
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
class Send implements Serializable {
// duhet te implementoje interfacin serizable ne menyre qe tja dergoj
// serverit
private static final long serialVersionUID = 1L;
public int getId() {
return id;
}
public int getAmount() {
return amount;
}
public int getPaid() {
return paid;
}
int id = 1;
int amount = 2000;
int paid = 800;
String name = "Andi Domi";
public String getName() {
return name;
}
}
public class Client {
public static void main(String[] args) throws Exception {
try {
URL url = new URL("http://localhost:3333");
HttpURLConnection s = (HttpURLConnection) url.openConnection();
s.setDoOutput(true);
s.setDoInput(true);
s.setRequestMethod("POST");
s.setUseCaches(false);
Send obj = new Send();
ObjectOutputStream objOut = new ObjectOutputStream(
s.getOutputStream());
objOut.writeObject(obj);
InputStream in = s.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
BufferedReader br = new BufferedReader(isr);
int c;
while ((c = br.read()) != -1) {
System.out.print((char) c);
}
objOut.close();
s.disconnect();
} catch (IOException ex) {
System.err.println(ex);
System.err.print("gabimi eshte ketu");
}
}
}
After your executeUpdate statement you need to do.
con.commit();
to save the transaction.
EDIT: Based on the chat discussion, we learned that the column named emri is actually Emri in the table and was throwing:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'emri' in 'field list'
Changing the name resolves the issue.
Now unrelated to your problem, you should be using a PreparedStatement instead and should be closing your connection and statement
try {
PreparedStatement s = con.prepareStatement("INSERT INTO person(id, emri, amount, paid) VALUES (?,?,?,?)");
s.setInt(1,id);
s.setString(2,emri);
s.setInt(3,amount);
s.setInt(4,paid);
int count = s.executeUpdate();
con.commit();
} catch(Exception e){
e.printStackTrace();
//something bad happened rollback
//any uncommitted changes
con.rollback();
} finally {
if (con != null) {
con.close();
}
}
first, use prepared statement[docs] to avoid from SQL INJECTION
String sql = "INSERT INTO person VALUES (?,?,?,?)";
PreparedStatement prest = con.prepareStatement(sql);
prest.setString(1,id);
prest.setString(2,emri); // or use setInt for integer
prest.setString(3,amount); // or use setInt for integer
prest.setString(4,paid);
prest.executeUpdate()
second, if the the number of values does not match the total number of columns in your table, it will also fail because you are using the implicit type of INSERT statement. To solve it, just supply the column names where you want the values should be stored, eg
String sql = "INSERT INTO person (col1, col2, col3, col4) VALUES (?,?,?,?)";
I've tried several spots to insert the finally block but no matter what I try it ends up making the code worse.
Here is my code, the 4th to last ending curly bracket is the one giving me the error. Any thoughts?
package com.tunestore.action;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.owasp.validator.html.*;
import org.owasp.esapi.*;
public class DownloadAction extends Action
{
private static final Log log = LogFactory.getLog(DownloadAction.class);
public static String DB_URL;
static
{
if (System.getProperty("tunestore.db.location") != null)
{
DB_URL = "jdbc:derby://localhost:1527/" + System.getProperty("tunestore.db.location");
}
else
{
DB_URL = "jdbc:derby://localhost:1527/" + System.getProperty("user.home") + "/.tunestore";
}
System.setProperty("jdbc.tunestore.url", DB_URL);
}
public static Connection getConnection() throws Exception
{
log.info("Opening database at " + DB_URL);
Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
Connection conn = DriverManager.getConnection(DB_URL);
return conn;
}
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)
throws Exception
{
DynaActionForm daf = (DynaActionForm)form;
String user = (String)request.getSession(true).getAttribute("USERNAME");
if(user != null)
{
Connection conn = null;
try
{
conn = DownloadAction.getConnection();
String sql2 = "SELECT ID FROM CD WHERE CD.BITS = ?";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(1, request.getParameter("cd"));
ResultSet rs2 = stmt2.executeQuery();
rs2.next();
String sql = "SELECT COUNT(*) "
+ "FROM TUNEUSER_CD "
+ "WHERE TUNEUSER_CD.TUNEUSER = ? AND TUNEUSER_CD.CD = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, user);
stmt.setInt(2, rs2.getInt(1));
ResultSet rs = stmt.executeQuery();
rs.next();
int owned = rs.getInt(1);
if(owned == 1)
{
try
{
// Try to open the stream first - if there's a goof, it'll be here
InputStream is = this.getServlet().getServletContext().getResourceAsStream("/WEB-INF/bits/" + request.getParameter("cd"));
if (is != null)
{
response.setContentType("audio/mpeg");
response.setHeader("Content-disposition", "attachment; filename=" + daf.getString("cd"));
byte[] buff = new byte[4096];
int bread = 0;
while ((bread = is.read(buff)) >= 0)
{
response.getOutputStream().write(buff, 0, bread);
}
}
else
{
ActionMessages errors = getErrors(request);
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("download.error"));
saveErrors(request, errors);
return mapping.findForward("error");
}
}
catch (Exception e)
{
e.printStackTrace();
ActionMessages errors = getErrors(request);
errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("download.error"));
saveErrors(request, errors);
return mapping.findForward("error");
}
return null;
}
}
}
}
}
That bracket is the location where your outer try block ends. It has no catch block and no finally block, so you get an error. Just add one or the other immediately after the bracket, or remove the try if it's not needed.
You only have one catch block, but two trys. Add a catch block for the first try-catch and you should have your issue solved.
Edit: Why are you nesting try-catch in the first place? I don't believe there is any need to do so.