logo
down
shadow

How to do you get output from Javascript into Java using ScriptEngine


How to do you get output from Javascript into Java using ScriptEngine

By : pawiromitchel96
Date : November 25 2020, 07:22 PM
this one helps. To answer you original question, you get back whatever you "return" at the end of the script. If you do not have a specific "return" statement then by default you get back the result from the last action (which in your case is the last iteration of the repeat loop). Therefore if you need more than the last action returned you must create the return value in your script and then return it at the end.
code :


Share : facebook icon twitter icon
Java ScriptEngine for Javascript: using XML

Java ScriptEngine for Javascript: using XML


By : GabiRepare
Date : March 29 2020, 07:55 AM
it should still fix some issue Rhino that was bundled with Java 1.6 is missing E4X support. From http://blogs.oracle.com/sundararajan/entry/e4x_is_not_mustang:
How do I use Java ScriptEngine to create a Javascript function

How do I use Java ScriptEngine to create a Javascript function


By : faizan ahmad
Date : March 29 2020, 07:55 AM
Does that help Why not creating a real Javascript function that you add to the script?
code :
function ifnotempty(value,sep){
    return value != undefined && value.length > 0 ? value + sep : '';
}
private String convertPsuedoFunctions(String mask)
{
    return 
         "function ifnotempty(value,sep){return value!=undefined&&value.length>0?value+sep:'';}"
         + mask;
}
private static final String defaultFunctions = 
     com.google.common.io.Files.toString(new File("functions.js"),Charsets.US_ASCII);

private String convertPsuedoFunctions(String mask)
{
    return defaultFunctions + mask;
}
Use a jar in JavaScript through Java ScriptEngine

Use a jar in JavaScript through Java ScriptEngine


By : user2041929
Date : March 29 2020, 07:55 AM
hop of those help? I am able to use the jar's classes within JavaScript this way, but you have to set the jar to the class path when you go to run it. I was after a solution similar to Jython/Python's where you're able to set the jar inside Java but I'm just going to create batch files and sh files and set it that way (seems easier to do it that way now). Here is my solution that works for me.
To Compile Then Run:
code :
    cd C:\your\directory\folder\with\the\javascript\and\java\files

    javac -d . ClassSpy.java FileSearch.java HelloWorld.java Main.java Parameters.java Run.java

    java -cp ./;C:\ABCAPI\bin\abcapi.jar hammer.main.Main gui=true input=JavaScriptStatus.js
    myvariable = Packages.abc.foo.pack.name;

    var foo = new myvariable.ClassFromTheJarFile("arg1","arg2");

    foo.doSomething();

    var fooSister = new myvariable.AnotherCLassFromTheJarFile("arg1");

    fooSister.doSomthingFromThisClass();
    myvariable = Packages.abc.foo.pack.name.ClassFromTheJarFile;
    var foo = new myvariable.ClassFromTheJarFile("arg1","arg2");
Is it possible to import javascript files to a java ScriptEngine

Is it possible to import javascript files to a java ScriptEngine


By : Utkarsh
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Actually I found the answer myself: as mentioned in the comment, it is possible to call several eval with different scripts, same engine, and the engine will keep the evaluated scripts in its context. So here is my code:
code :
public void executeScript(String scriptName, String[] dependencies) {
    try {
        FileReader script = new FileReader(scriptName);
        ScriptEngineManager factory = new ScriptEngineManager();
        ScriptEngine jsEngine = factory.getEngineByName("nashorn");

        if(dependencies != null) {
            for (String dependency : dependencies) {
                FileReader dependencyFile = new FileReader(dependency);
                jsEngine.eval(dependencyFile);
            }
        }

        jsEngine.eval(script);
    }
}
ScriptEngine - Calling javascript closure from java

ScriptEngine - Calling javascript closure from java


By : Aliza Catag
Date : March 29 2020, 07:55 AM
help you fix your problem I am trying to invoke a javascript closure from Java using ScriptEngine. See below the code snippet. I removed the script engine eval code for brevity.I was able to invoke the function which has a closure but not the closure, any help is appreciated , Solved the issue, here is the fully working code
code :
import jdk.nashorn.api.scripting.ScriptObjectMirror;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;

public class Main {

    public static class TestObj {

        public TestObj() {

        }
        public void setVariable(String name, Object value) {
            System.out.println(name + ":" + value);
            if (value instanceof ScriptObjectMirror) {
                ScriptObjectMirror scriptObjectMirror = (ScriptObjectMirror) value;
                String[] ownKeys = scriptObjectMirror.getOwnKeys(true);
                for (String k: ownKeys) {
                    System.out.println(scriptObjectMirror.get(k));
                }
            }
        }
    }

    public static void main(String[] args) throws ScriptException {
        System.out.println("Hello World!");


        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine engine = scriptEngineManager.getEngineByName("javascript");
        String js = "var transform = {\n" +
                "execute : function(execution) {\n" +
                "    print(\"hello\");" +
                "execution.setVariable(\"test\",\"testing\");\n" +
                "    function transform(execution) {\n" +
                "        execution.setVariable(\"result\", {result:\"myjson object\"});\n" +
                "        print(\"Testing\");\n" +
                "    }\n" +
                "    return transform;\n" +
                "}}";
        System.out.println(engine);
        engine.eval(js);
        //engine.put("execution", new TestObj());
        ScriptObjectMirror transform = (ScriptObjectMirror) engine.get("transform");
        ScriptObjectMirror execute = (ScriptObjectMirror) transform.callMember("execute", new TestObj());
        execute.call(execute,new TestObj());
        System.out.println("fully working code");
    }
}
Hello World!
jdk.nashorn.api.scripting.NashornScriptEngine@6d7b4f4c
hello
test:testing
result:[object Object]
myjson object
Testing
fully working code
Related Posts Related Posts :
  • Why is it mandatory for ternary operations to return a value?
  • How can I make my listview rows different heights
  • Array declaration trick : Is it bad to use it?
  • Calling different classes with if else statements
  • Free API for speech recognition system
  • Java: Objects in JFrame are messed up
  • Is there a similar of MessageBox of ExtJS in ADF Faces
  • Passing HttpServletResponse in Spring Boot controller method
  • Failed to load libraries: [netty_tcnative_linux_arm_32, netty_tcnative_linux_arm_32_fedora, netty_tcnative_arm_32, netty
  • How to build a small documents storage?
  • Getting pixel position of a text in an image
  • How do I get a list of Methods called from a Class in Eclipse IDE?
  • Convert string to day of week (not exact date)
  • Unable to understand how rounding is working for decimal digits (Java)
  • How to avoid java.lang.NoSuchMethodError: org.apache.poi.util.IOUtils.copy(Ljava/io/InputStream;Ljava/io/OutputStream;)
  • JTable Renderer not working with RowSorter?
  • From java.util.concurrent.Future<T> to play.libs.F.Promise<T>: How to do that in Java?
  • jUnit tests work in Eclipse, but fail in ant - java.lang.RuntimeException: Stub
  • How do i add a tooltip to existing gwt Textbox?
  • actor replying to non-actor
  • Google Cloud Messaging - server connection
  • Which classes are unmodifiable and cannot be intrumented and is there a way to bypass it?
  • Java & Jersey 1.17: Custom default response headers
  • Java rounding error
  • Setting custom RejectedExecutionHandler for ThreadPoolExecutor after executing some tasks?
  • Arquillian test class variables lose value
  • java.util.ConcurrentModificationException while inserting in ArrayList
  • How to write generic Java API without method Overloading
  • Java Serialization / Deserialization of an ArrayList works only on first program execution
  • Conway's Game of Life's rules dont apply properly
  • call a java method when Click on a html button without using javascript
  • Why does SSLSocketFactory.createSocket returns a Socket instead of SSLSocket?
  • How to schedule a task in Tomcat
  • compare two pdf files (approach) using java
  • What is the use of allowCoreThreadTimeout( ) in ThreadPoolExecutor?
  • Describe the Strategy Design Pattern in Java?
  • MongoDB too many open connections
  • Issue with generate JAXB classes with value constructors
  • Moving from one frame to another in java swing
  • Get a thread by Id
  • how to open front camera and back camera at same time?
  • Messed up with Java Declaration
  • Extracting chart in EXcel as image using java
  • How to get latitude and longitude in Android phone?
  • Do GC pauses and kill -STOP produce the same behavior?
  • Android HTML.ImageGetter Images resized
  • The way to instantiate map<String, List<String>> in Java
  • Java Making objects move while buttons held
  • Androidx Navigation View - `setNavigationItemSelectedListener` Doesn't Work
  • after compiling code JFrame does not appear
  • Netbeans project, JFrames ran from the main JFrame close all JFrames in project
  • Square Retrofit Client: How to enable/disable followRedirects? How to intercept redirect URL?
  • Java Circular Reference - Can’t Compile
  • Mouse click on specific time JAVA
  • android 4 onCreateDialog return type incompatible when overriding
  • Java Implementation of Oracle's DBMS_UTILITY.GET_HASH_VALUE Function
  • javac cannot be run, and furthermore does not seem installed
  • Function to obtain a thread given its ID
  • Java File path to Executable has spaces
  • Minimum Oracle Java VM heap memory setting?
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org