groovy.lang.Binding Java Examples
The following examples show how to use
groovy.lang.Binding.
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: 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 #2
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 #3
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 #4
Source File: TestScriptletProcessor.java From gsn with GNU General Public License v3.0 | 6 votes |
@Test public void testTimedField() { ScriptletProcessor processor = getProcessor(dataFields1, "return;"); StreamElement se = new StreamElement(dataFields1, data1); Binding context = processor.updateContext(se); processor.evaluate(processor.scriptlet, se, true); StreamElement seo = processor.formatOutputStreamElement(context); assertNotSame(seo.getTimeStamp(), 123456L); se.setTimeStamp(123456L); context = processor.updateContext(se); processor.evaluate(processor.scriptlet, se, true); seo = processor.formatOutputStreamElement(context); assertEquals(123456L, seo.getTimeStamp()); }
Example #5
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 #6
Source File: ScriptLauncher.java From groovy with Apache License 2.0 | 6 votes |
public void run() { final long id = Thread.currentThread().getId(); // run the script numIter times for (int i = 0; i < numIter; i++) { Builder builder = new Builder(); Binding binding = new Binding(); binding.setVariable("builder", builder); script = InvokerHelper.createScript(scriptClass, binding); script.run(); } latch.countDown(); }
Example #7
Source File: ScriptingManager.java From cuba with Apache License 2.0 | 6 votes |
@Authenticated @Override public String runGroovyScript(String scriptName) { try { Binding binding = new Binding(); binding.setVariable("persistence", persistence); binding.setVariable("metadata", metadata); binding.setVariable("configuration", configuration); binding.setVariable("dataManager", dataManager); Object result = scripting.runGroovyScript(scriptName, binding); return String.valueOf(result); } catch (Exception e) { log.error("Error runGroovyScript", e); return ExceptionUtils.getStackTrace(e); } }
Example #8
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 #9
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 #10
Source File: GroovyScript.java From engine with GNU General Public License v3.0 | 6 votes |
@Override public Object execute(Map<String, Object> variables) throws ScriptException { Map<String, Object> allVariables = new HashMap<String, Object>(); if (MapUtils.isNotEmpty(globalVariables)) { allVariables.putAll(globalVariables); } if (MapUtils.isNotEmpty(variables)) { allVariables.putAll(variables); } MDC.put(SCRIPT_URL_MDC_KEY, scriptUrl); try { return InvokerHelper.createScript(scriptClass, new Binding(allVariables)).run(); } catch (Exception e) { throw new ScriptException(e.getMessage(), e); } finally { MDC.remove(SCRIPT_URL_MDC_KEY); } }
Example #11
Source File: DynamicAttributesRecalculationTools.java From cuba with Apache License 2.0 | 6 votes |
protected Object evaluateGroovyScript(BaseGenericIdEntity entity, String groovyScript) { //noinspection unchecked Map<String, CategoryAttributeValue> dynamicAttributes = (Map<String, CategoryAttributeValue>) entity.getDynamicAttributes(); Map<String, Object> dynamicAttributesValues = new HashMap<>(); if (dynamicAttributes != null) { for (Map.Entry<String, CategoryAttributeValue> entry : dynamicAttributes.entrySet()) { dynamicAttributesValues.put(entry.getKey(), entry.getValue().getValue()); } } Binding binding = new Binding(); binding.setVariable("entity", entity); binding.setVariable("dynamicAttributes", dynamicAttributesValues); return scripting.evaluateGroovy(groovyScript, binding); }
Example #12
Source File: ApiGroovyCompiler.java From pushfish-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 #13
Source File: TestScriptletProcessor.java From gsn with GNU General Public License v3.0 | 6 votes |
@Test public void testCorrectScriptExecution() { ScriptletProcessor processor = getProcessor(dataFields1, "msg = 'Hello ' + ch.epfl.gsn; def msg1 = 'This is a script internal variable.'"); StreamElement se = new StreamElement(dataFields1, data1); Binding context = processor.updateContext(se); context.setVariable("ch.epfl.gsn", new String("Groovy GSN")); processor.evaluate(processor.scriptlet, se, true); assertNotNull(context.getVariable("msg")); assertEquals(context.getVariable("msg"), "Hello Groovy GSN"); Object o = null; try { o = context.getVariable("msg1"); } catch (Exception e) {} assertNull(o); }
Example #14
Source File: SecurityTestSupport.java From groovy with Apache License 2.0 | 6 votes |
protected void executeScript(Class scriptClass, Permission missingPermission) { try { Script script = InvokerHelper.createScript(scriptClass, new Binding()); script.run(); //InvokerHelper.runScript(scriptClass, null); } catch (AccessControlException ace) { if (missingPermission != null && missingPermission.implies(ace.getPermission())) { return; } else { fail(ace.toString()); } } if (missingPermission != null) { fail("Should catch an AccessControlException"); } }
Example #15
Source File: OpenShiftGlobalVariable.java From jenkins-client-plugin with Apache License 2.0 | 6 votes |
@Nonnull @Override public Object getValue(@Nonnull CpsScript script) throws Exception { Binding binding = script.getBinding(); script.println(); Object openshift; if (binding.hasVariable(getName())) { openshift = binding.getVariable(getName()); } else { // Note that if this were a method rather than a constructor, we // would need to mark it @NonCPS lest it throw // CpsCallableInvocation. openshift = script.getClass().getClassLoader() .loadClass("com.openshift.jenkins.plugins.OpenShiftDSL") .getConstructor(CpsScript.class).newInstance(script); binding.setVariable(getName(), openshift); } return openshift; }
Example #16
Source File: DslRecordMapper.java From divolte-collector with Apache License 2.0 | 6 votes |
public DslRecordMapper(final ValidatedConfiguration vc, final String groovyFile, final Schema schema, final Optional<LookupService> geoipService) { this.schema = Objects.requireNonNull(schema); logger.info("Using mapping from script file: {}", groovyFile); try { final DslRecordMapping mapping = new DslRecordMapping(schema, new UserAgentParserAndCache(vc), geoipService); final GroovyCodeSource groovySource = new GroovyCodeSource(new File(groovyFile), StandardCharsets.UTF_8.name()); final CompilerConfiguration compilerConfig = new CompilerConfiguration(); compilerConfig.setScriptBaseClass("io.divolte.groovyscript.MappingBase"); final Binding binding = new Binding(); binding.setProperty("mapping", mapping); final GroovyShell shell = new GroovyShell(binding, compilerConfig); shell.evaluate(groovySource); actions = mapping.actions(); } catch (final IOException e) { throw new UncheckedIOException("Could not load mapping script file: " + groovyFile, e); } }
Example #17
Source File: UserGroovyRight.java From projectforge-webapp with GNU General Public License v3.0 | 6 votes |
/** * PLEASE NOTE: This block is synchronized! Therefore this class should not be used for long running scripts! * @return Calls the Groovy script. */ @Override public boolean matches(final UserGroupCache userGroupCache, final PFUserDO user, final UserRightValue value) { synchronized (groovyScript) { final Binding binding = groovyScript.getBinding(); binding.setVariable("userGroupCache", userGroupCache); binding.setVariable("user", user); binding.setVariable("value", value); try { return (Boolean) groovyScript.run(); } catch (Exception ex) { log.error("Groovy-Execution-Exception: " + ex.getMessage(), ex); return false; } } }
Example #18
Source File: GroovyBeanDefinitionReader.java From blog_demos with Apache License 2.0 | 5 votes |
/** * Load bean definitions from the specified Groovy script. * @param encodedResource the resource descriptor for the Groovy script, * allowing to specify 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 { 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(), encodedResource.getResource().getFilename()); } 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 #19
Source File: ScriptManagerImpl.java From jira-groovioli with BSD 2-Clause "Simplified" License | 5 votes |
private Binding fromMap(Map<String, Object> parameters) { Map variables = new HashMap(baseVariables); if (parameters != null) { variables.putAll(parameters); } return new Binding(variables); }
Example #20
Source File: ServerDbUpdater.java From cuba with Apache License 2.0 | 5 votes |
@Override protected boolean executeGroovyScript(final ScriptResource file) { Binding bind = new Binding(); bind.setProperty("ds", getDataSource()); bind.setProperty("log", LoggerFactory.getLogger(String.format("%s$%s", DbUpdaterEngine.class.getName(), StringUtils.removeEndIgnoreCase(file.getName(), ".groovy")))); if (!StringUtils.endsWithIgnoreCase(file.getName(), "." + UPGRADE_GROOVY_EXTENSION)) { bind.setProperty("postUpdate", new PostUpdateScripts() { @Override public void add(Closure closure) { postUpdateScripts.put(closure, file); postUpdate.add(closure); } @Override public List<Closure> getUpdates() { return postUpdate.getUpdates(); } }); } try { scripting.evaluateGroovy(file.getContent(), bind, ScriptExecutionPolicy.DO_NOT_USE_COMPILE_CACHE); } catch (Exception e) { throw new RuntimeException(ERROR + "Error executing Groovy script " + file.name + "\n" + e.getMessage(), e); } return !postUpdateScripts.containsValue(file); }
Example #21
Source File: ScriptExtensions.java From groovy with Apache License 2.0 | 5 votes |
@SuppressWarnings("unchecked") private static void storeBindingVars(ScriptEngine self, Binding binding) { Set<Map.Entry<?, ?>> vars = binding.getVariables().entrySet(); for (Map.Entry<?, ?> me : vars) { self.put(me.getKey().toString(), me.getValue()); } }
Example #22
Source File: DataScriptHelperTest.java From open-platform-demo with GNU Affero General Public License v3.0 | 5 votes |
@Test public void test_useCache() { int count = MAX_COUNT; while (--count > 0) { String expr = "count * " + (count % 100); Binding binding = new Binding(); binding.setVariable("count", count); helper.eval(expr, binding); } }
Example #23
Source File: GroovyFacadeImpl.java From zstack with Apache License 2.0 | 5 votes |
@Override public void executeScriptByPath(String scriptPath, Map<Object, Object> context) { try { String scriptName = PathUtil.fileName(scriptPath); String scriptDir = PathUtil.parentFolder(scriptPath); GroovyScriptEngine gse = new GroovyScriptEngine(scriptDir); Binding binding = new Binding(context); gse.run(scriptName, binding); } catch (Exception e) { throw new CloudRuntimeException(e); } }
Example #24
Source File: GroovyCurvesSupplier.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Override public List<Curve> get(Network network) { List<Curve> curves = new ArrayList<>(); Binding binding = new Binding(); binding.setVariable("network", network); ExpressionDslLoader.prepareClosures(binding); extensions.forEach(e -> e.load(binding, curves::add)); GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration()); shell.evaluate(codeSource); return curves; }
Example #25
Source File: JMeterScriptProcessor.java From jsflight with Apache License 2.0 | 5 votes |
/** * Post process sample with groovy script. * * @param sampler * @param result * @param recorder * @return is sample ok */ public boolean processSampleDuringRecord(HTTPSamplerBase sampler, SampleResult result, JMeterRecorder recorder) { Binding binding = new Binding(); binding.setVariable(ScriptBindingConstants.LOGGER, LOG); binding.setVariable(ScriptBindingConstants.SAMPLER, sampler); binding.setVariable(ScriptBindingConstants.SAMPLE, result); binding.setVariable(ScriptBindingConstants.CONTEXT, recorder.getContext()); binding.setVariable(ScriptBindingConstants.JSFLIGHT, JMeterJSFlightBridge.getInstance()); binding.setVariable(ScriptBindingConstants.CLASSLOADER, classLoader); Script script = ScriptEngine.getScript(getStepProcessorScript()); if (script == null) { LOG.warn(sampler.getName() + ". No script found. Default result is " + SHOULD_BE_PROCESSED_DEFAULT); return SHOULD_BE_PROCESSED_DEFAULT; } script.setBinding(binding); LOG.info(sampler.getName() + ". Running compiled script"); Object scriptResult = script.run(); boolean shouldBeProcessed; if (scriptResult != null && scriptResult instanceof Boolean) { shouldBeProcessed = (boolean)scriptResult; LOG.info(sampler.getName() + ". Script result " + shouldBeProcessed); } else { shouldBeProcessed = SHOULD_BE_PROCESSED_DEFAULT; LOG.warn(sampler.getName() + ". Script result UNDEFINED. Default result is " + SHOULD_BE_PROCESSED_DEFAULT); } return shouldBeProcessed; }
Example #26
Source File: GroovyScriptEngineFactory.java From nexus-public with Eclipse Public License 1.0 | 5 votes |
@VisibleForTesting static String getContext(final Binding binding) { Optional<String> taskContext = getVariable(binding, "task", ScriptTask.class) .map(ts -> format("Task '%s'", ts.getName())); Optional<String> scriptContext = getVariable(binding,"scriptName", String.class) .map(name -> format("Script '%s'" , name)); return Stream.of(taskContext, scriptContext) .filter(Optional::isPresent) .map(Optional::get) .findFirst() .orElse("An unknown script"); }
Example #27
Source File: LoadFlowExtensionGroovyScriptTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
protected List<GroovyScriptExtension> getExtensions() { GroovyScriptExtension ext = new GroovyScriptExtension() { @Override public void load(Binding binding, ComputationManager computationManager) { binding.setVariable("n", fooNetwork); } @Override public void unload() { } }; return Arrays.asList(new LoadFlowGroovyScriptExtension(new LoadFlowParameters()), ext); }
Example #28
Source File: LockableResource.java From lockable-resources-plugin with MIT License | 5 votes |
/** * Checks if the script matches the requirement. * * @param script Script to be executed * @param params Extra script parameters * @return {@code true} if the script returns true (resource matches). * @throws ExecutionException Script execution failed (e.g. due to the missing permissions). * Carries info in the cause */ @Restricted(NoExternalUse.class) public boolean scriptMatches( @Nonnull SecureGroovyScript script, @CheckForNull Map<String, Object> params) throws ExecutionException { Binding binding = new Binding(params); binding.setVariable("resourceName", name); binding.setVariable("resourceDescription", description); binding.setVariable("resourceLabels", makeLabelsList()); try { Object result = script.evaluate(Jenkins.get().getPluginManager().uberClassLoader, binding); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine( "Checked resource " + name + " for " + script.getScript() + " with " + binding + " -> " + result); } return (Boolean) result; } catch (Exception e) { throw new ExecutionException( "Cannot get boolean result out of groovy expression. See system log for more info", e); } }
Example #29
Source File: GateFactory.java From stendhal with GNU General Public License v2.0 | 5 votes |
@Override public Object create(ConfigurableFactoryContext ctx) { final String orientation = ctx.getRequiredString("orientation"); final String image = ctx.getRequiredString("image"); final int autoclose = ctx.getInt("autoclose", 0); final String id = ctx.getString("identifier", null); final String message = ctx.getString("message", null); ChatCondition condition = null; final String condString = ctx.getString("condition", null); if (condString != null) { final GroovyShell interp = new GroovyShell(new Binding()); String code = "import games.stendhal.server.entity.npc.condition.*;\r\n" + condString; try { condition = (ChatCondition) interp.evaluate(code); } catch (CompilationFailedException e) { throw new IllegalArgumentException(e); } } final Gate gate = new Gate(orientation, image, condition); gate.setAutoCloseDelay(autoclose); gate.setRefuseMessage(message); gate.setIdentifier(id); return gate; }
Example #30
Source File: CubeDSL.java From kubernetes-pipeline-plugin with Apache License 2.0 | 5 votes |
@Nonnull @Override public Object getValue(CpsScript script) throws Exception { Binding binding = script.getBinding(); Object kubernetes; if (binding.hasVariable(getName())) { kubernetes = binding.getVariable(getName()); } else { // Note that if this were a method rather than a constructor, we would need to mark it @NonCPS lest it throw CpsCallableInvocation. kubernetes = CubeDSL.class.getClassLoader().loadClass("io.fabric8.kubernetes.pipeline.arquillian.cube.kubernetes.Cube").getConstructor(CpsScript.class).newInstance(script); binding.setVariable(getName(), kubernetes); } return kubernetes; }