When updating Cell in Excel using Fillo , getiing error as "NullPointerException" - java

I am using below code,i have checked pathname and sheet name is all fine.
I am using fillo version fillo-1.15.
public class T_Test {
public static void main(String[] args) throws Exception{
try {
com.codoid.products.fillo.Fillo fil_res = new com.codoid.products.fillo.Fillo();
com.codoid.products.fillo.Connection con_res = fil_res
.getConnection("C:\\Users\\admin\\workspace\\Good Connect\\Test_Data/Result\\LifePlanner_Result.xlsx");
String sql_res = "update Result_Data SET Product_ID = 'Sampoorna Raksha' Where TestCase_ID = 'TC1_SIS' ";
System.out.println(sql_res);
com.codoid.products.fillo.Recordset recordset_rec = con_res.executeQuery(sql_res);
con_res.close();
} catch (Exception e) {
System.out.println("Exception result set:" + e.toString());
}
}
}
Error is below:
java.lang.NullPointerException
Exception result set:java.lang.NullPointerException
at com.codoid.products.parser.SelectQueryParser.isWherePresent(SelectQueryParser.java:66)
at com.codoid.products.fillo.Select.getRecordset(Select.java:47)
at com.codoid.products.fillo.Connection.executeQuery(Connection.java:56)
at GoodSolutionAgence.T_Test.main(T_Test.java:89)

I believe the error is here:
com.codoid.products.fillo.Recordset recordset_rec = con_res.executeQuery(sql_res);
You are executing an UPDATE statement, not a SELECT query. An UPDATE statement won't return a record set, just the number of rows it updated. You therefore want to use executeUpdate in place of executeQuery:
int numberOfRowsUpdated = con_res.executeUpdate(sql_res);
However, the Fillo library could at least have warned you that you were using the wrong method. The fact that it threw a NullPointerException is in my opinion a bug in this library: it should handle this error condition better.

Null Pointer Exception occurs when you try to reference a variable that has not been initialized
com.codoid.products.fillo.Connection con_res = fil_res
.getConnection("C:\\Users\\admin\\workspace\\Good Connect\\Test_Data/Result\\LifePlanner_Result.xlsx");
In this case the con_res might be null since getConnection method is not functioning properly.
Now when you try to execute
con_res.executeQuery(sql_res);
It results in Null Pointer Exception.
Check whether con_res gets initialized properly and check the path specified in getConnection method

Related

How do I display database trigger errors on a web application through Payara5

This is a standard error I receive for all Errors parsed from Database Triggers. I use Payara5 as the Application Server and Netbeans 8.2 IDE. In the instance on the picture, it was supposed to display "ID Number mandatory for applicants order that 18 years of age".
How do I make sure that the exact error as in the trigger, appears on the Web Application?
Given your stacktrace it looks like you need to remove the ExceptionUtils.findRootException(ex).getMessage() and just use ex.getMessage() since the thrown topmost Exception already contains the message that you need.
I would try with the following code when an Exception is thrown:
catch (Exception ex) {
JSFUtils.addMessageSessionError(
ExceptionUtils.formatException(AdHocTools.getCurrentMethodName(),
ex.getMessage());
}
However, ExceptionUtils.findRootException(ex).getMessage() might be there for a reason. There are cases where the topmost Exception is pretty general (e.g. an EJBException) and you really need to get to the root exception to get a meaningful message.
You could also try with this code which returns an SQLException if applicable and in other cases the root Exception.
catch (Exception ex) {
Throwable rootCause = ex;
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
if ( rootCause instanceof java.sql.SQLException ) {
break;
}
rootCause = rootCause.getCause();
}
JSFUtils.addMessageSessionError(
ExceptionUtils.formatException(AdHocTools.getCurrentMethodName(),
rootCause.getMessage());
}

clearing batch preparedstatements

I have a java application which read files and writes to oracle db row by row.
We have come across a strange error during batch insert which does not occur during sequential insert. The error is strange because it occurs only with IBM JDK7 on AIX platform and I get this error on different rows every time. My code looks like below:
prpst = conn.prepareStatement(query);
while ((line = bf.readLine()) != null) {
numLine++;
batchInsert(prpst, line);
//onebyoneInsert(prpst, line);
}
private static void batchInsert(PreparedStatement prpst, String line) throws IOException, SQLException {
prpst.setString(1, "1");
prpst.setInt(2, numLine);
prpst.setString(3, line);
prpst.setString(4, "1");
prpst.setInt(5, 1);
prpst.addBatch();
if (++batchedLines == 200) {
prpst.executeBatch();
batchedLines = 0;
prpst.clearBatch();
}
}
private static void onebyoneInsert(PreparedStatement prpst, String line) throws Exception{
int batchedLines = 0;
prpst.setString(1, "1");
prpst.setInt(2, numLine);
prpst.setString(3, line);
prpst.setString(4, "1");
prpst.setInt(5, 1);
prpst.executeUpdate();
}
I get this error during batch insert mode :
java.sql.BatchUpdateException: ORA-01461: can bind a LONG value only for insert into a LONG column
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10345)
I already know why this Ora error occurs but this is not my case. I am nearly sure that I am not setting some large data to a smaller column. May be I am hitting some bugs in IBM jdk7 but could not prove that.
My question if there is a way that I can avoid this problem ? One by one insert is not an option because we have big files and it takes too much time.
Try with
prpst.setInt(5,new Integer(1))
What is the type of variable "numLine"?
Can you share type of columns corresponding to the fields you set in PreparedStatement?
Try once by processing with "onebyoneInsert". Share the output for this case. It might help identifying root cause.
Also print value of "numLine" to console.

program throws CharConversionException in Java?

I am getting the below mentioned error in my catch block when i print using e.printStackTrace();This only occurs for few records when i read it from the DB2 database. So basically only few records throw the error rest work fine.
I have almost 1000 line of code and i am not sure were do i start from in order to understand/debug this error ? IS there any hint that i can get from the error message i should use to solve it ?
from the method getDataFromEMPHCForEmployeeDetails()----- com.ibm.db2.jcc.am.SqlException: [jcc][t4][1065][12306][3.63.123] Caught java.io.CharConversionException. See attached Throwable for details. ERRORCODE=-4220, SQLSTATE=null
at com.ibm.db2.jcc.am.fd.a(fd.java:663)
at com.ibm.db2.jcc.am.fd.a(fd.java:60)
at com.ibm.db2.jcc.am.fd.a(fd.java:112)
at com.ibm.db2.jcc.am.ic.a(ic.java:2820)
at com.ibm.db2.jcc.am.ic.p(ic.java:521)
at com.ibm.db2.jcc.am.ic.N(ic.java:1558)
at com.ibm.db2.jcc.am.vn.e(vn.java:1147)
at com.ibm.db2.jcc.am.vn.getString(vn.java:1122)
at com.ibm.db2.jcc.am.vn.getString(vn.java:1698)
at CreateChart.getDataFromEMPHCForEmployeeDetails(CreateChart.java:330)
at CreateChart.iterateDirectReportNamesFromArrayList(CreateChart.java:594)
at CreateChart.getDataFromEMPHCForDirectReport(CreateChart.java:295)
at CreateChart.iterateSecondLineManagerNamesFromArrayList(CreateChart.java:562)
at CreateChart.getDataFromEMPHCForSecondLine(CreateChart.java:251)
at CreateChart.iterateThirdLineManagerNamesFromArrayList(CreateChart.java:533)
at CreateChart.getDataFromEMPHCForThirdLine(CreateChart.java:208)
at CreateChart.iterateDirectorNamesFromArrayList(CreateChart.java:506)
at CreateChart.getDataFromEMPHCForDirector(CreateChart.java:168)
at CreateChart.iterateVPNamesFromArrayList(CreateChart.java:472)
at CreateChart.getDataFromEMPHCForVp(CreateChart.java:126)
at CreateChart.iterateFuncVPNamesFromArrayList(CreateChart.java:434)
at CreateChart.getDataFromEMPHCForFuncVp(CreateChart.java:95)
at CreateChart.main(CreateChart.java:613)
Caused by: java.nio.charset.MalformedInputException: Input length = 186
at com.ibm.db2.jcc.am.t.a(t.java:19)
at com.ibm.db2.jcc.am.ic.a(ic.java:2816)
... 19 more
Caused by: sun.io.MalformedInputException
at sun.io.ByteToCharUTF8.convert(Unknown Source)
at com.ibm.db2.jcc.am.t.a(t.java:16)
... 20 more
.
public void getDataFromEMPHCForEmployeeDetails(String funcvp_name11, String vp_name11, String director_name11, String thirdline_name11, String secondline_name11, String directreport_name11){
String myQuery11;
if(directreport_name11 == ""){directreport_name11 = " AND DIRECT_REPORT IS NULL";}
else{directreport_name11 =" AND DIRECT_REPORT ='"+ directreport_name11.replace("'", "''")+"'";}
myQuery11 = "SELECT DISTINCT(SERIAL_NUM) FROM DB2INST1.EMP_HC WHERE "+funcvp_name11+" "+vp_name11+" "+director_name11+" "+thirdline_name11+" "+ secondline_name11+""+directreport_name11;
arraylistofEmployeeDetails = new ArrayList<String>();
try {
resultSet = st.executeQuery(myQuery11);
while (resultSet.next())
{
String SERIAL_NUM = resultSet.getString("SERIAL_NUM");
if(SERIAL_NUM == null){SERIAL_NUM="";}
if (SERIAL_NUM.length() > 40){SERIAL_NUM = "Too Long";}
arraylistofEmployeeDetails.add(SERIAL_NUM);
System.out.println(SERIAL_NUM+"\n");
}
if(! (arraylistofEmployeeDetails.isEmpty())){
writeEmployeeDetailsToJsonFile(arraylistofEmployeeDetails);
}
} catch (SQLException e) {
e.printStackTrace();
StringWriter wtr = new StringWriter();
PrintWriter pwtr = new PrintWriter(wtr);
e.printStackTrace(pwtr);
String stackTrace = wtr.toString();
error_logs.append("from getDataFromEMPHCForEmployeeDetails()----- "+stackTrace+"\n");
}
}
I had similar problem with CharConversionException on DB2 jdbc driver with 1.8 Oracle Java with same error code, once updated to a never version it worked fine.
I downloaded db2jcc_license_cu and db2jcc.jar from these links.
Maybe it is worth of trying.
Try adding a JVM parameter -Ddb2.jcc.charsetDecoderEncoder=3, it solved the issue for me.
After setting the parameter db2.jcc.charsetDecoderEncoder=3, an exception will not be thrown when a non-UTF8 character is encountered but rather it will be substituted by its equivalent Unicode replacement character.
See the IBM Support article for more details https://www.ibm.com/support/pages/sqlexception-message-caught-javaiocharconversionexception-and-errorcode-4220

When i tried running this code it causes " Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0" this exception

import javax.speech.*;
import java.util.*;// creates a default Systhesize
import javax.speech.synthesis.*; //code for text-speech engine
public class SpeechUtils
{
String speaktext;
public void dospeak(String speak,String voicename)
{
speaktext=speak;
String voiceName =voicename;
try
{
SynthesizerModeDesc desc = new
SynthesizerModeDesc(null,"general",Locale.US,null,null);
Synthesizer synthesizer = Central.createSynthesizer(desc);
synthesizer.allocate();
synthesizer.resume();
desc = (SynthesizerModeDesc)
synthesizer.getEngineModeDesc();
Voice[] voices = desc.getVoices();
Voice voice = null;
for (int i = 0; i < voices.length; i++)
{
if (voices[i].getName().equals(voiceName))
{
voice = voices[i];
break;
}
}
synthesizer.getSynthesizerProperties().setVoice(voice);
synthesizer.speakPlainText(speaktext, null);
synthesizer.waitEngineState(Synthesizer.QUEUE_EMPTY);
synthesizer.deallocate();
}catch (Exception e)
{
String message = " missing speech.properties in " + System.getProperty("user.home") + "\n";
System.out.println(""+e);
System.out.println(message);}
}
public static void main(String[] args)
{
SpeechUtils obj=new SpeechUtils();
obj.dospeak(args[0],"life is beautiful");//getting an exception here....
}
}
How to fix this exception? i am getting an error like
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at SpeechUtils.main(SpeechUtils.java:44)".
It is a Java program or text to speech conversion.i imported all the necessary libraries.But unable to fix this exception alone
You need to provide a runtime argument while running the program. As in your code your accessing the first argument:
obj.dospeak(args[0],"life is beautiful");//getting an exception here....
If you don't provide an argument then there will be no element at index 0 of args array and hence accessing it using args[0] will throw ArrayIndexOutOfBoundsException. You need to run your code like this:
java SpeechUtils argument
replace argument with the actual value you want to input to your program
You need to pass some argument when you do call to your program from commandline
java SpeechUtils "I am doing well"
please remember
java.lang.ArrayIndexOutOfBoundsException:10
means that Array which you are trying to access does not have any element assigned to it at Array[10]
i.e. 11th element is missing. Here you are getting exception at 0 which means 0th element is not there
Missing argument While execution of the program.
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Error caused due to missing argument which you need to provide, since you had used args[0] in the code obj.dospeak(args[0],"life is beautiful"); So pass argument while runtime. args[0] denote array with its first element so, only one argument is necessary to run your program.
Use the command java SpeechUtils YourArgumentYouWantToAdd

PMD rules: How to properly solve this DD-anomaly issue

I have the following Android code:
public final List<MyObj> getList() {
Cursor cursor = null;
try {
final String queryStr = GET_LIST_STATEMENT;
cursor = db.rawQuery(queryStr, new String[] {});
List<MyObj> list = null;
//here I get the data from de cursor.
return list ;
} catch (SQLiteFullException ex) {
//do something to treat the exception.
} finally {
if (cursor != null) {
cursor.close();
}
}
}
When I run PMD analysis over this code, I get the following issue: Found 'DD'-anomaly for variable 'cursor' (lines '182'-'185').
The line 182 is: Cursor cursor = null;.
The line 185 is: cursor = db.rawQuery(queryStr, new String[] {});
So, I understand that the problem is that I'm doing a Premature Initialization in the line 182 (I never read the variable between the lines 182 and 185), but if I don't do that, I can't have the code closing the cursor in the finally block.
What to do in this case? Just ignore this PMD issue? Can I configure PMD to don't rise up this specific kind of DD-anomaly (not all DD-anomaly)? Should PMD be smart enough to doesn't rise up this issue?
Another example of DD-anomaly that I think is not a real problem:
Date distributeDate;
try {
distributeDate = mDf.parse(someStringDate);
} catch (ParseException e) {
Log.e("Problem", "Problem parsing the date of the education. Apply default date.");
distributeDate = Calendar.getInstance().getTime();
}
In this case, the anomaly occurs with the distributeDate variable.
The documentation is pretty easy to understand:
Either you use annotations to suppress warnings:
// This will suppress UnusedLocalVariable warnings in this class
#SuppressWarnings("PMD.UnusedLocalVariable")
public class Bar {
void bar() {
int foo;
}
}
or you use a comment:
public class Bar {
// 'bar' is accessed by a native method, so we want to suppress warnings for it
private int bar; //NOPMD
}
When it comes to your specific code, I'd say that the easiest way to handle it is to not use a finally block even though this would look like the perfect place for it.

Categories