javax.script.ScriptEngine.put()方法的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(11.9k)|赞(0)|评价(0)|浏览(339)

本文整理了Java中javax.script.ScriptEngine.put()方法的一些代码示例,展示了ScriptEngine.put()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ScriptEngine.put()方法的具体详情如下:
包路径:javax.script.ScriptEngine
类名称:ScriptEngine
方法名:put

ScriptEngine.put介绍

[英]Associates a key and a value in the ScriptEngine ENGINE_SCOPE bindings.
[中]在ScriptEngine_范围绑定中关联一个键和一个值。

代码示例

代码示例来源:origin: internetarchive/heritrix3

@Override
protected void innerProcess(CrawlURI curi) {
  // depending on previous configuration, engine may 
  // be local to this thread or shared
  ScriptEngine engine = getEngine(); 
  synchronized(engine) {
    // synchronization is harmless for local thread engine,
    // necessary for shared engine
    engine.put("curi",curi);
    engine.put("appCtx", appCtx);
    try {
      engine.eval("process(curi)");
    } catch (ScriptException e) {
      logger.log(Level.WARNING,e.getMessage(),e);
    } finally { 
      engine.put("curi", null);
      engine.put("appCtx", null);
    }
  }
}

代码示例来源:origin: internetarchive/heritrix3

@Override
public DecideResult innerDecide(CrawlURI uri) {
  // depending on previous configuration, engine may 
  // be local to this thread or shared
  ScriptEngine engine = getEngine(); 
  synchronized(engine) {
    // synchronization is harmless for local thread engine,
    // necessary for shared engine
    try {
      engine.put("object",uri);
      engine.put("appCtx", appCtx);
      return (DecideResult)engine.eval("decisionFor(object)");
    } catch (ScriptException e) {
      logger.log(Level.WARNING,e.getMessage(),e);
      return DecideResult.NONE;
    } finally {
      engine.put("object", null);
      engine.put("appCtx", null);
    }
  }
}

代码示例来源:origin: zendesk/maxwell

public Scripting(String filename) throws IOException, ScriptException, NoSuchMethodException {
  ScriptEngineManager manager = new ScriptEngineManager();
  ScriptEngine engine = manager.getEngineByName("nashorn");
  String externJS = new String(Files.readAllBytes(Paths.get(filename)));
  engine.put("logger", LOGGER);
  engine.eval(externJS);
  processRowFunc = getFunc(engine, "process_row", filename);
  processHeartbeatFunc = getFunc(engine, "process_heartbeat", filename);
  processDDLFunc = getFunc(engine, "process_ddl", filename);
  if ( processRowFunc == null && processHeartbeatFunc == null && processDDLFunc == null )
    LOGGER.warn("expected " + filename + " to define at least one of: process_row,process_heartbeat,process_ddl");
}

代码示例来源:origin: kiegroup/optaplanner

public static int resolveThreadPoolSizeScript(String propertyName, String script, String... magicValues) {
  final String scriptLanguage = "JavaScript";
  ScriptEngine scriptEngine = new ScriptEngineManager().getEngineByName(scriptLanguage);
  if (scriptEngine == null) {
    throw new IllegalStateException("The " + propertyName + " (" + script
        + ") could not resolve because the JVM doesn't support scriptLanguage (" + scriptLanguage + ").\n"
        + "Maybe try running in a normal JVM.");
  }
  scriptEngine.put(AVAILABLE_PROCESSOR_COUNT, Runtime.getRuntime().availableProcessors());
  Object scriptResult;
  try {
    scriptResult = scriptEngine.eval(script);
  } catch (ScriptException e) {
    throw new IllegalArgumentException("The " + propertyName + " (" + script
        + ") is not in magicValues (" + Arrays.toString(magicValues)
        + ") and cannot be parsed in " + scriptLanguage
        + " with the variables ([" + AVAILABLE_PROCESSOR_COUNT + "]).", e);
  }
  if (!(scriptResult instanceof Number)) {
    throw new IllegalArgumentException("The " + propertyName + " (" + script
        + ") is resolved to scriptResult (" + scriptResult + ") in " + scriptLanguage
        + " but is not a " + Number.class.getSimpleName() + ".");
  }
  return ((Number) scriptResult).intValue();
}

代码示例来源:origin: internetarchive/heritrix3

/**
 * Create a new ScriptEngine instance, preloaded with any supplied
 * source file and the variables 'self' (this ScriptedDecideRule) 
 * and 'context' (the ApplicationContext). 
 * 
 * @return  the new Interpreter instance
 */
protected ScriptEngine newEngine() {
  ScriptEngine interpreter = new ScriptEngineManager().getEngineByName(engineName);
  interpreter.put("self", this);
  interpreter.put("context", appCtx);
  
  Reader reader = null;
  try {
    reader = getScriptSource().obtainReader();
    interpreter.eval(reader);
  } catch (ScriptException e) {
    logger.log(Level.SEVERE,"script problem",e);
  } finally {
    IOUtils.closeQuietly(reader);
  }
  return interpreter; 
}

代码示例来源:origin: internetarchive/heritrix3

/**
   * Create a new {@link ScriptEngine} instance, preloaded with any supplied
   * source file and the variables 'self' (this {@link ScriptedProcessor}) and
   * 'context' (the {@link ApplicationContext}).
   * 
   * @return the new ScriptEngine instance
   */
  protected ScriptEngine newEngine() {
    ScriptEngine interpreter = new ScriptEngineManager().getEngineByName(engineName);

    interpreter.put("self", this);
    interpreter.put("context", appCtx);
    
    Reader reader = null;
    try {
      reader = getScriptSource().obtainReader();
      interpreter.eval(reader);
    } catch (ScriptException e) {
      logger.log(Level.SEVERE,"script problem",e);
    } finally {
      IOUtils.closeQuietly(reader);
    }

    return interpreter; 
  }
}

代码示例来源:origin: kiegroup/jbpm

public void execute(ProcessContext context) throws Exception {
  ScriptEngineManager factory = new ScriptEngineManager();
  ScriptEngine engine = factory.getEngineByName("JavaScript");
  engine.put("kcontext", context);
  
  // insert globals into context
  Globals globals = context.getKieRuntime().getGlobals();
  
  if (globals != null && globals.getGlobalKeys() != null) {
    for (String gKey : globals.getGlobalKeys()) {
      engine.put(gKey, globals.get(gKey));
    }
  }
  if (context.getProcessInstance() != null && context.getProcessInstance().getProcess() != null) {
    // insert process variables
    VariableScopeInstance variableScope = (VariableScopeInstance) ((WorkflowProcessInstance)context.getProcessInstance())
        .getContextInstance(VariableScope.VARIABLE_SCOPE);

    Map<String, Object> variables = variableScope.getVariables();
    if (variables != null ) {
      for (Entry<String, Object> variable : variables.entrySet()) {
        engine.put(variable.getKey(), variable.getValue());
      }
    }
  }
  engine.eval(expr);
}

代码示例来源:origin: kiegroup/jbpm

engine.put(gKey, globals.get(gKey));
engine.put("kcontext", context);
if (context.getProcessInstance() != null && context.getProcessInstance().getProcess() != null) {
  if (variables != null ) {
    for (Entry<String, Object> variable : variables.entrySet()) {
      engine.put(variable.getKey(), variable.getValue());
Object value = engine.eval(expr);

代码示例来源:origin: jphp-group/jphp

@Test
public void testVariableSet() throws Exception {
  ScriptEngineManager factory = new ScriptEngineManager();
  ScriptEngine engine = factory.getEngineByName("jphp");
  engine.put("foo", "bar");
  Object value = engine.eval("<?php return $foo;");
  Assert.assertEquals("bar", value.toString());
}

代码示例来源:origin: groovy/groovy-core

@Test
public void testSimpleExample() throws ScriptException {
  // tag::jsr223_init[]
  ScriptEngineManager factory = new ScriptEngineManager();
  ScriptEngine engine = factory.getEngineByName("groovy");
  // end::jsr223_init[]
  // tag::jsr223_basic[]
  Integer sum = (Integer) engine.eval("(1..10).sum()");
  assertEquals(new Integer(55), sum);
  // end::jsr223_basic[]
  // tag::jsr223_variables[]
  engine.put("first", "HELLO");
  engine.put("second", "world");
  String result = (String) engine.eval("first.toLowerCase() + ' ' + second.toUpperCase()");
  assertEquals("hello WORLD", result);
  // end::jsr223_variables[]
}

代码示例来源:origin: oblac/jodd

protected String run(String html, String query) throws ScriptException {
  Jerry doc = Jerry.jerry(html);
  scriptEngine.put("doc", doc);
  scriptEngine.eval(query);
  return doc.html();
}

代码示例来源:origin: stackoverflow.com

int eval(String code) {
  code = "function f () {" + code + "} f()"; // Or otherwise
  ScriptEngineManager factory = new ScriptEngineManager();
  ScriptEngine engine = factory.getEngineByName("JavaScript");
  engine.put("score", 1.4);
  Number num = (Number) engine.eval(code);
  return num.intValue();
}

代码示例来源:origin: jwpttcg66/NettyGameServer

/**
 * 执行指定的脚本内容
 *
 * @param content    脚本内容
 * @param params    执行参数
 * @return            脚本执行结果的返回值
 */
public static Object executeScriptContent(String content,
    Map<String, Object> params) {
  ScriptEngine engine = manager.getEngineByName("JavaScript");
  if (params != null) {
    for (Map.Entry<String, Object> pair : params.entrySet()) {
      engine.put(pair.getKey(), pair.getValue());
    }
  }
  try {
    return engine.eval(content);
  } catch (ScriptException e) {
    logger.error("", e);
  }
  return null;
}

代码示例来源:origin: stackoverflow.com

// build a Map
Map<String, String> map = new HashMap<String, String>();
map.put("bye", "now");

// Convert it to a NativeObject (yes, this could have been done directly)
NativeObject nobj = new NativeObject();
for (Map.Entry<String, String> entry : map.entrySet()) {
  nobj.defineProperty(entry.getKey(), entry.getValue(), NativeObject.READONLY);
}

// Get Engine and place native object into the context
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("javascript");
engine.put("map", nobj);

// Standard Javascript dot notation prints 'now' (as it should!)
engine.eval("println(map.bye);");

代码示例来源:origin: lenskit/lenskit

public static void main(String[] args) throws IOException, ScriptException {
    File scriptFile = new File(args[0]);
    ScriptEngineManager sem = new ScriptEngineManager();
    String ext = Files.getFileExtension(scriptFile.getName());
    ScriptEngine engine = sem.getEngineByExtension(ext);
    engine.put("cmdArgs", Arrays.asList(args).subList(1, args.length));
    try (Reader reader = Files.newReader(scriptFile, Charsets.UTF_8)) {
      engine.eval(reader);
    }
  }
}

代码示例来源:origin: jwpttcg66/NettyGameServer

if (params != null) {
  for (Map.Entry<String, Object> pair : params.entrySet()) {
    engine.put(pair.getKey(), pair.getValue());
  reader = new InputStreamReader(new FileInputStream(path),
      STRING_CHARSET);
  return engine.eval(reader);
} catch (FileNotFoundException | UnsupportedEncodingException | ScriptException e) {
  logger.error("", e);

代码示例来源:origin: lenskit/lenskit

private void writeSvgFile(DAGNode<Component, Dependency> graph, File outFile) throws IOException, LenskitCommandException {
  StringWriter sw = new StringWriter();
  logger.info("writing graph to memory");
  GraphDumper.renderGraph(graph, sw);
  String dotSrc = sw.toString();
  logger.debug("setting up script engine");
  ScriptEngineManager sem = new ScriptEngineManager();
  ScriptEngine engine = sem.getEngineByMimeType("text/javascript");
  try (InputStream istr = Graph.class.getResourceAsStream("/META-INF/resources/webjars/viz.js/1.5.1/viz.js");
     Reader rdr = new InputStreamReader(istr)) {
    logger.debug("loading Viz.js");
    engine.put(ScriptEngine.FILENAME, "viz.js");
    engine.eval(rdr);
  } catch (ScriptException e) {
    logger.error("error loading Viz.js", e);
    throw new LenskitCommandException("Could not load Viz.js", e);
  }
  engine.put("dotSrc", dotSrc);
  engine.put("outFile", outFile);
  try (InputStream istr = Graph.class.getResourceAsStream("render-graph.js");
     Reader rdr = new InputStreamReader(istr)) {
    logger.info("rendering graph to {}", outFile);
    engine.put(ScriptEngine.FILENAME, "render-graph.js");
    engine.eval(rdr);
  } catch (ScriptException e) {
    logger.error("error evaluating render script", e);
    throw new LenskitCommandException("could not evaluate SVG renderer", e);
  }
}

代码示例来源:origin: SeanDragon/protools

engine.put(key, paramMap.get(key));
engine.eval(templateContent);

代码示例来源:origin: bluejoe2008/openwebflow

@Override
public void notify(UserDetailsEntity[] users, Task task) throws Exception
{
  for (UserDetailsEntity user : users)
  {
    if (user == null)
      continue;
    ScriptEngine scriptEngine = new JuelScriptEngineFactory().getScriptEngine();
    scriptEngine.put("user", user);
    scriptEngine.put("task", task);
    String email = user.getProperty(UserDetailsEntity.STRING_PROPERTY_EMAIL);
    if (email != null)
    {
      _mailSender.sendMail(email, (String) scriptEngine.eval(_subjectTemplate),
        (String) scriptEngine.eval(_messageTemplate));
    }
  }
}

代码示例来源:origin: naver/ngrinder

@Test
public void testPerfTestScript() throws ScriptException {
  ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
  engine.put("A", 10);
  engine.put("B", 4);
  System.out.println(engine.eval(" [(A / 2), (A + 3)];"));
}

相关文章