List of usage examples for javax.script ScriptEngine put
public void put(String key, Object value);
From source file:com.amalto.core.util.Util.java
public static void updateUserPropertyCondition(List conditions, String userXML) { for (int i = conditions.size() - 1; i >= 0; i--) { if (conditions.get(i) instanceof WhereCondition) { WhereCondition condition = (WhereCondition) conditions.get(i); if (condition.getRightValueOrPath() != null && condition.getRightValueOrPath().length() > 0 && condition.getRightValueOrPath().contains(USER_PROPERTY_PREFIX)) { String rightCondition = condition.getRightValueOrPath(); String userExpression = rightCondition.substring(rightCondition.indexOf("{") + 1, //$NON-NLS-1$ rightCondition.indexOf("}"));//$NON-NLS-1$ try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Groovy engine evaluating " + userExpression + ".");//$NON-NLS-1$ //$NON-NLS-2$ }/* w w w . j a va 2 s. c om*/ ScriptEngine scriptEngine = SCRIPT_FACTORY.getEngineByName("groovy"); //$NON-NLS-1$ User user = User.parse(userXML); scriptEngine.put("user_context", user);//$NON-NLS-1$ Object expressionValue = scriptEngine.eval(userExpression); if (expressionValue != null) { String result = String.valueOf(expressionValue); if (!"".equals(result.trim())) { condition.setRightValueOrPath(result); } else { conditions.remove(i); } } else { conditions.remove(i); } } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug(e.getMessage(), e); } LOGGER.warn("No such property " + userExpression); conditions.remove(i); } } } } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldClearBindingsBetweenEvals() throws Exception { final ScriptEngine engine = new GremlinGroovyScriptEngine(); engine.put("g", g); engine.put("marko", convertToVertexId("marko")); assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()")); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("s", "marko"); assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next()); try {/*from ww w . j a v a 2 s .co m*/ engine.eval("g.V().has('name',s).next()"); fail("This should have failed because s is no longer bound"); } catch (Exception ex) { final Throwable t = ExceptionUtils.getRootCause(ex); assertEquals(MissingPropertyException.class, t.getClass()); assertTrue(t.getMessage().startsWith("No such property: s for class")); } }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.CLASSIC) public void shouldProperlyHandleBindings() throws Exception { final ScriptEngine engine = new GremlinGroovyScriptEngine(); engine.put("g", g); engine.put("marko", convertToVertexId("marko")); Assert.assertEquals(g.V(convertToVertexId("marko")).next(), engine.eval("g.V(marko).next()")); final Bindings bindings = engine.createBindings(); bindings.put("g", g); bindings.put("s", "marko"); bindings.put("f", 0.5f); bindings.put("i", 1); bindings.put("b", true); bindings.put("l", 100l); bindings.put("d", 1.55555d); assertEquals(engine.eval("g.E().has('weight',f).next()", bindings), g.E(convertToEdgeId("marko", "knows", "vadas")).next()); assertEquals(engine.eval("g.V().has('name',s).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval(//w w w . j a v a2 s . com "g.V().sideEffect{it.get().property('bbb',it.get().value('name')=='marko')}.iterate();g.V().has('bbb',b).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval( "g.V().sideEffect{it.get().property('iii',it.get().value('name')=='marko'?1:0)}.iterate();g.V().has('iii',i).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval( "g.V().sideEffect{it.get().property('lll',it.get().value('name')=='marko'?100l:0l)}.iterate();g.V().has('lll',l).next()", bindings), g.V(convertToVertexId("marko")).next()); assertEquals(engine.eval( "g.V().sideEffect{it.get().property('ddd',it.get().value('name')=='marko'?1.55555d:0)}.iterate();g.V().has('ddd',d).next()", bindings), g.V(convertToVertexId("marko")).next()); }
From source file:org.jaffa.rules.util.ScriptEnginePool.java
/** * Initializes the script engine with the global context and provided variables * * @param scriptEngine The script engine to initialize * @param vars Variables to add to the script engine *//*from w ww . jav a 2s. c om*/ private void initEngine(ScriptEngine scriptEngine, Map<String, Object> vars) { if (vars == null) { return; } // Set the variable values for (Map.Entry<String, Object> var : vars.entrySet()) { try { scriptEngine.put(var.getKey(), var.getValue()); } catch (Exception e) { log.error("Error adding bean to interpreter", e); } } }
From source file:org.unitime.timetable.server.script.ScriptExecution.java
@Override protected void execute() throws Exception { org.hibernate.Session hibSession = ScriptDAO.getInstance().getSession(); Transaction tx = hibSession.beginTransaction(); try {// ww w . j a va2 s . c om setStatus("Starting up...", 3); Script script = ScriptDAO.getInstance().get(iRequest.getScriptId(), hibSession); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName(script.getEngine()); engine.put("hibSession", hibSession); engine.put("session", SessionDAO.getInstance().get(getSessionId())); engine.put("log", this); incProgress(); engine.getContext().setWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { String line = String.valueOf(cbuf, off, len); if (line.endsWith("\n")) line = line.substring(0, line.length() - 1); if (!line.isEmpty()) info(line); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); engine.getContext().setErrorWriter(new Writer() { @Override public void write(char[] cbuf, int off, int len) throws IOException { String line = String.valueOf(cbuf, off, len); if (line.endsWith("\n")) line = line.substring(0, line.length() - 1); if (!line.isEmpty()) warn(line); } @Override public void flush() throws IOException { } @Override public void close() throws IOException { } }); incProgress(); debug("Engine: " + engine.getFactory().getEngineName() + " (ver. " + engine.getFactory().getEngineVersion() + ")"); debug("Language: " + engine.getFactory().getLanguageName() + " (ver. " + engine.getFactory().getLanguageVersion() + ")"); for (ScriptParameter parameter : script.getParameters()) { String value = iRequest.getParameters().get(parameter.getName()); if ("file".equals(parameter.getType()) && iFile != null) { debug(parameter.getName() + ": " + iFile.getName() + " (" + iFile.getSize() + " bytes)"); engine.put(parameter.getName(), iFile); continue; } if (value == null) value = parameter.getDefaultValue(); if (value == null) { engine.put(parameter.getName(), null); continue; } debug(parameter.getName() + ": " + value); if (parameter.getType().equalsIgnoreCase("boolean")) { engine.put(parameter.getName(), "true".equalsIgnoreCase(value)); } else if (parameter.getType().equalsIgnoreCase("long")) { engine.put(parameter.getName(), Long.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("int") || parameter.getType().equalsIgnoreCase("integer")) { engine.put(parameter.getName(), Integer.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("double")) { engine.put(parameter.getName(), Double.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("float")) { engine.put(parameter.getName(), Float.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("short")) { engine.put(parameter.getName(), Short.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("byte")) { engine.put(parameter.getName(), Byte.valueOf(value)); } else if (parameter.getType().equalsIgnoreCase("department")) { engine.put(parameter.getName(), DepartmentDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("departments")) { List<Department> departments = new ArrayList<Department>(); for (String id : value.split(",")) if (!id.isEmpty()) departments.add(DepartmentDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), departments); } else if (parameter.getType().equalsIgnoreCase("subject")) { engine.put(parameter.getName(), SubjectAreaDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("subjects")) { List<SubjectArea> subjects = new ArrayList<SubjectArea>(); for (String id : value.split(",")) if (!id.isEmpty()) subjects.add(SubjectAreaDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), subjects); } else if (parameter.getType().equalsIgnoreCase("building")) { engine.put(parameter.getName(), BuildingDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("buildings")) { List<Building> buildings = new ArrayList<Building>(); for (String id : value.split(",")) if (!id.isEmpty()) buildings.add(BuildingDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), buildings); } else if (parameter.getType().equalsIgnoreCase("room")) { engine.put(parameter.getName(), RoomDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("rooms")) { List<Room> rooms = new ArrayList<Room>(); for (String id : value.split(",")) if (!id.isEmpty()) rooms.add(RoomDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), rooms); } else if (parameter.getType().equalsIgnoreCase("location")) { engine.put(parameter.getName(), LocationDAO.getInstance().get(Long.valueOf(value), hibSession)); } else if (parameter.getType().equalsIgnoreCase("locations")) { List<Location> locations = new ArrayList<Location>(); for (String id : value.split(",")) if (!id.isEmpty()) locations.add(LocationDAO.getInstance().get(Long.valueOf(id), hibSession)); engine.put(parameter.getName(), locations); } else { engine.put(parameter.getName(), value); } } incProgress(); if (engine instanceof Compilable) { setStatus("Compiling script...", 1); CompiledScript compiled = ((Compilable) engine).compile(script.getScript()); incProgress(); setStatus("Running script...", 100); compiled.eval(); } else { setStatus("Running script...", 100); engine.eval(script.getScript()); } hibSession.flush(); tx.commit(); setStatus("All done.", 1); incProgress(); } catch (Exception e) { tx.rollback(); error("Execution failed: " + e.getMessage(), e); } finally { hibSession.close(); } }
From source file:com.amalto.core.util.Util.java
public static IWhereItem fixWebConditions(IWhereItem whereItem, String userXML) throws Exception { if (whereItem == null) { return null; }//w w w. j a v a 2s . com if (whereItem instanceof WhereLogicOperator) { List<IWhereItem> subItems = ((WhereLogicOperator) whereItem).getItems(); for (int i = subItems.size() - 1; i >= 0; i--) { IWhereItem item = subItems.get(i); item = fixWebConditions(item, userXML); if (item instanceof WhereLogicOperator) { if (((WhereLogicOperator) item).getItems().size() == 0) { subItems.remove(i); } } else if (item instanceof WhereCondition) { WhereCondition condition = (WhereCondition) item; if (condition.getRightValueOrPath() != null && condition.getRightValueOrPath().length() > 0 && condition.getRightValueOrPath().contains(USER_PROPERTY_PREFIX)) { subItems.remove(i); } } else if (item == null) { subItems.remove(i); } } } else if (whereItem instanceof WhereCondition) { WhereCondition condition = (WhereCondition) whereItem; if (condition.getRightValueOrPath() != null && condition.getRightValueOrPath().length() > 0 && condition.getRightValueOrPath().contains(USER_PROPERTY_PREFIX)) { // TMDM-7207: Only create the groovy script engine if needed (huge performance issues) // TODO Should there be some pool of ScriptEngine instances? (is reusing ok?) ScriptEngine scriptEngine = SCRIPT_FACTORY.getEngineByName("groovy"); //$NON-NLS-1$ if (userXML != null && !userXML.isEmpty()) { User user = User.parse(userXML); scriptEngine.put("user_context", user);//$NON-NLS-1$ } String rightCondition = condition.getRightValueOrPath(); String userExpression = rightCondition.substring(rightCondition.indexOf('{') + 1, rightCondition.indexOf('}')); try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Groovy engine evaluating " + userExpression + ".");//$NON-NLS-1$ //$NON-NLS-2$ } Object expressionValue = scriptEngine.eval(userExpression); if (expressionValue != null) { String result = String.valueOf(expressionValue); if (!"".equals(result.trim())) { condition.setRightValueOrPath(result); } } } catch (Exception e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("No such property " + userExpression, e); } } } if (!condition.getOperator().equals(WhereCondition.EMPTY_NULL)) { whereItem = "*".equals(condition.getRightValueOrPath()) //$NON-NLS-1$ || ".*".equals(condition.getRightValueOrPath()) ? null : whereItem; } } else { throw new XmlServerException("Unknown Where Type : " + whereItem.getClass().getName()); } if (whereItem instanceof WhereLogicOperator) { return ((WhereLogicOperator) whereItem).getItems().size() == 0 ? null : whereItem; } return whereItem; }
From source file:org.apache.tinkerpop.gremlin.groovy.jsr223.GremlinGroovyScriptEngineOverGraphTest.java
@Test @LoadGraphWith(LoadGraphWith.GraphData.MODERN) public void shouldLoadImports() throws Exception { final ScriptEngine engineNoImports = new GremlinGroovyScriptEngine( (CompilerCustomizerProvider) NoImportCustomizerProvider.INSTANCE); try {// w w w . jav a 2 s.com engineNoImports.eval("Vertex.class.getName()"); fail("Should have thrown an exception because no imports were supplied"); } catch (Exception se) { assertTrue(se instanceof ScriptException); } final ScriptEngine engineWithImports = new GremlinGroovyScriptEngine( (CompilerCustomizerProvider) new DefaultImportCustomizerProvider()); engineWithImports.put("g", g); assertEquals(Vertex.class.getName(), engineWithImports.eval("Vertex.class.getName()")); assertEquals(2l, engineWithImports.eval("g.V().has('age',gt(30)).count().next()")); assertEquals(Direction.IN, engineWithImports.eval("Direction.IN")); assertEquals(Direction.OUT, engineWithImports.eval("Direction.OUT")); assertEquals(Direction.BOTH, engineWithImports.eval("Direction.BOTH")); }
From source file:com.mgmtp.jfunk.core.scripting.ScriptExecutor.java
private void initGroovyCommands(final ScriptEngine scriptEngine, final ScriptContext scriptContext) { Commands commands = new Commands(scriptContext); for (MetaProperty mp : commands.getMetaClass().getProperties()) { String propertyType = mp.getType().getCanonicalName(); String propertyName = mp.getName(); if (propertyType.equals(groovy.lang.Closure.class.getCanonicalName())) { scriptEngine.put(propertyName, commands.getProperty(propertyName)); }/*from ww w . jav a 2 s . c om*/ } }
From source file:com.github.safrain.remotegsh.server.RgshFilter.java
/** * Create a script engine with stdout and stderr replaced by {@link ServletResponse#getWriter()}. * Script extensions in {@link #scriptExtensions} will be evaluated after the engine creation. *//*from www . java 2 s . c om*/ private ScriptEngine prepareEngine(HttpServletRequest request, HttpServletResponse response) throws IOException { ScriptEngine engine = createGroovyEngine(); PrintWriter writer = response.getWriter(); engine.getContext().setWriter(writer); engine.getContext().setErrorWriter(writer); engine.put("_request", request); engine.put("_response", response); engine.put("_charset", charset); try { for (Entry<String, CompiledScript> entry : scriptExtensions.entrySet()) { try { entry.getValue().eval(engine.getContext()); } catch (ScriptException e) { //Ignore script extension evaluation errors log.log(Level.WARNING, String.format("Error evaluating script extension '%s'", entry.getKey()), e); } } } catch (Exception e) { log.log(Level.SEVERE, "Error while creating engine.", e); throw new RuntimeException(e); } return engine; }
From source file:org.opentestsystem.delivery.testreg.domain.constraintvalidators.JexlAssertValidator.java
@Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { Object evaluationResult;//from w ww. java2s . c om final ScriptEngine jexlScriptEngine = getJexlScriptEngine(); boolean hasValueInImplicitEligibilityRule = false; final boolean isImplicitEligibilityRule = value instanceof ImplicitEligibilityRule; if (isImplicitEligibilityRule) { final ImplicitEligibilityRule ierValue = (ImplicitEligibilityRule) value; hasValueInImplicitEligibilityRule = StringUtils.isNotBlank(ierValue.getValue()); } if (!isImplicitEligibilityRule || hasValueInImplicitEligibilityRule) { jexlScriptEngine.put(this.alias, value); try { evaluationResult = jexlScriptEngine.eval(this.script); } catch (final ScriptException e) { throw new ConstraintDeclarationException(e); } if (!(evaluationResult instanceof Boolean)) { throw new ConstraintDeclarationException("Evaluation Result should be a boolean type"); } return Boolean.TRUE.equals(evaluationResult); } return true; }