Java Code Examples for javax.script.ScriptEngineManager#getEngineByExtension()

The following examples show how to use javax.script.ScriptEngineManager#getEngineByExtension() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: StandardScriptFactory.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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;
}
 
Example 2
Source File: StandardScriptFactory.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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;
}
 
Example 3
Source File: StandardScriptFactory.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example 4
Source File: JSR223Tasklet.java    From org.openntf.domino with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example 5
Source File: ScriptLoader.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: AbstractSchedulerCommandTest.java    From scheduling with GNU Affero General Public License v3.0 6 votes vote down vote up
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());
}
 
Example 7
Source File: SoapController.java    From microcks with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 8
Source File: EngineScript.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example 9
Source File: ApplicationContextImpl.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example 10
Source File: TreePredictUDFv1.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 11
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 12
Source File: ScriptEngineSample.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
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);
    }
 
Example 13
Source File: KpiService.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
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);
	}
}
 
Example 14
Source File: HelloWorldJSFile.java    From javase with MIT License 5 votes vote down vote up
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()));
}
 
Example 15
Source File: JavaScriptEnginesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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 });
                }
            }
        }
    }
}
 
Example 16
Source File: ScriptUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
/**
 * 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;
    }
}
 
Example 17
Source File: KotlinScriptEngineTest.java    From dynkt with GNU Affero General Public License v3.0 4 votes vote down vote up
@BeforeClass
public static void setUpBeforeClass() throws Exception {
	ScriptEngineManager mgr = new ScriptEngineManager();
	engine = mgr.getEngineByExtension("kts");
}
 
Example 18
Source File: CScriptingDialog.java    From binnavi with Apache License 2.0 4 votes vote down vote up
/**
 * 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();
}
 
Example 19
Source File: AppTest.java    From luaj with MIT License 4 votes vote down vote up
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);
}
 
Example 20
Source File: ScriptEngineSample.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 3 votes vote down vote up
public static void scripting(String userInput) throws ScriptException {

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

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

    }