JAVA - path issue (works in eclipse, not in cmd) - java

Why the following iniciation works in eclipse:
private static MaxentTagger maxentTagger = new MaxentTagger("c:\\DP\\lemma\\models\\english-left3words-distsim.tagger");
but in command line it throws:
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 org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoa
der.java:58)
Caused by: java.lang.ExceptionInInitializerError
at dp.beans.MySearch.<init>(MySearch.java:122)
at dp.runable.Main.main(Main.java:25)
... 5 more
Caused by: java.lang.IllegalArgumentException: name
at sun.misc.URLClassPath$Loader.findResource(Unknown Source)
at sun.misc.URLClassPath.findResource(Unknown Source)
at java.net.URLClassLoader$2.run(Unknown Source)
at java.net.URLClassLoader$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findResource(Unknown Source)
at java.lang.ClassLoader.getResource(Unknown Source)
at java.net.URLClassLoader.getResourceAsStream(Unknown Source)
at edu.stanford.nlp.io.IOUtils.findStreamInClasspathOrFileSystem(IOUtils.java:370)
at edu.stanford.nlp.io.IOUtils.getInputStreamFromURLOrClasspathOrFileSystem(IOUtils.java:399)
at edu.stanford.nlp.tagger.maxent.MaxentTagger.readModelAndInit(MaxentTagger.java:646)
at edu.stanford.nlp.tagger.maxent.MaxentTagger.<init>(MaxentTagger.java:284)
at edu.stanford.nlp.tagger.maxent.MaxentTagger.<init>(MaxentTagger.java:248)
at dp.data.Settings.<clinit>(Settings.java:80)
... 7 more
Settings.java:80 corresponding with MaxentTagger iniciation..
Is there a different way to declare windows path, which works in both, eclipse and cmd?
update (the findStreamInClasspathOrFileSystem method):
private static InputStream [More ...] findStreamInClasspathOrFileSystem(String name) throws FileNotFoundException
{
String path = null;
if (name.startsWith("/")) {
path = name.substring(1);
}
// - even though this may look like a regular file, it may be a path inside a jar in the CLASSPATH
// - check for this first. This takes precedence over the file system.
InputStream is = null;
if (path != null) {
is = IOUtils.class.getClassLoader().getResourceAsStream(path);
// windows File.separator is \, but getting resources only works with /
if (is == null) {
is = IOUtils.class.getClassLoader().getResourceAsStream(path.replaceAll("\\\\", "/"));
}
}
// if not found in the CLASSPATH, load from the file system
if (is == null) is = new FileInputStream(name);
return is;
}
update: no matter if i change the path to:
"c:/DP/lemma/models/english-left3words-distsim.tagger");
"c:\\\\DP\\\\lemma\\\\models\\\\english-left3words-distsim.tagger");
its behaviour is still the same (works in eclipce, not in cmd)

Your code seems to load a resource from the classath, using the ClassLoader. The path should take the following form:
com/yourcompany/yourapp/english-left3words-distsim.tagger
where com.yourcompany.yourapp is the package where the file resides.
See http://docs.oracle.com/javase/6/docs/api/java/lang/ClassLoader.html#getResource%28java.lang.String%29
EDIT:
The code of IOUtils.getInputStreamFromURLOrClasspathOrFileSystem() passes two badly formatted paths (c:\... and c:/...) to ClassLoader.getResourceAsStream(), and expects this method to simply return null instead of throwing an exception, which is wrong. I would simply decide where I want to load the resource rom: either the classpath (and thus use ClassLosader.getResourceAsStream()) or the file system (and thus use new FileInputStream()).

Related

Loading ontology to extract all the imported name spaces

I am trying to load an ontology saved on my PC. The file format is .n3.
After a lot of work and searching for the possible solutions, I didn't find an appropriate way to load an ontology.
I tried the following code:
import edu.stanford.smi.protegex.owl.ProtegeOWL;
import edu.stanford.smi.protegex.owl.model.OWLModel;
public class Extractor {
public static void main(String[] args) {
String ontologyURI = "file:///C:/acco.n3";
try {
OWLModel owlModel = ProtegeOWL.createJenaOWLModelFromURI(ontologyURI);
System.out.println("Worked");
}catch (Exception exception) {
System.out.println("Error can't upload the ontologie ");
}
}
}
but it always gives me this error:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
at com.hp.hpl.jena.graph.Node.<clinit>(Node.java:35)
at com.hp.hpl.jena.rdf.model.impl.ResourceImpl.fresh(ResourceImpl.java:108)
at com.hp.hpl.jena.rdf.model.impl.ResourceImpl.<init>(ResourceImpl.java:68)
at com.hp.hpl.jena.rdf.model.ResourceFactory$Impl.createResource(ResourceFactory.java:176)
at com.hp.hpl.jena.rdf.model.ResourceFactory.createResource(ResourceFactory.java:69)
at com.hp.hpl.jena.vocabulary.RDF.resource(RDF.java:29)
at com.hp.hpl.jena.vocabulary.RDF.<clinit>(RDF.java:37)
at com.hp.hpl.jena.datatypes.xsd.impl.XMLLiteralType.<clinit>(XMLLiteralType.java:30)
at com.hp.hpl.jena.datatypes.TypeMapper.<clinit>(TypeMapper.java:52)
at edu.stanford.smi.protegex.owl.model.impl.OWLSystemFrames.createRDFSDatatypes(Unknown Source)
at edu.stanford.smi.protegex.owl.model.impl.OWLSystemFrames.createOWLInstances(Unknown Source)
at edu.stanford.smi.protegex.owl.model.impl.OWLSystemFrames.createOWLMetaModel(Unknown Source)
at edu.stanford.smi.protegex.owl.model.impl.OWLSystemFrames.<init>(Unknown Source)
at edu.stanford.smi.protegex.owl.swrl.SWRLSystemFrames.<init>(Unknown Source)
at edu.stanford.smi.protegex.owl.model.impl.AbstractOWLModel.createSystemFrames(Unknown Source)
at edu.stanford.smi.protegex.owl.model.impl.AbstractOWLModel.createSystemFrames(Unknown Source)
at edu.stanford.smi.protege.model.DefaultKnowledgeBase.<init>(DefaultKnowledgeBase.java:79)
at edu.stanford.smi.protegex.owl.model.impl.AbstractOWLModel.<init>(Unknown Source)
at edu.stanford.smi.protegex.owl.jena.JenaOWLModel.<init>(Unknown Source)
at edu.stanford.smi.protegex.owl.jena.JenaKnowledgeBaseFactory.createKnowledgeBase(Unknown Source)
at edu.stanford.smi.protege.model.Project.createDomainKB(Project.java:429)
at edu.stanford.smi.protege.model.Project.createDomainKnowledgeBase(Project.java:447)
at edu.stanford.smi.protegex.owl.jena.creator.OwlProjectFromUriCreator.create(Unknown Source)
at edu.stanford.smi.protegex.owl.ProtegeOWL.createJenaOWLModelFromURI(Unknown Source)
at Extractor.main(Extractor.java:28)
Caused by: java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 25 more
I need your help in solving this error, or perhaps find a way to load ontologies to extract knowledge from them.
Thanks in advance.
Update:
I added the missing dependencies to the class path as #Roddy of the Frozen Peas suggested.
but it gives me the following error:
WARNING: [Local Folder Repository] The specified file must be a directory. (C:\eclipse-workspace\NewEx\plugins\edu.stanford.smi.protegex.owl) -- LocalFolderRepository.update()
Exception in thread "main" java.lang.NoClassDefFoundError: org/protege/editor/owl/model/hierarchy/roots/Relation
at edu.stanford.smi.protegex.owl.jena.parser.TripleProcessor.<init>(Unknown Source)
at edu.stanford.smi.protegex.owl.jena.parser.GlobalParserCache.getTripleProcessor(Unknown Source)
at edu.stanford.smi.protegex.owl.jena.parser.ProtegeOWLParser.loadTriples(Unknown Source)
at edu.stanford.smi.protegex.owl.jena.parser.ProtegeOWLParser.run(Unknown Source)
at edu.stanford.smi.protegex.owl.jena.JenaKnowledgeBaseFactory.loadKnowledgeBase(Unknown Source)
at edu.stanford.smi.protege.model.Project.loadDomainKB(Project.java:1346)
at edu.stanford.smi.protege.model.Project.createDomainKnowledgeBase(Project.java:456)
at edu.stanford.smi.protegex.owl.jena.creator.OwlProjectFromUriCreator.create(Unknown Source)
at edu.stanford.smi.protegex.owl.ProtegeOWL.createJenaOWLModelFromURI(Unknown Source)
at Extractor.main(Extractor.java:10)
Caused by: java.lang.ClassNotFoundException: org.protege.editor.owl.model.hierarchy.roots.Relation
at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)
at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:190)
at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:499)
... 10 more
any suggestions please?
java.lang.ClassNotFoundException: org.protege.editor.owl.model.hierarchy.roots.Relation
There are other dependencies you need. Rather than going piecemeal, you should use a build system that can resolve the dependency closure for you, such as Maven, Gradle or similar.
The problem here is not Protege specific or ontology related, it's just plain Java libraries missing from the classpath.
Note that your code does not use OWL API. These classes are Jena classes and Protege classes (from Protege 3.x, I'd think). Note that Protege 3.x is a very dated API. Consider using a newer version (5.2.0 or newer), or directly using the actual OWL API. See https://github.com/owlcs/owlapi/wiki/Documentation
OWL API also has zip files containing all dependencies, which might simplify your work (Maven is still better than resolving dependencies by hand). See https://github.com/owlcs/releases/tree/master/owlapi/5

Running linux command in java

I want to run "ls" command in java and my code is-
Note:- I am using WINDOWS.
import java.io.IOException;
public class Example
{
public void fn()
{
Runtime run = Runtime.getRuntime();
Process p = null;
String cmd = "ls";
try {
p = run.exec(cmd);
p.getErrorStream();
p.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
System.out.println("ERROR.RUNNING.CMD");
} finally {
p.destroy();
}
}
public static void main(String[] args) throws IOException
{
Example sp = new Example();
sp.fn();
}
}
but I am getting following error while running this code in eclipse-
java.io.IOException: Cannot run program "ls": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at Example.fn(Example.java:12)
at Example.main(Example.java:28)
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>(Unknown Source)
at java.lang.ProcessImpl.start(Unknown Source)
... 6 more
Exception in thread "main" ERROR.RUNNING.CMD
java.lang.NullPointerException
at Example.fn(Example.java:23)
at Example.main(Example.java:28)
what needs to be corrected? what library, etc. should I add to execute this piece of code?
If you want to run any command from Java ensure that executable of this file is present in PATH environment variable.
Or at least you have to set working directory to /usr/bin or similar.
One more solution is to use absolute path to executable, e.g.:
Runtime.getRuntime().exec("/usr/bin/ls");
But it is bad way to specify absolute path to any file.
Why don't you use File#listFiles()?

Tess4J InvocationTargetException

I have a problem running the below java code outside of the eclipse compiler. Inside the compiler it works fine, but after exporting as a runnable jar I get an InvocationTargetException. I believe it is relevant to the dll files but after reading other solutions here and tryinging to implement them the problem remained unresolved. So my question is it possible to configure eclipse, through code or settings, to export the program correctly?
Relevant Code
BTW C:\Program Files\Tesseract-OCR contains tessdata, gsdll64.dll, liblept170.dll, libtesseract303.dll
Maven Dependencies are tess4j, junit, ghost4j
public Bot() {
System.setProperty("jna.library.path", "C:/Program Files/Tesseract-OCR");
ocr2 = new Tesseract();
ocr2.setDatapath("C:/Program Files/Tesseract-OCR");
initLists();
System.out.println(scan(0,0,500,500));
}
public String scan(int x, int y, int x2, int y2) {
BufferedImage i = rob.getScreen(x, y, x2, y2);
i = toBufferedImage(i.getScaledInstance(i.getWidth()*2, i.getHeight() *2, Image.SCALE_SMOOTH));
try {
return ocr2.doOCR(i).trim();
} catch (TesseractException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "";
}
Error
C:\Users\Blue\Desktop>java -jar bot.jar
Exception in thread "main" 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 org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader.main(JarRsrcLoader.java:58)
Caused by: java.lang.UnsatisfiedLinkError: The specified module could not be found.
at com.sun.jna.Native.open(Native Method)
at com.sun.jna.Native.open(Native.java:1759)
at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:260)
at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:398)
at com.sun.jna.Library$Handler.<init>(Library.java:147)
at com.sun.jna.Native.loadLibrary(Native.java:412)
at com.sun.jna.Native.loadLibrary(Native.java:391)
at net.sourceforge.tess4j.util.LoadLibs.getTessAPIInstance(LoadLibs.java:78)
at net.sourceforge.tess4j.TessAPI.<clinit>(TessAPI.java:40)
at net.sourceforge.tess4j.Tesseract.init(Tesseract.java:360)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:273)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:256)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:237)
at net.sourceforge.tess4j.Tesseract.doOCR(Tesseract.java:221)
at debug.Bot.scan(Bot.java:480)
at debug.Bot.<init>(Bot.java:53)
at debug.Bot.main(Bot.java:24)
... 5 more
C:\Users\Blue\Desktop>pause
Press any key to continue . . .
In case anyone has a similar issue what I did was copy the 3 .dll files into my System32 folder. I then got an issue with image.io, which the site had plenty of answers for. My personal solution was exporting the jar as my code and a separate folder for the libraries.

java.lang.NoClassDefFoundError when Translating

I am using the Apertium Translator and using the sample code they provide. My code is like this.
import com.robtheis.aptr.language.Language;
import com.robtheis.aptr.translate.Translate;
public class Test {
public static void main(String[] args) throws Exception {
// Set the Apertium API Key - Get yours at http://api.apertium.org/register.jsp
Translate.setKey("BNSCFhEL8DoTApc2I1+aa3UYkVg");
String translatedText = Translate.execute("Hola, mundo!", Language.SPANISH, Language.ENGLISH);
System.out.println(translatedText);
}
}
I have no errors or warnings and when I run the program I get the following errors.
Exception in thread "main" java.lang.NoClassDefFoundError: org/json/simple/JSONValue
at com.robtheis.aptr.ApertiumTranslatorAPI.jsonSubObjToString(ApertiumTranslatorAPI.java:195)
at com.robtheis.aptr.ApertiumTranslatorAPI.retrieveSubObjString(ApertiumTranslatorAPI.java:140)
at com.robtheis.aptr.translate.Translate.execute(Translate.java:56)
at maple.Test.main(Test.java:11)
Caused by: java.lang.ClassNotFoundException: org.json.simple.JSONValue
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
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)
... 4 more
The .jar I'm using is the second one from https://github.com/rmtheis/apertium-translator-java-api/downloads
You have to download the first one. The first jar file (apertium-translator-java-api-0.2-jar-with-dependencies.jar) contains the all dependencies needed..
Or you add a json library to your project path..
Well JVM is not able to find some class at Runtime which was available at compile time. That is the reason of NoClassDefFoundError
Below you also have ClassNotFoundException for this class org.json.simple.JSONValue
which means you are trying to load the particular class at run-time by name.
Both of them related to Java Class Path.
I don't know alot about jSON stuff. But you are missing this file org.json.simple.JSONValue you can take it from here http://code.google.com/p/json-simple/
add the above jar file in your class path . And the code will definitely run. Guaranteed.!!!
Thanks

Why are classLoader magic values in defineClass() throwing an exception?

I want to write a classLoader that can help me implement customized classes and ultimately a whole component at run time. Right now I'm in process of loading the class.
I'm trying to load this role.java file. However when I get to this part of the code:
myClass = super.defineClass(className, classData, 0, classData.length);
I get this exception:
Exception in thread "main" java.lang.ClassFormatError: Incompatible magic value 1885430635 in class file C:\Users\ARIFAH\Downloads\Compressed\eUML2 free version\with classLoader code\2\archetypedComponentWithNull\src\aC\Role/java
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at java.lang.ClassLoader.defineClass(Unknown Source)
at customCL.customClassLoader.loadClass(customClassLoader.java:116)
at java.lang.ClassLoader.loadClass(Unknown Source)
at customCL.customClassLoader.main(customClassLoader.java:145)
I've read posts saying "you need something like OSGi". That would be similar to working on something new from scratch, which I'd like to avoid.
Why am I getting this error?
You aren't actually loading a real class file. The magic value of any valid class file is 0xCAFEBABE, and this magic in hex is 0x7061636B.
Notice that if we convert 0x7061636B to ASCII byte by byte, it turns out to be the string "pack". This means that the file you think is a class file actually starts with the string "pack".

Categories