Jpype passing arguments to Java - java

I have a java programmer with following line
service.loadPropertiesForItems(Inbox, new PropertySet(ItemSchema.Subject, ItemSchema.Body));
Program calls classes and methods from external jars.
I want to write equivalent code in python which calls external jars like my java program does.
Using Jpype I implemented the code but it fails on following line
service.loadPropertiesForItems(inbox, ewsPkg.PropertySet(ewsPkg.ItemSchema.Subject, ewsPkg.ItemSchema.Body))
Here PropertySet, ItemSchema are classes which I use from external jar.
ItemSchema.Subject and ewsPkg.ItemSchema.Body are class type
Running the code I get following error on line mentioned above -
service.loadPropertiesForItems(inbox, ewsPkg.PropertySet(ewsPkg.ItemSchema.Subject, ewsPkg.ItemSchema.Body))
File "C:\Python27\lib\site-packages\jpype\_jclass.py", line 79, in _javaInit
self.__javaobject__ = self.__class__.__javaclass__.newClassInstance(*args)
RuntimeError: No matching overloads found. at src/native/common/jp_method.cpp:121
Thanks

As suggested by Martin https://github.com/originell/jpype/issues/117
following code works well
ItemSchema = ewsPkg.ItemSchema
PropertyDefinition = ewsPkg.PropertyDefinition
Subject = ItemSchema.Subject
Body = ItemSchema.Body
args = JArray(PropertyDefinition)([ItemSchema.Subject, Body])
PropertySet = ewsPkg.PropertySet(args)

Related

Missing resolveStrategy breaks DSL when executed from runnable jar

I'm using the Groovy Spreadsheet Builder within one of my Grails projects to export some data as Excel file.
Everything works great until I create a runnable jar (using gradle assemble) and use this.
I'm using the builder within a service like this:
class ExcelService {
...
void export(OutputStream outputStream) {
...
PoiSpreadsheetBuilder.create(outputStream).build {
apply ExcelStylesheet
...
}
}
...
}
When I try to export my data from the app started using the generated jar I will get the following MissingMethodException:
groovy.lang.MissingMethodException: No signature of method: my.package.ExcelService.apply() is applicable for argument types: (java.lang.Class)
The (Java) interface of SpreadsheetBuilder looks like this:
public interface SpreadsheetBuilder {
void build(#DelegatesTo(strategy = Closure.DELEGATE_FIRST, value = WorkbookDefinition.class) #ClosureParams(value = FromString.class, options = "builders.dsl.spreadsheet.builder.api.WorkbookDefinition") Configurer<WorkbookDefinition> workbookDefinition);
}
While debugging the execution of the code and the jar I found the difference while stepping through invokeMethod() of ClosureMetaClass.
When closure.getResolveStrategy(); in the working version is called Closure.DELEGATE_FIRST will be returned. Debugging the jar, the result will be 0 so that the MissingMethodException will be thrown later due to the wrong resolve strategy.
For now I have no idea how to solve this problem.
What is/could be the reason for this behavior?
What can I do to solve this issue?
I'm using Grails 3.3.8 with Java OpenJDK 1.8.0_192.
If you don't need to support JDK 7, you could upgrade to Groovy Spreadsheet Builder 2.0.0.RC1 which is only JDK 8 compatible but appears to solve the problem.
#ClosureParams and #DelegatesTo are applicable to parameters of type groovy.lang.Closure. In this case, you have applied it to Configurer<WorkbookDefinition>.

saved .pb file(created using darkflow) not loading in java

I used the following command to create a .pb file:
flow --model ../YOLOv2/alexeyAB_darknet/darknet-master/cfg/yolov2-dppedestrian.cfg --load ../YOLOv2/alexeyAB_darknet/darknet-master/backup/yolov2-dppedestrian_33900.weights --savepb
Although the model was created successfully, when I load it into my java tensorflow application, I get the following error:
Exception in thread "Thread-9" org.tensorflow.TensorFlowException: Could not find meta graph def matching supplied tags: { serve }. To inspect available tag-sets in the SavedModel, please use the SavedModel CLI: saved_model_cli
The problem is in the second line of code:
String model_path = "/home/adisys/Desktop/cloudiV2/models/yolo_pedestrian/saved_model";
SavedModelBundle model = SavedModelBundle.load(model_path, "serve");
I tried digging deep and found this link:
Can not load pb file in tensorflow serving
Following the link I ran the following command:
saved_model_cli show --dir saved_model/
The output is as follows:
/home/adisys/anaconda3/lib/python3.6/site-packages/h5py/init.py:34: FutureWarning: Conversion of the second argument of issubdtype from float to np.floating is deprecated. In future, it will be treated as np.float64 == np.dtype(float).type. from ._conv import register_converters as _register_converters
The given SavedModel contains the following tag-sets:
As can be seen, there were no tag-sets displayed.
What could be the issue?
I just saw your post, I'm sure the problem has solved itself now, but I'm leaving the comment for others working with darkflow. The command --savepb needs to be assigned as --savepb True

Running XSLT to RDF framework fails because of Saxon

I´m using Krextor to convert XML to RDF. It runs fine from the command line.
I try to run it from Java (Eclipse) using this code.
private static void XMLToRDF() throws KrextorException, ValidityException, ParsingException, IOException, XSLException{
Element root = new Element("person");
Attribute friend = new Attribute("friends", "http://van-houten.name/milhouse");
root.addAttribute(friend);
Element name = new Element("name");
name.appendChild("Bart Simpson");
root.appendChild(name);
nu.xom.Document inputDocument = new nu.xom.Document(root);
System.out.println(inputDocument.toXML());
Element root1 = inputDocument.getRootElement();
System.out.println(root1);
Krextor k = new Krextor();
nu.xom.Document outputDocument = k.extract("socialnetwork","turtle",inputDocument);
System.out.println(outputDocument.toString());
}
I have the following problem problem
Exception in thread "main" java.lang.NoClassDefFoundError: net/sf/saxon/CollectionURIResolver
Caused by: java.lang.ClassNotFoundException: net.sf.saxon.CollectionURIResolver
I have included Saxon9he in the classpath, and I have also added manually as a library in the project but the error is the same.
I am the main developer of Krextor. And, #Michael Kay, actually a colleague of Grangel, so I will resolve the concrete problem with him locally.
So indeed the last Saxon version with which I did serious testing was 9.1; after that I haven't used Krextor integrated into Java but mainly used Krextor from the command line.
#Grangel, could you please file an issue for Krextor, and then we can work on fixing it together.
Indeed, #Michael Kay, for a while I had been including more recent Saxon versions with Krextor and updated the command line wrapper to use them (such as to add different JARs to the classpath), but I have not necessarily updated the Java wrapper code.

Error in Udf of pig

I am new to pig. I wrote a UDF in pig and used it in my pig script. But it gives following error
ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1070: Could not resolve UserDefined.PartsOfSpeech using imports: [, java.lang., org.apache.pig.builtin., org.apache.pig.impl.builtin.]
Here is my UDF code
public String exec(Tuple input) throws IOException {
//my code here
}
Here is my pig script
REGISTER /home/bigdata/NetBeansProjects/UserDefined/dist/UserDefined.jar
a = load '/user/bigdata/json' using TextLoader() as (input:chararray);
b = foreach a GENERATE UserDefined.PartsOfSpeech(input);
In the above code UserDefined is my package name and PartsOfSpeech is my class name
The error message says that Pig cannot find UserDefined.PartsOfSpeech.
What package declaration does PartsOfSpeech.java have at the top of the file?
If the package declaration is package com.my.company; try this instead:
REGISTER /home/bigdata/NetBeansProjects/UserDefined/dist/UserDefined.jar
a = load '/user/bigdata/json' using TextLoader() as (input:chararray);
b = foreach a GENERATE com.my.company.PartsOfSpeech(input);
That is, replace UserDefined.PartsOfSpeech(input) with com.my.company.PartsOfSpeech(input) since the UDF is located in the package com.my.company.
Also, consider using the DEFINE keyword in your Pig script so you don't need to repeat com.my.company every time you use PartsOfSpeech.
DEFINE PartsOfSpeech UserDefined.dist.PartsOfSpeech();
REGISTER /home/bigdata/NetBeansProjects/UserDefined/dist/UserDefined.jar
a = load '/user/bigdata/json' using TextLoader() as (input:chararray);
b = foreach a GENERATE PartsOfSpeech(input);
There is more information about DEFINE in Chapter 5 of Alan Gates' Programming Pig: http://chimera.labs.oreilly.com/books/1234000001811/ch05.html#udf_define.
Here is an example of DEFINE from Gates' book:
--define.pig
register 'your_path_to_piggybank/piggybank.jar';
define reverse org.apache.pig.piggybank.evaluation.string.Reverse();
divs = load 'NYSE_dividends' as (exchange:chararray, symbol:chararray,
date:chararray, dividends:float);
backwards = foreach divs generate reverse(symbol);
Before compiling your UDF(java class) make sure you have mentioned package name properly. for example if you have mentioned package name-
package com.pig.udf;
It means you need to take care of directory in your linux box as well.
you can follow below mentioned steps to create jar -
Create directory using
mkdir -p com/pig/udf
Create your java class with package com.pig.udf
Compile your java source code using command
javac -cp /usr/lib/pig-0.12.0.2.0.6.0-76.jar YourClass.java
Then go to the directory where you want to create jar for now -
cd ../../..
Now create jar using below command
jar -cvf yourJarName.jar com/
Register the jar in your script using keyword "register" followed by path of the jar
Now use your jar with keyword com.pig.udf.YourJavaClassName
for your scenerio -
REGISTER /home/bigdata/NetBeansProjects/UserDefined/dist/UserDefined.jar
a = load '/user/bigdata/json' using TextLoader() as (input:chararray);
b = foreach a GENERATE com.pig.udf.PartsOfSpeech(input);

Why does Jython not find this module? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
How to run a python script from java?
I am running a Python script using Jython and got this error:
Exception in thread "main" Traceback (innermost last): File "C:\Facebook\LoginPython\Facebook.py", line 5, in ? ImportError: no module named cookielib
Why doesn't this work?
A little bit more about using Jython - had my share of problems with that as well. Note that this may not be the best way to do it, but it works fine for me.
I assume you want to call a function foo in module bar from your Java code that takes a string argument and returns a string:
PythonInterpreter interpreter = new PythonInterpreter();
// Append directory containing module to python search path and import it
interpreter.exec("import sys\n" + "sys.path.append(pathToModule)\n" +
"from bar import foo");
PyObject meth = interpreter.get("foo");
PyObject result = meth.__call__(new PyString("Test!"));
String real_result = (String) result.__tojava__(String.class);
The sys.path.append() part is only necessary if your module isn't part of the Python search path by default, which may very well be the problem if you get Import or Module not find errors.
Also you need to cast the objects between the java and python versions, you'll need to look that up if necessary, so far I only needed primitive types that were easy to cast, not sure if it's as easy for arbitrary java objects.
Use Jython to run Python on the JVM. Use PyDev to develop with Python (or Jython) on Eclipse.

Categories