Running java jar classes with python using javabridge - java

I am trying to invoke some classes that are in jar file from python.I have set path and trying to run it like this :
import javabridge as jv
path=r'D:\myFiles\swinglibrary-1.9.5.jar'
jars = jv.JARS+[path]
jv.start_vm(run_headless=True,class_path=jars)
print(str(jv.get_static_field("org.robotframework.swing.SwingLibrary","runKeyword", a)))
I get this below error when i execute this :
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
print(str(javabridge.get_static_field("org.robotframework.swing.SwingLibrary", "runKeyword", a)))
File "C:\Python27\lib\site-packages\javabridge\jutil.py", line 952, in get_static_field
raise JavaException(jexception)
JavaException: org.robotframework.swing.SwingLibrary
I am not sure how to invoke a class in a jar using javabridge.Can anyone help me out with this?

Related

Python Jpype can't see Java classes in JAR file

I am trying to work through what should be a simple problem, but am missing something. I have a very simple Java class:
package blah.blah;
public class Tester {
public String testMethod1() { return "GotHere"; }
public String testMethod2() { return "GotHereToo"; }
} // Tester
I am trying to get it to load into JPype:
import jpype
import jpype.imports
from jpype.types import *
path_to_jvm = "C:\\Java\\OracleJDK-8_241_x64\\jre\\bin\\server\\jvm.dll"
jpype.startJVM(path_to_jvm, classpath=["C:\\Users\\Administrator\\eclipse-workspace\\JpypeTest\\src;"])
from java.lang import System
print(System.getProperty("java.class.path"))
from java.io import ObjectInputStream
from blah.blah import Tester
tester = Tester()
print(tester.testMethod1())
print(tester.testMethod2())
jpype.shutdownJVM()
Everything works fine when I load the class directly using the above code. It stops working when I try to get it to load the Class file via a JAR.
jpype.startJVM(path_to_jvm, classpath=["C:\\Users\\Administrator\\JpypeTest.jar;"])
The error I get is:
Traceback (most recent call last):
File ".\jpype_test.py", line 16, in <module>
from blah.blah import Tester
ModuleNotFoundError: No module named 'blah'
PS C:\Users\Administrator> python .\jpype_test.py
C:\Users\Administrator\JpypeTest.jar;
Traceback (most recent call last):
File ".\jpype_test.py", line 16, in <module>
from blah.blah import Tester
ModuleNotFoundError: No module named 'blah'
I have built the JAR file a few different ways from Eclipse 2020/09 using JAR export and from the command line using:
C:\Users\Administrator\eclipse-workspace\JpypeTest\src>"C:\Java\OracleJDK-8_241_x64\bin"\jar cf C:\Users\Administrator\JpypeTest.jar blah\blah\*.class
I have confirmed that the JVM and the python interpreter are both 64 bit. I have also done my best to ensure the JVM is exactly the same between Eclipse, the command line and Python.
From what I can see, the JAR looks fine regardless of how I build it. It contains the blah\blah directory and the Tester.class file under it. The manifest is the only other file in the JAR.
I have also tried creating the JAR file with the class file at different directory levels (ie. one level of blah directories and no levels of blah directory).
Here are the versions of the python software:
Python 3.8.5 (default, Sep 3 2020, 21:29:08) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win32
Package Version
------------ -------------------
certifi 2020.6.20
JPype1 1.0.2
pip 20.2.3
setuptools 50.3.0.post20201006
wheel 0.35.1
wincertstore 0.2
I clearly have the base plumbing working since it can see the class file. Any thoughts on why the JAR is failing?
Thanks a bunch for your consideration.
Check that you don't have a directory called "blah" that python would look in for modules. This would hide your Java classes, as per https://jpype.readthedocs.io/en/latest/userguide.html#importing-java-classes :
One important caveat when dealing with importing Java modules. Python always imports local directories as modules before calling the Java importer. So any directory named java, com, or org will hide corresponding Java package. We recommend against naming directories as java or top level domain.

How to execute a groovy script using the classes from an external jar file

Editing the original question.
I am trying to execute a groovy script which uses classes from an external jar. How can I execute the groovy file from command line?
This is the command I tried
groovy -cp .:cicdutilities-1.0-SNAPSHOT.jar:http-builder-0.4.0.jar Test_Execution.groovy
and getting the error :
`org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: /Users/sroy107/git/CICD-2020/src/main/java/com/groovy/Test_Execution.groovy: 188: unable to resolve class HTTPBuilder # line 188, column 24. def http = new HTTPBuilder(baseUrl) ^ 1 error`
I was not aware earlier that we need two jars.
This command is not working. Could somme one please help me on this.

Stanford Parser - java.io.IOException: Unable to resolve as either class path, filename or URL

I can not make Stanford Parser Version 3.5.1 work. I know that newer versions of this tool are available but I have tons of old code using this particular version. This is for an academic course.
I am using Windows 7, JDK 1.8.0_65, python 3.3.3 and NLTK 3.0.2
My environment variables are as follows:
CLASSPATH : C:\Program Files (x86)\stanford-parser-full-2015-01-30\jars\stanford-parser-3.5.1-models.jar;C:\Program Files (x86)\stanford-parser-full-2015-01-30\jars\stanford-parser-3.5.1-sources.jar;C:\Program Files (x86)\stanford-parser-full-2015-01-30\jars\stanford-parser.jar
JAVA_HOME : C:\Program Files\Java\jdk1.8.0_65\bin
Path : C:\ProgramData\Oracle\Java\javapath;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Common Files\Apple\Internet Services\;C:\Program Files\Git\cmd;C:\Program Files (x86)\stanford-parser-full-2015-01-30\jars\
I run this code:
from nltk.parse import stanford
parser = stanford.StanfordParser(model_path='C:\Program Files
(x86)\stanford-parser-full-2015-01-30\edu\stanford\lp\models\lexparser\englishPCFG.ser.gz')
parser.raw_parse('I love apples')
And I am getting this error
Loading parser from serialized file C:\Program Files
(x86)\stanford-parser-full-2015-01-30\edu\stanford\lp\models\lexparser\englishPCFG.ser.gz
...
java.io.IOException: Unable to resolve "C:\Program Files
(x86)\stanford-parser-full-2015-01-30\edu\stanford\lp\models\lexparser\englishPCFG.ser.gz"
as either class path, filename or URL
at
edu.stanford.nlp.io.IOUtils.getInputStreamFromURLOrClasspathOrFileSystem(IOUtils.java:463)
at edu.stanford.nlp.io.IOUtils.readStreamFromString(IOUtils.java:396)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserFromSerializedFile(LexicalizedParser.java:599)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserFromFile(LexicalizedParser.java:394)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.loadModel(LexicalizedParser.java:181)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.main(LexicalizedParser.java:1395)
Loading parser from text file C:\Program Files
(x86)\stanford-parser-full-2015-01-30\edu\stanford\lp\models\lexparser\englishPCFG.ser.gz
java.io.IOException: Unable to resolve "C:\Program Files
(x86)\stanford-parser-full-2015-01-30\edu\stanford\lp\models\lexparser\englishPCFG.ser.gz"
as either class path, filename or URL
at
edu.stanford.nlp.io.IOUtils.getInputStreamFromURLOrClasspathOrFileSystem(IOUtils.java:463)
at edu.stanford.nlp.io.IOUtils.readerFromString(IOUtils.java:591)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserFromTextFile(LexicalizedParser.java:533)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.getParserFromFile(LexicalizedParser.java:396)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.loadModel(LexicalizedParser.java:181)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.main(LexicalizedParser.java:1395)
Exception in thread "main" java.lang.NullPointerException
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.loadModel(LexicalizedParser.java:183)
at
edu.stanford.nlp.parser.lexparser.LexicalizedParser.main(LexicalizedParser.java:1395)
Traceback (most recent call last): File
"C:\Users\Zimtyth\Desktop\PFE\Implémentation\Codes\Code
final\Lib_Stanford_Parser.py", line 100, in
resultat = parse_sent("My name is Melroy and i want to win.") File "C:\Users\Zimtyth\Desktop\PFE\Implémentation\Codes\Code
final\Lib_Stanford_Parser.py", line 10, in parse_sent
return parser.raw_parse(sent) File "C:\Python33\lib\site-packages\nltk\parse\stanford.py", line 152, in
raw_parse
return next(self.raw_parse_sents([sentence], verbose)) File "C:\Python33\lib\site-packages\nltk\parse\stanford.py", line 170, in
raw_parse_sents
return self._parse_trees_output(self._execute(cmd, '\n'.join(sentences), verbose)) File
"C:\Python33\lib\site-packages\nltk\parse\stanford.py", line 230, in
_execute
stdout=PIPE, stderr=PIPE) File "C:\Python33\lib\site-packages\nltk\internals.py", line 161, in java
raise OSError('Java command failed : ' + str(cmd)) OSError: Java command failed : ['C:\Program
Files\Java\jdk1.8.0_65\bin\java.exe', '-mx1000m', '-cp',
'C:\Program Files
(x86)\stanford-parser-full-2015-01-30\jars\stanford-parser.jar;C:\Program
Files
(x86)\stanford-parser-full-2015-01-30\jars\stanford-parser-3.5.1-models.jar',
'edu.stanford.nlp.parser.lexparser.LexicalizedParser', '-model',
'C:\Program Files
(x86)\stanford-parser-full-2015-01-30\edu\stanford\lp\models\lexparser\englishPCFG.ser.gz',
'-sentences', 'newline', '-outputFormat', 'penn', '-encoding', 'utf8',
'c:\users\zimtyth\appdata\local\temp\tmpbf5zdg']
I have already checked a couple of answers in SO about this like this but still I could not make it work. It looks like a Java problem, please tell me what am I doing wrong here?
I would guess that your code isn't right and you don't have any file at the location 'C:\Program Files (x86)\stanford-parser-full-2015-01-30\edu\stanford\lp\models\lexparser\englishPCFG.ser.gz'.
If the models jar file is on your classpath, you should be able to get things to work by giving the model path (inside the jar file):
parser = stanford.StanfordParser(model_path='edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz')
The other choice is to expand the jar file (jar -xf) and then you would have an englishPCFG.ser.gz file, which you could as a parameter to the model_path.
p.s. For other people reading this in 2019+: You shouldn't actually be using this NLTK package at all any more, but rather: nltk.parse.corenlp.CoreNLPParser

pyjnius "Class not found" when importing jar file

I'm trying to make pyjnius work with a jar file I built from java application, but I keep getting the "Class not found" error:
>>> import os
>>> os.environ['CLASSPATH'] = "~/workspace/myapp-Tools/Admin/Console/couchdb/myapp-web.jar"
>>> from jnius import autoclass
>>> bla = autoclass('com/myapp/webapp/server/helpers/licensee/CalculationHelper')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 150, in autoclass
c = find_javaclass(clsname)
File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:12815)
jnius.JavaException: Class not found 'com/myapp/webapp/server/helpers/licensee/CalculationHelper'
>>>
of course I've checked:
jar tf myapp-web.jar
and com/myapp/webapp/server/helpers/licensee/CalculationHelper.class is in there
I've also tried setting the classpath this way:
import jnius_config
jnius_config.set_classpath('.', '~/workspace/myapp-Tools/Admin/Console/couchdb/')
#import jnius
from jnius import autoclass
But this gave me the same result.
I'm working on a virtualenv btw.
I've tried all approaches I could find online, but it is simply not working. I had to manually install pyjnius because using pip got me an old version of it.
Any help would be greatly appreciated.
Edit: tried this with a jar not created by me and I see a different error
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import jnius_config
>>> jnius_config.add_classpath('/home/sam/workspace/someproject/*')
>>> jnius_config.expand_classpath()
'/home/sam/workspace/someproject/annotations.jar:/home/sam/workspace/someproject/junit-4.10.jar:/home/sam/workspace/someproject/ postgresql-8.1-408.jdbc3.jar'
>>> import jnius
>>> from jnius import autoclass
>>> test = autoclass('org/postgresql/geometric/PGcircle.class')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 150, in autoclass
c = find_javaclass(clsname)
File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:12815)
jnius.JavaException: Class not found 'org/postgresql/geometric/PGcircle/class'
>>> test = autoclass('org/postgresql/geometric/PGcircle')
Exception in thread "main" java.lang.NoClassDefFoundError: org/postgresql/geometric/PGcircle/class
Caused by: java.lang.ClassNotFoundException: org.postgresql.geometric.PGcircle.class
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)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 156, in autoclass
for constructor in c.getConstructors():
File "jnius_export_class.pxi", line 562, in jnius.JavaMethod.__call__ (jnius/jnius.c:19385)
File "jnius_export_class.pxi", line 649, in jnius.JavaMethod.call_method (jnius/jnius.c:20409)
File "jnius_utils.pxi", line 43, in jnius.check_exception (jnius/jnius.c:3533)
jnius.JavaException: JVM exception occured
>>> test = autoclass('org/postgresql/geometric/PGcircl')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/sam/workspace/myapp-Tools/Admin/Console/couchdb/virtualenv/local/lib/python2.7/site-packages/jnius/reflect.py", line 150, in autoclass
c = find_javaclass(clsname)
File "jnius_export_func.pxi", line 23, in jnius.find_javaclass (jnius/jnius.c:12815)
jnius.JavaException: Class not found 'org/postgresql/geometric/PGcircl'
>>>
and here are the contents of jar tf on that jar:
sam#lambda ~/workspace$ jar tf ./someproject/postgresql-8.1-408.jdbc3.jar
META-INF/
META-INF/MANIFEST.MF
...
org/postgresql/geometric/PGbox.class
org/postgresql/geometric/PGcircle.class
org/postgresql/geometric/PGline.class
org/postgresql/geometric/PGlseg.class
org/postgresql/geometric/PGpath.class
org/postgresql/geometric/PGpoint.class
org/postgresql/geometric/PGpolygon.class
...
sam#lambda ~/workspace$
Again... any help will be greatly appreciated!
tl;dr: make sure the .java files are compiled to (at most) the same Java version .class files as the Java version on the system that will import the file with pyjnius.
Longer version:
I had a very similar problem, with one big difference: some files worked without any problem and others (in the same directory) didn't.
The problem with the files that resulted in the 'Class not found' exception was that I compiled them under Windows, which has Java 8. Ubuntu however currently installs Java 7 when you run "sudo apt-get install default-jdk".
And so, pyjnius couldn't import the Java 8 files on my Java 7 Ubuntu install. It's strange that it throws a 'Class not found' exception, instead of something more descriptive. Changing the target output to 1.7 fixed my problem.
I solved this problem by exporting the JAR as a runnable JAR file in Eclipse:
create an empty main method somewhere if you don't have one (export didn't work for me otherwise)
go to File->Export...
select Java->Runnable JAR file
click Next
select the main method in the Launch configuration
select your Export destination
select "Copy required libraries into a sub-folder next to the generated JAR" as Library handling (the only option that worked for me in my special case, but you can also test the others)
click Finish
It works fine when I use my jar file.
Did you try to use the full path to define CLASSPATH?
Windows 7
Python 2.7.8
jnius 1.1-dev
This page will be useful as a reference.
http://www.hackzine.org/using-apache-tika-from-python-with-jnius.html
I just wanted to leave a comment but I don't have enough reputation for it.
So I leave an answer as a comment.
And you'd better not to use "/" instead of "." when you call autoclass.
See the link below.
http://pyjnius.readthedocs.org/en/latest/api.html#jnius.autoclass
Old Post, but posting an answer if it is useful for someone.
I see two issues there, not sure if you have tried these together:
Change
jnius_config.set_classpath('.', '~/workspace/myapp-Tools/Admin/Console/couchdb/')
To
jnius_config.set_classpath('.', '~/workspace/myapp-Tools/Admin/Console/couchdb/*')
And
test = autoclass('org/postgresql/geometric/PGcircl')
To
test = autoclass('org.postgresql.geometric.PGcircl')
Have you tried to add CLASSPATH via export then run your python script? This worked for me.
$ export CLASSPATH="~/workspace/myapp-Tools/Admin/Console/couchdb/myapp-web.jar"
i solved this isue by putting CLASSPATH in .bashrc
CLASSPATH="~/documents/download/programs/tika-app.jar"
and it works properly
The code below adds a jar to the classpath and then displays the classpath to further debug.
import os
import jnius_config
jnius_config.add_classpath("PATH_HERE/SOME.jar")
from jnius import autoclass, cast
ClassLoader = autoclass('java.lang.ClassLoader')
cl = ClassLoader.getSystemClassLoader()
ucl = cast('java.net.URLClassLoader', cl)
urls = ucl.getURLs()
tmp = [url.getFile() for url in urls]
print('\n'.join(tmp))

Why 'import mmap' throws ImportError in jython

I'm new to python and jython. I had a script in python which imports mmap, it works fine without any issues. I need to invoke a function in that script from a java class, which throws the following exception upon execution.
Exception in thread "main"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named mmap
I executed the same script in jython which gives me the below error.
C:\jython2.5.3>jython.bat d:\Python\AddConfToFile.py
Traceback (most recent call last):
File "d:\Python\AddConfToFile.py", line 9, in <module>
import mmap
ImportError: No module named mmap
I'm not able to find any suggestions through Google. Am I missing some thing here, kindly Help me fix this.
Thanks in Advance
Adithyan
The mmap module is not available under Jython. You will need to find an alternative.
It's just because the Jython doesn't support mmap still..As explained in the FAQ in the official site, in the paragraph below:
Modules that we don't support, and perhaps won't, include bsddb3, curses, dbm, gdbm,
ioctl, mmap, pty, Tkinter, and win32reg. Some of these might be readily doable, like
mapping the curses module against CHARVA, but given limited resources, are not likely to
be worked on. (Contributions welcome!)

Categories