Can't instantiate class error in JSF, caused by NullPointerException - java

Here is my managed Bean class,
public class ChartBean implements Serializable {
private PieChartModel pieModel;
public ChartBean(){
createPieModel();
}
public PieChartModel getPieModel() {
return pieModel;
}
private void createPieModel(){
try {
pieModel = new PieChartModel();
String query = "SELECT b.countryname,count(b.countryname) FROM info.summery a,info.countrymcc b;";
Connector conn = new Connector();
Statement str = (Statement) conn.getConn().createStatement();
ResultSet res = str.executeQuery(query);
while(res.next()){
pieModel.set(res.getString(1), Integer.parseInt(res.getString(2)));
}
} catch (SQLException ex) {
Logger.getLogger(ChartBean.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But the problem is when it is compiled it gives an error like this "Cant instantiate class: org.primefaces.examples.view.ChartBean". What is the reason??
StackTrace:
Caused by: java.lang.NullPointerException at
org.primefaces.examples.view.ChartBean.createPieModel(ChartBean.java:45) at
org.primefaces.examples.view.ChartBean.<init>(ChartBean.java:32) at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorI‌​
mpl.java:39) at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorA‌​
ccessorImpl.java:27) at java.lang.reflect.Constructor.newInstance(Constructor.java:513) at
java.lang.Class.newInstance0(Class.java:355) at java.lang.Class

By a process of elimination, the problem is happening because conn.getConn() is returning null. You should be able to simply confirm that the exception occurs at that line (by checking the line number!), and we know that conn cannot be null, so it must be result of getConn() that is null.
That's about as far as I can go without knowing what the Connector class is and how its getConn() method works.
For the record, here's how I eliminated other possibilities.
The NPE is being thrown in the createPieModel call ... and not in some method called from createPieModel:
1. private void createPieModel(){
2. try {
3. pieModel = new PieChartModel();
4. String query = "SELECT b.countryname,count(b.countryname) FROM info.summery a,info.countrymcc b;";
5. Connector conn = new Connector();
6. Statement str = (Statement) conn.getConn().createStatement();
7. ResultSet res = str.executeQuery(query);
8. while(res.next()){
9. pieModel.set(res.getString(1), Integer.parseInt(res.getString(2)));
10. }
11. } catch (SQLException ex) {
12. Logger.getLogger(ChartBean.class.getName()).log(Level.SEVERE, null, ex);
13. }
14. }
It cannot be line 3 because any NPE would be thrown in the constructor.
It cannot be line 4
It cannot be line 5 - see line 3
It could be line 6
It cannot be line 7 - because str must be non-null (if we get that far)
It cannot be line 8 - because executeQuery never returns null
It cannot be line 9 - because res and pieModel must be non-null.
It cannot be line 12 - because nothing there can return a null.
Hence it can only happen on line 6.

Related

JavaFX Text Area Append Causes Two Errors

I am writing a program that checks prices and if it increases past a set amount then lets the user know by putting into a JavaFX text area line by line with a time stamp, appendText() spits out 2 errors. The error codes don't point to anything specific which is causing me to go in circles.
Most of the code works and if I use System.out.print() instead the code runs perfectly, but if I use txtContent.appendText() then at a random time in the first five minutes I will get one of the following errors.
Exception in thread "JavaFX Application Thread" java.lang.NullPointerException: Cannot read the array length because "this.lines" is null
at javafx.graphics#19/com.sun.javafx.text.PrismTextLayout.layout(PrismTextLayout.java:1222)
at javafx.graphics#19/com.sun.javafx.text.PrismTextLayout.ensureLayout(PrismTextLayout.java:223)
at javafx.graphics#19/com.sun.javafx.text.PrismTextLayout.getBounds(PrismTextLayout.java:246)
at javafx.graphics#19/javafx.scene.text.Text.getLogicalBounds(Text.java:432)
at javafx.graphics#19/javafx.scene.text.Text.doComputeGeomBounds(Text.java:1187)
at javafx.graphics#19/javafx.scene.text.Text$1.doComputeGeomBounds(Text.java:149)
at javafx.graphics#19/com.sun.javafx.scene.shape.TextHelper.computeGeomBoundsImpl(TextHelper.java:90)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
at javafx.graphics#19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
at javafx.graphics#19/javafx.scene.Node.getGeomBounds(Node.java:3787)
at javafx.graphics#19/javafx.scene.Node.getLocalBounds(Node.java:3735)
at javafx.graphics#19/javafx.scene.Node$MiscProperties$3.computeBounds(Node.java:6825)
at javafx.graphics#19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9840)
at javafx.graphics#19/javafx.scene.Node$LazyBoundsProperty.get(Node.java:9810)
at javafx.graphics#19/javafx.scene.Node.getBoundsInLocal(Node.java:3415)
at javafx.controls#19/javafx.scene.control.skin.TextAreaSkin$ContentView.layoutChildren(TextAreaSkin.java:1324)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1207)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Parent.layout(Parent.java:1214)
at javafx.graphics#19/javafx.scene.Scene.doLayoutPass(Scene.java:592)
at javafx.graphics#19/javafx.scene.Scene$ScenePulseListener.pulse(Scene.java:2512)
at javafx.graphics#19/com.sun.javafx.tk.Toolkit.lambda$runPulse$2(Toolkit.java:407)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics#19/com.sun.javafx.tk.Toolkit.runPulse(Toolkit.java:406)
at javafx.graphics#19/com.sun.javafx.tk.Toolkit.firePulse(Toolkit.java:436)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:575)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.pulse(QuantumToolkit.java:555)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.pulseFromQueue(QuantumToolkit.java:548)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.lambda$runToolkit$11(QuantumToolkit.java:352)
at javafx.graphics#19/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
at java.base/java.lang.Thread.run(Thread.java:1589)
Exception in thread "JavaFX Application Thread" java.lang.IndexOutOfBoundsException: Index -1 out of bounds for length 2
at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:100)
at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckIndex(Preconditions.java:106)
at java.base/jdk.internal.util.Preconditions.checkIndex(Preconditions.java:302)
at java.base/java.util.Objects.checkIndex(Objects.java:385)
at java.base/java.util.ArrayList.get(ArrayList.java:427)
at javafx.base#19/com.sun.javafx.collections.ObservableListWrapper.get(ObservableListWrapper.java:89)
at javafx.base#19/com.sun.javafx.collections.VetoableListDecorator.get(VetoableListDecorator.java:305)
at javafx.graphics#19/javafx.scene.Parent.updateCachedBounds(Parent.java:1704)
at javafx.graphics#19/javafx.scene.Parent.recomputeBounds(Parent.java:1648)
at javafx.graphics#19/javafx.scene.Parent.doComputeGeomBounds(Parent.java:1501)
at javafx.graphics#19/javafx.scene.Parent$1.doComputeGeomBounds(Parent.java:115)
at javafx.graphics#19/com.sun.javafx.scene.ParentHelper.computeGeomBoundsImpl(ParentHelper.java:84)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBoundsImpl(RegionHelper.java:78)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.superComputeGeomBounds(RegionHelper.java:62)
at javafx.graphics#19/javafx.scene.layout.Region.doComputeGeomBounds(Region.java:3355)
at javafx.graphics#19/javafx.scene.layout.Region$1.doComputeGeomBounds(Region.java:168)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.computeGeomBoundsImpl(RegionHelper.java:89)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.computeGeomBounds(NodeHelper.java:117)
at javafx.graphics#19/javafx.scene.Node.updateGeomBounds(Node.java:3825)
at javafx.graphics#19/javafx.scene.Node.getGeomBounds(Node.java:3787)
at javafx.graphics#19/javafx.scene.Node.getLocalBounds(Node.java:3735)
at javafx.graphics#19/javafx.scene.Node.intersectsBounds(Node.java:5270)
at javafx.graphics#19/javafx.scene.Node$1.intersectsBounds(Node.java:559)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.intersectsBounds(NodeHelper.java:264)
at javafx.graphics#19/javafx.scene.layout.Region.doPickNodeLocal(Region.java:3224)
at javafx.graphics#19/javafx.scene.layout.Region$1.doPickNodeLocal(Region.java:184)
at javafx.graphics#19/com.sun.javafx.scene.layout.RegionHelper.pickNodeLocalImpl(RegionHelper.java:104)
at javafx.graphics#19/com.sun.javafx.scene.NodeHelper.pickNodeLocal(NodeHelper.java:130)
at javafx.graphics#19/javafx.scene.Node.pickNode(Node.java:5180)
at javafx.graphics#19/javafx.scene.Scene$MouseHandler.pickNode(Scene.java:4037)
at javafx.graphics#19/javafx.scene.Scene.pick(Scene.java:2067)
at javafx.graphics#19/javafx.scene.Scene$MouseHandler.process(Scene.java:3847)
at javafx.graphics#19/javafx.scene.Scene.processMouseEvent(Scene.java:1887)
at javafx.graphics#19/javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2620)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:411)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:301)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:399)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$2(GlassViewEventHandler.java:450)
at javafx.graphics#19/com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:424)
at javafx.graphics#19/com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:449)
at javafx.graphics#19/com.sun.glass.ui.View.handleMouseEvent(View.java:551)
at javafx.graphics#19/com.sun.glass.ui.View.notifyMouse(View.java:937)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at javafx.graphics#19/com.sun.glass.ui.win.WinApplication.lambda$runLoop$3(WinApplication.java:184)
at java.base/java.lang.Thread.run(Thread.java:1589)
Normally when I get errors like this I will follow errors to the part that I wrote something incorrect or made some mistake with my work. But these don't point to anything in particular other than my runLoop which is pretty simple.
try
{
Database.deleteLastRow();
Database.updateRows();
JSONAccess.createNewRow();
if(increaseCounter)
{
rowCounter++;
}
if(rowCounter >= Main.calculatedRows)
{
if(testLine)
{
System.out.println("Starting");
testLine = false;
}
increaseCounter = false;
MainGUI.txtContent.appendText("\n New Section");
Database.compareValues();
}
}
catch (Exception e)
{
MainGUI.btnStart.setDisable(false);
MainGUI.btnStop.setDisable(true);
System.out.println("Test to see if something goes wrong");
}
public static void compareValues() throws Exception
{
Class.forName("org.hsqldb.jdbc.JDBCDriver");
for (String tableName : symbolsList)
{
String compareSql = "SELECT * FROM tbl_" + tableName + " ORDER BY id";
prepStatement = connection.prepareStatement(compareSql);
ResultSet rs = prepStatement.executeQuery();
int rowNum = 1;
while (rs.next())
{
if (rowNum == 1)
{
dblNew = rs.getDouble("val");
}
if (rowNum == Main.calculatedRows)
{
dblOld = rs.getDouble("val");
}
rowNum = Main.calculatedRows;
}
mathsCompare(tableName, dblNew, dblOld);
}
}
public static void mathsCompare(String tableName1, double dblNew1, double dblOld1) throws Exception
{
if(dblNew1>dblOld1)
{
double dblChange = ((dblNew1-dblOld1)/dblOld1)*100;
if(dblChange >= Main.dblPercentage)
{
MainGUI.txtContent.appendText("\n" + tableName1);
System.out.print("\n" + tableName1);
}
}
}
If I have both System.out.println and MainGUI.txtContent.appendText enabled then the console gets an extra set of values out before the error comes out but thats when I get stumped
Any help appreciated.

How is Throwable.getSuppressed() supported from Android API 31

When testing a code that does nasty reflective operations on Throwable fields, then it is failing on Android API 31. The reason is that Throwable.suppressedExceptions field is no longer present.
I did more tests between Android API 30 and 31:
public class ThrowableInternalTest {
private static final String TAG = "ThrowableInternal";
#Test
public void suppressedExceptionsFieldIsPresent() throws Exception {
Log.w(TAG, "Android API: " + VERSION.SDK_INT);
// Checking internal fields
Field[] fields = Throwable.class.getDeclaredFields();
String fieldNames = Stream.of(fields).map(Field::getName).collect(Collectors.joining(","));
Log.w(TAG, "Throwable fields: " + fieldNames);
// Manually setting suppressed exceptions
Exception suppressed = new Exception();
Exception exception = new Exception();
exception.addSuppressed(suppressed);
Log.w(TAG, "exception.getSuppressed(): " + exception.getSuppressed().length);
// Using try-with-resource block which should have suppressed exceptions
try {
try (ThrowingClosable ignored = new ThrowingClosable()) {
throw new Exception();
}
} catch (Throwable t) {
Log.w(TAG, "try-with-resource suppressed: " + t.getSuppressed().length);
}
// Results:
// minSdkVersion: 18
// Android API: 30
// Throwable fields: backtrace,cause,detailMessage,stackTrace,suppressedExceptions,serialVersionUID
// exception.getSuppressed(): 0
// try-with-resource suppressed: 0
// minSdkVersion: 19
// Android API: 30
// Throwable fields: backtrace,cause,detailMessage,stackTrace,suppressedExceptions,serialVersionUID
// exception.getSuppressed(): 1
// try-with-resource suppressed: 1
// minSdkVersion: 18
// Android API: 31
// Throwable fields: backtrace,cause,detailMessage,stackTrace,serialVersionUID
// exception.getSuppressed(): 0
// try-with-resource suppressed: 0
// minSdkVersion: 19
// Android API: 31
// Throwable fields: backtrace,cause,detailMessage,stackTrace,serialVersionUID
// exception.getSuppressed(): 1
// try-with-resource suppressed:1
}
private static class ThrowingClosable implements AutoCloseable {
#Override
public void close() throws Exception {
throw new Exception();
}
}
}
When minSdkVersion is below 19, then Throwable.getSuppressed() always returns an empty array. With higher minSdkVersion, then it is working properly.
Although, the suppressedExceptions field is only present on API 30, not on 31.
But in the Android SDK source code, the suppressedExceptions field is present on both API: 30 and 31.
I'm curious how API 31 could have suppressed exception working even without the suppressedExceptions field ?
Also why suppressed exceptions are not supported when minSdkVersion is below 19 ?

What type of exception is (0)null?

I am using Apache Axis, and I am getting exception of type (0)null. Here is partial stack trace:
....
....
org.springframework.batch.core.job.AbstractJob.execute(AbstractJob.java:281)
at org.springframework.batch.core.launch.support.SimpleJobLauncher$1.run(SimpleJobLauncher.java:120)
at java.lang.Thread.run(Thread.java:744)
Caused by: (0)null
at org.apache.axis.transport.http.HTTPSender.readFromSocket(HTTPSender.java:744)
at org.apache.axis.transport.http.HTTPSender.invoke(HTTPSender.java:144)
at org.apache.axis.strategies.InvocationStrategy.visit(InvocationStrategy.java:32)
at org.apache.axis.SimpleChain.doVisiting(SimpleChain.java:118)
at org.apache.axis.SimpleChain.invoke(SimpleChain.java:83)
at org.apache.axis.client.AxisClient.invoke(AxisClient.java:165)
at org.apache.axis.client.Call.invokeEngine(Call.java:2784)
at org.apache.axis.client.Call.invoke(Call.java:2767)
at org.apache.axis.client.Call.invoke(Call.java:2443)
at org.apache.axis.client.Call.invoke(Call.java:2366)
at org.apache.axis.client.Call.invoke(Call.java:1812)
at com.netsuite.webservices.platform_2012_1.NetSuiteBindingStub.upsertList(NetSuiteBindingStub.java:11841)
....
....
Following is what I see in HTTPSender source code.
....
AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);
....
throw fault;
....
So the exception is of type AxisFault, but it looks like statusMessage is null. Line 444 is:
AxisFault fault = new AxisFault("HTTP", "(" + returnCode + ")" + statusMessage, null, null);
The (0)null part comes from "(" + returnCode + ")" + statusMessage. statusMessage itself is assigned in line 742:
String statusMessage = msgContext.getStrProp(HTTPConstants.MC_HTTP_STATUS_MESSAGE);
returnCode is set to 0 early on in the method. The next few statements should set it to its correct value:
Integer rc = (Integer) msgContext.getProperty(HTTPConstants.MC_HTTP_STATUS_CODE);
if (rc != null) {
returnCode = rc.intValue();
} else {
// No return code?? Should have one by now.
}
After this, the if block and none of the else if blocks get executed since the return code is 0 (because rc is null). It finally lands up in the else block where it generates the AxisFault exception.
You will notice that the statusMessage itself is null. The only place I can see it setting this property is on line 641, which is the readHeadersFromSocket method.
The only way the status message and the return code will not be set is if they are already null, or if there is an error earlier on in the method, which causes control to break out of the for loop that starts on line 581. Of particular interest are line 585 and line 598, both of which are if statements that will break out of the loop if their test-condition is true. One of these statements checks to see if the value of inp.read() is -1 (which means that the end of the stream has been reached), the other checks to see if the length of what was read in is 0. These conditions can hold true if there is a network error (i.e., nothing read from the socket) or if nothing was returned from the server (zero-length data). So if any of these conditions are true, control breaks out of the loop. Eventually, readFromSocket will throw the exception since it wasn't able to get a return code. But because the failure happened before it could even set an error message, you get a null error message.
tl; dr; There is probably some sort of network/read error.

Writing Excel data to database in Java

This is my method that I use to write excel file data to a database.
public static void executeSQLUpdate(String sql, List<Object> arguments) {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = getConnection(); //a method that returns a java.sql.Connection to your database
System.out.println("\n01)conection :"+con);
pstmt = con.prepareStatement(sql);
System.out.println("\n02)pstn :"+pstmt);
System.out.println( "\n03)arguments size :"+arguments.size());
if (arguments != null) {
int i = 1;
System.out.println( "\n04)if :"+arguments);
for(Object o : arguments) {
System.out.println( "\n05)executeSQLUpdate");
System.out.println( "\n06)object."+o);
System.out.println("\n07)................... :"+i + o);
pstmt.setObject(i, o);
System.out.println("\n08)____________________"+i+o);
}
}
System.out.print("\n09)errorchk........... :");
//method to execute insert, update, delete statements...
pstmt.executeUpdate();
System.out.print("\n10)+++++++++++++++++ :");
} catch(SQLException e) {
System.out.println("\n11)************* :"+e);
//handle the error...
} finally {
//closing the resources (always in finally block, not in the try!)
try {
if (pstmt != null) {
pstmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
}
}
}
Up to no 07 all the system out are working. But after that any system out are not working. What is the reason for that? Is there any error in this one?
This is my out put:
run:
AAA BBB CCC
DDD EEE FFF
GGG HHH III
JJJ KKK LLL
MMM NNN OOO
PPP QQQ RRR
01)conection :com.mysql.jdbc.JDBC4Connection#6e70c7
02)pstn :com.mysql.jdbc.JDBC4PreparedStatement#29428e: INSERT INTO files_1 VALUES(** NOT SPECIFIED , NOT SPECIFIED , NOT SPECIFIED **)
03)arguments size :6
04)if :[[AAA, BBB, CCC], [DDD, EEE, FFF], [GGG, HHH, III], [JJJ, KKK, LLL], [MMM, NNN, OOO], [PPP, QQQ, RRR]]
05)executeSQLUpdate :
06)object :[AAA, BBB, CCC]
07)................... :1[AAA, BBB, CCC]
08)__________ :1[AAA, BBB, CCC]
05)executeSQLUpdate :
06)object :[DDD, EEE, FFF]
07)................... :1[DDD, EEE, FFF]
08)__________ :1[DDD, EEE, FFF]
05)executeSQLUpdate :
06)object :[GGG, HHH, III]
07)................... :1[GGG, HHH, III]
08)__________ :1[GGG, HHH, III]
05)executeSQLUpdate :
06)object :[JJJ, KKK, LLL]
07)................... :1[JJJ, KKK, LLL]
08)__________ :1[JJJ, KKK, LLL]
05)executeSQLUpdate :
06)object :[MMM, NNN, OOO]
07)................... :1[MMM, NNN, OOO]
08)__________ :1[MMM, NNN, OOO]
05)executeSQLUpdate :
06)object :[PPP, QQQ, RRR]
07)................... :1[PPP, QQQ, RRR]
08)__________ :1[PPP, QQQ, RRR]
09)errorchk........... :
11)***** :No value specified for parameter 2
java.sql.SQLException: No value specified for parameter 2
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1075)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:984)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:929)
at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2560)
at com.mysql.jdbc.PreparedStatement.fillSendPacket(PreparedStatement.java:2536)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2383)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2327)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2312)
at com.project.bulk.ReadExcelFile.executeSQLUpdate(ReadExcelFile.java:112)
at com.project.bulk.ReadExcelFile.MethodToData(ReadExcelFile.java:138)
at com.project.bulk.ReadExcelFile.main(ReadExcelFile.java:39)
BUILD SUCCESSFUL (total time: 3 seconds)
One error for sure is that you increment i two times!!!
System.out.println("\n07)..................."+i++ + o); // one
pstmt.setObject(i++, o); // two
This means that you don't set the even indices, just the odd ones: 1, 3, 5...
This should correct this error:
System.out.println("\n07)..................."+i + o);
pstmt.setObject(i++, o); // only once, and after the evaluation!
EDIT
*Second, but also big mistake*
} catch(SQLException e) {
System.out.println("\n11)************* :"+e); //WTF?
//handle the error...
}
excuse me for shouting, this has to happen now!
Please, for our and your (future) colleagues' mental health's sake, DO NOT EVER DO THIS AGAIN!
Printing exceptions must happen in one of two ways:
logger.error("message", e);
e.printStackTrace();
As these reserve the stack trace, and thus enable proper debugging of the code
but should never, ever, ever, never! happen in any of these ways:
System.out.print(e)
System.out.print(e.getMessage)
System.out.print("message " + e.getMessage)
logger.error(e.getMessage)
So correctly this should be:
} catch(SQLException e) {
System.out.println("\n11)************* :"+e.getMessage());
e.printStackTrace();
//TODO: handle the error...
}
By the way: using proper logging like log4j is well worth the time! It consumes much more time to clean up all the System.out.*, than to set a proper loglevel...
EDIT2
As for the SQL error:
String sql = "INSERT INTO files_1 VALUES(?)";
This SQL line tells the DBMS that it will have one parameter to deal with. The table has 3 columns, so you need to specify 3 values. Either constants, or parameters (by using ?). So you should have:
String sql = "INSERT INTO files_1 VALUES(?,?,?)";
As indicated by your error
java.sql.SQLException: Invalid argument value: java.io.NotSerializableException
you're trying to set a value with a parameter that's not serializable in this line:
pstmt.setObject(i++, o);
Please make sure that all of your values are either primitives or values that can be mapped to database columns like String or Date.
You can find out which data you're trying to set by putting in a line like this (using a logging framework or System.out.println:
System.out.println("setObject: " + o + ", Class: " + o.getClass());

How to get the line number in error in java?

I know that the line in error is to_return = find(list,false); How can I get the line number of this line when there is NullPointerException type of error? Or in line number in general?
I tried few things. The closest is this one Called.getLineNumber() which gives me the line number of StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
public TestObject[] myfind(Subitem list )throws Exception{
TestObject[]to_return=null;
try {
to_return = find(list,false);
}
catch (RationalTestException ex) {
//logStoreException(ex);
StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
StackTraceElement Calling = new Throwable().fillInStackTrace().getStackTrace()[1];
throw new Exception (this.add_debugging_info(Called, Calling, ex.getMessage()));
}
catch (NullPointerException npe) {
StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
StackTraceElement Calling = new Throwable().fillInStackTrace().getStackTrace()[1];
logStoreException(npe);
System.out.println("Line number: "+npe.getStackTrace()[0].getLineNumber());
System.out.println("Line number2: "+Integer.toString(Called.getLineNumber()));
System.out.println(this.add_debugging_info(Called, Calling, npe.getMessage()));
throw new Exception (this.add_debugging_info(Called, Calling, npe.getMessage()));
}
catch (Exception ex) {
StackTraceElement Called = new Throwable().fillInStackTrace().getStackTrace()[0];
StackTraceElement Calling = new Throwable().fillInStackTrace().getStackTrace()[1];
throw new Exception (this.add_debugging_info(Called, Calling, ex.getMessage()));
}
finally {
//unregisterAll();
//unregister(to);
return to_return;
}
}
If you just want the current stack trace, use Thread.currentThread().getStackTrace()
If you want to force the JVM to fill in the stack traces, please set the option -XX:-OmitStackTraceInFastThrow on your JVM.
When running in Eclipse, to get the line number itself, you need to get the StackTrace array and call getLineNumber() on it.
The following worked for me in my Utils class, isSessionConnectible method:
... catch (ClassFormatError cfe) {
logger.error("Problem ClassFormatError connecting. " + cfe.getMessage() + " " + cfe.getCause());
int size = cfe.getStackTrace().length - 1;
logger.error(" Root cause: " + cfe.getStackTrace()[size].getMethodName() + " " + cfe.getStackTrace()[size].getClassName());
if (size>1) {
logger.error(" Penultimate cause: method=" + cfe.getStackTrace()[size-1].getMethodName() + " class=" + cfe.getStackTrace()[size-1].getClassName() +
" line=" + cfe.getStackTrace()[size-1].getLineNumber());
}
Result when thrown:
2018-07-06 12:00:12 ERROR Utils:319 - Problem ClassFormatError connecting to Hibernate. Absent Code attribute in method that is not native or abstract in class file javax/transaction/SystemException null
2018-07-06 12:00:12 ERROR Utils:322 - Root cause: main <mypackage>.Utils
2018-07-06 12:00:12 ERROR Utils:324 - Penultimate cause: method=isSessionConnectible class=<mypackage>.Utils line=306
BTW, in Eclipse, make sure that Window --> Preferences --> Java --> Compiler has the checkbox marked at "Add line number attributes to generated class files".

Categories

Resources