NullPointerException while using jruby - java

I embed jruby script engine into my java program by using javax.script.ScriptEngineManager
I made some jruby code that end with do ~ end block,
after running all code, NullPointerException occured.
but code ends with any other statement, no exception occurs.
version : 1.7.19
Caused by: java.lang.NullPointerException
at org.jruby.embed.variable.Argv.updateARGV(Argv.java:169)
at org.jruby.embed.variable.Argv.retrieve(Argv.java:158)
at org.jruby.embed.variable.VariableInterceptor.retrieve(VariableInterceptor.java:154)
at org.jruby.embed.internal.BiVariableMap.retrieve(BiVariableMap.java:378)
at org.jruby.embed.internal.EmbedEvalUnitImpl.run(EmbedEvalUnitImpl.java:124)
in ARGV.java updateARGV
if (vars.containsKey((Object)name)) {
var = vars.getVariable((RubyObject)receiver.getRuntime().getTopSelf(), name);
var.setRubyObject(argv);
vars.getVariable returned null because of isReceiverIdentical return false
in BiVariableMap.java
if (var.isReceiverIdentical(receiver)) {
return var;
}
In isReceiverIdentical, this method just compare receiver with BiVariable's receiver usgin '=='.
Is this jruby bug? Or do I have to do something for this?
If you need more information about this problem, plz comment it!
I got ScriptEngine(engine) from ScriptEngineManager and set some java instance and method like this
engine.put("this", console);
engine.eval("$command = $this.java_method :command, [java.lang.String]");
here is my test ruby code. result and tab is java object
that has some method return String and list.
result = $command.call "something to pass"
puts result.getMessage
tabular = result.getData
tabular.each do |tab|
rows = tab.getRows
rows.each do |row|
puts row
end
puts tab.getColumnNames
end

I had created ruby type object in my java code by creating new Ruby object...
This causes checking fail in updateARGV because a receiver that register variable in BiVariableMap and another receiver that update variable are different.
So, I got a Ruby object from new ScriptingContainer(from it we can always get a same Ruby object if local context is singleton) and used it to create new ruby type object in my java code.
Reference: https://github.com/jruby/jruby/wiki/RedBridge#Singleton

Related

Read c++ console output from method call using Java

Currently, I am trying to read the console output of my program when there is a method call. How it works is, my Java program calls the JNI wrapper to invoke the C++ method call. My C++ is using std::cout. The payload.invoke will invoke my c++ library API. Inside the c++ API there are a few cout statements. That is the statement I want to read it as a variable in Java.
The current PrintStream only supports out, print, println and printf.Each time when there is a method call, there are bunch of logs being printed out in command prompt. Now, I would like my java program to read those output which my C++ prints out.
This is my current Java code:
public void execute() {
try {
Matcher m = Pattern.compile("([^()]*)[(]([^()]*)[)]").matcher(getPayloadString());
m.find();
boolean passed;
if (m.group(2).isEmpty()) {
// this is where it invoke the method
passed = (boolean) payload.invoke(testcase);
System.out.println("Boolean is: " + passed + "\n");
}else {
passed = (boolean) payload.invoke(testcase, ObjectCreator.convertParameters(m.group(2)));
System.out.println("Boolean2 is: " + passed + "\n");
}
String output = passed ? "PASS" : "FAIL";
// I want to use the console output string variable here -> xxxx
TestCase.printResult(payload.getName(), output, m.group(2), xxxx, "");
} catch (Exception ex) {
ex.printStackTrace();
}
}
Are there any ways to do it? Previously I tried using one of the tutorial from here. but that seems not working. Can someone help me out with this please. Thanks in advance.
If you have full control of the .cpp codebase it is possible for you to change the std::cout to become a ostream& instead.
By referencing a base class you can easily switch the implementation.
Do a JNI-Stream whichh extends the ostream& and just overwrite the operators you need to send JNI wrapped callbacks to java.
Then depending on if you run native or Java style use your JNI-Stream instead of the std::cout.
I would do something as seen in the link below to package and send the data to Java:
JNI - How to callback from C++ or C to Java?
that is my 2 cents.
Read carefully the JNI tutorial.
https://www.baeldung.com/jni
Follow the tutorial.
Basically you need to create a java class with a static block to load the C++ library:
static {
System.loadLibrary("native");
}
Then you can create your own static java method and invoke a method on the library.
If what you need is read the output from a system call, it's a different matter.
This can help you:
Java Runtime.getRuntime(): getting output from executing a command line program

Execute a Scala action inside an Java Controller (PlayFramework)

I've create an app using the Playfrawork with Java.
And I'm using the SecureSocial plugin on it.
Inside my controller there is a method that one of the process of it is to execute the handle start reset password inside the SecureSocial.
But that method is written in Scala.
If I refer the method inside my Java source like this:
Registration.handleStartResetPassword();
Nothing happens! Same if I change to the following line:
Registration.handleStartResetPassword().apply();
Same as the following source code block:
play.api.libs.iteratee.Iteratee<byte[], SimpleResult> it = Registration.handleStartResetPassword().apply(ctx()._requestHeader());
Future<SimpleResult> future = it.run();
Option<Try<SimpleResult>> result = future.value();
SimpleResult res = result.get().get();
I removed all my code and just tried to execute the Secure Social code but nothing happens.
Here is my method:
public static Result resetPassword() {
Registration.handleStartResetPassword().apply();
return TODO;
}
My route is this one:
POST /reset controllers.ProfileController.resetPassword
Edited: Added another way that I've tried to run but just didm't got the method running.
When you call handleStartResetPassword() you get an instance of Action back, it doesn't actually do anything until you to feed it with a particular request by calling Action.apply(request) which will then actually run the logic for that controller action and return a Future<Result>.
Not entirely sure if you can bridge backwards and get a play Java async result out of that though.

Some problems on sphinx for Java API

I'm new to sphinx, and I've encountered a few problems:
$1 After setting max_matches = 200 in class searchd in csft.conf, I called
org.sphx.api.test.main(new String[]{"-h", "127.0.0.1","-i", "magnet","-p", "9312", "-l", "100", "keyword"});
in a java main method. The error returned is
Error: searchd error: per-query max_matches=1000 out of bounds (per-server max_matches=200)
As you can see, I've added the param: -l = 100, what else should I set to prevent this error in Java?
$2 I want to use sortMode = SphinxClient.SPH_SORT_TIME_SEGMENTS to have the search result ordering by time desc. My attribute is written like this in csft.conf:
sql_attr_timestamp=UNIX_TIMESTAMP(upload_time) as dt
Could anyone tell me how can I set the attribute in Java code? I've tried to set the sortClause String in java, but it always said that Attribute XXX has not been found.
$3 I want to know whether SphinxClient in Java is thread safe, becaust I don't like to create a SphinxClient instance every time a person do a query.
Thanks in advance!
If the class you are using is https://code.google.com/p/sphinxtools/source/browse/trunk/src/org/sphx/test/test.java?r=2
then the function never even inspects 'argv'. It hardcodes all the variables. There is nothing passed as the third param to setLimits
sql_attr_timestamp simply accepts a column name, no functions or anything. The function call HAS to be in the main sql_query
My java is very rusty, but would have to say no. It stores all sort of state in private varibles. Multiple threads using the client at once will clober them.

tuProlog unknown behavior

I'm using tuProlog to integrate Prolog with Java, to do so I have defined a prolog.pl file with the following code:
go:-write('hello world!'),nl.
Then, in my Java project I Have the Main Class that invokes this:
Prolog engine = new Prolog();
Theory theory = new Theory(new FileInputStream("prolog.pl"));
try {
engine.setTheory(theory);
} catch (InvalidTheoryException ex) {
}
SolveInfo solution = engine.solve("go.");
if (solution.isSuccess()) {
System.out.println(solution.getSolution());
}
This code should output 'hello world', however, it outputs 'go', any ideas of why this behavior?
Finally found that the behavior was not erratic at all :)
The solution is to add this code just before calling the Solve Method.
engine.addOutputListener(new OutputListener() {
#Override
public void onOutput(OutputEvent e) {
finalResult += e.getMsg();
}
});
finalResult is just a Global variable that contains the returned String produced by Prolog Write instruction.
Your solution it's (correctly) the succeded Prolog query (go/0), what you expect ('hello world!') it's the output of a builtin, as such you should inspect the 'stdout' of your Java engine.
Otherwise, code your program to 'return' info in variables.
go(X) :- X = 'hello world!'.
Then tuProlog will provide the methods to access instanced variables.
I don't know about tuProlog/Java, but when calling Swi-Prolog from PHP, I must put 'halt' as the final statement of the predicate to tell Prolog to exit and return control back to php.
go:-write('hello world!'),nl, halt.

how to pass java output as a matlab variable?

I have written a Java program which is invoked using system() function, thus it runs on the command window of Matlab. Now I want to know if there's another way to run a Java program other than running it on command window? Can it be run on any user made GUI in Matlab? Another problem is, I want to know if my program has some string value as output, which is generally displayed on command window, how can i store it in variable in Matlab?
Hope to hear from you very soon.
The Hello World solution by The MathWorks provides some insights on how to run a simple 'Hello World' java application inside MATLAB. You may change the Java code a bit, in order to have a method that returns a String.
public class HelloWorld
{
public String hello()
{
String helloWorld = "Hello World!";
return helloWorld;
}
}
Once this simple class is compiled and on the MATLAB JVM classpath create an instance and invoke the method with the following two commands.
o = HelloWorld
output = o.hello;
The String returned by the HelloWorld instance is assigned to the MATLAB variable output.
There is no need for a system command with Java code in MATLAB. You have direct access to the JVM from inside MATLAB. For an application with a complex GUI, break out to Java.
Undocumented Java is a valuable source on MATLAB, Java and GUIs.
Yes the classpath set is correct.
I modified the code, using it without main..
class HelloWorld
{
public String Hello()
{
String helloWorld="Hello World!";
return helloWorld;
}
}
Now, as per guided i try to create instance obj in Matlab, with following command:
o = HelloWorld;
Here I get following err:
??? No constructor 'HelloWorld' with
matching signature found.
The next command indicated it this:
output = o.hello;
which wouldnt work unless instance is created.

Categories