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

The following examples show how to use groovy.lang.Binding#setProperty() . 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: GroovyTest.java    From streamline with Apache License 2.0 7 votes vote down vote up
@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 2
Source File: RunScriptTool.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Override
public void run(CommandLine line, ToolRunningContext context) {
    Path file = context.getFileSystem().getPath(line.getOptionValue(FILE));
    if (file.getFileName().toString().endsWith(".groovy")) {
        try {
            Binding binding = new Binding();
            binding.setProperty("args", line.getArgs());
            GroovyScripts.run(file, binding, context.getOutputStream());
        } catch (Exception e) {
            Throwable rootCause = StackTraceUtils.sanitizeRootCause(e);
            rootCause.printStackTrace(context.getErrorStream());
        }
    } else {
        throw new IllegalArgumentException("Script type not supported");
    }
}
 
Example 3
Source File: GroovyInterpreter.java    From COMP6237 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public GroovyInterpreter(Binding binding) throws IOException {
	this.binding = binding;
	if (this.binding == null)
		this.binding = new Binding();

	is = new PipedInputStream();
	os = new PipedOutputStream();
	pis = new PipedInputStream(os);
	pos = new PipedOutputStream(is);

	System.setProperty(TerminalFactory.JLINE_TERMINAL, "none");
	AnsiConsole.systemInstall();
	Ansi.setDetector(new AnsiDetector());

	binding.setProperty("out", new ImmediateFlushingPrintWriter(pos));

	shell = new Groovysh(binding, new IO(pis, pos, pos));
	// {
	// @Override
	// public void displayWelcomeBanner(InteractiveShellRunner runner) {
	// // do nothing
	// }
	// };
	shell.getIo().setVerbosity(Verbosity.QUIET);
}
 
Example 4
Source File: GroovySlide.java    From COMP6237 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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 5
Source File: ShellTest.java    From knox with Apache License 2.0 6 votes vote down vote up
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: DslRecordMapper.java    From divolte-collector with Apache License 2.0 6 votes vote down vote up
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 7
Source File: GroovySetIdIssueTest.java    From powsybl-core with Mozilla Public License 2.0 5 votes vote down vote up
@Test
public void test() {
    thrown.expect(PowsyblException.class);
    thrown.expectMessage("ID modification of 'GEN' is not allowed");
    Network network = EurostagTutorialExample1Factory.create();
    Binding binding = new Binding();
    binding.setProperty("network", network);
    GroovyShell shell = new GroovyShell(binding);
    shell.evaluate("network.getGenerator('GEN').id = 'FOO'");
}
 
Example 8
Source File: GroovyService.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@PostConstruct
public void init() {
    ImportCustomizer importCustomizer = new ImportCustomizer();
    importCustomizer.addStarImports("net.dv8tion.jda.api.entities");

    configuration = new CompilerConfiguration();
    configuration.addCompilationCustomizers(importCustomizer);

    sharedData = new Binding();
    sharedData.setProperty("ctx", context);
}
 
Example 9
Source File: FoldersServiceBean.java    From cuba with Apache License 2.0 5 votes vote down vote up
@Override
public List<AppFolder> reloadAppFolders(List<AppFolder> folders) {
    log.debug("Reloading AppFolders {}", folders);

    StopWatch stopWatch = new Slf4JStopWatch("AppFolders");
    stopWatch.start();

    try {
        if (!folders.isEmpty()) {
            Binding binding = new Binding();
            binding.setVariable("persistence", persistence);
            binding.setVariable("metadata", metadata);
            binding.setProperty("userSession", userSessionSource.getUserSession());

            for (AppFolder folder : folders) {
                Transaction tx = persistence.createTransaction();
                try {
                    if (loadFolderQuantity(binding, folder)) {
                        tx.commit();
                    }
                } finally {
                    tx.end();
                }
            }
        }

        return folders;
    } finally {
        stopWatch.stop();
    }
}
 
Example 10
Source File: ServerDbUpdater.java    From cuba with Apache License 2.0 5 votes vote down vote up
@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 11
Source File: DbUpdaterEngine.java    From cuba with Apache License 2.0 5 votes vote down vote up
protected boolean executeGroovyScript(ScriptResource file) {
    try {
        ClassLoader classLoader = getClass().getClassLoader();
        CompilerConfiguration cc = new CompilerConfiguration();
        cc.setRecompileGroovySource(true);

        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) {
                    super.add(closure);

                    log.warn("Added post update action will be ignored for data store [{}]", storeNameToString(storeName));
                }
            });
        }

        GroovyShell shell = new GroovyShell(classLoader, bind, cc);
        Script script = shell.parse(file.getContent());
        script.run();
    } catch (Exception e) {
        throw new RuntimeException(
                String.format("%sError executing Groovy script %s\n%s", ERROR, file.name, e.getMessage()), e);
    }
    return true;
}
 
Example 12
Source File: SecureKnoxShellTest.java    From knox with Apache License 2.0 5 votes vote down vote up
/**
 * 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 13
Source File: HttpAsyncMockServiceImpl.java    From AnyMock with Apache License 2.0 4 votes vote down vote up
private Binding buildBindig(HttpServletRequest request, HttpURLConnection httpURLConnection) {
    Binding binding = new Binding();
    binding.setProperty("request", request);
    binding.setProperty("httpURLConnection", httpURLConnection);
    return binding;
}
 
Example 14
Source File: HttpSyncMockServiceImpl.java    From AnyMock with Apache License 2.0 4 votes vote down vote up
private Binding buildSyncBinding(HttpServletRequest request, HttpServletResponse response) {
    Binding binding = new Binding();
    binding.setProperty("request", request);
    binding.setProperty("response", response);
    return binding;
}
 
Example 15
Source File: GroovyScript.java    From streamline with Apache License 2.0 4 votes vote down vote up
private void addToBinding(Map<String, Object> fieldsToValues, Binding binding) {
    for (Map.Entry<String, Object> entry : fieldsToValues.entrySet()) {
        binding.setProperty(entry.getKey(), entry.getValue());
    }
}