javax.script.ScriptEngineManager#getEngineByExtension ( )源码实例Demo

下面列出了javax.script.ScriptEngineManager#getEngineByExtension ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Nullable
protected ScriptEngine retrieveScriptEngine(ScriptSource scriptSource) {
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager(this.beanClassLoader);

	if (this.scriptEngineName != null) {
		return StandardScriptUtils.retrieveEngineByName(scriptEngineManager, this.scriptEngineName);
	}

	if (scriptSource instanceof ResourceScriptSource) {
		String filename = ((ResourceScriptSource) scriptSource).getResource().getFilename();
		if (filename != null) {
			String extension = StringUtils.getFilenameExtension(filename);
			if (extension != null) {
				ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension);
				if (engine != null) {
					return engine;
				}
			}
		}
	}

	return null;
}
 
@Nullable
protected ScriptEngine retrieveScriptEngine(ScriptSource scriptSource) {
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager(this.beanClassLoader);

	if (this.scriptEngineName != null) {
		return StandardScriptUtils.retrieveEngineByName(scriptEngineManager, this.scriptEngineName);
	}

	if (scriptSource instanceof ResourceScriptSource) {
		String filename = ((ResourceScriptSource) scriptSource).getResource().getFilename();
		if (filename != null) {
			String extension = StringUtils.getFilenameExtension(filename);
			if (extension != null) {
				ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension);
				if (engine != null) {
					return engine;
				}
			}
		}
	}

	return null;
}
 
源代码3 项目: lams   文件: StandardScriptFactory.java
protected ScriptEngine retrieveScriptEngine(ScriptSource scriptSource) {
	ScriptEngineManager scriptEngineManager = new ScriptEngineManager(this.beanClassLoader);

	if (this.scriptEngineName != null) {
		return StandardScriptUtils.retrieveEngineByName(scriptEngineManager, this.scriptEngineName);
	}

	if (scriptSource instanceof ResourceScriptSource) {
		String filename = ((ResourceScriptSource) scriptSource).getResource().getFilename();
		if (filename != null) {
			String extension = StringUtils.getFilenameExtension(filename);
			if (extension != null) {
				ScriptEngine engine = scriptEngineManager.getEngineByExtension(extension);
				if (engine != null) {
					return engine;
				}
			}
		}
	}

	return null;
}
 
源代码4 项目: org.openntf.domino   文件: JSR223Tasklet.java
@Override
public void run() {
	Database database = Factory.getSession(SessionType.CURRENT).getDatabase(databasePath_);

	ScriptEngineManager manager = new ScriptEngineManager();
	ScriptEngine engine = manager.getEngineByExtension(scriptExt_);

	engine.put("database", database);
	engine.put("session", database.getAncestorSession());

	ScriptContext context = engine.getContext();
	context.setWriter(new PrintWriter(System.out));
	context.setErrorWriter(new PrintWriter(System.err));

	try {
		engine.eval(script_);
	} catch (ScriptException e) {
		throw new RuntimeException(e);
	}
}
 
源代码5 项目: scheduling   文件: AbstractSchedulerCommandTest.java
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    jobIdFaker = new DataFaker<JobIdData>(JobIdData.class);
    jobIdFaker.setGenerator("readableName", new PrefixPropertyGenerator("job", 1));

    when(context.getRestClient()).thenReturn(restClient);
    when(restClient.getScheduler()).thenReturn(restApi);
    when(context.resultStack()).thenReturn(stack);

    capturedOutput = new ByteArrayOutputStream();
    userInput = new StringBuffer();

    ScriptEngineManager mgr = new ScriptEngineManager();
    engine = mgr.getEngineByExtension("js");
    when(context.getEngine()).thenReturn(engine);

    when(context.getProperty(eq(AbstractIModeCommand.TERMINATE), any(Class.class), anyBoolean())).thenReturn(false);

    //Mockito.when(ApplicationContextImpl.currentContext()).thenReturn(context);
    ApplicationContextImpl.mockCurrentContext(context.newApplicationContextHolder());
}
 
源代码6 项目: scheduling   文件: ScriptLoader.java
/**
 * Main function
 * @param args command arguments.
 * @throws Exception if fails.
 */
public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.err.println("Usage : scriptloader script");
        System.exit(1);
    }

    String filename = args[0];
    String[] split = filename.split("\\.");

    if (split.length < 2) {
        System.err.println("Script must have an extension");
        System.exit(-2);
    }

    try (Reader reader = new FileReader(args[0])) {
        ScriptEngineManager sem = new ScriptEngineManager();
        ScriptEngine engine = sem.getEngineByExtension(split[split.length - 1]);
        engine.eval(reader);
    }
}
 
源代码7 项目: netbeans   文件: JavaScriptEnginesTest.java
private static void fillArray(final ScriptEngineManager man, boolean allowAllAccess, List<Object[]> arr) {
    for (ScriptEngineFactory f : man.getEngineFactories()) {
        final String name = f.getEngineName();
        if (
                f.getMimeTypes().contains("text/javascript") ||
                name.contains("Nashorn")
                ) {
            final ScriptEngine eng = f.getScriptEngine();
            arr.add(new Object[] { name, "engineFactories", implName(eng), eng, allowAllAccess });
            for (String n : eng.getFactory().getNames()) {
                ScriptEngine byName = n == null ? null : man.getEngineByName(n);
                if (byName != null && eng.getClass() == byName.getClass()) {
                    arr.add(new Object[] { n, "name", implName(byName), byName, allowAllAccess });
                }
            }
            for (String t : eng.getFactory().getMimeTypes()) {
                ScriptEngine byType = t == null ? null : man.getEngineByMimeType(t);
                if (byType != null && eng.getClass() == byType.getClass()) {
                    arr.add(new Object[] { t, "type", implName(byType), byType, allowAllAccess });
                }
            }
            for (String e : eng.getFactory().getExtensions()) {
                ScriptEngine byExt = e == null ? null : man.getEngineByExtension(e);
                if (byExt != null && eng.getClass() == byExt.getClass()) {
                    arr.add(new Object[] { e, "ext", implName(byExt), byExt, allowAllAccess });
                }
            }
        }
    }
}
 
源代码8 项目: javase   文件: HelloWorldJSFile.java
public static void main(String[] args) throws Exception {
  ScriptEngineManager m = new ScriptEngineManager();

  // Sets up Nashorn JavaScript Engine
  ScriptEngine e = m.getEngineByExtension("js");

  // Nashorn JavaScript syntax.
   e.eval("print ('Hello, ')");

  // world.js contents: print('World!\n');
  Path p1 = Paths.get("/home/stud/javase/lectures/c06/src/nashornjs/word.js");

  e.eval(new FileReader(p1.toString()));
}
 
源代码9 项目: Knowage-Server   文件: KpiService.java
private void checkMandatory(HttpServletRequest req, JSError jsError, Kpi kpi) throws JSONException, EMFUserError {
	if (kpi.getName() == null) {
		jsError.addErrorKey(NEW_KPI_NAME_MANDATORY);
	}
	if (kpi.getDefinition() == null) {
		jsError.addErrorKey(NEW_KPI_DEFINITION_MANDATORY);
	} else {
		// validating kpi formula
		ScriptEngineManager sm = new ScriptEngineManager();
		ScriptEngine engine = sm.getEngineByExtension("js");
		String script = new JSONObject(kpi.getDefinition()).getString("formula");
		script = script.replace("M", "");
		if (script.matches("[\\s\\+\\-\\*/\\d\\(\\)]+")) {
			try {
				engine.eval(script);
			} catch (Throwable e) {
				jsError.addErrorKey(NEW_KPI_DEFINITION_SYNTAXERROR);
			}
		} else {
			jsError.addErrorKey(NEW_KPI_DEFINITION_INVALIDCHARACTERS);
		}
		// validating kpi formula
		JSONArray measureArray = new JSONObject(kpi.getDefinition()).getJSONArray("measures");
		IKpiDAO dao = getKpiDAO(req);
		String[] measures = measureArray.join(",").split(",");
		dao.existsMeasureNames(measures);
	}
}
 
源代码10 项目: Android_Code_Arbiter   文件: ScriptEngineSample.java
public static void scriptingSafe() throws ScriptException {

        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension("js");

        String code = "var test=3;test=test*2;";
        Object result = scriptEngine.eval(code);
    }
 
源代码11 项目: scipio-erp   文件: ScriptUtil.java
/**
 * Returns a compiled script.
 *
 * @param filePath Script path and file name.
 * @return The compiled script, or <code>null</code> if the script engine does not support compilation.
 * @throws IllegalArgumentException
 * @throws ScriptException
 * @throws IOException
 */
public static CompiledScript compileScriptFile(String filePath) throws ScriptException, IOException {
    Assert.notNull("filePath", filePath);
    CompiledScript script = parsedScripts.get(filePath);
    if (script == null) {
        ScriptEngineManager manager = getScriptEngineManager();
        String fileExtension = getFileExtension(filePath); // SCIPIO: slight refactor
        if ("bsh".equalsIgnoreCase(fileExtension)) { // SCIPIO: 2018-09-19: Warn here, there's nowhere else we can do it...
            Debug.logWarning("Deprecated Beanshell script file invoked (" + filePath + "); "
                    + "this is a compatibility mode only (runs as Groovy); please convert to Groovy script", module);
            fileExtension = "groovy";
        }
        ScriptEngine engine = manager.getEngineByExtension(fileExtension);
        if (engine == null) {
            throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
        }
        engine = configureScriptEngineForInvoke(engine); // SCIPIO: 2017-01-27: Custom configurations for the engine
        try {
            Compilable compilableEngine = (Compilable) engine;
            URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
            BufferedReader reader = new BufferedReader(new InputStreamReader(scriptUrl.openStream(), UtilIO
                .getUtf8()));
            script = compilableEngine.compile(reader);
            if (Debug.verboseOn()) {
                Debug.logVerbose("Compiled script " + filePath + " using engine " + engine.getClass().getName(), module);
            }
        } catch (ClassCastException e) {
            if (Debug.verboseOn()) {
                Debug.logVerbose("Script engine " + engine.getClass().getName() + " does not implement Compilable", module);
            }
        }
        if (script != null) {
            parsedScripts.putIfAbsent(filePath, script);
        }
    }
    return script;
}
 
源代码12 项目: incubator-hivemall   文件: TreePredictUDFv1.java
JavascriptEvaluator() throws UDFArgumentException {
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension("js");
    if (!(engine instanceof Compilable)) {
        throw new UDFArgumentException(
            "ScriptEngine was not compilable: " + engine.getFactory().getEngineName()
                    + " version " + engine.getFactory().getEngineVersion());
    }
    this.scriptEngine = engine;
    this.compilableEngine = (Compilable) engine;
}
 
源代码13 项目: scheduling   文件: ApplicationContextImpl.java
@Override
public ScriptEngine getEngine() {
    ScriptEngine engine = getProperty(SCRIPT_ENGINE, ScriptEngine.class);
    if (engine == null) {
        ScriptEngineManager mgr = new ScriptEngineManager();
        engine = mgr.getEngineByExtension("js");
        if (engine == null) {
            throw new CLIException(REASON_OTHER, "Cannot obtain JavaScript engine instance.");
        }
        engine.getContext().setWriter(getDevice().getWriter());
        setProperty(SCRIPT_ENGINE, engine);
    }
    return engine;
}
 
源代码14 项目: scheduling   文件: EngineScript.java
/**
 * Execute a script and return a result of this form : 'selected={true|false}'
 * Return null if problem occurs
 *
 * @param the path of your script
 * @param the language of your script
 * @param propertyFile the file where to find the properties to test
 * 			behavior just used for the test. The filePath (relative issue) is passed to the script as argument
 * @return the result string or null if problem occurs
 */
public static String EvalScript(String pathFile, Language language, String propertyFile) {
    // ScriptEngineManager
    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine moteur;

    // Engine selection
    switch (language) {
        case javascript:
        case python:
        case ruby:
            moteur = manager.getEngineByExtension(language.getExtension());
            break;
        default:
            System.out.println("Invalid language");
            return null;
    }

    try {
        Bindings bindings = moteur.getBindings(ScriptContext.ENGINE_SCOPE);
        bindings.clear();
        bindings.put(propertiesFile, propertyFile);
        moteur.eval(readFile(new File(pathFile)), bindings);

        return "selected=" + bindings.get("selected");
    } catch (ScriptException e) {
        e.printStackTrace();
        return null;
    }
}
 
源代码15 项目: microcks   文件: SoapController.java
private String getDispatchCriteriaFromScriptEval(Operation operation, String body, HttpServletRequest request) {
   ScriptEngineManager sem = new ScriptEngineManager();
   try {
      // Evaluating request with script coming from operation dispatcher rules.
      ScriptEngine se = sem.getEngineByExtension("groovy");
      SoapUIScriptEngineBinder.bindSoapUIEnvironment(se, body, request);
      return (String) se.eval(operation.getDispatcherRules());
   } catch (Exception e) {
      log.error("Error during Script evaluation", e);
   }
   return null;
}
 
源代码16 项目: scipio-erp   文件: ScriptUtil.java
/**
 * Executes the script at the specified location and returns the result.
 *
 * @param filePath Script path and file name.
 * @param functionName Optional function or method to invoke.
 * @param scriptContext Script execution context.
 * @param args Function/method arguments.
 * @return The script result.
 * @throws ScriptException
 * @throws NoSuchMethodException
 * @throws IOException
 * @throws IllegalArgumentException
 */
public static Object executeScript(String filePath, String functionName, ScriptContext scriptContext, Object[] args) throws ScriptException, NoSuchMethodException, IOException {
    Assert.notNull("filePath", filePath, "scriptContext", scriptContext);
    scriptContext.setAttribute(ScriptEngine.FILENAME, filePath, ScriptContext.ENGINE_SCOPE);
    if (functionName == null) {
        // The Rhino script engine will not work when invoking a function on a compiled script.
        // The test for null can be removed when the engine is fixed.
        CompiledScript script = compileScriptFile(filePath);
        if (script != null) {
            return executeScript(script, functionName, scriptContext, args);
        }
    }
    String fileExtension = getFileExtension(filePath);
    if ("bsh".equalsIgnoreCase(fileExtension)) { // SCIPIO: 2018-09-19: Warn here, there's nowhere else we can do it...
        Debug.logWarning("Deprecated Beanshell script file invoked (" + filePath + "); "
                + "this is a compatibility mode only (runs as Groovy); please convert to Groovy script", module);
        // FIXME?: This does not properly use the GroovyLangVariant.BSH bindings for scripts in filesystem... unclear if should have
        fileExtension = "groovy";
    }
    ScriptEngineManager manager = getScriptEngineManager();
    ScriptEngine engine = manager.getEngineByExtension(fileExtension);
    if (engine == null) {
        throw new IllegalArgumentException("The script type is not supported for location: " + filePath);
    }
    engine = configureScriptEngineForInvoke(engine); // SCIPIO: 2017-01-27: Custom configurations for the engine
    if (Debug.verboseOn()) {
        Debug.logVerbose("Begin processing script [" + filePath + "] using engine " + engine.getClass().getName(), module);
    }
    engine.setContext(scriptContext);
    URL scriptUrl = FlexibleLocation.resolveLocation(filePath);
    try (
            InputStreamReader reader = new InputStreamReader(new FileInputStream(scriptUrl.getFile()), UtilIO
                    .getUtf8());) {
        Object result = engine.eval(reader);
        if (UtilValidate.isNotEmpty(functionName)) {
            try {
                Invocable invocableEngine = (Invocable) engine;
                result = invocableEngine.invokeFunction(functionName, args == null ? EMPTY_ARGS : args);
            } catch (ClassCastException e) {
                throw new ScriptException("Script engine " + engine.getClass().getName()
                        + " does not support function/method invocations");
            }
        }
        return result;
    }
}
 
源代码17 项目: dynkt   文件: KotlinScriptEngineTest.java
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	ScriptEngineManager mgr = new ScriptEngineManager();
	engine = mgr.getEngineByExtension("kts");
}
 
源代码18 项目: binnavi   文件: CScriptingDialog.java
/**
 * Executes a script file without displaying it in the dialog.
 *
 * @param scriptFile The file to execute.
 */
private void executeScriptFile(final File scriptFile) {
  final List<Pair<String, Object>> bindings = toPairList(m_bindings);

  final ScriptEngineManager manager = new ScriptEngineManager();

  final ScriptEngine engine =
      manager.getEngineByExtension(FileUtils.getFileExtension(scriptFile));

  final IScriptConsole console = new ConsoleWriter(new StringWriter());

  engine.getContext().setWriter(console.getWriter());

  bindings.add(new Pair<String, Object>("SCRIPT_CONSOLE", console));

  final ScriptThread thread = new ScriptThread(engine, scriptFile, bindings);

  CProgressDialog.showEndless(
      getOwner(), String.format("Executing '%s'", scriptFile.getAbsolutePath()), thread);

  if (thread.getException() != null) {
    CUtilityFunctions.logException(thread.getException());

    final String message = "E00108: " + "Script file could not be executed";
    final String description = CUtilityFunctions.createDescription(String.format(
        "The script file '%s' could not be executed.",
        scriptFile.getAbsolutePath()), new String[] {
        "The script file is in use by another program and can not be read.",
        "You do not have sufficient rights to read the file",
        "The script contains a bug that caused an exception."},
        new String[] {"BinNavi can not read the script file."});

    NaviErrorDialog.show(CScriptingDialog.this, message, description, thread.getException());
  }

  final IScriptPanel panel = (IScriptPanel) scriptTab.getSelectedComponent();

  panel.setOutput(console.getOutput());

  toFront();
}
 
源代码19 项目: luaj   文件: AppTest.java
public void testScriptEngineEvaluation() throws ScriptException {
    ScriptEngineManager sem = new ScriptEngineManager();
    ScriptEngine e = sem.getEngineByExtension(".lua");
    String result = e.eval("return math.pi").toString().substring(0,8);
    assertEquals("3.141592", result);
}
 
源代码20 项目: Android_Code_Arbiter   文件: ScriptEngineSample.java
public static void scripting(String userInput) throws ScriptException {

        ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
        ScriptEngine scriptEngine = scriptEngineManager.getEngineByExtension("js");

        Object result = scriptEngine.eval("test=1;" + userInput);

    }