Example usage for javax.script ScriptEngineManager ScriptEngineManager

List of usage examples for javax.script ScriptEngineManager ScriptEngineManager

Introduction

In this page you can find the example usage for javax.script ScriptEngineManager ScriptEngineManager.

Prototype

public ScriptEngineManager() 

Source Link

Document

The effect of calling this constructor is the same as calling ScriptEngineManager(Thread.currentThread().getContextClassLoader()).

Usage

From source file:org.okj.im.model.Member.java

/**
 * QQ/*from   w w  w . ja  v a 2  s.c o m*/
 * @return
 */
public String getEncodePassword(AuthToken token) {
    if (StringUtils.isNotBlank(account.getPassword())) {
        InputStream in = null;
        try {
            in = ClassLoaderUtils.getResourceAsStream("encodePass.js", this.getClass());
            Reader inreader = new InputStreamReader(in);
            ScriptEngineManager m = new ScriptEngineManager();
            ScriptEngine se = m.getEngineByName("javascript");
            se.eval(inreader);
            Object t = se
                    .eval("passwordEncoding(\"" + account.getPassword() + "\",\"" + token.getVerifycodeHex()
                            + "\",\"" + StringUtils.upperCase(token.getVerifycode()) + "\");");

            return t.toString();
        } catch (Exception ex) {
            LogUtils.error(LOGGER, "", ex);
        }
        return account.getPassword();
    }
    return account.getPassword();
}

From source file:org.tomitribe.tribestream.registryng.bootstrap.Provisioning.java

@PostConstruct
public void init() {
    loginContext.setUsername("system");

    ofNullable(script).ifPresent(s -> {
        final ScriptEngine engine = new ScriptEngineManager().getEngineByExtension("js");
        final Bindings bindings = engine.createBindings();
        bindings.put("props", System.getProperties());

        final File file = new File(s);
        if (file.isFile()) {
            try (final Reader reader = new FileReader(file)) {
                engine.eval(reader, bindings);
            } catch (final IOException | ScriptException e) {
                throw new IllegalArgumentException(e);
            }// w  w  w  .  j  a v  a  2 s. c o  m
        } else {
            try {
                engine.eval(s, bindings);
            } catch (final ScriptException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });
    restore();
}

From source file:it.delli.mwebc.command.impl.EventCommand.java

public void execute(Page page, JsonObject data) {
    String eventName = data.get("event").getAsString();
    String eventType = data.get("eventType").getAsString();
    String method = data.get("forward").getAsString();
    Widget widget = null;/* ww  w  .  j a  va2 s  . c o m*/
    EventListener eventListener = null;
    if (data.get("id") != null) {
        widget = page.getWidget(data.get("id").getAsString());
        eventListener = widget.getEventListener(eventName);
    } else {
        eventListener = page.getEventListener();
    }
    Class eventTypeClass = page.getApplication().getEventClass(eventType);
    Event event = null;
    try {
        event = (Event) eventTypeClass.getConstructor(String.class, Widget.class, JsonObject.class)
                .newInstance(eventName, widget, data.get("data").getAsJsonObject());
    } catch (Exception e) {
        log.error("Exception in creating event instance for event type " + eventType);
    }
    ;
    event.setPage(page);
    // bind widgets
    ReflectionUtils.bindWidgets(eventListener, page);
    //
    Method forwardMethod = null;
    if (eventListener instanceof PageEventListener && page.getWidget(method) != null) {
        try {
            it.delli.mwebc.widget.Method widgetMethod = (it.delli.mwebc.widget.Method) page.getWidget(method);
            ScriptEngineManager factory = new ScriptEngineManager();
            ScriptEngine engine = factory.getEngineByName("groovy");
            engine.put("eventListener", null);
            engine.eval(widgetMethod.getScript());
            eventListener = (EventListener) engine.get("eventListener");
            forwardMethod = eventListener.getClass().getMethod(method, Event.class);
            forwardMethod.setAccessible(true);
        } catch (Exception e) {
            log.error("Exception in getting method to execute", e);
        }
    } else {
        try {
            forwardMethod = eventListener.getClass().getMethod(method, Event.class);
            forwardMethod.setAccessible(true);
        } catch (Exception e) {
            log.error("Exception in getting method to execute", e);
        }
    }
    if (forwardMethod != null) {
        if (event.getWidget() != null) {
            log.info("Executing forward method " + eventListener.getClass().getName() + "."
                    + forwardMethod.getName() + " for event " + event.getName() + " on widget "
                    + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")");
        } else {
            log.info("Executing forward method " + eventListener.getClass().getName() + "."
                    + forwardMethod.getName() + " for event " + event.getName());
        }
        try {
            forwardMethod.invoke(eventListener, event);
        } catch (Exception e) {
            if (event.getWidget() != null) {
                log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "."
                        + forwardMethod.getName() + " for event " + event.getName() + " on widget "
                        + event.getWidget().getClass().getName() + " (" + event.getWidget().getId() + ")", e);
            } else {
                log.error("Exception in executing of forward method " + eventListener.getClass().getName() + "."
                        + forwardMethod.getName() + " for event " + event.getName(), e);
            }
            log.error("Exception in forward method execution", e);
        }
    } else {
        log.info("Forward method does not exist in event listener " + eventListener.getClass().getName()
                + " for event " + event.getName());
        log.info("Notifying end of failed execution for event " + event.getName());
    }
}

From source file:org.graphwalker.machines.ExtendedFiniteStateMachine.java

public ExtendedFiniteStateMachine(boolean usingJsEngine) {
    super();/* w  ww  .  ja  v a 2s.  c  om*/
    namespaceStack = new Stack<CannedNameSpace>();
    if (usingJsEngine) {
        mgr = new ScriptEngineManager();
        jsEngine = mgr.getEngineByExtension("js");
        accessableFilter = new AccessableEdgeFilter(jsEngine);
    } else {
        beanShellEngine = new Interpreter();
        accessableFilter = new AccessableEdgeFilter(beanShellEngine);
    }
    Void = new VoidPrintStream();
}

From source file:it.geosolutions.geobatch.action.scripting.ScriptingTest.java

@Test
public void testGroovy() throws ScriptException {

    String engineName = "groovy";

    ScriptEngineManager mgr = new ScriptEngineManager();
    // create a JavaScript engine
    ScriptEngine engine = mgr.getEngineByName(engineName);
    assertNotNull("Can't find engine '" + engineName + "'", engine);

    ScriptEngineFactory sef = engine.getFactory();
    System.out.println("FACTORY for " + engineName + ": " + "'" + sef.getEngineName() + "' " + "'"
            + sef.getLanguageName() + "' " + "'" + sef.getExtensions() + "' " + "'" + sef.getNames() + "' ");

    // evaluate code from String
    engine.eval("println \"hello, groovy\"");
}

From source file:org.nuxeo.automation.scripting.test.TestCompileAndContext.java

@Test
public void serviceShouldBeDeclared() throws Exception {
    ScriptEngineManager engineManager = new ScriptEngineManager();
    ScriptEngine engine = engineManager.getEngineByName(AutomationScriptingConstants.NASHORN_ENGINE);
    assertNotNull(engine);/*  ww w  .  j  a  v  a 2s  .c  om*/

    InputStream stream = this.getClass().getResourceAsStream("/checkWrapper.js");
    assertNotNull(stream);
    engine.eval(scriptingService.getJSWrapper());
    engine.eval(IOUtils.toString(stream));
    assertEquals("Hello" + System.lineSeparator(), outContent.toString());
}

From source file:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * // w w w.  j  a  v  a  2 s. c  om
 * @param command
 * @return
 */
public static <T> Object interprete(String command, Hstore hstore, AbstractResult<T> object,
        boolean useRecursion, ResultOptions resultOptions) {

    if (jsEngine == null) {
        ScriptEngineManager sem = new ScriptEngineManager();
        jsEngine = sem.getEngineByName("JavaScript");
        System.out.println("JS Engine: " + jsEngine.getClass().getCanonicalName());
        Bindings b = jsEngine.createBindings();
        b.put("nn", new SystemApi());
        jsEngine.setBindings(b, ScriptContext.GLOBAL_SCOPE);
    }

    command = command.replace("\\%", "{PERCENT}");

    Pattern p;
    if (!useRecursion) {
        p = PATTERN_COMMAND;
    } else {
        p = PATTERN_RECURSIVE_COMMAND;

        Matcher m = p.matcher(command);
        while (m.find()) {
            String replace = m.group(0);
            //System.out.println("found: " + replace);
            String toReplace = String.valueOf(interprete(replace, hstore, object, false, resultOptions));
            //System.out.println("replacing: " + m.group(0) + " -> " + toReplace);
            command = command.replace(m.group(0), toReplace);
        }

        command = command.replace("{PERCENT}", "%");
        return command;
    }

    Matcher m = p.matcher(command);
    command = command.replace("{PERCENT}", "%");

    String scriptCommand;
    String[] args;

    if (m.find()) {
        if (m.groupCount() != 2) {
            return command;
        }
        scriptCommand = m.group(1);

        if (!COMMAND_EVAL.equals(scriptCommand)) {
            args = m.group(2).trim().split("\\s");
        } else {
            args = new String[] { m.group(2).trim() };
        }
    } else {
        return command;
    }

    try {
        if (COMMAND_RANDOM.equals(scriptCommand)) {
            return random(args);
        } else if (COMMAND_PARAM.equals(scriptCommand)) {
            return parse(args, hstore, object, resultOptions);
        } else if (COMMAND_EVAL.equals(scriptCommand)) {
            return eval(args, hstore, object);
        } else if (COMMAND_RANDOM_URL.equals(scriptCommand)) {
            return randomUrl(args);
        } else {
            return command;
        }
    } catch (ScriptException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:edu.dfci.cccb.mev.limma.domain.cli.CliRLimmaTest.java

@Before
public void setupLimmaResult() throws IOException, DatasetException {
    try (InputStream inp = getClass().getResourceAsStream("/mouse_test_dataset.tsv");
            ByteArrayOutputStream copy = new ByteArrayOutputStream()) {
        IOUtils.copy(inp, copy);//from   w  ww .j av a2s  .  c om
        Dataset dataset = new SimpleDatasetBuilder().setParserFactories(asList(new SuperCsvParserFactory()))
                .setValueStoreBuilder(new FlatFileValueStoreBuilder())
                .build(new MockTsvInput("mock", copy.toString()));
        Selection experiment = new SimpleSelection("experiment", new Properties(), asList("A", "B", "C"));
        Selection control = new SimpleSelection("control", new Properties(), asList("D", "E", "F"));
        dataset.dimension(COLUMN).selections().put(experiment);
        dataset.dimension(COLUMN).selections().put(control);
        result = new StatelessScriptEngineFileBackedLimmaBuilder()
                .r(new ScriptEngineManager().getEngineByName("CliR"))
                .composerFactory(new SuperCsvComposerFactory()).dataset(dataset).control(control)
                .experiment(experiment).species(Species.MOUSE).go("BP").test("Fisher test").build();
    }
}

From source file:com.mnxfst.stream.pipeline.element.script.ScriptEvaluatorPipelineElement.java

/**
 * @see akka.actor.UntypedActor#preStart()
 *///from   ww  w  . j ava 2 s  . com
public void preStart() throws Exception {

    // initialize the script engine 
    ScriptEngineManager factory = new ScriptEngineManager();
    try {
        this.scriptEngine = factory.getEngineByName(getStringProperty(CONFIG_SCRIPT_ENGINE_NAME));
    } catch (Exception e) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL, e.getMessage()), getSelf());
        return;
    }

    // iterate from zero to max, read out init code snippets and interrupt if an empty one occurs
    for (int i = 0; i < Integer.MAX_VALUE; i++) {
        String initScript = getStringProperty(CONFIG_SCRIPT_INIT_CODE_PREFIX + i);
        if (StringUtils.isNotBlank(initScript)) {
            this.initScripts.add(loadScript(initScript.toString()));
        } else {
            break;
        }
    }

    // fetch the script to be applied for each message
    String scriptUrl = getStringProperty(CONFIG_SCRIPT_EVAL_CODE);
    //      this.evalScript = getStringProperty(CONFIG_SCRIPT_EVAL_CODE);
    if (StringUtils.isBlank(scriptUrl)) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL, "Required script code missing"), getSelf());
        return;
    }
    this.evalScript = loadScript(scriptUrl);

    // retrieve the name of the variable where the script expects the input 
    this.scriptInputVariable = getStringProperty(CONFIG_SCRIPT_INPUT_VARIABLE);
    if (StringUtils.isBlank(this.scriptInputVariable)) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL, "Required input variable missing"),
                        getSelf());
        return;
    }

    // retrieve the name of the variable where the script writes the identifier of the next pipeline element to
    this.scriptOutputNextElementVariable = getStringProperty(CONFIG_SCRIPT_OUTPUT_NEXT_ELEMENT_VARIABLE);
    if (StringUtils.isBlank(this.scriptOutputNextElementVariable)) {
        context().parent()
                .tell(new PipelineElementSetupFailedMessage(getPipelineElementConfiguration().getPipelineId(),
                        getPipelineElementConfiguration().getElementId(),
                        PipelineElementSetupFailedMessage.GENERAL,
                        "Required output (next element) variable missing"), getSelf());
        return;
    }

    // if the set of init scripts is not empty, provide them to the script engine 
    if (!initScripts.isEmpty()) {
        for (String script : initScripts) {
            this.scriptEngine.eval(script);
        }
    }
}

From source file:sample.fa.ScriptRunnerApplication.java

void createGUI() {
    Box buttonBox = Box.createHorizontalBox();

    JButton loadButton = new JButton("Load");
    loadButton.addActionListener(this::loadScript);
    buttonBox.add(loadButton);/*  w ww .  j  av  a 2s. co m*/

    JButton saveButton = new JButton("Save");
    saveButton.addActionListener(this::saveScript);
    buttonBox.add(saveButton);

    JButton executeButton = new JButton("Execute");
    executeButton.addActionListener(this::executeScript);
    buttonBox.add(executeButton);

    languagesModel = new DefaultComboBoxModel();

    ScriptEngineManager sem = new ScriptEngineManager();
    for (ScriptEngineFactory sef : sem.getEngineFactories()) {
        languagesModel.addElement(sef.getScriptEngine());
    }

    JComboBox<ScriptEngine> languagesCombo = new JComboBox<>(languagesModel);
    JLabel languageLabel = new JLabel();
    languagesCombo.setRenderer((JList<? extends ScriptEngine> list, ScriptEngine se, int index,
            boolean isSelected, boolean cellHasFocus) -> {
        ScriptEngineFactory sef = se.getFactory();
        languageLabel.setText(sef.getEngineName() + " - " + sef.getLanguageName() + " (*."
                + String.join(", *.", sef.getExtensions()) + ")");
        return languageLabel;
    });
    buttonBox.add(Box.createHorizontalGlue());
    buttonBox.add(languagesCombo);

    scriptContents = new JTextArea();
    scriptContents.setRows(8);
    scriptContents.setColumns(40);

    scriptResults = new JTextArea();
    scriptResults.setEditable(false);
    scriptResults.setRows(8);
    scriptResults.setColumns(40);

    JSplitPane jsp = new JSplitPane(JSplitPane.VERTICAL_SPLIT, scriptContents, scriptResults);

    JFrame frame = new JFrame("Script Runner");
    frame.add(buttonBox, BorderLayout.NORTH);
    frame.add(jsp, BorderLayout.CENTER);

    frame.pack();
    frame.addWindowListener(new WindowAdapter() {
        @Override
        public void windowClosing(WindowEvent e) {
            System.exit(0);
        }
    });
    frame.setVisible(true);
}