Java Code Examples for groovy.lang.Binding#setVariable()

The following examples show how to use groovy.lang.Binding#setVariable() . 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 vote down vote up
/**
 * 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: ApiGroovyCompiler.java    From pushfish-android with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 3
Source File: TestScriptletProcessor.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
@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 4
Source File: GroovyScriptBase.java    From java-trader with Apache License 2.0 6 votes vote down vote up
/**
 * 对于部分只读变量, 需要保护起来
 */
@Override
public void setProperty(String property, Object newValue) {
    Binding binding = getBinding();
    //先判断本地局部变量是否存在
    if ( binding.hasVariable(property) ) {
        binding.setVariable(property, newValue);
        return;
    }
    //标准变量不允许设置
    if ( context.varExists(property)) {
        return;
    }
    //旧的设置变量方式
    super.setProperty(property, newValue);
}
 
Example 5
Source File: ScriptingManager.java    From cuba with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: LoadFlowExtensionGroovyScriptTest.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
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 7
Source File: GroovyExecutor.java    From mdw with Apache License 2.0 5 votes vote down vote up
public Object evaluate(String expression, Map<String, Object> bindings)
throws ExecutionException {
    binding = new Binding();

    for (String bindName : bindings.keySet()) {
        binding.setVariable(bindName, bindings.get(bindName));
    }

    return runScript(expression);
}
 
Example 8
Source File: DataScriptHelperTest.java    From open-platform-demo with GNU Affero General Public License v3.0 5 votes vote down vote up
@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 9
Source File: GroovyBeanDefinitionReader.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * 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 10
Source File: RouteRuleFilter.java    From springboot-learning-example with Apache License 2.0 5 votes vote down vote up
public Map<String,Object> filter(Map<String,Object> input) {

    Binding binding = new Binding();
    binding.setVariable("input", input);

    GroovyShell shell = new GroovyShell(binding);
    
    String filterScript = "def field = input.get('field')\n"
                                  + "if (input.field == 'buyer') { return ['losDataBusinessName':'losESDataBusiness3', 'esIndex':'potential_goods_recommend1']}\n"
                                  + "if (input.field == 'seller') { return ['losDataBusinessName':'losESDataBusiness4', 'esIndex':'potential_goods_recommend2']}\n";
    Script script = shell.parse(filterScript);
    Object ret = script.run();
    System.out.println(ret);
    return (Map<String, Object>) ret;
}
 
Example 11
Source File: GroovyDynamicModelsSupplier.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public List<DynamicModel> get(Network network) {
    List<DynamicModel> dynamicModels = new ArrayList<>();

    Binding binding = new Binding();
    binding.setVariable("network", network);

    ExpressionDslLoader.prepareClosures(binding);
    extensions.forEach(e -> e.load(binding, dynamicModels::add));

    GroovyShell shell = new GroovyShell(binding, new CompilerConfiguration());
    shell.evaluate(codeSource);

    return dynamicModels;
}
 
Example 12
Source File: ITestUtils.java    From pom-manipulation-ext with Apache License 2.0 5 votes vote down vote up
/**
 * Run runScript.groovy script in workingDir directory.
 *
 * @param workingDir - Directory with groovy script.
 * @param file - groovy script to run
 * @throws Exception if an error occurs
 */
private static void runScript( String workingDir, String file )
    throws Exception
{
    File verify = new File( workingDir + File.separator + file + ".groovy" );
    if ( !verify.isFile() )
    {
        return;
    }
    Binding binding = new Binding();
    binding.setVariable( "basedir", workingDir );
    GroovyScriptEngine engine = new GroovyScriptEngine( workingDir );
    engine.run( file + ".groovy", binding );
}
 
Example 13
Source File: PipelineDSLGlobal.java    From simple-build-for-pipeline-plugin with MIT License 5 votes vote down vote up
@Override
public Object getValue(CpsScript script) throws Exception {
    Binding binding = script.getBinding();

    CpsThread c = CpsThread.current();
    if (c == null)
        throw new IllegalStateException("Expected to be called from CpsThread");

    ClassLoader cl = getClass().getClassLoader();

    String scriptPath = "dsl/" + getFunctionName() + ".groovy";
    Reader r = new InputStreamReader(cl.getResourceAsStream(scriptPath), "UTF-8");

    GroovyCodeSource gsc = new GroovyCodeSource(r, getFunctionName() + ".groovy", cl.getResource(scriptPath).getFile());
    gsc.setCachable(true);


    Object pipelineDSL = c.getExecution()
            .getShell()
            .getClassLoader()
            .parseClass(gsc)
            .newInstance();
    binding.setVariable(getName(), pipelineDSL);
    r.close();


    return pipelineDSL;
}
 
Example 14
Source File: TestService.java    From groovy-script-example with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Binding groovyBinding = new Binding();
    groovyBinding.setVariable("testService", new TestService());
    GroovyShell groovyShell = new GroovyShell(groovyBinding);

    String scriptContent = "import pers.doublebin.example.groovy.script.service.TestService\n" +
            "def query = new TestService().testQuery(1L);\n" +
            "query";

    /*String scriptContent = "def query = testService.testQuery(2L);\n" +
            "query";*/

    Script script = groovyShell.parse(scriptContent);
    System.out.println(script.run());
}
 
Example 15
Source File: GroovyShellWrapper.java    From artifactory_ssh_proxy with Apache License 2.0 5 votes vote down vote up
protected void runGroovy() {
    try {
        LOGGER.info("Running groovy shell");
        IO io = new IO(in, out, err);

        LOGGER.info("in: {} out: {}  err: {}", in, out, err);

        // TODO: fix to allow other bindings.
        Binding binding = new Binding();
        binding.setVariable("out", io.out);

        Groovysh groovysh = new Groovysh(binding, io);
        InteractiveShellRunner isr = new InteractiveShellRunner(groovysh, new GroovyPrompt(this));

        isr.setErrorHandler(new OutputStreamErrorHandler(this, err));

        try {
            // groovysh.run((String) null);
            isr.run();
        } catch (Exception e) {
            try (PrintStream ps = new PrintStream(out)) {
                e.printStackTrace(ps);
            }
            this.alive = false;
        }
    } finally {
        this.alive = false;
        destroy();
        callback.onExit(exitValue());
    }
}
 
Example 16
Source File: Controller.java    From xdat_editor with MIT License 5 votes vote down vote up
@FXML
private void execute() {
    Binding binding = new Binding();
    IOEntity xdat = editor.getXdatObject();
    binding.setVariable("xdat", xdat);
    GroovyShell shell = new GroovyShell(xdat.getClass().getClassLoader(), binding);

    PrintStream out = System.out;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream scriptOut = new PrintStream(baos, false);
    System.setOut(scriptOut);

    output.setText("");
    String script = scriptTemplate
            .replace("$pckg", editor.getXdatClass().getPackage().getName())
            .replace("$text", scriptText.getText());
    editor.execute(() -> {
        shell.evaluate(script);

        return null;
    }, exception -> exception.printStackTrace(scriptOut), () -> {
        System.setOut(out);

        Platform.runLater(() -> {
            output.setText(baos.toString());

            editor.setXdatObject(null);
            editor.setXdatObject(xdat);
        });
    });
}
 
Example 17
Source File: ScriptInGroovy.java    From stendhal with GNU General Public License v2.0 5 votes vote down vote up
/**
 * manages a script written in groovy
 *
 * @param filename filename
 */
public ScriptInGroovy(final String filename) {
	super(filename);
	groovyScript = filename;
	groovyBinding = new Binding();
	groovyBinding.setVariable("game", this);
	groovyBinding.setVariable("logger", logger);
	groovyBinding.setVariable("storage", new HashMap<Object, Object>());

	groovyBinding.setVariable("rules", SingletonRepository.getRuleProcessor());
	groovyBinding.setVariable("world", SingletonRepository.getRPWorld());
}
 
Example 18
Source File: ScriptExtensions.java    From groovy with Apache License 2.0 4 votes vote down vote up
private static void retrieveBindingVars(ScriptEngine self, Binding binding) {
    Set<Map.Entry<String, Object>> returnVars = self.getBindings(ScriptContext.ENGINE_SCOPE).entrySet();
    for (Map.Entry<String, Object> me : returnVars) {
        binding.setVariable(me.getKey(), me.getValue());
    }
}
 
Example 19
Source File: GroovyBeanDefinitionReader.java    From spring-analysis-note with MIT License 4 votes vote down vote up
/**
 * 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);
	}

	if (logger.isTraceEnabled()) {
		logger.trace("Loading Groovy bean definitions from " + encodedResource);
	}

	Closure beans = new Closure(this) {
		@Override
		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(getBeanClassLoader(), 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));
	}

	int count = getRegistry().getBeanDefinitionCount() - countBefore;
	if (logger.isDebugEnabled()) {
		logger.debug("Loaded " + count + " bean definitions from " + encodedResource);
	}
	return count;
}
 
Example 20
Source File: GroovyScriptEngine.java    From groovy with Apache License 2.0 3 votes vote down vote up
/**
 * Run a script identified by name with a single argument.
 *
 * @param scriptName name of the script to run
 * @param argument   a single argument passed as a variable named <code>arg</code> in the binding
 * @return a <code>toString()</code> representation of the result of the execution of the script
 * @throws ResourceException if there is a problem accessing the script
 * @throws ScriptException   if there is a problem parsing the script
 */
public String run(String scriptName, String argument) throws ResourceException, ScriptException {
    Binding binding = new Binding();
    binding.setVariable("arg", argument);
    Object result = run(scriptName, binding);
    return result == null ? "" : result.toString();
}