Can not read excel file in javafx when it converted to JAR - excel

I am using Apache POI for reading excel file (in xls and xlsx format).
It runs fine in IDE (I am using IntelliJ), but when I make the project to JAR, it can't read the excel file. I tried by giving full path of excel file, but not working.
File name spelling is right, file is not protected or read only format. Everything is good until I run JAR.
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(Unknown Source)
at com.sun.javafx.application.LauncherImpl.launchApplication(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at sun.launcher.LauncherHelper$FXHelper.main(Unknown Source)
Caused by: java.lang.NoClassDefFoundError: org/apache/poi/hssf/usermodel/HSSFWorkbook
at TakeInput.Take(TakeInput.java:25)
at MainGUI.main(MainGUI.java:53)
... 11 more
Caused by: java.lang.ClassNotFoundException: org.apache.poi.hssf.usermodel.HSSFWorkbook
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
... 13 more
Exception running application MainGUI
Here is my TakeInput Class:
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import java.io.*;
import java.util.Arrays;
import java.util.Comparator;
import java.util.StringTokenizer;
public class TakeInput {
public void Take() throws Exception{
System.out.println("Inside TakeInput class..");
File f = new File("courses.xls");
FileInputStream fs = new FileInputStream(f);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
int CSECourseCounter=0;
for(int i=0;i<=sheet.getLastRowNum();i++){
String tempCode = sheet.getRow(i).getCell(0).getStringCellValue();
StringTokenizer tok = new StringTokenizer(tempCode);
String codeTok=tok.nextToken();
if(codeTok.equals("CSE") || codeTok.equals("CSI")) {
CSECourseCounter++;
}
}
CourseInfo[] courses = new CourseInfo[CSECourseCounter];
for(int i=0;i<CSECourseCounter;i++)
courses[i]=new CourseInfo();
System.out.println(sheet.getLastRowNum());
for(int i=0,j=0;i<=sheet.getLastRowNum();i++){
String tempCode = sheet.getRow(i).getCell(0).getStringCellValue();
StringTokenizer tok = new StringTokenizer(tempCode);
String codeTok=tok.nextToken();
if(codeTok.equals("CSE") || codeTok.equals("CSI")) {
courses[j].code = sheet.getRow(i).getCell(0).getStringCellValue();
courses[j].title = sheet.getRow(i).getCell(1).getStringCellValue();
courses[j].section = sheet.getRow(i).getCell(2).getStringCellValue();
courses[j].day = sheet.getRow(i).getCell(4).getStringCellValue();
courses[j].time = sheet.getRow(i).getCell(5).getStringCellValue();
//courses[i].room = sheet.getRow(i).getCell(6).getNumericCellValue();
//System.out.println(courses[j].code);
j++;
//CSECourseCounter++;
}
}
Arrays.sort(courses, new Comparator<CourseInfo>() {
#Override
public int compare(CourseInfo o1, CourseInfo o2) {
return o1.title.compareTo(o2.title);
}
});
System.out.println("CSE courses = "+CSECourseCounter);
for(int i=0;i<CSECourseCounter;i++){
courses[i].setCampus();
courses[i].setLabCLassAndTimeSlot();
courses[i].setDay();
}
//***************************** CourseInfo to a linked list ******************
for(int i=0;i<courses.length;i++){
CourseToLinkedList temp = AddSearchCourse.searchCourse(courses[i].code);
if(temp==null) {
AddSearchCourse.addCourse(courses[i].title,courses[i].code,courses[i].islabClass);
CourseToLinkedList temp1 = AddSearchCourse.searchCourse(courses[i].code);
temp1.addSections(courses[i].code,courses[i].title,courses[i].section,courses[i].day,courses[i].time,
courses[i].timeStart,courses[i].timeEnd,courses[i].room,
courses[i].faculty,courses[i].credit,courses[i].assigned,
courses[i].campus,courses[i].dept,courses[i].islabClass,
courses[i].timeSlot,courses[i].labTimeSlot,courses[i].day1,courses[i].day2
);
}
else{
CourseToLinkedList temp1 = AddSearchCourse.searchCourse(courses[i].code);
temp1.addSections(courses[i].code,courses[i].title,courses[i].section,courses[i].day,courses[i].time,
courses[i].timeStart,courses[i].timeEnd,courses[i].room,
courses[i].faculty,courses[i].credit,courses[i].assigned,
courses[i].campus,courses[i].dept,courses[i].islabClass,
courses[i].timeSlot,courses[i].labTimeSlot,courses[i].day1,courses[i].day2
);
}
}
System.out.println("outside try catch..");
}
}
I put a copy of this excel file which is in the project folder to that folder where JAR file situated. No problem with location.

As I can see the logs, this issue may happen because of dependency jars for your code. try to add the jar(may be 'jakarta-poi-version.jar') having class 'HSSFWorkbook' into your class path and then try to run it again.

Related

SparkHadoopWriter Failing with NPE at UserProvider

I am using Spark to write data to Hbase, I can read data just fine but write is failing with following exception. I found similar issue that got resolved by adding *site.xml and hbase JARs. But it is not working for me. I am trying to read data from a table write data to another table. i can read data just fine but getting exception while writing.
JavaPairRDD<ImmutableBytesWritable, Put> tablePuts = hBaseRDD.mapToPair(new PairFunction<Tuple2<ImmutableBytesWritable, Result>, ImmutableBytesWritable, Put>() {
#Override
public Tuple2<ImmutableBytesWritable, Put> call(Tuple2<ImmutableBytesWritable, Result> results) throws Exception {
byte[] accountId = results._2().getValue(Bytes.toBytes(COLFAMILY), Bytes.toBytes("accountId"));
String rowKey = new String(results._2().getRow();
String accountId2 = (Bytes.toString(accountId));
String prefix = getMd5Hash(rowKey);
String newrowKey = prefix + rowKey;
Put put = new Put( Bytes.toBytes(newrowKey) );
put.addColumn(Bytes.toBytes("def"), Bytes.toBytes("accountId"), accountId);
}
});
Job newAPIJobConfiguration = Job.getInstance(conf);
newAPIJobConfiguration.getConfiguration().set(TableOutputFormat.OUTPUT_TABLE, OUT_TABLE_NAME);
newAPIJobConfiguration.setOutputFormatClass(org.apache.hadoop.hbase.mapreduce.TableOutputFormat.class);
newAPIJobConfiguration.setOutputKeyClass(org.apache.hadoop.hbase.io.ImmutableBytesWritable.class);
newAPIJobConfiguration.setOutputValueClass(org.apache.hadoop.io.Writable.class);
tablePuts.saveAsNewAPIHadoopDataset(newAPIJobConfiguration.getConfiguration());
Exception in thread "main" java.lang.NullPointerException
at org.apache.hadoop.hbase.security.UserProvider.instantiate(UserProvider.java:123)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:214)
at org.apache.hadoop.hbase.client.ConnectionFactory.createConnection(ConnectionFactory.java:119)
at org.apache.hadoop.hbase.mapreduce.TableOutputFormat.checkOutputSpecs(TableOutputFormat.java:177)
at org.apache.spark.internal.io.HadoopMapReduceWriteConfigUtil.assertConf(SparkHadoopWriter.scala:387)
at org.apache.spark.internal.io.SparkHadoopWriter$.write(SparkHadoopWriter.scala:71)
at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply$mcV$sp(PairRDDFunctions.scala:1083)
at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply(PairRDDFunctions.scala:1081)
at org.apache.spark.rdd.PairRDDFunctions$$anonfun$saveAsNewAPIHadoopDataset$1.apply(PairRDDFunctions.scala:1081)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:151)
at org.apache.spark.rdd.RDDOperationScope$.withScope(RDDOperationScope.scala:112)
at org.apache.spark.rdd.RDD.withScope(RDD.scala:363)
at org.apache.spark.rdd.PairRDDFunctions.saveAsNewAPIHadoopDataset(PairRDDFunctions.scala:1081)
at org.apache.spark.api.java.JavaPairRDD.saveAsNewAPIHadoopDataset(JavaPairRDD.scala:831)
at com.voicebase.etl.s3tohbase.HbaseScan2.main(HbaseScan2.java:148)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:879)
at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:197)
at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:227)
at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:136)
at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

NoClassDefFoundError on Kotlin class in JUnit test at runtime

My Kotlin class compiles and runs on an emulator without a problem. But when I test it, Android Studio says the class is not found.
Here's the Kotlin class and an example of using it:
// Product.kt
data class Product(
val id: Int,
val name: String,
val manufacturer: String)
// MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Product product = new Product(0, "foo", "bar");
TextView textView = findViewById(R.id.textView);
textView.setText(product.getName());
}
}
However when I write a JUnit test for the Kotlin class:
// ProductTest.java
public class ProductTest {
#Test
public void getName() throws Exception {
Product p = new Product(0, "foo", "bar");
assertThat(p.getName(), equalTo("foo"));
}
}
Android Studio compiles the code, but refuses to run the test:
java.lang.NoClassDefFoundError: com/example/Product
at com.example.ProductTest.getName(ProductTest.java:15)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMainV2.main(AppMainV2.java:131)
Caused by: java.lang.ClassNotFoundException: com.example.Product
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 28 more
Here comes the dependencies section in the module-level build.gradle:
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
testCompile "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
testCompile 'junit:junit:4.12'
}
What did I do wrong?
The solution is to create a new task in the module build.gradle file.
android {
task copyTestClasses(type: Copy) {
from "build/tmp/kotlin-classes/debugUnitTest"
into "build/intermediates/classes/debug"
}
Then add that task to the "Before launch" section of the test run configuration.
This currently doesn't work with the latest tools. There is an open issue for this in the Jetbrains tracker.
This is an open issue, I guess it will be fixed soon:
https://youtrack.jetbrains.com/issue/KT-17951
https://issuetracker.google.com/issues/38454212
Meanwhile, you can use the following workaround:
task copyTestClasses(type: Copy) {
from "build/tmp/kotlin-classes/debugUnitTest"
into "build/intermediates/classes/debug"
}
task copySdkClasses(type: Copy) {
from "build/tmp/kotlin-classes/debug"
into "build/intermediates/classes/debug"
}
Add it to your Gradle file (after android {...} section)
After that, open your tests configuration and add new "before launch" step which will execute those tasks:
Someone confirmed this bug has been fixed in Android Studio 3 Canary 3: https://issuetracker.google.com/issues/38454212

DrJava scriptengine doesn't work

I try to evaluate math expression in string form using scriptengine, but it throws me NullPointerException
java.lang.NullPointerException
at Math.main(Math.java:12)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
Here is the code:
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Math{
public static void main(String[] args){
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine jsEngine = mgr.getEngineByName("JavaScript");
try {
System.out.println("scriptEngine result: "+jsEngine.eval("{2+4*3*[1+(1+2+4)]}"));
} catch (ScriptException ex) {
Logger.getLogger(Math.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
i tried the same code in netbeans and it works, but i also need it to work in DrJava development environment.
Is it possible to resolve this or is there any other library that can evaluate string like this with combination of all parenthesis "{[()]}"?

getResourceAsStream() doesn't see resource

I want to unpack resources from my jar file. The structure of jar looks like this:
my.jar
META-INF
resources
my.exe
my.dll
my
namespace
UnpackResourceFromThisClass.class
I want to unpack my.exe and my.dll from jar file. I tried to unpack those files using this code:
try {
InputStream is = getClass().getResourceAsStream("/resources/my.exe")
OutputStream os = new FileOutputStream(new File(destDir))
Files.copy(is, os)
os.close()
is.close()
}
catch (NullPointerException e) {
e.printStackTrace();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (SecurityException e) {
e.printStackTrace();
}
but it doesn't work. Any ideas? As a result I get this error:
java.lang.NullPointerException
at java.nio.file.Files.provider(Files.java:65)
at java.nio.file.Files.newInputStream(Files.java:106)
at java.nio.file.Files.copy(Files.java:2884)
at java_nio_file_Files$copy.call(Unknown Source)
at org.codehaus.groovy.runtime.callsite.CallSiteArray.defaultCall(CallSiteArray.java:42)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:108)
at org.codehaus.groovy.runtime.callsite.AbstractCallSite.call(AbstractCallSite.java:120)
at pl.ydp.gradle.Is2k8Task.getResources(Is2k8Task.groovy:84)
at pl.ydp.gradle.Is2k8Task.build(Is2k8Task.groovy:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.codehaus.groovy.reflection.CachedMethod.invoke(CachedMethod.java:90)
at groovy.lang.MetaMethod.doMethodInvoke(MetaMethod.java:233)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:1047)
at groovy.lang.MetaClassImpl.invokeMethod(MetaClassImpl.java:877)
at org.gradle.api.internal.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:216)
This is groovy code which will be used in gradle custom task.
You seem to be writing Java... Not sure if this will get you round your problem, but the above could be written in Groovy as:
this.getClass().getResource( '/resources/my.exe' ).withInputStream { ris ->
new File( destDir ).withOutputStream { fos ->
fos << ris
}
}
Delete the leading slash, getResourceAsStream will use the absolute path if the first character is a slash.

SMB connection with java

Hi i have created a test program to connect with SMB protocol. My motive is to create a test.txt file on a shared location like String path="smb://192.168.143.134/rtf2xml/"+sharedFolder+"/test.txt";
But when I try to run my program (below is the code sample)
import java.io.IOException;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
public class Test {
/**
* #param args
* #throws IOException
*/
public static void main(String[] args) throws IOException {
String user = "abc";
String pass ="123456";
String sharedFolder="INPUT";
String path="smb://192.168.143.134/rtf2xml/"+sharedFolder+"/test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("192.168.143.134",user, pass);
SmbFile smbFile = new SmbFile(path, auth);
smbFile.createNewFile();
SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
smbfos.write("testing....and writing to a file".getBytes());
System.out.println("completed ...nice !");
}
}
It is throwing exception
Exception in thread "main" jcifs.smb.SmbException: Failed to negotiate
jcifs.smb.SmbException: Timeout trying to open socket
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at jcifs.netbios.NbtSocket.<init>(NbtSocket.java:59)
at jcifs.smb.SmbTransport.run(SmbTransport.java:342)
at java.lang.Thread.run(Unknown Source)
at jcifs.smb.SmbTransport.start(SmbTransport.java:315)
at jcifs.smb.SmbTransport.negotiate0(SmbTransport.java:865)
at jcifs.smb.SmbTransport.negotiate(SmbTransport.java:941)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:119)
at jcifs.smb.SmbFile.connect(SmbFile.java:827)
at jcifs.smb.SmbFile.connect0(SmbFile.java:797)
at jcifs.smb.SmbFile.open0(SmbFile.java:852)
at jcifs.smb.SmbFile.createNewFile(SmbFile.java:2265)
at Test.main(Test.java:22)
at jcifs.smb.SmbTransport.negotiate(SmbTransport.java:947)
at jcifs.smb.SmbTree.treeConnect(SmbTree.java:119)
at jcifs.smb.SmbFile.connect(SmbFile.java:827)
at jcifs.smb.SmbFile.connect0(SmbFile.java:797)
at jcifs.smb.SmbFile.open0(SmbFile.java:852)
at jcifs.smb.SmbFile.createNewFile(SmbFile.java:2265)
at Test.main(Test.java:22)
How to get rid of this?
But l think you have to make sure that the destination server(192.168.143.134) is up and alive.
you can write it the following way, since the IP in included in the smb link.
public static void main(String[] args) throws IOException {
String user = "abc";
String pass ="123456";
String sharedFolder="INPUT";
String path="smb://192.168.143.134/rtf2xml/"+sharedFolder+"/test.txt";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("",user, pass);//note here
SmbFile smbFile = new SmbFile(path, auth);
smbFile.createNewFile();
SmbFileOutputStream smbfos = new SmbFileOutputStream(smbFile);
smbfos.write("testing....and writing to a file".getBytes());
System.out.println("completed ...nice !");
}
....

Resources