groovy.lang.GroovyShell Java Examples
The following examples show how to use
groovy.lang.GroovyShell.
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: TestCaseScript.java From mdw with Apache License 2.0 | 7 votes |
/** * Matches according to GPath. */ public Closure<Boolean> gpath(final String condition) throws TestException { return new Closure<Boolean>(this, this) { @Override public Boolean call(Object request) { try { GPathResult gpathRequest = new XmlSlurper().parseText(request.toString()); Binding binding = getBinding(); binding.setVariable("request", gpathRequest); return (Boolean) new GroovyShell(binding).evaluate(condition); } catch (Exception ex) { ex.printStackTrace(getTestCaseRun().getLog()); getTestCaseRun().getLog().println("Failed to parse request as XML/JSON. Stub response: " + AdapterActivity.MAKE_ACTUAL_CALL); return false; } } }; }
Example #2
Source File: GroovyTest.java From streamline with Apache License 2.0 | 7 votes |
@Test public void testGroovyShell() throws Exception { GroovyShell groovyShell = new GroovyShell(); final String s = "x > 2 && y > 1"; Script script = groovyShell.parse(s); Binding binding = new Binding(); binding.setProperty("x",5); binding.setProperty("y",3); script.setBinding(binding); Object result = script.run(); Assert.assertEquals(true, result); log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s, script.getBinding().getProperty("x"), script.getBinding().getProperty("y"), result); binding.setProperty("y",0); result = script.run(); Assert.assertEquals(false, result); log.debug("evaluating [{}] with (x,y)=({},{}) => {}\n", s, binding.getProperty("x"), binding.getProperty("y"), result); }
Example #3
Source File: LoadEmbeddedGroovyTest.java From rice with Educational Community License v2.0 | 7 votes |
@Test public void testNativeGroovy() { Binding binding = new Binding(); binding.setVariable("foo", new Integer(2)); GroovyShell shell = new GroovyShell(binding); Object value = shell.evaluate("println 'Hello World!'; x = 123; return foo * 10"); Assert.assertTrue(value.equals(new Integer(20))); Assert.assertTrue(binding.getVariable("x").equals(new Integer(123))); }
Example #4
Source File: BenchmarkGroovyExpressionEvaluation.java From incubator-pinot with Apache License 2.0 | 6 votes |
@Setup public void setup() throws IllegalAccessException, InstantiationException { _concatScriptText = "firstName + ' ' + lastName"; _concatBinding = new Binding(); _concatScript = new GroovyShell(_concatBinding).parse(_concatScriptText); _concatCodeSource = new GroovyCodeSource(_concatScriptText, Math.abs(_concatScriptText.hashCode()) + ".groovy", GroovyShell.DEFAULT_CODE_BASE); _concatGCLScript = (Script) _groovyClassLoader.parseClass(_concatCodeSource).newInstance(); _maxScriptText = "longList.max{ it.toBigDecimal() }"; _maxBinding = new Binding(); _maxScript = new GroovyShell(_maxBinding).parse(_maxScriptText); _maxCodeSource = new GroovyCodeSource(_maxScriptText, Math.abs(_maxScriptText.hashCode()) + ".groovy", GroovyShell.DEFAULT_CODE_BASE); _maxGCLScript = (Script) _groovyClassLoader.parseClass(_maxCodeSource).newInstance(); }
Example #5
Source File: PlatformLineWriterTest.java From groovy with Apache License 2.0 | 6 votes |
public void testPlatformLineWriter() throws IOException, ClassNotFoundException { String LS = System.lineSeparator(); Binding binding = new Binding(); binding.setVariable("first", "Tom"); binding.setVariable("last", "Adams"); StringWriter stringWriter = new StringWriter(); Writer platformWriter = new PlatformLineWriter(stringWriter); GroovyShell shell = new GroovyShell(binding); platformWriter.write(shell.evaluate("\"$first\\n$last\\n\"").toString()); platformWriter.flush(); assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString()); stringWriter = new StringWriter(); platformWriter = new PlatformLineWriter(stringWriter); platformWriter.write(shell.evaluate("\"$first\\r\\n$last\\r\\n\"").toString()); platformWriter.flush(); assertEquals("Tom" + LS + "Adams" + LS, stringWriter.toString()); }
Example #6
Source File: GroovySlide.java From COMP6237 with BSD 3-Clause "New" or "Revised" License | 6 votes |
@Override public Component getComponent(int width, int height) throws IOException { final JPanel base = new JPanel(); base.setOpaque(false); base.setPreferredSize(new Dimension(width, height)); base.setLayout(new BoxLayout(base, BoxLayout.Y_AXIS)); final Binding sharedData = new Binding(); final GroovyShell shell = new GroovyShell(sharedData); sharedData.setProperty("slidePanel", base); final Script script = shell.parse(new InputStreamReader(GroovySlide.class.getResourceAsStream("../test.groovy"))); script.run(); // final RSyntaxTextArea textArea = new RSyntaxTextArea(20, 60); // textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_GROOVY); // textArea.setCodeFoldingEnabled(true); // final RTextScrollPane sp = new RTextScrollPane(textArea); // base.add(sp); return base; }
Example #7
Source File: VariableGeneratorService.java From easy_javadoc with Apache License 2.0 | 6 votes |
/** * 生成自定义变量 * * @param customValueMap 自定义值 * @param placeholder 占位符 * @param innerVariableMap 内部变量映射 * @return {@link String} */ private String generateCustomVariable(Map<String, CustomValue> customValueMap, Map<String, Object> innerVariableMap, String placeholder) { Optional<CustomValue> valueOptional = customValueMap.entrySet().stream() .filter(entry -> placeholder.equalsIgnoreCase(entry.getKey())).map(Entry::getValue).findAny(); // 找不到自定义方法,返回原占位符 if (!valueOptional.isPresent()) { return placeholder; } CustomValue value = valueOptional.get(); switch (value.getType()) { case STRING: return value.getValue(); case GROOVY: try { return new GroovyShell(new Binding(innerVariableMap)).evaluate(value.getValue()).toString(); } catch (Exception e) { LOGGER.error(String.format("自定义变量%s的groovy脚本执行异常,请检查语法是否正确且有正确返回值:%s", placeholder, value.getValue()), e); return value.getValue(); } default: return ""; } }
Example #8
Source File: Groovy.java From groovy with Apache License 2.0 | 6 votes |
private void configureCompiler() { if (scriptBaseClass != null) { configuration.setScriptBaseClass(scriptBaseClass); } if (configscript != null) { Binding binding = new Binding(); binding.setVariable("configuration", configuration); CompilerConfiguration configuratorConfig = new CompilerConfiguration(); ImportCustomizer customizer = new ImportCustomizer(); customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder"); configuratorConfig.addCompilationCustomizers(customizer); GroovyShell shell = new GroovyShell(binding, configuratorConfig); File confSrc = new File(configscript); try { shell.evaluate(confSrc); } catch (IOException e) { throw new BuildException("Unable to configure compiler using configuration file: " + confSrc, e); } } }
Example #9
Source File: GroovyInterpreter.java From zeppelin with Apache License 2.0 | 6 votes |
@Override public void open() { CompilerConfiguration conf = new CompilerConfiguration(); conf.setDebug(true); shell = new GroovyShell(conf); String classes = getProperty("GROOVY_CLASSES"); if (classes == null || classes.length() == 0) { try { File jar = new File( GroovyInterpreter.class.getProtectionDomain().getCodeSource().getLocation().toURI() .getPath()); classes = new File(jar.getParentFile(), "classes").toString(); } catch (Exception e) { log.error(e.getMessage()); } } log.info("groovy classes classpath: " + classes); if (classes != null && classes.length() > 0) { File fClasses = new File(classes); if (!fClasses.exists()) { fClasses.mkdirs(); } shell.getClassLoader().addClasspath(classes); } }
Example #10
Source File: CustomQueryValidator.java From rdflint with MIT License | 6 votes |
@Override public void validateTripleSet(LintProblemSet problems, String file, List<Triple> tripeSet) { if (this.getParameters().getRules() == null) { return; } // execute sparql & custom validation Graph g = Factory.createGraphMem(); tripeSet.forEach(g::add); Model m = ModelFactory.createModelForGraph(g); this.getParameters().getRules().stream() .filter(r -> file.matches(r.getTarget())) .forEach(r -> { Query query = QueryFactory.create(r.getQuery()); QueryExecution qe = QueryExecutionFactory.create(query, m); Binding binding = new Binding(); binding.setVariable("rs", qe.execSelect()); binding.setVariable("log", new ProblemLogger(this, problems, file, r.getName())); GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration()); shell.evaluate(r.getValid()); }); }
Example #11
Source File: ShellTest.java From knox with Apache License 2.0 | 6 votes |
private void testPutGetScript(String script) throws IOException, URISyntaxException { setupLogging(); DistributedFileSystem fileSystem = miniDFSCluster.getFileSystem(); Path dir = new Path("/user/guest/example"); fileSystem.delete(dir, true); fileSystem.mkdirs(dir, new FsPermission("777")); fileSystem.setOwner(dir, "guest", "users"); Binding binding = new Binding(); binding.setProperty("gateway", driver.getClusterUrl()); URL readme = driver.getResourceUrl("README"); File file = new File(readme.toURI()); binding.setProperty("file", file.getAbsolutePath()); GroovyShell shell = new GroovyShell(binding); shell.evaluate(driver.getResourceUrl(script).toURI()); String status = (String) binding.getProperty("status"); assertNotNull(status); String fetchedFile = (String) binding.getProperty("fetchedFile"); assertNotNull(fetchedFile); assertThat(fetchedFile, containsString("README")); }
Example #12
Source File: AccessCheckingPortalFactory.java From stendhal with GNU General Public License v2.0 | 6 votes |
/** * Creates a new ChatAction from ConfigurableFactoryContext. * * @param ctx * ConfigurableFactoryContext * @return * ChatAction instance */ protected ChatAction getRejectedAction(final ConfigurableFactoryContext ctx) { String value = ctx.getString("rejectedAction", null); if (value == null) { return null; } Binding groovyBinding = new Binding(); final GroovyShell interp = new GroovyShell(groovyBinding); try { String code = "import games.stendhal.server.entity.npc.action.*;\r\n" + value; return (ChatAction) interp.evaluate(code); } catch (CompilationFailedException e) { throw new IllegalArgumentException(e); } }
Example #13
Source File: GroovyScriptPostProcessor.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@Override public void process(Network network, ComputationManager computationManager) throws Exception { if (Files.exists(script)) { LOGGER.debug("Execute groovy post processor {}", script); try (Reader reader = Files.newBufferedReader(script, StandardCharsets.UTF_8)) { CompilerConfiguration conf = new CompilerConfiguration(); Binding binding = new Binding(); binding.setVariable("network", network); binding.setVariable("computationManager", computationManager); GroovyShell shell = new GroovyShell(binding, conf); shell.evaluate(reader); } } }
Example #14
Source File: StandaloneTestCaseRun.java From mdw with Apache License 2.0 | 6 votes |
@SuppressWarnings("unchecked") private static void setupContextClassLoader(GroovyShell shell) { final Thread current = Thread.currentThread(); @SuppressWarnings("rawtypes") class DoSetContext implements PrivilegedAction { ClassLoader classLoader; public DoSetContext(ClassLoader loader) { classLoader = loader; } public Object run() { current.setContextClassLoader(classLoader); return null; } } AccessController.doPrivileged(new DoSetContext(shell.getClassLoader())); }
Example #15
Source File: ApiGroovyCompiler.java From Pushjet-Android with BSD 2-Clause "Simplified" License | 6 votes |
private void applyConfigurationScript(File configScript, CompilerConfiguration configuration) { VersionNumber version = parseGroovyVersion(); if (version.compareTo(VersionNumber.parse("2.1")) < 0) { throw new GradleException("Using a Groovy compiler configuration script requires Groovy 2.1+ but found Groovy " + version + ""); } Binding binding = new Binding(); binding.setVariable("configuration", configuration); CompilerConfiguration configuratorConfig = new CompilerConfiguration(); ImportCustomizer customizer = new ImportCustomizer(); customizer.addStaticStars("org.codehaus.groovy.control.customizers.builder.CompilerCustomizationBuilder"); configuratorConfig.addCompilationCustomizers(customizer); GroovyShell shell = new GroovyShell(binding, configuratorConfig); try { shell.evaluate(configScript); } catch (Exception e) { throw new GradleException("Could not execute Groovy compiler configuration script: " + configScript.getAbsolutePath(), e); } }
Example #16
Source File: GroovyMain.java From groovy with Apache License 2.0 | 6 votes |
private static void setupContextClassLoader(GroovyShell shell) { final Thread current = Thread.currentThread(); class DoSetContext implements PrivilegedAction<Object> { ClassLoader classLoader; public DoSetContext(ClassLoader loader) { classLoader = loader; } public Object run() { current.setContextClassLoader(classLoader); return null; } } AccessController.doPrivileged(new DoSetContext(shell.getClassLoader())); }
Example #17
Source File: StandaloneTestCaseRun.java From mdw with Apache License 2.0 | 6 votes |
/** * Standalone execution for Gradle. */ public void run() { startExecution(); CompilerConfiguration compilerConfig = new CompilerConfiguration(System.getProperties()); compilerConfig.setScriptBaseClass(TestCaseScript.class.getName()); Binding binding = new Binding(); binding.setVariable("testCaseRun", this); ClassLoader classLoader = this.getClass().getClassLoader(); GroovyShell shell = new GroovyShell(classLoader, binding, compilerConfig); shell.setProperty("out", getLog()); setupContextClassLoader(shell); try { shell.run(new GroovyCodeSource(getTestCase().file()), new String[0]); finishExecution(null); } catch (IOException ex) { throw new RuntimeException(ex.getMessage(), ex); } }
Example #18
Source File: GroovyConsoleState.java From Lemur with BSD 3-Clause "New" or "Revised" License | 5 votes |
protected void enable() { console = new Console(); console.setShell(new EnhancedShell(console.getShell())); //, scriptList)); console.run(); // See if we have any script text from last time Preferences prefs = Preferences.userNodeForPackage(getClass()); final String lastText = prefs.get(PREF_LAST_SCRIPT, null); if( lastText != null ) { SwingUtilities.invokeLater( new Runnable() { public void run() { console.getInputArea().setText(lastText); } }); } outputWindow = console.getOutputWindow(); frame = (JFrame)console.getFrame(); GroovyShell shell = console.getShell(); // So now that the console has been "run" we need to set the script // engine's stdout to the latest stdout. This is done through // jsr223's ScriptContext. Many Bothans died to bring us this // information. ScriptContext context = engine.getContext(); context.setWriter(new PrintWriter(System.out)); }
Example #19
Source File: OctopusGremlinShell.java From bjoern with GNU General Public License v3.0 | 5 votes |
public void initShell() { this.shell = new GroovyShell(new OctopusCompilerConfiguration()); openDatabaseConnection(dbName); loadStandardQueryLibrary(); registerMethodMissingHandler(); }
Example #20
Source File: GeoscriptConsole.java From hortonmachine with GNU General Public License v3.0 | 5 votes |
public static void main( String[] args ) { try { if (args.length == 1) { GroovyShell shell = new GroovyShell(); shell.run(new File(args[0]), Collections.EMPTY_LIST); } else { Logger.INSTANCE.init(); SettingsController.applySettings(null); new GeoscriptConsole(); } } catch (Exception e) { e.printStackTrace(); } }
Example #21
Source File: BlockTargetFactory.java From stendhal with GNU General Public License v2.0 | 5 votes |
/** * Create a ChatAction * * @param action the configuration String * @return the action or null * @throws CompilationFailedException */ private ChatAction createAction(String action) throws CompilationFailedException { final GroovyShell interp = createGroovyShell(); String code = "import games.stendhal.server.entity.npc.action.*;\r\n" + action; ChatAction created = (ChatAction) interp.evaluate(code); return created; }
Example #22
Source File: DataScriptHelperTest.java From open-platform-demo with GNU Affero General Public License v3.0 | 5 votes |
@Test public void test_single_createShell() { int count = MAX_COUNT; while (--count > 0) { String expr = "count * 100"; Binding binding = new Binding(); binding.setVariable("count", count); new GroovyShell(binding).evaluate(expr); } }
Example #23
Source File: SecureKnoxShellTest.java From knox with Apache License 2.0 | 5 votes |
/** * Do the heavy lifting here. */ private void webhdfsPutGet() throws Exception { DistributedFileSystem fileSystem = miniDFSCluster.getFileSystem(); Path dir = new Path("/user/guest/example"); fileSystem.delete(dir, true); fileSystem.mkdirs(dir, new FsPermission("777")); fileSystem.setOwner(dir, "guest", "users"); final File jaasFile = setupJaasConf(baseDir, keytab, hdfsPrincipal); final Binding binding = new Binding(); binding.setProperty("jaasConf", jaasFile.getAbsolutePath()); binding.setProperty("krb5conf", krb5conf); binding.setProperty("gateway", driver.getClusterUrl()); URL readme = driver.getResourceUrl("README"); File file = new File(readme.toURI()); binding.setProperty("file", file.getAbsolutePath()); final GroovyShell shell = new GroovyShell(binding); shell.evaluate(getResourceUrl(SCRIPT).toURI()); String status = (String) binding.getProperty("status"); assertNotNull(status); String fetchedFile = (String) binding.getProperty("fetchedFile"); assertNotNull(fetchedFile); assertTrue(fetchedFile.contains("README")); }
Example #24
Source File: DataScriptHelperTest.java From open-platform-demo with GNU Affero General Public License v3.0 | 5 votes |
@Test public void test_createShell() { int count = MAX_COUNT; while (--count > 0) { String expr = "count * " + (count % 100); Binding binding = new Binding(); binding.setVariable("count", count); new GroovyShell(binding).evaluate(expr); } }
Example #25
Source File: EditorScriptingComponent.java From jmonkeybuilder with Apache License 2.0 | 5 votes |
/** * Run the current script. */ private void run() { String code = editorComponent.getCode(); for (final String type : imports) { final String check = "import " + type; if (code.contains(check)) { code = code.replace(check, ""); } } final StringBuilder result = new StringBuilder(); imports.forEach(result, (type, stringBuilder) -> stringBuilder.append("import ").append(type).append('\n')); result.append(code); variables.forEach(shell, GroovyShell::setVariable); try { shell.evaluate(result.toString()); } catch (final Exception e) { EditorUtil.handleException(null, this, e); return; } applyHandler.run(); }
Example #26
Source File: EventLoader.java From accumulo-recipes with Apache License 2.0 | 5 votes |
public EventLoader(String query) { Preconditions.checkNotNull(query); Preconditions.checkArgument(!query.equals("")); try { // call groovy expressions from Java code Binding binding = new Binding(); binding.setVariable("q", QueryBuilder.create()); GroovyShell shell = new GroovyShell(binding); qb = (QueryBuilder) shell.evaluate(query); } catch(Exception e) { throw new RuntimeException("There was an error parsing the groovy query string. "); } }
Example #27
Source File: GroovyExecutor.java From orbit-image-analysis with GNU General Public License v3.0 | 5 votes |
public static void main(String[] args) throws Exception { OrbitLogAppender.GUI_APPENDER = false; if (args == null || args.length < 1) throw new IllegalArgumentException("No URL argument found. Call: GroovyExecutor <URL>"); // TODO: Do this properly... //doTrustToCertificates(); //URL url = new URL("https://chiron.idorsia.com/stash/projects/ORBIT/repos/public-scripts/browse/QuantPerGroupLocalTest.groovy?at=5ff41667c494870aaacbe37fa43fd46fd4c9659c&raw"); URL url = new URL(args[0]); String content = RawUtilsCommon.getContentStr(url); logger.debug("executing code:\n" + content); logger.info("start executing groovy code"); GroovyShell shell = new GroovyShell(); shell.evaluate(content); logger.info("finished"); }
Example #28
Source File: GroovyBeanDefinitionReader.java From spring4-understanding with Apache License 2.0 | 5 votes |
/** * Load bean definitions from the specified Groovy script or XML file. * <p>Note that {@code ".xml"} files will be parsed as XML content; all other kinds * of resources will be parsed as Groovy scripts. * @param encodedResource the resource descriptor for the Groovy script or XML file, * allowing specification of an encoding to use for parsing the file * @return the number of bean definitions found * @throws BeanDefinitionStoreException in case of loading or parsing errors */ public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException { // Check for XML files and redirect them to the "standard" XmlBeanDefinitionReader String filename = encodedResource.getResource().getFilename(); if (StringUtils.endsWithIgnoreCase(filename, ".xml")) { return this.standardXmlBeanDefinitionReader.loadBeanDefinitions(encodedResource); } Closure beans = new Closure(this) { public Object call(Object[] args) { invokeBeanDefiningClosure((Closure) args[0]); return null; } }; Binding binding = new Binding() { @Override public void setVariable(String name, Object value) { if (currentBeanDefinition != null) { applyPropertyToBeanDefinition(name, value); } else { super.setVariable(name, value); } } }; binding.setVariable("beans", beans); int countBefore = getRegistry().getBeanDefinitionCount(); try { GroovyShell shell = new GroovyShell(getResourceLoader().getClassLoader(), binding); shell.evaluate(encodedResource.getReader(), "beans"); } catch (Throwable ex) { throw new BeanDefinitionParsingException(new Problem("Error evaluating Groovy script: " + ex.getMessage(), new Location(encodedResource.getResource()), null, ex)); } return getRegistry().getBeanDefinitionCount() - countBefore; }
Example #29
Source File: GroovyScript.java From streamline with Apache License 2.0 | 5 votes |
private groovy.lang.Script getParsedScript() { if (parsedScript == null) { synchronized (this) { parsedScript = new ThreadLocal<groovy.lang.Script>() { @Override protected groovy.lang.Script initialValue() { return new GroovyShell().parse(expression); } }; } } return parsedScript.get(); }
Example #30
Source File: EditorScriptingComponent.java From jmonkeybuilder with Apache License 2.0 | 5 votes |
/** * Instantiates a new Editor scripting component. * * @param applyHandler the apply handler */ public EditorScriptingComponent(@NotNull final Runnable applyHandler) { this.applyHandler = applyHandler; this.editorComponent = new GroovyEditorComponent(true); this.editorComponent.setFocusTraversable(true); this.editorComponent.prefHeightProperty().bind(heightProperty().multiply(0.6)); this.editorComponent.prefWidthProperty().bind(widthProperty()); this.headerComponent = new GroovyEditorComponent(false); this.headerComponent.prefHeightProperty().bind(heightProperty().multiply(0.4)); this.headerComponent.prefWidthProperty().bind(widthProperty()); this.shell = new GroovyShell(); this.variables = DictionaryFactory.newObjectDictionary(); this.imports = ArrayFactory.newArray(String.class); final Label headersLabel = new Label(Messages.EDITOR_SCRIPTING_COMPONENT_HEADERS + ":"); final Label scriptBodyLabel = new Label(Messages.EDITOR_SCRIPTING_COMPONENT_BODY + ":"); final Button runButton = new Button(Messages.EDITOR_SCRIPTING_COMPONENT_RUN); runButton.setOnAction(event -> run()); add(headersLabel, 0, 0, 1, 1); add(headerComponent, 0, 1, 1, 1); add(scriptBodyLabel, 0, 2, 1, 1); add(editorComponent, 0, 3, 1, 1); add(runButton, 0, 4, 1, 1); FXUtils.addClassTo(this, CssClasses.EDITOR_SCRIPTING_COMPONENT); }