전체 페이지뷰

2017년 3월 6일 월요일

Java Code Examples for javax.script.ScriptEngine

http://www.programcreek.com/java-api-examples/index.php?api=javax.script.ScriptEngine

Example 1
Project: siebog   File: ScriptLoader.java View source code8 votesvote downvote up
public Invocable load(String url, String state) throws ScriptException, NoSuchMethodException {
 ScriptEngineManager manager = new ScriptEngineManager();
 ScriptEngine engine = manager.getEngineByName("JavaScript");
 engine.eval(getFullAgentSouce(url));
 Invocable invocable = (Invocable) engine;
 Object jsAgent = invocable.invokeFunction("getAgentInstance");
 // inject state and signal arrival
 invocable.invokeMethod(jsAgent, "setState", state);
 invocable.invokeMethod(jsAgent, "onArrived", System.getProperty("jboss.node.name"), true);
 return invocable;
}
 
Example 2
Project: xbpm5   File: ScriptingEngines.java View source code8 votesvote downvote up
protected Object evaluate(String script, String language, Bindings bindings) {
  ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(language);

  if (scriptEngine == null) {
    throw new ActivitiException("Can't find scripting engine for '" + language + "'");
  }

  try {
    return scriptEngine.eval(script, bindings);
  } catch (ScriptException e) {
    throw new ActivitiException("problem evaluating script: " + e.getMessage(), e);
  }
}
 

Example 3
Project: btpka3.github.com   File: Main.java View source code7 votesvote downvote up
@SuppressWarnings("unchecked")
public static void main(String[] args) throws ScriptException {
    ScriptEngineManager manager = new ScriptEngineManager();
    List<ScriptEngineFactory> factories = manager.getEngineFactories();
    for (ScriptEngineFactory f : factories) {
        System.out.println("egine name:" + f.getEngineName());
        System.out.println("engine version:" + f.getEngineVersion());
        System.out.println("language name:" + f.getLanguageName());
        System.out.println("language version:" + f.getLanguageVersion());
        System.out.println("names:" + f.getNames());
        System.out.println("mime:" + f.getMimeTypes());
        System.out.println("extension:" + f.getExtensions());
        System.out.println("-----------------------------------------------");
    }

    ScriptEngine engine = manager.getEngineByName("js");
    engine.put("a", 4);
    engine.put("b", 6);
    Object maxNum = engine.eval("function max_num(a,b){return (a>b)?a:b;}max_num(a,b);");
    System.out.println("max_num:" + maxNum + ", (class = " + maxNum.getClass() + ")");

    @SuppressWarnings("rawtypes")
    Map m = new HashMap();
    m.put("c", 10);
    engine.put("m", m);

    engine.eval("var x= max_num(a,m.get('c'));");
    System.out.println("max_num:" + engine.get("x"));
}
 
Example 4
Project: jsr223-nativeshell   File: CmdScriptEngineTest.java View source code7 votesvote downvote up
@Test
public void evaluate_use_bindings() throws Exception {
    ScriptEngine bashScriptEngine = scriptEngine;

    bashScriptEngine.put("string", "aString");
    bashScriptEngine.put("integer", 42);
    bashScriptEngine.put("float", 42.0);

    Integer returnCode = (Integer) bashScriptEngine.eval("echo %string% %integer% %float%");

    assertEquals(NativeShellRunner.RETURN_CODE_OK, returnCode);
    assertEquals("aString 42 42.0\n", scriptOutput.toString());
}
 
Example 5
Project: NucleusFramework   File: ScriptUtils.java View source code7 votesvote downvote up
/**
 * Evaluate a script into a script engine.
 *
 * @param engine   The script engine.
 * @param context  The script context.
 * @param script   The script to evaluate.
 *
 * @return The results returned from the script, if any.
 */
public static Result<Object> eval(ScriptEngine engine, ScriptContext context, IScript script) {

    File file = script.getFile();

    String filename = file != null ? file.getName() : "<unknown>";
    String engineName = engine.getFactory().getEngineName();
    boolean isNashorn = engineName.contains("Nashorn");

    engine.put(ScriptEngine.FILENAME, filename);
    context.setAttribute(ScriptEngine.FILENAME, filename, ScriptContext.ENGINE_SCOPE);

    Object result;

    try {
        if (isNashorn) {

            context.setAttribute("script", script.getScript(), ScriptContext.ENGINE_SCOPE);
            context.setAttribute("scriptName", filename, ScriptContext.ENGINE_SCOPE);

            // evaluate script into Nashorn
            result = engine.eval("load({ script: script, name: scriptName})", context);
        }
        else {
            // evaluate script
            result = engine.eval(script.getScript(), context);
        }

        return new Result<Object>(true, result);

    } catch (Throwable e) {
        e.printStackTrace();
        return new Result<Object>(false);
    }
}
 
Example 6
Project: Desktop   File: PdfUtilitiesController.java View source code7 votesvote downvote up
private void runAppleScript(String readerPath, String filePath, int page) throws ScriptException, IOException {
    StringBuilder builder = new StringBuilder();
    builder.append("global pdfPath\n");
    builder.append("global page\n");
    builder.append("set pdfPath to POSIX file \""+filePath+"\"\n");
    builder.append("set page to "+ page +" as text\n");
    if(readerPath.endsWith(".app")) {
     builder.append("set pdfReaderPath to \""+readerPath+"\"\n\n");
    }
    else{
     builder.append("set pdfReaderPath to null\n\n");
    }
    
    URL url = PdfUtilitiesController.class.getResource("/mac_os/OpenOnPageHead.appleScript");
    appendResourceContent(builder, url);
    if(readerPath.endsWith("Skim.app")) {
     url = PdfUtilitiesController.class.getResource("/mac_os/OpenOnPageSkim.appleScript");
        appendResourceContent(builder, url);
    }
    else {
     url = PdfUtilitiesController.class.getResource("/mac_os/OpenOnPageDefault.appleScript");
        appendResourceContent(builder, url);
    }
    
    final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
       Thread.currentThread().setContextClassLoader(null);
      
       ScriptEngineManager mgr = new ScriptEngineManager();
    ScriptEngine engine = mgr.getEngineByName("AppleScript");
    
       Thread.currentThread().setContextClassLoader(contextClassLoader);     
 engine.eval(builder.toString());  
 LogUtils.info("Successfully ran apple script");
}
 
Example 7
Project: jtotus   File: NordnetConnect.java View source code7 votesvote downvote up
public String fetchEncryptedPassword(String encryptJS, String pass, String pubKey, String sessionId) {
    String password = null;

    StartUpLoader loader = StartUpLoader.getInstance();

    //ScriptEngineManager mgr = loader.getLoadedScriptManager();
    //         Bindings bindings = mgr.getBindings();

     ScriptEngine engine =  loader.getLoadedEngine();
     Bindings bindings = engine.getBindings(ScriptContext.GLOBAL_SCOPE);

     try {
         StringBuilder strBuild = new StringBuilder();
         strBuild.append(encryptJS);

         strBuild.append(" \n var keyObj = RSA.getPublicKey(\'"+pubKey+"\');\n"
                        + "  var encryptedPass = RSA.encrypt(\'"+pass+"\', keyObj, \'"+sessionId+"\');\n");

         engine.eval(strBuild.toString(), bindings);

         password = (String)bindings.get("encryptedPass");
         
    } catch (ScriptException ex) {
        Logger.getLogger(NordnetConnector.class.getName()).log(Level.SEVERE, null, ex);
    }

     log.info("JavaScript engine loaded:" + engine.NAME);

     return password;
}
 
Example 8
Project: FireflowEngine20   File: ScriptEngineHelper.java View source code7 votesvote downvote up
private static Object evaluateJSR233Expression(RuntimeContext rtCtx,Expression fireflowExpression,Map<String,Object> contextObjects){
 ScriptEngine scriptEngine = rtCtx.getScriptEngine(fireflowExpression.getLanguage());
 
 ScriptContext scriptContext = new SimpleScriptContext();
 Bindings engineScope = scriptContext
   .getBindings(ScriptContext.ENGINE_SCOPE);
 engineScope.putAll(contextObjects);
 try {
  Object result = scriptEngine.eval(fireflowExpression.getBody(), scriptContext);
  return result;
 } catch (ScriptException e) {
  throw new RuntimeException("Can NOT evaluate the expression. ",e);
 }
}
 
Example 9
Project: gatein-portal   File: TestModule.java View source code7 votesvote downvote up
private void assertReader(Object expected, Reader reader) {
    try {
        assertNotNull(reader);
        StringWriter script = new StringWriter();
        IOTools.copy(reader, script);
        ScriptEngineManager mgr = new ScriptEngineManager();
        ScriptEngine engine = mgr.getEngineByName("JavaScript");
        engine.eval(script.toString());
        Object test = engine.get("test");
        assertEquals(expected, test);
    } catch (Exception e) {
        throw failure(e);
    }
}
 
Example 10
Project: org.openscada.deploy   File: Configuration.java View source code7 votesvote downvote up
public void applyScriptOverride ( final File file ) throws FileNotFoundException, ScriptException
{
    if ( file.isDirectory () )
    {
        return;
    }

    this.logStream.println ( "Running script: " + file ); //$NON-NLS-1$

    final ScriptEngineManager manager = new ScriptEngineManager ();

    final ScriptEngine engine = manager.getEngineByExtension ( getExtension ( file ) );
    final ScriptContext context = engine.getContext ();
    context.setAttribute ( "items", this.items.toArray (), ScriptContext.ENGINE_SCOPE ); //$NON-NLS-1$
    context.setAttribute ( "baseDir", file.getParent (), ScriptContext.ENGINE_SCOPE );//$NON-NLS-1$

    engine.eval ( new FileReader ( file ) );
}
 
Example 11
Project: Athena   File: EOObject.java View source code7 votesvote downvote up
/** to be called in {@link #validateBeforeInsert(UserContext)} */
  private void entityScopedValidation() {
if (getEntity().getValidationLogic() == null || getEntity().getValidationLogic().trim().length() == 0) {
 // nothing to validate.
 return;
}

String validationScript = "__result = (" + getEntity().getValidationLogic() + "); "; //$NON-NLS-1$ //$NON-NLS-2$

if(log.isDebugEnabled()) {
 log.debug("JS: " + validationScript); //$NON-NLS-1$
}

ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("js"); //$NON-NLS-1$
for (int i = 0; i < getEntity().countAttributes(); i++) { // put all attributes into the engine.
 engine.put(getEntity().getAttribute(i).getSystemName(), getObject(i));
}

Object result = null;
try {
 result = engine.eval(validationScript);
 if ((Boolean) result) {
  return;
 } else {
  throw new ValidationException(null, this, getEntity(), null, LocalizedMessages
    .getString("AbstractGeneratedEntity.VALIDATION_CODE_RETURNED_FALSE")); //$NON-NLS-1$
 }
} catch (Exception e) {
 throw new ValidationException(null, this, getEntity(), null, LocalizedMessages.getString(
   "AbstractGeneratedEntity.VALIDATION_FAILED", e.getMessage(), validationScript)); //$NON-NLS-1$
}
  }
 
Example 12
Project: ui-bindings   File: EngineScopeTest.java View source code7 votesvote downvote up
public static void main(String[] args) throws ScriptException {
 final ScriptEngineManager manager = new ScriptEngineManager();
 final ScriptEngine engine = manager.getEngineByName("js");

 final SimpleBindings bindings = new SimpleBindings();
 bindings.put("name", "World");

 engine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);

 final SimpleBindings evalBindings = new SimpleBindings();
 evalBindings.put("name", "Another world");

 System.out.println(engine.eval("\"Hello \"+name")); // Default scope
 System.out.println(engine.eval("\"Hello \"+name", evalBindings));
}
 
Example 13
Project: deepnighttwo   File: ScriptInJavaMainApp.java View source code7 votesvote downvote up
private static void aboutBindings(ScriptEngine jsEngine)
  throws ScriptException {
 Bindings bindings = jsEngine.createBindings();
 bindings.put("value", "Value from bindings conext");
 jsEngine.eval("println(value)", bindings);
 // the following code will trigger an exception
 try {
  jsEngine.eval("println(value)");
 } catch (ScriptException ex) {
  System.out.println("Exception :" + ex.getMessage());
 }
 // here is the script engine runtime context
 ScriptContext scriptConext = jsEngine.getContext();
 System.out.println(scriptConext);
 // just for this script engine;
 Bindings engineBindings = jsEngine
   .getBindings(ScriptContext.ENGINE_SCOPE);
 System.out.println(engineBindings.size());
 // shared with all script engines created by the same
 // ScriptEngineManager
 System.out.println(jsEngine.getBindings(ScriptContext.GLOBAL_SCOPE)
   .size());
 // set ENGINE_SCOPE bindings and now the invocation has no exception.
 jsEngine.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
 jsEngine.eval("println(value)");
}
 

댓글 없음:

댓글 쓰기