Writing Excel data to database in Java - 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());

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.

R Integrate with Java using Rserve

I have build an application connecting R and java using the RServe package. In this project I use neuralnet to predict output. Where is the source code that I use are as follows:
myneuralnetscript=function(){
trainingData = read.csv("D:\\Kuliah\\Semester V\\TA\\Implementasi\\training.csv")
testingData = read.csv("D:\\Kuliah\\Semester V\\TA\\Implementasi\\testing.csv")
X1training <- trainingData$open
X2training <- trainingData$high
X3training <- trainingData$low
X4training <- trainingData$close
X5training <- trainingData$volume
targetTraining <- trainingData$target
X1testing <- testingData$open
X2testing <- testingData$high
X3testing <- testingData$low
X4testing <- testingData$close
X5testing <- testingData$volume
targetTesting <- testingData$target
xTraining <- cbind(X1training,X2training,X3training,X4training,X5training)
sum.trainingData <- data.frame(xTraining,targetTraining)
net.sum <- neuralnet(targetTraining~X1training+X2training+X3training+X4training+X5training, sum.trainingData, hidden=5,act.fct="logistic")
xTesting <- cbind(X1testing,X2testing,X3testing,X4testing,X5testing)
sum.testingData <- data.frame(xTesting,targetTesting)
result <- compute(net.sum,sum.testingData[,1:5])
return(result)
}
The output generated as follows:
Here the program from Java to access the results of the R.
public static void main(String[] args) {
RConnection connection = null;
try {
/* Create a connection to Rserve instance running on default port
* 6311
*/
connection = new RConnection();
//Directory of R script
connection.eval("source('D:\\\\Kuliah\\\\Semester V\\\\TA\\\\Implementasi\\\\R\\\\neuralNet.R')");
//Call method
double output = connection.eval("myneuralnetscript()").asDouble();
System.out.println(output);
} catch (RserveException | REXPMismatchException e) {
System.out.println("There is some problem indeed...");
}
}
However, the output that appears is "There is some problem indeed ...".
Please do not catch exceptions just to print a useless message. Remove your try catch and declare main to throw Exception. That way you'll see the actual error.
Either Rserve is not running locally on 6311 or it's failing to evaluate or the result of second evaluation cannot be coerced into a single double.
When you run eval do
tryCatch({CODE},e=function ()e)
instead and check if return inherits from try-error and get the message

R, Java, RCaller

So i'm trying to use RCaller to do the following (in psuedo-code):
x=simarray(..) // in java
'send x to R'
run y = rlogcon(40000, sort(x)) //in R, rlogcon is part of rlogcondens and the function
produces a numeric vector of length 40000
//send y to java and hold it in a double matrix.
this is what i've got in my main function (i've adapted one of the examples I found, but I must have made a mistake/misunderstood something. I tested the example on my machine, and it worked as expected):
RCaller caller = new RCaller();
RCode code = new RCode();
double[] x = a.simarraysimbeta(5, 1, 100, 30, 40); //some method
savesample("simarraysimbeta.txt",x); //testing, it works.
caller.setRscriptExecutable("C:\\Program Files\\R\\R-3.1.0\\bin\\Rscript.exe");
code.addDoubleArray("X", x);
code.addRCode("library(logcondens)"); //rlogcon is part of logcondens library
code.addRCode("ols <- rlogcon(40,000, sort(X))");
caller.setRCode(code);
caller.runAndReturnResult("ols");
double[] residuals = caller.getParser().getAsDoubleArray("X_star");
and the following relevent imports:
import rcaller.RCaller;
import rcaller.RCode;
import rcaller;
I get the following error:
Exception in thread "main" rcaller.exception.ParseException: Can not
handle R results due to : rcaller.exception.ParseException: Can not
parse output: The generated file
C:\Users\jo\AppData\Local\Temp\Routput8804446513483695061 is empty
here is the output:
concat<-function(to,...){
to<-paste(to,toString(...),sep="");
return(to);
}
cleanNames<-function(names){
cleanNames<-paste(unlist(strsplit(names,"\\.")),collapse="_");
Exception in thread "main" rcaller.exception.ParseException: Can not
handle R results due to : rcaller.exception.ParseException: Can not
parse output: The generated file
C:\Users\jo\AppData\Local\Temp\Routput8804446513483695061 is empty
cleanNames<-paste(unlist(strsplit(cleanNames,"<")),collapse="");
at rcaller.RCaller.runAndReturnResult(RCaller.java:409)
cleanNames<-paste(unlist(strsplit(cleanNames,">")),collapse="");
at dissertation.Dissertation.main(Dissertation.java:709)
cleanNames<-paste(unlist(strsplit(cleanNames," ")),collapse="");
cleanNames<-paste(unlist(strsplit(cleanNames,"\\(")),collapse="");
cleanNames<-paste(unlist(strsplit(cleanNames,"\\)")),collapse="");
cleanNames<-paste(unlist(strsplit(cleanNames,"\\[")),collapse="");
cleanNames<-paste(unlist(strsplit(cleanNames,"\\]")),collapse="");
cleanNames<-paste(unlist(strsplit(cleanNames,"\\*")),collapse="");
return(cleanNames);
}
makevectorxml<-function(code,objt,name=""){
xmlcode<-code;
if(name==""){
varname<-cleanNames(deparse(substitute(obj)));
}else{
varname<-name;
}
obj<-objt;
n <- 0; m <- 0
mydim <- dim(obj)
if(!is.null(mydim)){
n <- mydim[1]; m <- mydim[2];
}else{
n <- length(obj); m <- 1;
}
if(is.matrix(obj)) obj<-as.vector(obj);
if(typeof(obj)=="language") obj<-toString(obj);
if(typeof(obj)=="logical") obj<-as.character(obj);
if(is.vector(obj) && is.numeric(obj)){
xmlcode<-paste(xmlcode,"<variable name=\"",varname,"\" type=\"numeric\" n=\"", n, "\" m=\"", m, "\">",sep="");
for (i in obj){
xmlcode<-paste(xmlcode,"<v>",sep="");
xmlcode<-paste(xmlcode,toString(i),sep="");
xmlcode<-paste(xmlcode,"</v>",sep="");
}
xmlcode<-paste(xmlcode,"</variable>\n",sep="");
}
if(is.vector(obj) && is.character(obj)){
xmlcode<-paste(xmlcode,"<variable name=\"",varname,"\" type=\"character\">\n",sep="");
for (i in obj){
xmlcode<-paste(xmlcode,"<v>",sep="");
xmlcode<-paste(xmlcode,toString(i),sep="");
xmlcode<-paste(xmlcode,"</v>",sep="");
}
xmlcode<-paste(xmlcode,"</variable>\n");
}
return(xmlcode);
}
makexml<-function(obj,name=""){
xmlcode<-"<?xml version=\"1.0\"?>\n";
xmlcode<-concat(xmlcode,"<root>\n");
if(!is.list(obj)){
xmlcode<-makevectorxml(xmlcode,obj,name);
}
else{
objnames<-names(obj);
for (i in 1:length(obj)){
xmlcode<-makevectorxml(xmlcode,obj[[i]],cleanNames(objnames[[i]]));
}
}
xmlcode<-concat(xmlcode,"</root>\n");
return(xmlcode);
}
X<-c(##100 doubles);
library(logcondens)
ols <- rlogcon(40,000, sort(X))
cat(makexml(obj=ols, name="ols"), file="C:/Users/##/AppData/Local/Temp/Routput8804446513483695061")
40,000 shold be 40000 in your code.
There are two ways in which a file remains empty:
there is an error in R code
the result is NULL or NA
I recommend you to use tryCach in R
ols <- tryCatch({
rlogcon(40,000, sort(X))
}, error = function(e) {
-1
})
And at the end if ols equlas -1, you'll know that there was an error in R

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

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.

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