default directory must be absolute - java

My code calls the methods in the log4j package:
org.apache.log4j.PropertyConfigurator.configure("log4j.properties")
There is no problem running on Windows system and Linux virtual machine. However, when running on a Linux virtual machine provided by the company, the following error occurs, as following picture shows:
Where do I start to resolve it?
Supplement:
this is my code:
public static void main(String[] args) {
PropertyConfigurator.configure(configDir + File.separator + "log4j.properties");
if(log.isDebugEnabled()) {
log.debug("load completeļ¼š" + configDir + File.separator + "log4j.properties");
}
}
The first line of execution reports an error, error is:
Exception in thread "main" java.lang.ExceptionInInitializerError
...
at org.apache.log4j.PropertyConfigurator.configure(PropertyConfigurator.java:315)
at com.dcits.provider.BaffleProvider.main(BaffleProvider.java:29)
Caused by: java.lang.RuntimeException: default directory must be absolute
...

The default FileSystem can not be constructed when the user directory system property (i.e "user.dir"), is NOT an absolute path.
Executing this code in Java 8 on both Windows and AIX generates runtime exceptions similar to that seen by the original poster.
public class RelativeUserDir
{
public static void main(String[] args)
{
// Set the "user.dir" property to the "current directory" relative path
System.setProperty("user.dir", ".");
FileSystems.getDefault();
}
}
Windows:
Exception in thread "main" java.lang.AssertionError: Default directory is not an absolute path
at sun.nio.fs.WindowsFileSystem.<init>(WindowsFileSystem.java:61)
at sun.nio.fs.WindowsFileSystemProvider.<init>(WindowsFileSystemProvider.java:53)
at sun.nio.fs.DefaultFileSystemProvider.create(DefaultFileSystemProvider.java:36)
at java.nio.file.FileSystems$DefaultFileSystemHolder.getDefaultProvider(FileSystems.java:108)
at java.nio.file.FileSystems$DefaultFileSystemHolder.access$000(FileSystems.java:89)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:98)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:96)
at java.security.AccessController.doPrivileged(Native Method)
at java.nio.file.FileSystems$DefaultFileSystemHolder.defaultFileSystem(FileSystems.java:96)
at java.nio.file.FileSystems$DefaultFileSystemHolder.<clinit>(FileSystems.java:90)
at java.nio.file.FileSystems.getDefault(FileSystems.java:176)
at RelativeUserDir.main(RelativeUserDir.java:12)
AIX:
Exception in thread "main" java.lang.ExceptionInInitializerError
at java.lang.J9VMInternals.ensureError(J9VMInternals.java:146)
at java.lang.J9VMInternals.recordInitializationFailure(J9VMInternals.java:135)
at java.nio.file.FileSystems.getDefault(FileSystems.java:187)
at RelativeUserDir.main(RelativeUserDir.java:10)
Caused by: java.lang.RuntimeException: default directory must be absolute
at sun.nio.fs.UnixFileSystem.<init>(UnixFileSystem.java:67)
at sun.nio.fs.AixFileSystem.<init>(AixFileSystem.java:55)
at sun.nio.fs.AixFileSystemProvider.newFileSystem(AixFileSystemProvider.java:62)
at sun.nio.fs.AixFileSystemProvider.newFileSystem(AixFileSystemProvider.java:55)
at sun.nio.fs.UnixFileSystemProvider.<init>(UnixFileSystemProvider.java:68)
at sun.nio.fs.AixFileSystemProvider.<init>(AixFileSystemProvider.java:57)
at java.lang.J9VMInternals.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1773)
at sun.nio.fs.DefaultFileSystemProvider.createProvider(DefaultFileSystemProvider.java:60)
at sun.nio.fs.DefaultFileSystemProvider.create(DefaultFileSystemProvider.java:78)
at java.nio.file.FileSystems$DefaultFileSystemHolder.getDefaultProvider(FileSystems.java:119)
at java.nio.file.FileSystems$DefaultFileSystemHolder.access$000(FileSystems.java:100)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:109)
at java.nio.file.FileSystems$DefaultFileSystemHolder$1.run(FileSystems.java:107)
at java.security.AccessController.doPrivileged(AccessController.java:638)
at java.nio.file.FileSystems$DefaultFileSystemHolder.defaultFileSystem(FileSystems.java:107)
at java.nio.file.FileSystems$DefaultFileSystemHolder.<clinit>(FileSystems.java:101)
... 2 more

When encountering this problem, especially when running under jdk1.7, notice whether the 'user.dir' environment variable has been changed or set. The problem I encountered is that the 'user.dir' was wrongly set by me

Related

Error: Could not find or load main class InputAddress; Caused by: java.lang.NoClassDefFoundError: inputaddress/InputAddress (wrong name: <filename> ) [duplicate]

I wrote a java program to test RESTful web services by using Netbeans7.0.1 and it works fine there. Now I wrote the build.xml file to compile the code and when I try to run the generated .class file I always got this exception:
Exception in thread "main" java.lang.NoClassDefFoundError: ClientREST (wrong name: clientrest/ClientREST)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
Could not find the main class: ClientREST. Program will exit.
The name and path are correct, so any thoughts why I'm getting this exception?
Exception in thread "main" java.lang.NoClassDefFoundError: ClientREST
So, you ran it as java ClientREST. It's expecting a ClientREST.class without any package.
(wrong name: clientrest/ClientREST)
Hey, the class is trying to tell you that it has a package clientrest;. You need to run it from the package root on. Go one folder up so that you're in the folder which in turn contains the clientrest folder representing the package and then execute java clientrest.ClientREST.
You should not go inside the clientrest package folder and execute java ClientREST.
I encountered this error using command line java:
java -cp stuff/src/mypackage Test
where Test.java resides in the package mypackage.
Instead, you need to set the classpath -cp to the base folder, in this case, src, then prepend the package to the file name.
So it will end up looking like this:
java -cp stuff/src mypackage.Test
To further note on Garry's reply: The class path is the base directory where the class itself resides. So if the class file is here -
/home/person/javastuff/classes/package1/subpackage/javaThing.class
You would need to reference the class path as follows:
/home/person/javastuff/classes
So to run from the command line, the full command would be -
java -cp /home/person/javastuff/classes package1/subpackage/javaThing
i.e. the template for the above is
java_executable -cp classpath the_class_itself_within_the_class_path
That's how I finally got mine to work without having the class path in the environment
Probably the location you are generating your classes in doesnt exists on the class path. While running use the jvm arg -verbose while running and check the log whether the class is being loaded or not.
The output will also give you clue as to where the clasess are being loaded from, make sure that your class files are present in that location.
Try the below syntax:
Suppose java File resides here: fm/src/com/gsd/FileName.java
So you can run using the below syntax:
(Make current directory to 'fm')
java src.com.gsd.FileName
Suppose you have class A
and a class B
public class A{
public static void main(String[] args){
....
.....
//creating classB object
new classB();
}
}
class B{
}
this issue can be resolved by moving class B inside of class A and using static keyword
public class A{
public static void main(String[] args){
....
.....
//creating class B
new classB();
static class B{
}
}
Here is my class structure
package org.handson.basics;
public class WithoutMain {
public static void main() {
System.out.println("With main()...");
}
}
To compile this program, I had to use absolute path. So from src/main/java I ran:
javac org/handson/basics/WithoutMain.java
Initially I tried with the below command from basics folder and it didn't work
basics % java WithoutMain
Error: Could not find or load main class WithoutMain
Caused by: java.lang.NoClassDefFoundError: org/handson/basics/WithoutMain (wrong name: WithoutMain)
Later I went back to src\main\java folder and ran the class with relevant package structure, which worked as expected.
java % java org.handson.basics.WithoutMain
With main()...
I also have encountered this error on Windows when using Class.forName() where the class name I use is correct except for case.
My guess is that Java is able to find the file at the path (because Windows paths are case-insensitive) but the parsed class's name does not match the name given to Class.forName().
Fixing the case in the class name argument fixed the error.

cmu sphinx4 java - Runtime exception caused by FileNotFoundException

I have recently made a Java project with Sphinx4. I found this code online, and I slimmed it down to this to test if Sphinx4 was working:
public class App
{
private static final String ACOUSTIC_MODEL =
"resource:/edu/cmu/sphinx/models/en-us/en-us";
private static final String DICTIONARY_PATH =
"resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict";
public static void main(String[] args) throws Exception {
Configuration configuration = new Configuration();
configuration.setAcousticModelPath(ACOUSTIC_MODEL);
configuration.setDictionaryPath(DICTIONARY_PATH);
configuration.setGrammarName("dialog");
LiveSpeechRecognizer jsgfRecognizer =
new LiveSpeechRecognizer(configuration);
jsgfRecognizer.startRecognition(true);
while (true) {
String utterance = jsgfRecognizer.getResult().getHypothesis();
if (utterance.startsWith("hello")) {
System.out.println("Hello back!");
}
else if (utterance.startsWith("exit")) {
break;
}
}
jsgfRecognizer.stopRecognition();
}
}
However, it gave me this error:
Exception in thread "main" java.lang.RuntimeException: Allocation of search manager resources failed
at edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager.allocate(WordPruningBreadthFirstSearchManager.java:247)
at edu.cmu.sphinx.decoder.AbstractDecoder.allocate(AbstractDecoder.java:103)
at edu.cmu.sphinx.recognizer.Recognizer.allocate(Recognizer.java:164)
at edu.cmu.sphinx.api.LiveSpeechRecognizer.startRecognition(LiveSpeechRecognizer.java:47)
at com.weebly.controllingyourcomputer.bartimaeus.App.main(App.java:27)
Caused by: java.io.FileNotFoundException:
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
at sun.net.www.protocol.file.FileURLConnection.connect(FileURLConnection.java:90)
at sun.net.www.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:188)
at java.net.URL.openStream(URL.java:1038)
at edu.cmu.sphinx.linguist.language.ngram.SimpleNGramModel.open(SimpleNGramModel.java:403)
at edu.cmu.sphinx.linguist.language.ngram.SimpleNGramModel.load(SimpleNGramModel.java:277)
at edu.cmu.sphinx.linguist.language.ngram.SimpleNGramModel.allocate(SimpleNGramModel.java:114)
at edu.cmu.sphinx.linguist.lextree.LexTreeLinguist.allocate(LexTreeLinguist.java:334)
at edu.cmu.sphinx.decoder.search.WordPruningBreadthFirstSearchManager.allocate(WordPruningBreadthFirstSearchManager.java:243)
... 4 more
I thought it might be something about it not being able to find the paths for ACOUSTIC_MODEL or DICTIONARY_PATH, so I changed the resource: strings to things like %HOME%\\Downloads\\sphinx4-5prealpha-src\\sphinx4-5prealpha-src\\sphinx4-data\\src\\main\\resources\\edu\\cmu\\sphinx\\models\\en-us or paths with forward slashes or with C:\Users\Username\... but none of the paths worked. I know the paths exist because I copy and pasted them from the properties window of the actual resources.
So my question is: is it some of the code that I deleted from the original source code that is causing this error, is it something wrong with the paths, or is it entirely different?
EDIT
By the way, I am using Maven to build my project. I added the dependencies specified on the Sphinx4 website to my pom.xml, but it didn't work (it didn't recognize imports such as edu.com.sphinx.xxx) so I downloaded the JARs from the website they said to download them from and added them to my projects "Libraries" in my Java Build Path in Eclipse.
is it some of the code that I deleted from the original source code that
is causing this error
Yes, you deleted too much.
To recognize with grammar you need to make three calls:
configuration.setGrammarPath(GRAMMAR_PATH);
configuration.setGrammarName(GRAMMAR_NAME);
configuration.setUseGrammar(true);

Java ProcessBuilder Debugger Netbeans

I am having trouble with the deeper layers of the JVM and its debugging functionality.
What I am trying to do is start a separate java program using ProcessBuilder and let it communicate with my main process. All works fine unless I add the command
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=1044",
to the ProcessBuilder.
Class toExecute = ExampleSimulationController.class;
String javaHome = System.getProperty("java.home");
String javaBin = javaHome
+ File.separator + "bin"
+ File.separator + "java";
String classpath = System.getProperty("java.class.path");
String className = toExecute.getCanonicalName();
ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp",
"-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=1044",
classpath, className);
builder.redirectErrorStream(true);
In adding this line to the ProcessBuilder (with the intention to add debugging functionality to the subprocess as described, for example, here: What are Java command line options to set to allow JVM to be remotely debugged?
I get an exception when trying to read as follows:
BufferedReader mainProcessConsoleOutput = new BufferedReader(new InputStreamReader(mainSimulation.getInputStream()));
and further down:
if(!(line = mainProcessConsoleOutput.readLine()).equals("someText"))
The exception is as follows:
Main Process: Exception in thread "main" java.lang.NoClassDefFoundError: /Users/...[path].../build/classes
Main Process: Caused by: java.lang.ClassNotFoundException: .Users.[same_Path].build.classes
Main Process: at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
Main Process: at java.security.AccessController.doPrivileged(Native Method)
Main Process: at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
Main Process: at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
Main Process: at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
Main Process: at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
Exception in thread "main" java.lang.NullPointerException
at [PacketStructure].SimulationController.main(SimulationController.java:66)
I am using Netbeans as IDE and know about "Attaching a Debugger" and giving it the same port as specified in the command I pass to the ProcessBuilder. However, I don't know when I have to do this - before I specify a breakpoint in the subprocess? Afterwards? So far I did not find any indication that my subprocess is communicating with a debugger in any way.
What seems suspicious to me as well is the fact that the exception is thrown when I try to read from subprocess' stream - and not someplace earlier.
I do use ObjectInputStream and ObjectOutputStream to pass serialized data from one process to the other, but since I cannot debug the subprocess I don't know if that is a potential source of the problem.
I use MacOs.
Since the solution of this problem lies beyond my knowledge of the Java Magic, please help me in solving this riddle.
Thanks,
M
The classpath value must immediately follow the classpath argument.
After a lot of time spent trying to solve the problem I finally did:
ProcessBuilder builder = new ProcessBuilder(javaBin,"-agentlib:jdwp=transport=dt_socket,address=localhost:8000,server=n,suspend=y","-cp", classpath, className);
By adding the "-cp" command after the "-agentlib" command apparently the classpath is matched correctly with the className.
Should I have known that the order in which commands are passed is important?
Thx

Not able to execute an exe file from java using ProcessBuilder

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.

How to load AttachProvider (attach.dll) dynamically

I'm using com.sun.tools.attach from jdk's tools.jar and it need an specified java.library.path env pointing to attach.dll at startup to properly instatiate provider such as WindowsAttachProvider. For some reasons I need to dynamic loading one of bundled attach.dll. I'm try to use some like this:
public static void main(String[] args) throws Exception {
Path bin = Paths.get(System.getProperty("user.dir"),"bin").toAbsolutePath();
switch (System.getProperty("os.arch")) {
case "amd64":
bin = bin.resolve("win64");
break;
default:
bin = bin.resolve("win32");
}
// Dynamic setting of java.library.path only seems not sufficient
System.setProperty("java.library.path", System.getProperty("java.library.path") + File.pathSeparator + bin.toString());
// So I try to manual loading attach.dll. This is not sufficient too.
System.load(bin.resolve("attach.dll").toString());
// I'm using com.sun.tools.attach in my app
new myApp();
}
If I run this out of jdk (in normall jre) it's report to me:
java.util.ServiceConfigurationError: com.sun.tools.attach.spi.AttachProvider:
Provider sun.tools.attach.WindowsAttachProvider could not be instantiated:
java.lang.UnsatisfiedLinkError: no attach in java.library.path
Exception in thread "main" com.sun.tools.attach.AttachNotSupportedException:
no providers installed
at com.sun.tools.attach.VirtualMachine.attach(...
How to install attach provider without specifying -Djava.library.path to point attach.dll at startup?
The API you are using is using loadLibrary(String). It seems you cannot successfully pre-empt (cause it to succeed) this by invoking the more explicit load(String) first.
So you must to specify the path in java.library.path.
That System property is set once early in JVM lifecycle and is not modifiable by standard means.
So the conventional solution will be to pass an appropriate java.library.path when you launch the JVM.
Alternatively, you could look into the hacks to change this property after JVM startup using reflection. I have not tried any of these.
For example, see here:
System.setProperty( "java.library.path", "/path/to/libs" );
Field fieldSysPath = ClassLoader.class.getDeclaredField( "sys_paths" );
fieldSysPath.setAccessible( true );
fieldSysPath.set( null, null );
BTW, I would recommend pre-pending your custom path to the existing path, rather than replacing it.

Categories