Java Scripting Engine importing my classes does not work - java

A code is worth 1000 words of explaining it :-)
package jasim;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
public class JSTest {
public static void main(String[] args) throws ScriptException {
ScriptEngine jse = new ScriptEngineManager().getEngineByExtension("js");
jse.eval("println(new jasim.JSTest().toString)");
}
#Override
public String toString() {
return "JSTest Object";
}
}
This code will fail with the below exception:
Exception in thread "main" javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "jasim" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
How do I import my own classes into the ScriptEngine?

After looking at the Mozilla Rhino docs, the solution is either to use:
importPackage(Packages.jasim) within the script, or to use new Packages.jasim.JSTest()
This is not so clear in the Sun docs regarding the importPackage in the ScriptingEngine docs.

The same way you import javax.script.ScriptEngine;...
Just make sure your classes are in the CLASSPATH

Related

Nashorn java.lang.NoClassDefFoundError: jdk/nashorn/api/scripting/JSObject

I am migrating my Eclipse RCP to use JDK 8 and I heavily use the JS ScriptEngine. Now that Nashorn is introduced I had to add the following line to get the importClass and importPackage functions to work:
load("nashorn:mozilla_compat.js");
After doing so, I got java.lang.NoClassDefFoundError: jdk/nashorn/api/scripting/JSObject.
I am using Nashorn inside an Eclipse RCP. The problem occurs when I call a Java function from the Javascript and try to use the parameter sent. The parameter I want to send is a Javascript function that I would like to execute call on later in the code.
I have the following code:
TestNashorn.java
package com.test.nashorn;
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.script.Invocable;
import jdk.nashorn.api.scripting.JSObject;
public class TestNashorn {
public static void main(String[] args) {
ScriptEngine engine = (new ScriptEngineManager()).getEngineByName("js");
try {
engine.eval(new FileReader("C:/Users/user/workspace_nashorn/TestNashorn/src/com/test/nashorn/test.js"));
Object o = ((Invocable)engine).invokeFunction("generate");
} catch (ScriptException | FileNotFoundException | NoSuchMethodException e) {
e.printStackTrace();
}
}
public static int test(JSObject o1) {
System.out.println(o1.getClass().toString());
JSObject som = ((JSObject)o1);
return 1;
}
}
test.js
load("nashorn:mozilla_compat.js");
importClass(com.test.nashorn.TestNashorn);
function generate()
{
function asd(variablex) { print('Hello, ' + variablex); }
var result = TestNashorn.test(asd);
}
The problem occurs in line JSObject som = ((JSObject)o1);, although I can successfully import jdk.nashorn.api.scripting.JSObject;.
The exception message exactly says:
jdk.nashorn.api.scripting.JSObject cannot be found by com.test.nashorn_1.0.0.qualifier
So.. I got to fix my issue and was able to use JSObject in my code. What I have done was the following:
Added -Dorg.osgi.framework.bundle.parent=ext to myproduct.product file
This added it to the .ini file in my product build which revealed the classes found in Nashorn APIs.

Could not find or load main class FaceDetect in java with angus.ai

I get the following error when I try to run
java -cp 'angus-sdk-java-0.0.2-jar-with-dependencies.jar:.' FaceDetect
I am following a tutorial for face detection in http://angus-doc.readthedocs.io/en/latest/getting-started/java.html . Below is my java code,
import java.io.IOException;
import org.json.simple.JSONObject;
import ai.angus.sdk.Configuration;
import ai.angus.sdk.Job;
import ai.angus.sdk.ProcessException;
import ai.angus.sdk.Root;
import ai.angus.sdk.Service;
import ai.angus.sdk.impl.ConfigurationImpl;
import ai.angus.sdk.impl.File;
public class FaceDetect {
public static void main(String[] args) throws IOException, ProcessException {
Configuration conf = new ConfigurationImpl();
Root root = conf.connect();
Service service = root.getServices().getService("age_and_gender_estimation", 1);
JSONObject params = new JSONObject();
params.put("image", new File("Downloads/IMG_1060.jpg"));
Job job = service.process(params);
System.out.println(job.getResult().toJSONString());
}
}
I don't understand the problem with it. I have tried all the answers in the stack overflow but nothing is working for me.
remove the single qoutes around the classpath:
java -cp angus-sdk-java-0.0.2-jar-with-dependencies.jar:. FaceDetect

Missing scheme (IllegalArgumentException) while using java.nio.file.Paths interface

this is a really simple java question. I am using Java 8 with eclipse kepler on a linux system. I've been trying to try out NIO.2. My code is:
package lucasTest;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.file.*;
public class Lucas {
public static void main(String[] args) throws URISyntaxException{
URI u = new URI("./Lucas.java");
Path p = Paths.get(u);
}
}
I get the following error:
Exception in thread "main" java.lang.IllegalArgumentException: Missing scheme
at java.nio.file.Paths.get(Paths.java:134)
at lucasTest.Lucas.main(Lucas.java:10)
Please help!
Thanks,
Lucas
Your uri declaration is missing the scheme for files (file:///):
u = new URI("file:///./Lucas.java");
Path p = Paths.get(u);
should work. As an alternative you can try
Path p2 = Paths.get(".", "Lucas.java");

Python Import Error - Cannot import name

Brand new to Python & JYthon. I'm going through a simple tutorial and am struggling with the basics and am hoping for some insight.
Created a PyDev project called 'PythonTest' In that I created a module called test (test.py) and the code looks like this
class test():
def __init__(self,name,number):
self.name = name
self.number = number
def getName(self):
return self.name
def getNumber(self):
return self.number
I then created a java project called pythonJava and in it created three classes.
ITest.java which looks like this
package com.foo.bar;
public interface ITest {
public String getName();
public String getNumber();
}
TestFactory.java which looks like this
package com.ngc.metro;
import org.python.core.PyObject;
import org.python.core.PyString;
import org.python.util.PythonInterpreter;
public class TestFactory {
private final PyObject testClass;
public TestFactory() {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("from test import test");
testClass = interpreter.get("test");
}
public ITest create(String name, String number) {
PyObject testObject = testClass.__call__(new PyString(name),
new PyString(name), new PyString(number));
return (ITest) testObject.__tojava__(ITest.class);
}
}
And finally Main.java
public class Main {
private static void print(ITest testInterface) {
System.out.println("Name: " + testInterface.getName());
System.out.println("Number: " + testInterface.getNumber());
}
public static void main(String[] args) {
TestFactory factory = new TestFactory();
print(factory.create("BUILDING-A", "1"));
print(factory.create("BUILDING-B", "2"));
print(factory.create("BUILDING-C", "3"));
}
}
When I run Main.java I get the following error:
Exception in thread "main" Traceback (most recent call last): File
"", line 1, in ImportError: cannot import name test
Can someone advise me on what I'm doing wrong? I was under the impression I needed two imports one for the module (test.py) and the one for the class "test"
EDIT 1:
To avoid the easy question of my sys.path I have the following from IDLE
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 18 2013, 21:18:40) [MSC v.1600
32 bit (Intel)] on win32 Type "copyright", "credits" or "license()"
for more information. import sys print(sys.path) ['',
'C:\Python33\Lib\idlelib', 'C:\Python33', 'C:\Python33\Lib',
'C:\Python33\DLLs', 'C:\workspace\myProject\src',
'C:\Windows\system32\python33.zip',
'C:\Python33\lib\site-packages']
from test import test
t = test.test(1,2)
t.getName()
1
Actually, it seems a PYTHONPATH issue... as you're getting it from IDLE I can't say how things are actually in your Java env (and IDLE is using Python, but in your run you should be using Java+Jython -- in which case you're probably not using the proper sys.path for Jython -- at least I don't see any place having the PYTHONPATH defined in the code above to include the path to your .py files).
Also, if you're doing Java+Jython, see the notes on the end of: http://pydev.org/manual_101_project_conf2.html for configuring the project in PyDev.

Java-Sandbox example throwing java.lang.NoClassDefFoundError

Anyone with experience using Java-Sandbox, I have implemented one of the basic examples found in the documentation but i cant get it working.
Code:
SandPlayground.java
import java.util.concurrent.TimeUnit;
import net.datenwerke.sandbox.*;
import net.datenwerke.sandbox.SandboxContext.AccessType;
import net.datenwerke.sandbox.SandboxContext.RuntimeMode;
import net.datenwerke.sandbox.SandboxedEnvironment;
public class SandPlayground {
/**
* #param args
*/
public static void main(String[] args) {
System.out.println("Running...");
SandboxService sandboxService = SandboxServiceImpl.initLocalSandboxService();
// configure context
SandboxContext context = new SandboxContext();
//context.setRunRemote(true);
context.setRunInThread(true);
context.setMaximumRunTime(2, TimeUnit.SECONDS, RuntimeMode.ABSOLUTE_TIME);
context.addClassPermission(AccessType.PERMIT, "java.lang.System");
context.addClassPermission(AccessType.PERMIT, "java.io.PrintStream");
//run code in sandbox
SandboxedCallResult<String> result = sandboxService.runSandboxed(MyEnvironment.class, context, "This is some value");
// output result
System.out.println(result.get());
}
}
MyEnvironment.java
import net.datenwerke.sandbox.SandboxedEnvironment;
public class MyEnvironment implements SandboxedEnvironment<String> {
private final String myValue;
public MyEnvironment(String myValue){
this.myValue = myValue;
}
#Override
public String execute() throws Exception {
/* run untrusted code */
System.out.println(myValue);
/* return some value */
return "This is a different value";
}
}
And I'm getting the error:
EDIT: I've included the dependencies, but I'm still getting some errors:
With the code above I get:
Exception in thread "main" net.datenwerke.sandbox.exception.SandboxedTaskKilledException: killed task as maxmimum runtime was exceeded
at net.datenwerke.sandbox.SandboxMonitorDaemon.testRuntime(SandboxMonitorDaemon.java:82)
at net.datenwerke.sandbox.SandboxMonitorDaemon.run(SandboxMonitorDaemon.java:57)
at java.lang.Thread.run(Thread.java:724)
and when i remove the context.setMaximumRunTime() call, I get:
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/commons/collections/map/IdentityMap ...
Any help is much appreciated.
most likely you are missing the javassist library (see the documentatio of the sandbox for dependencies: http://blog.datenwerke.net/p/the-java-sandbox.html). You'll find the javassist library on sourceforge at: https://sourceforge.net/projects/jboss/files/Javassist/
The javaassist library is used to remove finalizers in loaded code. This can be turned off in the sandbox context:
contex.setRemoveFinalizers(false)
Hope this helps.

Categories

Resources