java - Jar file can't be executed on another pc - java

I have an executable jar file I compiled from my program and I ran it on my PC. It works perfectly fine when I ran it in my command prompt using java -jar [nameofjar.jar]
However, I tried testing it on another pc. Using command prompt to run the same jar file, it throws an error:
D:\QA06122018_2>java -jar Indexing.jar
java.lang.NullPointerException
at IndexDriver.processText(IndexDriver.java:81)
at IndexDriver.index(IndexDriver.java:140)
at Main.main(Main.java:44).....
Both PC are using the same operating system and settings.
I even looked at the code regarding the error and there doesn't seem to be any problem with it. Ran fine on my IDE.
Is there anything I might overlooked?
EDIT:
The code :
public PreparedStatement preparedStatement = null;
MysqlAccessIndex con = new MysqlAccessIndex();
public Connection con1 = con.connect();
String path1;
public void index() throws Exception {
// Connection con1 = con.connect();
try {
Statement statement = con1.createStatement();
ResultSet rs = statement.executeQuery("select * from filequeue where Status='Active' LIMIT 5");
while (rs.next()) {
// get the filepath of the PDF document
path1 = rs.getString(2);
int getNum = rs.getInt(1);
Statement test = con1.createStatement();
test.executeUpdate("update filequeue SET STATUS ='Processing' where UniqueID="+getNum);
try {
// call the index function
PDDocument document = PDDocument.load(new File(path1),MemoryUsageSetting.setupTempFileOnly());
if (!document.isEncrypted()) {
PDFTextStripper tStripper = new PDFTextStripper();
for(int p=1; p<=document.getNumberOfPages();++p) {
tStripper.setStartPage(p);
tStripper.setEndPage(p);
try {
String pdfFileInText = tStripper.getText(document);
processText(pdfFileInText);
System.out.println("Page "+p+" done");
}catch (Exception e){
e.printStackTrace();
Statement statement1 = con1.createStatement();
statement1.executeUpdate("update filequeue SET Error ='E0003' where UniqueID="+getNum);
statement1.executeUpdate("update filequeue SET Status ='Error' where UniqueID="+getNum);
con1.commit();
con1.close();
}
}
}
// After completing the process, update status: Complete
Statement pre= con1.createStatement();
pre.executeUpdate("update filequeue SET STATUS ='Complete' where UniqueID="+getNum);
// con1.commit();
preparedStatement.close();
document.close();
System.out.println("Successfully commited changes to the database!");
con1.commit();
// con1.close();
// updateComplete_DB(getNum);
} catch (Exception e) {
try {
System.err.println(e);
Statement statement1 = con1.createStatement();
statement1.executeUpdate("update filequeue SET STATUS ='Error' where UniqueID="+getNum);
statement1.executeUpdate("update filequeue SET Error ='E0002' where UniqueID="+getNum);
con1.commit();
// add rollback function
rollbackEntries();
}catch (Exception e1){
System.out.println("Could not rollback updates :" + e1.getMessage());
}
}
// con1.close();
}
}catch(Exception e){
e.printStackTrace();
//System.out.println("lalala");
}
//con1.commit();
con1.close();
}
Calling the method:
public void processText(String text) throws SQLException {
String lines[] = text.split("\\r?\\n");
for (String line : lines) {
String[] words = line.split(" ");
String sql="insert IGNORE into test.indextable values (?,?);";
preparedStatement = con1.prepareStatement(sql);
int i=0;
for (String word : words) {
// check if one or more special characters at end of string then remove OR
// check special characters in beginning of the string then remove
// insert every word directly to table db
word=word.replaceAll("([\\W]+$)|(^[\\W]+)", "");
preparedStatement.setString(1, path1);
preparedStatement.setString(2, word);
preparedStatement.executeUpdate();
}
}
preparedStatement.close();
}

The root cause is that there were no lines to process.
You appear to only create prepared statements inside the for (String line : lines) { loop. But you only close the last statement you created (outside that loop).
When you don't have any lines, preparedStatement is null, because you never created one.
Even when you have lines to process, you are creating lots of prepared statements but only closing the last one.
You should probably create one prepared statement at the start of the method and reuse it for the whole method, closing it at the end.

Related

Append row in Sql without replacing previous row java

So i have database with value like this...
i'm trying to append the value by using insert into without replacing it,the data from this txt file...
but when i reload/refresh the database there is no new data being appended into the database...,
here is my code....
public static void importDatabase(String fileData){
try{
File database = new File(fileData);
FileReader fileInput = new FileReader(database);
BufferedReader in = new BufferedReader(fileInput);
String line = in.readLine();
line = in.readLine();
String[] data;
while (line != null){
data = line.split(",");
int ID = Integer.parseInt(data[0]);
String Nama = data[1];
int Gaji = Integer.parseInt(data[2]);
int Absensi = Integer.parseInt(data[3]);
int cuti = Integer.parseInt(data[4]);
String Status = data[5];
String query = "insert into list_karyawan values(?,?,?,?,?,?)";
ps = getConn().prepareStatement(query);
ps.setInt(1,ID);
ps.setString(2,Nama);
ps.setInt(3,Gaji);
ps.setInt(4,Absensi);
ps.setInt(5,cuti);
ps.setString(6,Status);
line = in.readLine();
}
ps.executeUpdate();
ps.close();
con.close();
System.out.println("Database Updated");
in.close();
}catch (Exception e){
System.out.println(e);
}
}
When i run it, it shows no error but the data never get into database, where did i go wrong?.,...
Auto-commit mode is enabled by default.
The JDBC driver throws a SQLException when a commit or rollback operation is performed on a connection that has auto-commit set to true.
Symptoms of the problem can be unexpected application behavior
update the JVM configuration for the ActiveMatrix BPM node to use the following Oracle connection property:
autoCommitSpecCompliant=false Try once
Note:I am not able to put as comment so i posted as a answer

opencsv creating empty csv

I need to convert result set into csv for any database (not just postgres)
Empty csv file is being created when I use opencsv.
Here's the code of doGet method in the servlet:
final String JDBC_DRIVER = "org.postgresql.Driver";
final String DB_URL = "jdbc:postgresql://localhost:5432/postgres";
// Database credentials
final String USER = "postgres";
final String PASS = "12345";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
PreparedStatement ps = null;
Connection conn = null;
try {
// Register JDBC driver
Class.forName("org.postgresql.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
//stmt = conn.createStatement();
String sql = "SELECT * FROM users";
ps = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
/*if(rs.next()){
System.out.println("Name = "+rs.getString("first_name"));
}*/ //prints name so rs is not empty
//rs.first();
CSVWriter writer = new CSVWriter(new FileWriter("Test.csv"));
//even tried with seperator '\t' or ','
writer.writeAll(rs, true);
writer.close();
out.println("</body></html>");
// Clean-up environment
rs.close();
ps.close();
conn.close();
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (ps != null)
ps.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
} //end try
Not sure what's the error. Tried different way but csv is always empty.
Even tried writer.flush(), rs.beforeFirst(), rs.first() nothing works.
Is your problem that you do not see data in the html - if that is the case then instead of creating a new FileWriter in the CSVWriter just pass in you out variable.
Or is it that you checked the Test.csv and file and nothing is there? if so then first check to see if there is actually data in the result set by adding the following after executeQuery:
rs.last();
long numberOfRecords = rs.getRow();
rs.beforeFirst();
System.out.println("Number of Users in table is: " + numberOfRecords);

Unexpected memory using when using Postgres jdbc driver

I am trying to execute a query using postgre sql driver for java jdbc.
I have an issue with memory buildup my statement is in a loop and then sleeps.
The problem is when I look at the job in task manager I can see the memory climbing 00,004K at a time. I have read the documentation I have closed all connections statements resultsets but this still happens.
Please could you tell me what is causing this in my code.
String sSqlString = new String("SELECT * FROM stk.comms_data_sent_recv " +
"WHERE msgtype ='RECEIVE' AND msgstat ='UNPRC' " +
"ORDER BY p6_id,msgoccid " +
"ASC; ");
ResultSet rs = null;
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:postgresql://p6tstc01:5432/DEVC_StockList?autoCloseUnclosedStatements=true&logUnclosedConnections=true&preparedStatementCacheQueries=0&ApplicationName=P6Shunter", "P6dev",
"admin123");
//Main Loop
while(true)
{
try{
Statement statement = connection.createStatement();
statement.executeQuery(sSqlString);
//rs.close();
statement.close();
//connection.close();
rs = null;
//connection = null;
statement =null;
}
finally {
//connection.close();
}
try {
Thread.sleep(loopTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Notice the commented out code.. I did close all but that did not seem to make a difference. Whet I did see is that it seems that the statement executeQuery(sSqlString); is causing this the reason I think so is if I remove the statement there is no memory leak.
I could be wrong but please assist me.
UPDATE:
I have changed my code as with your recommendations. Hope its a bit better please let me know if I need to change something.
My main loop :
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
//Main Loop
while(true)
{
getAndProcessAllUnprcMessagesFromStockList();
try {
Thread.sleep(loopTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My Function it will call do fetch data :
public static void getAndProcessAllUnprcMessagesFromStockList() throws Exception
{
ResultSet rs = null;
Statement statement = null;
Connection connection =null;
String sSqlString = new String("SELECT * FROM stk.comms_data_sent_recv " +
"WHERE msgtype ='RECEIVE' AND msgstat ='UNPRC' " +
"ORDER BY p6_id,msgoccid " +
"ASC; ");
try{
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection(
"jdbc:postgresql://p6tstc01:5432/DEVC_StockList?autoCloseUnclosedStatements=true&logUnclosedConnections=true&preparedStatementCacheQueries=0&ApplicationName=P6Shunter", "P6dev",
"admin123");
PreparedStatement s = connection.prepareStatement(sSqlString,
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
rs = s.executeQuery();
while (rs.next()) {
//Process records
UnprcMsg msg = new UnprcMsg();
msg.setP6Id(rs.getString(1));
msg.setMsgOccId(rs.getString(2));
msg.setWsc(rs.getString(3));
msg.setMsgId(rs.getString(4));
msg.setMsgType(rs.getString(5));
msg.setMsgStatus(rs.getString(6));
//JOptionPane.showMessageDialog(null,msg.getP6Id(), "InfoBox: " + "StockListShunter", JOptionPane.INFORMATION_MESSAGE);
//msg2 = null;
}
rs.close();
s.close();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
connection.close();
}
}
I have closed my connections statements and results.
I also downloaded eclipse memory analyzer and I ran the jar witch will execute my main loop. Ran it for about an hour and here's some of the data I got from memory analyzer..
Leak suspects :
Now I know I cant go on the memory usage of task manager but whats the difference? Why does task manager show the following :
I was concerned about the memory usage I see in task manager? should I be?

Database rows reading into list of objects

public static List<SPACE_CreateLicenseModel> SPACE_getDetails() throws ClassNotFoundException, FileNotFoundException, JSONException{
SPACE_CreateLicenseModel view = new SPACE_CreateLicenseModel();
Statement stmt = null;
Connection connect = null;
List<SPACE_CreateLicenseModel> allData = new ArrayList<SPACE_CreateLicenseModel>();
try {
connect = SPACE_DBController.SPACE_getConnection();
stmt = connect.createStatement();
JSONObject obj = SPACE_Parse.parse ("C:/Users/Rachana/workspace/SPACEOM/WebContent/Data/SPACE_Database.json");
String tablename = obj.getString("table_name");
String sql = "SELECT * FROM " + tablename + " WHERE (SPLD_LicenseActiveStatus <> 5 OR SPLD_LicenseActiveStatus IS NULL)";
ResultSet result = stmt.executeQuery(sql);
int i =0;
while (result.next()) {
view.setSPLD_DeviceID_Mfg(result.getString(1));
view.setSPLD_DeviceID_ModelNo(result.getString(2));
view.setSPLD_DeviceID_SrNo(result.getString(3));
view.setSPLD_DeviceID_Search_mode(result.getByte(4));
view.setSPLD_LicenseType(result.getByte(5));
view.setSPLD_LicenseTypeChangedDate(result.getDate(6));
view.setSPLD_LicenseActiveStatus(result.getByte(7));
view.setSPLD_LicenseActiveDate(result.getDate(8));
view.setSPLD_LicenseAccess(result.getByte(9));
view.setSPLD_LicenseAccessMaxNo(result.getInt(10));
view.setSPLD_LicenseAccessCounter(result.getInt(11));
view.setSPLD_LicenseStartDate(result.getDate(12));
view.setSPLD_LicenseExpiryDate(result.getDate(13));
view.setSPLD_LicenseeOrg(result.getString(14));
view.setSPLD_LicenseeAddress(result.getString(15));
view.setSPLD_LocationActive(result.getString(16));
view.setSPDL_Longitude(result.getDouble(17));
view.setSPDL_Latitude(result.getDouble(18));
view.setSPDL_LocationTolerance(result.getFloat(19));
view.setSPLD_FutureOption1(result.getString(20));
view.setSPLD_FutureOption2(result.getString(21));
view.setSPLD_FutureOption3(result.getString(22));
view.setSPLD_FutureOption4(result.getInt(23));
view.setSPLD_FutureOption5(result.getInt(24));
view.setSPLD_StatCounter1_FirstUseDate(result.getDate(25));
view.setSPLD_StatCounter2_MessageTotal(result.getInt(26));
view.setSPLD_StatCounter3_FailedAttempts(result.getInt(27));
view.setSPLD_StatCounter4_FirstFailedAttemptDate(result.getDate(28));
view.setSPLD_StatCounter5_LastFailedAttemptDate(result.getDate(29));
view.setSPLD_StatCounter6(result.getInt(30));
view.setSPLD_StatCounter7(result.getInt(31));
view.setSPLD_StatCounterOption1(result.getString(32));
view.setSPLD_StatCounterOption2(result.getString(33));
view.setSPLD_StatCounterOption3(result.getString(34));
view.setSPLD_StatCounterOption4(result.getInt(35));
view.setSPLD_StatCounterOption5(result.getInt(36));
view.setSPLD_MainContact1Name(result.getString(37));
view.setSPLD_MainContact2Name(result.getString(38));
view.setSPLD_MobileNo1(result.getString(39));
view.setSPLD_MobileNo2(result.getString(40));
view.setSPLD_EmailID1(result.getString(41));
view.setSPLD_EmailID2(result.getString(42));
view.setSPLD_CustomerDetailOption1(result.getString(43));
view.setSPLD_CustomerDetailOption2(result.getString(44));
view.setSPLD_BroadCastGEN1(result.getString(45));
view.setSPLD_BroadCastGEN2(result.getString(46));
view.setSPLD_BroadCastID1(result.getInt(47));
view.setSPLD_DevSpecGEN1(result.getString(48));
view.setSPLD_DevSpecGEN2(result.getString(49));
view.setSPLD_DevSpecGEN3(result.getString(50));
view.setSPLD_DevSpecID1(result.getInt(51));
view.setSPLD_DevSpecID2(result.getInt(52));
view.setSPLD_MessageStatus(result.getString(53).charAt(0));
allData.add(i,view);
i++;
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(connect!=null)
connect.close();
}catch(SQLException se){
se.printStackTrace();
}
}
return allData;
}
I am fetching all the rows of the database and storing it in array. But while displaying only the last row is getting printed. The list elements are getting overridden. i.e., allData.add(1,view), allData.add(2,view) , allData.add(3,view) , allData.add(4,view) etc everything are same.
As you are not creating a new Object for each iteration of the loop, it is re-using the same object, so try
Statement stmt = null;
Connection connect = null;
List<SPACE_CreateLicenseModel> allData = new ArrayList<SPACE_CreateLicenseModel>();
try {
connect = SPACE_DBController.SPACE_getConnection();
....
while (result.next()) {
SPACE_CreateLicenseModel view = new SPACE_CreateLicenseModel();
Cause:
Currently for each row same object is getting updated hence all your objects in list have same values (Last Row).
Resolution:
You need to initialize SPACE_CreateLicenseModel each time in loop for every row.
while (result.next()) {
SPACE_CreateLicenseModel view = new SPACE_CreateLicenseModel();
view.setSPLD_DeviceID_Mfg(result.getString(1));
.
.
allData.add(i,view);
i++;
}
Hope this helps
Create a new view object with every iteration of your while loop. Every time you loop through the same view object is getting over written in memory. The final time your loop runs it replaces it with the last row values which is being displayed when you are printing your data...
while(yourCondition){
view = new SPACE_CreateLicenseModel();
//your code goes here....
}
Adding the above line in your loop will create a new view Object and will be added to your allData variable.

Hitting stored proc - javax.ejb.EJBException

I'm trying to hit a stored procedure but I'm getting this error message: 'javax.ejb.EJBException'... I've never worked with stored procedures so the exception is a bit Greek to me.
Anyone that could perhaps shed some light on this? Below I pasted the code that I wrote:
#WebMethod(operationName = "getSpecimenResultsXml")
public String getSpecimenResultsXml(#WebParam(name = "specimenGuid") String specimenGuid, #WebParam(name = "publicationGuid") String publicationGuid, #WebParam(name = "forProvider") String forProvider) {
//Method variables
ResultSet rs = null;
String xml = null;
// 1) get server connection
Connection conn = dataBaseConnection.getConnection();
// 2) Pass recieved parameters to stored proc.
try {
CallableStatement proc =
conn.prepareCall("{ call getSpecimenReportXml(?, ?, ?) }");
proc.setString(1, specimenGuid);
proc.setString(2, publicationGuid);
proc.setString(3, forProvider);
proc.execute();
rs = proc.getResultSet();
} catch (SQLException e) {
System.out.println("--------------Error in getSpecimenResultsXml------------");
System.out.println("Cannot call stored proc: " + e);
System.out.println("--------------------------------------------------------");
}
// 3) Get String from result set
try {
xml = rs.getString(1);
} catch (SQLException e) {
System.out.println("--------------Error in getSpecimenResultsXml------------");
System.out.println("Cannot retrieve result set: " + e);
System.out.println("--------------------------------------------------------");
}
// 4) close connection
try {
conn.close();
} catch (Exception e) {
System.out.println("--------------Error in getSpecimenResultsXml------------");
System.out.println("Cannot close connection: " + e);
System.out.println("--------------------------------------------------------");
}
// 5) return the returned String
return xml;
}
Oh and the stored procedure us called getSpecimenReportXml...
Your exception would say 'caused by' somewhere - which is a big clue. If it's an NPE then you might want to check the values of dataBaseConnection and conn to make sure they've been set. Use a debugger to do this, but the exception should tell you exactly which line caused the problem.

Categories

Resources