Instantiate a java class in python and send it back to java - java

I have a class in java:
public class MyClass{
public String a=null;
public String b=null;
public String c=null;
public String d=null;
public static String testMyClass() {
//my method instruction using the attributes a,b,c and d
}
The trouble is that MyClass attributes must be received from python to be able to use the method testMyClass. So is it possible to instantiate a java class from python and after send it back to java using py4j?
Anyone can show how to make it if it is possible? Or have another alternative?

I don't think that is possible unless someone knows of a "bridge" utility between Java and Python.
However, you may do this:
Create a JSON in the Python script in a structure that matches that of MyClass
Receive it in your Java method and deserialize the JSON into an instance of MyClass using Jackson or some JSON tool.
Your next problem will be the communication between you Java process and Python process. For that, see if this StackOverflow question helps: Passing data from Java process to a python script

Related

How to pass Java object to a Java function in mule

I am trying to invoke a java function in mule.I converted the payload into the Object and passed it in the function.
The name of the Java object created is req.
The method validate accepts a Java Object Of type Example
public HashMap<String, String> validate(Example req) {.......}
Example class looks like this:
Class Example{
String key1;
String key2;
String key3;
}
XML configuration looks like this :
<java:new constructor="Example(java.lang.String,java.lang.String,java.lang.String)" doc:name="New Example" doc:id="6a1d5c8c-a1f0-446e-ab49-99a21fbbf4b9" class="Entities.Example" target="req">
<java:args ><![CDATA[#[{key1 :payload.key1,key2: payload.key2, key3:payload.key3}]]]></java:args>
</java:new>
<java:invoke doc:name="Invoke" doc:id="dd5f6534-06c8-4f4d-b3aa-c634a629898e" class="Implementations.ValidationServiceImpl" instance="#[vars.validator]" method="validate(Entities.Example)">
<java:args ><![CDATA[#[vars.req]]]></java:args>
</java:invoke>
I get the following error:
I don't know why is it not passing the java object as a whole.
Please try with this and see. If it works for you please let me know. We need to improve the mule documentation in this case
<java:args >#[{req: vars.req}]</java:args>

Accessing C# Object in java as method parameter using jni4net

We are able to call java in C# code and able to pass Strings and integers as method parameters. Able to access Strings are integers directly by using java java.lang.String and java.lang.Integer with out issues.
But when we pass C# custom object as method parameter we could not find a way to access it.
Eg: Employee.cs is the C# class with parameter name.
Used proxygen to create EmployeeLibraray.dll, EmployeeLibraray.j4n.dll and EmployeeLibraray.j4n.
C# code where we are trying to pass C# object
var bs = new BridgeSetup();
bs.AddAllJarsClassPath("./");
Bridge.CreateJVM(bs);
Bridge.RegisterAssembly(typeof(JavaTest).Assembly);
JavaTest obj = new JavaTest(); ================================> JavaTest
is the class generated using proxygen where it is called in C#
EmployeeLibraray.Employee e = new EmployeeLibraray.Employee();
===========> Custom C# object to be passed to Java
e.LoginName = "test";
obj.execute( e);
Code in java
public void execute(system.Object inputObj) throws Exception {
}
Question
How should we cast the inputObj as Employee so that can access directly e.getName().

What does Naming.lookup() do?

I have been going through a very simple example to set up a Remote Method Invocation application and while going through the client side code I am not able to understand one code as shown below. Definitely, gaps in my knowledge because I though an interface cannot have objects unless you use Anonymous Inner Class. So in the code below how did we creat an object of Remote Interface. It seems some sort of type-casting to me if I had to guess.
import java.rmi.*;
public class HelloClient {
public static void main(String args[]) {
try {
if (args.length < 0) {
System.err.println("usage: java HelloClient string …\n");
System.exit(1);
}
HelloInterface hello = (HelloInterface)Naming.lookup("//localhost/Hello");
This last line is what I am not able to understand what exactly is happening here with (HelloInterface) part?
HelloInterface hello = (HelloInterface)Naming.lookup("//localhost/Hello");
This Naming.lookup() call inspects the RMI Registry running in the localhost for a binding under the name "Hello".
It returns an Object that has to be cast to whatever remote interface you're expecting it to be.
You can then use that object to call the remote methods defined in the interface.
I thought an interface cannot have objects unless you use Anonymous Inner Class.
I have no idea what you're talking about here. Any class can implement an interface. This is rather basic.
So in the code below how did we create an object of Remote Interface
We didn't. We got it as a return value from the Registry, where it was put by the server.
It seems some sort of type-casting to me if I had to guess.
No need to guess. That's exactly what it is. There is only one 'sort' of typecasting, and this is how you write it. This is also rather basic.
HelloInterface hello = (HelloInterface)Naming.lookup("//localhost/Hello");
What is this mean ?
It is basically looking for an object in the server object pool registered with a name //localhost/Hello. this is called JNDI name
Depending on the type of server, this can be configured within the server configuration file.

How do I use a Java-defined instance method in Lua?

I'm aware that it is possible to use Java defined static methods in Lua, due to the section "Libraries of Java Functions" on http://luaj.org/luaj/README.html.
However I am struggling to find out how I can use the same for instance methods, I have a shortened example here:
private static class CallbackStore {
public void test(final String test) {
}
}
(I am aware that I can use a static method here as well, but it is not possible with the real life scenario)
I am using the following Lua code:
-- Always name this function "initCallbacks"
function initCallbacks(callbackStore)
callbackStore.test("test")
end
Which does not work as it is expecting userdata back, but I give it a string.
And I call the Lua code like this:
globals.load(new StringReader(codeTextArea.getText()), "interopTest").call();
CallbackStore callbackStore = new CallbackStore();
LuaValue initCallbacks = globals.get("initCallbacks");
initCallbacks.invoke(CoerceJavaToLua.coerce(callbackStore));
where the Lua code is returned by codeTextArea.getText()
Bottom line of my question is, how do I make my code running with test as an instance method?
When accessing member functions (in Lua objects in general, not just luaj) you have to provide the this argument manually as the first argument like so:
callbackStore.test(callbackStore,"test")
Or, you can use the shorthand notation for the same thing:
callbackStore:test("test")

Parse Java class (for code representation) to JSON object

In an android application I'm developing I need to get a json file containing some data to reconstruct the lines of code of a java class.
Is there any java/javascript library that allows to convert/parse a java class (that doesn't just have fields, but also methods defined inside it) in JSON format, and vice-versa?
EDIT: I'd also need to keep track of the whole project's structure (something like antlr?)
EDIT2: My bad, I wanted to store a java class code into a JSON object to represent it, I was also thinking to create my own json object, this way, by parsing the Java code and finding methods, classes, parameters.
{
"file": "PATH/TO/.java",
"language": "java",
"from": 0,
"to": 255,
"classes": [
"Test:2"
//...
],
"lines": [
[
"public class Test{"
//...
]
]
}
But if a good starting point is present, that would be great.
The trouble is that existing tools (such as GWT) are "only" able to create functioning JS code that is meant to be executed in browsers. But it does not necessarily resemble the original Java class. Your use case sounds quite different. It looks like you want to represent Java source code as JSON data and you don't need/want to execute it.
I fear you may have to create your own tool for that, that meets your specific requirements. I also fear that this tool must be able to parse the Java code because using simple regexes for extracting the data won't help here much because of nested types (interfaces, classes, enums) and also because a single Java file may contain multiple type declarations (even though not encouraged, but it is possible).
Here are a few links for Java parsers:
http://code.google.com/p/javaparser/ (unfortunately only Java 1.5)
http://www.ibm.com/developerworks/opensource/library/os-ast/ (discusses the Eclipse Java parser which is very robust and probably most suitable for your requirement)
You could also create your own parser using ANTLR as you suggest. The latest ANTLR version has some visitor pattern you need to implement in Java, as far as I know. You could implement a visitor that successively constructs your JSON output.
However, you really should use Eclipse's ASTParser for that, because you can easily iterate all methods of your class and get their implementation code as String.
You can use jackson library - http://jackson.codehaus.org/: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/
Use GSON: "GOOGLE for JSON" it's a google open source JSON Library, it can convert Java Object t o JSON object and vice-versa
You have Gson package that convert Json String to Java object and vice versa.
MyClass.java
public class MyClass {
private String mStr = "";
public String getStr() {
return mStr;
}
public void setStr(String mStr) {
this.mStr = mStr;
}
}
Main.java
public class Main {
public static void main(String[] args) {
String jsonString = "{ \"mStr\": \"foo\" }";
Gson mGson = new Gson();
MyClass res = mGson.fromJson(jsonString, MyClass.class);
System.out.println(res.getStr());
}
}
Output: foo
[Edit 1]
You can't store to Json class structure, only data
[Edit 2]
From your fix I understand followed thing:
This Json String represents behavior what to do with "text" file , suppose, you download from server. But no mater what inside Json String 1st of all you need to convert it to Object in Java (if you want to use Java) and after that according to rules (took from Json String) write any logic. For sure java code is able to generate Java files. Your example tells you:
to get text from line ... to line,
create file named xxxx.java
copy it to ...
So use my example above, create class, lets say Launcher:
public class Launcher{
private String file;
private String language;
private int from;
private int to;
private List<String> classes;
private List<SomeOtherClass> lines;
....
}

Categories

Resources