I am working on a project that is going to do serial communication and I want to package the java-simple-serial-connector (jssc) as part of the project.
I don't want to install the jssc.jar file on the system because this project is going to be run a bunch of different machines so it would be much easier to package the .jar with my executable .jar.
I have added jssc.jar to my build path but when I run the program (note it isn't finished yet) I get the following error:
Exception in thread "main" java.lang.NoClassDefFoundError: SerialCommunication
Caused by: java.lang.ClassNotFoundException: SerialCommunication
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Here is my code
import jssc.*;
public class SerialCommunication {
public static void main(String[] args) {
String[] portNames;
if(System.getProperty("os.name").equals("Mac OS X")){
portNames = SerialPortList.getPortNames("/dev/");
System.out.println("OS X");
} else {
portNames = SerialPortList.getPortNames("COM");
System.out.println("Windows");
}
for (int i = 0; i < portNames.length; i++) {
System.out.println(portNames[i]);
}
SerialPort serialPort = new SerialPort(portNames[0]);
try {
serialPort.openPort();// Open serial port
serialPort.setParams(SerialPort.BAUDRATE_9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
serialPort.writeBytes("This is a test string".getBytes());
serialPort.closePort();// Close serial port
} catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
Under the build path I added the jssc.jar as a library and as an external library. Both of them fail in the same way. I have also cleaned the solution.
EDIT:
My file structure is the following
/src
SerialCommunication.java
/lib
jssc.jar
Here is my build path
How do I get the program to execute properly with the jssc.jar in the path?
Is the JRE you are using for running the program >= than the JDK with which jssc.jar was compiled?
Related
I have a very simple Java program that connects to a PostgreSQL database to find if there are any databases by a specific naming pattern. When I find them I'm trying to delete them through the Java JDBC code. The Java code works fine when I manually run it, but what I'm trying to achieve is to automate this Java call through a batch file.
Can anyone throw any light on this? It's been frustratingly long that I'm struggling to find a solution for this.
My Java Code:
public class CreateBatchToCleanNamedDBs {
public static void main(String[] args) {
Connection connection = null;
BufferedReader input = null;
try {
String line;
RandomAccessFile batchFile = new RandomAccessFile("C:/batch.sql", "rw");
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "Welcome12!");
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select datname from pg_database where datname like 'sample_db%';");
while (rs.next()) {
batchFile.writeBytes("DROP DATABASE " + rs.getString("datname") + ";\n");
System.out.println(rs.getString("datname"));
}
Process batchProcess = Runtime.getRuntime().exec("C:/Program Files/PostgreSQL/9.5/bin/psql -h localhost -U postgres -f C:/batch.sql");
input = new BufferedReader(new InputStreamReader(batchProcess.getInputStream()));
if(batchFile.length()!= 0) {
while ((line = input.readLine()) != null) {
System.out.println(line);
}
}
batchFile.close();
} catch(Exception exception) {
System.out.println("Exception caught: " + exception);
exception.printStackTrace();
} finally {
try {
connection.close();
} catch (SQLException sqlexception) {
sqlexception.printStackTrace();
}
}
}
}
My Batch file script:
#echo off
setlocal
if not defined JAVA_HOME goto :NoJavaFound
"%JAVA_HOME%\bin\java.exe" -jar "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs
goto :end
:NoJavaFound
echo JAVA_HOME environment variable is not set.
goto :end
:end
endlocal
I have both the jar file (my Java code, shown above) and the batch script file on the Desktop (same folder) and attempting to run - but I'm getting a NullPointerException, as my java code is missing the PostgreSQL jdbc driver. I've tried to add that as a parameter in multiple ways, but nothing works.
Error details:
C:\Users\pavan>C:\Users\pbonda\Desktop\deletedb.bat
Exception caught: java.lang.ClassNotFoundException: org.postgresql.Driver
java.lang.ClassNotFoundException: org.postgresql.Driver
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)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:20)
Exception in thread "main" java.lang.NullPointerException
at connect.postgresql.CreateBatchToCleanNamedDBs.main(CreateBatchToCleanNamedDBs.java:45)
When calling java with an executable jar, the classpath provided to the java command is ignored.
You should either :
explicitly call the target class, with your jar in the classPath (i.e. "%JAVA_HOME%\bin\java.exe" -cp "%~dp0\deletedb.jar;%~dp0\postgresql-9.4.1207.jar;" connect.postgresql.CreateBatchToCleanNamedDBs)
specify the jar's classpath dependencies in its MANIFEST.MF file as well as its main class ; then you can execute the jar with java -jar. See this Oracle doc
add the postgresql jar into the your current jre's extentions library directory, or in the global extentions library directory. See this Oracle doc Deprecated in JavaSE 8, dropped in JavaSE9
try with:
"%JAVA_HOME%\bin\java.exe" -cp "%~dp0\postgresql-9.4.1207.jar;%~dp0\deletedb.jar" connect.postgresql.CreateBatchToCleanNamedDBs
I have a problem with the API Sphinx4 and I can't figure out why it doesn't work.
I try to write a little class for capture the voice of an user and write his speaking on a file.
1) I have create a new java project on Eclispe.
2) I have create the class TranscriberDemo.
3) I have create a folder "file".
4) I have copy the folder "en-us" and the files "cmudict-en-us.dict", "en-us.lm.dmp", "10001-90210-01803.wav" on the folder "file".
5) I don't use maven, so I have just include the jar files "sphinx4-core-1.0-SNAPSHOT.jar" and "sphinx4-data-1.0-SNAPSHOT.jar".
you can download them here:
core: https://1fichier.com/?f3y6vqupdr
data: https://1fichier.com/?lpzz8jyerv
I know that the source code is available
here: https://github.com/erka/sphinx-java-api
or here: http://sourceforge.net/projects/cmusphinx/files/sphinx4
But I don't use maven so I can't compile them.
My class:
import java.io.InputStream;
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.SpeechResult;
import edu.cmu.sphinx.api.StreamSpeechRecognizer;
import edu.cmu.sphinx.result.WordResult;
public class TranscriberDemo
{
public static void main(String[] args) throws Exception
{
System.out.println("Loading models...");
Configuration configuration = new Configuration();
// Load model from the jar
configuration.setAcousticModelPath("file:en-us");
configuration.setDictionaryPath("file:cmudict-en-us.dict");
configuration.setLanguageModelPath("file:en-us.lm.dmp");
StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration);
InputStream stream = TranscriberDemo.class.getResourceAsStream("file:10001-90210-01803.wav");
stream.skip(44);
// Simple recognition with generic model
recognizer.startRecognition(stream);
SpeechResult result;
while ((result = recognizer.getResult()) != null)
{
System.out.format("Hypothesis: %s\n", result.getHypothesis());
System.out.println("List of recognized words and their times:");
for (WordResult r : result.getWords())
{
System.out.println(r);
}
System.out.println("Best 3 hypothesis:");
for (String s : result.getNbest(3))
System.out.println(s);
}
recognizer.stopRecognition();
}
}
My log:
Loading models...
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Function
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:191)
at edu.cmu.sphinx.util.props.ConfigurationManager.getPropertySheet(ConfigurationManager.java:91)
at edu.cmu.sphinx.util.props.ConfigurationManagerUtils.listAllsPropNames(ConfigurationManagerUtils.java:556)
at edu.cmu.sphinx.util.props.ConfigurationManagerUtils.setProperty(ConfigurationManagerUtils.java:609)
at edu.cmu.sphinx.api.Context.setLocalProperty(Context.java:198)
at edu.cmu.sphinx.api.Context.setAcousticModel(Context.java:88)
at edu.cmu.sphinx.api.Context.<init>(Context.java:61)
at edu.cmu.sphinx.api.Context.<init>(Context.java:44)
at edu.cmu.sphinx.api.AbstractSpeechRecognizer.<init>(AbstractSpeechRecognizer.java:37)
at edu.cmu.sphinx.api.StreamSpeechRecognizer.<init>(StreamSpeechRecognizer.java:35)
at TranscriberDemo.main(TranscriberDemo.java:27)
Caused by: java.lang.ClassNotFoundException: com.google.common.base.Function
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 12 more
Thanks for your help =)
There are multiple issues with your code and your actions:
3) I have create a folder "file".
Not needed
4) I have copy the folder "en-us" and the files "cmudict-en-us.dict", "en-us.lm.dmp", "10001-90210-01803.wav" on the folder "file".
Not needed, you already have models as part of sphinx4-data package.
5) I don't use maven, so I have just include the jar files "sphinx4-core-1.0-SNAPSHOT.jar" and "sphinx4-data-1.0-SNAPSHOT.jar".
This is very wrong because you took outdated jars from unauthorized location. The right place to download jars is listed in tutorial http://oss.sonatype.org
https://oss.sonatype.org/service/local/repositories/snapshots/content/edu/cmu/sphinx/sphinx4-core/1.0-SNAPSHOT/sphinx4-core-1.0-20150223.210646-7.jar
https://oss.sonatype.org/service/local/repositories/snapshots/content/edu/cmu/sphinx/sphinx4-data/1.0-SNAPSHOT/sphinx4-data-1.0-20150223.210601-7.jar
You took malicious jars from some random website which might have a virus or rootkit in them.
here: https://github.com/erka/sphinx-java-api
This is a wrong link too. The correct link is http://github.com/cmusphinx/sphinx4
InputStream stream = TranscriberDemo.class.getResourceAsStream("file:10001-90210-01803.wav");
Here you use file: URL scheme which points to files in inappropriate context. If you want to create InputStream from file do like this:
InputStream stream = new FileInputStream(new File("10001-90210-01803.wav"));
Exception in thread "main" java.lang.NoClassDefFoundError: com/google/common/base/Function
This error is caused by the fact you took a jar from other place and it said you need additional dependencies. When you see ClassDefFoundError it means you need to add additional jar into your classpath. With official sphinx4 you should not see this error.
Solved.
In fact it was a silly mistake...
Thank you #Nikolay for your answer. I already accept your answer but I resume the process here:
1) Download the sphinx4-core and sphinx4-data jars from https://oss.sonatype.org/#nexus-search;quick~sphinx4.
2) Include them in your project.
3) Test your code.
import edu.cmu.sphinx.api.Configuration;
import edu.cmu.sphinx.api.LiveSpeechRecognizer;
import edu.cmu.sphinx.api.SpeechResult;
public class SpeechToText
{
public static void main(String[] args) throws Exception
{
Configuration configuration = new Configuration();
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
LiveSpeechRecognizer recognizer = new LiveSpeechRecognizer(configuration);
recognizer.startRecognition(true);
SpeechResult result;
while ((result = recognizer.getResult()) != null)
{
System.out.println(result.getHypothesis());
}
recognizer.stopRecognition();
}
}
And that is all!
If you need the source code of Sphinx4: https://github.com/cmusphinx/sphinx4
I am making a project to run C, C++ and Java, from within Java code itself. It works absolutely fine for Java, and the problem is faced when compiling and executing C and C++ files.
I got my compilation right with this code and I can get the executable file generated in my specified path. But now when I run the executable binary from ProcessBuilder I get an error saying that 'file was not found'. Please see to the code and tell me what is going wrong and where??
public void processCode(String path,String lang)throws IOException
{
String cmd="",s=null,out=null,file="";
totalTime=0;
ProcessBuilder process=new ProcessBuilder();
process.directory(new File(path));
if(lang.equals("c")||lang.equals("cpp"))
{
cmd=threadNum+".exe";
process.command(cmd);
}
else if(lang.equals("java"))
{
cmd="java";
file="Main"+threadNum;
process.command(new String[]{cmd,file});
}
process.redirectInput(new File(PATH+"Input\\" + prob + ".txt"));
process.redirectOutput(new File(PATH+"Output.txt"));
Process p=process.start();
long start=System.currentTimeMillis();
while (true)
{
try{
if(p.exitValue()==0)
{
totalTime=(int)(System.currentTimeMillis()-start);
break;
}
}
catch (Exception e)
{
}
if(System.currentTimeMillis()-start>2000)
{
res=1;
p.destroy();
break;
}
}
if(res!=1)
{
compareFile();
}
}
The method is called from here
And the error generated is :
Exception in thread "main" java.io.IOException: Cannot run program "19.exe" (in directory "C:\wamp\www\usercodes\lokesh"): CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
at Contest.processCode(Main.java:202)
at Contest.compileCode(Main.java:180)
at Contest.makeFile(Main.java:157)
at Contest.main(Main.java:53)
at Main.main(Main.java:15)
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 com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:188)
at java.lang.ProcessImpl.start(ProcessImpl.java:132)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1021)
... 10 more
Setting the directory of a ProcessBuilder does not have any effect on where the system will look for the executable when it tries to start a process. It merely sets the current working directory of the newly-created process to this directory, should it be able to launch a process successfully. Your program 19.exe may well exist in C:\wamp\www\usercodes\lokesh, but unless this folder is on the PATH, the system will not be able to start your process.
Try running the process using the full path of the executable instead of just 19.exe.
It does have to be said that the error message is somewhat misleading. It says that it couldn't find your executable, and then it says 'in directory ...', which implies that that was where it was looking for it.
I am attempting to run the following Java code on an Ubuntu system. The code should create a blank PDF file using the pdfbox class:
import org.apache.pdfbox.pdmodel.*;
import java.io.*;
public class BlankPDF {
public static void main(String[] args) {
PDDocument doc = null;
try{
doc = new PDDocument();
} catch (IOException ie){
System.out.println(ie);
}
doc.addPage(new PDPage());
try{
doc.save("Empty PDF.pdf");
doc.close();
} catch (Exception io){
System.out.println(io);
}
}
}
I have the following class dependencies in the same directory as the script:
pdfbox-1.7.0.jar
jempbox-1.7.0.jar
fontbox-1.7.0.jar
commons-logging-1.1.1.jar
I used the following command to compile the script:
sudo javac BlankPDF.java -classpath pdfbox-1.7.0.jar:fontbox-1.7.0.jar:jempbox-1.7.0.jar:commons-logging-1.1.1.jar
Which returned no output and created a .class file (indicating that the compilation worked correctly?)
But when I attempt to run the code using the following command:
sudo java BlankPDF -classpath pdfbox-1.7.0.jar:fontbox-1.7.0.jar:jempbox-1.7.0.jar:commons-logging-1.1.1.jar
I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/pdfbox/pdmodel/PDDocument
at BlankPDF.main(BlankPDF.java:15)
Caused by: java.lang.ClassNotFoundException: org.apache.pdfbox.pdmodel.PDDocument
at java.net.URLClassLoader$1.run(URLClassLoader.java:217)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:205)
at java.lang.ClassLoader.loadClass(ClassLoader.java:321)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:294)
at java.lang.ClassLoader.loadClass(ClassLoader.java:266)
... 1 more
What am I missing?
The name of the class must be the last argument to java. The flags must precede it. If you put flags at the end of the command lines, as here, they are ignored. So:
java -classpath .:pdfbox-1.7.0.jar:fontbox-1.7.0.jar:jempbox-1.7.0.jar:commons-logging-1.1.1.jar BlankPDF
With ref to above answer,don't forget to add current directory (with dot sign) as well in command with jars in classpath
java -classpath hello.jar:. SampleProgram
I modified a Java code in Eclipse on my laptop with a Windows O.S. Now I have to run the code on a linux O.S. via SSH. I copied all the files and I tried to compile the code. The compilation went well, so there were no errors in the code. Anyway, when I tried to run it, the following errors appeared on the shell:
[ac6411#epigenetic models]$ java TanaModel
Exception in thread "main" java.lang.NoClassDefFoundError: TanaModel (wrong name: models/TanaModel)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:620)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:124)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:260)
at java.net.URLClassLoader.access$000(URLClassLoader.java:56)
at java.net.URLClassLoader$1.run(URLClassLoader.java:195)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:188)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:276)
at java.lang.ClassLoader.loadClass(ClassLoader.java:251)
at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
Do you know what kind of the problem is?I'm new in Java coding, so I don't know how to solve it. Thank you.
wrong name: models/TanaModel
This means it expected to find TanaModel.class under the models directory, but found it somewhere else (maybe the current directory?). Put the class file in a the models directory, and run it as
java models.TanaModel
Java expects class files to be organized in directories that mirror the package structure you used in your source code.
java.lang.NoClassDefFoundError: TanaModel (wrong name: models/TanaModel) at
What command did you run, I'm guessing java TanaModel ?
Most likely your TanaModel is declared to be in package models;
Try calling it like this:
java models.TanaModel
If it is a Eclipse security issue, this would help.
//Java Code
try
{
AccessController.doPrivileged(new PrivilegedAction<Object>()
{
public Object run()
{
try
{
// Insert code here to do required action (get or open file)
}
catch (Exception e)
{
// Insert code to catch exception from trying to do above action
}
}
}
);
}
catch(Exception e)
{
// Insert code to catch failed doPrivileged()
}
When you try to run your program, try calling it like this:
java models.TanaModel