Java Code Examples for org.codehaus.groovy.control.CompilerConfiguration#setScriptBaseClass()

The following examples show how to use org.codehaus.groovy.control.CompilerConfiguration#setScriptBaseClass() . 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: 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 2
Source File: GroovyTradletImpl.java    From java-trader with Apache License 2.0 6 votes vote down vote up
@Override
public void init(TradletContext context) throws Exception {
    this.group = context.getGroup();
    this.beansContainer = context.getBeansContainer();
    this.functionClasses = loadStandardScriptFunctionClasses();
    this.functionClasses.putAll(discoverPluginScriptFunctions(beansContainer.getBean(PluginService.class)));
    logger.info("Tradlet group "+group.getId()+" discoverd functions: "+new TreeSet<>(functionClasses.keySet()));

    CompilerConfiguration scriptConfig = new CompilerConfiguration();
    scriptConfig.setTargetBytecode(CompilerConfiguration.JDK8);
    scriptConfig.setRecompileGroovySource(false);
    scriptConfig.setScriptBaseClass(GroovyScriptBase.class.getName());
    scriptLoader = new GroovyClassLoader(getClass().getClassLoader(), scriptConfig);

    initVars();

    reload(context);
}
 
Example 3
Source File: GroovyExecutor.java    From hugegraph-loader with Apache License 2.0 6 votes vote down vote up
public void execute(String groovyScript, HugeClient client) {
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(DelegatingScript.class.getName());
    ImportCustomizer importCustomizer = new ImportCustomizer();
    importCustomizer.addImports(HugeClient.class.getName());
    importCustomizer.addImports(SchemaManager.class.getName());
    config.addCompilationCustomizers(importCustomizer);

    GroovyShell shell = new GroovyShell(getClass().getClassLoader(),
                                        this.binding, config);

    // Groovy invoke java through the delegating script.
    DelegatingScript script = (DelegatingScript) shell.parse(groovyScript);
    script.setDelegate(client);
    script.run();
}
 
Example 4
Source File: TestCaseScript.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * performs groovy substitutions with this as delegate and inherited bindings
 */
protected String substitute(String before) {
    if (!before.contains("${"))
        return before;
    // escape all $ not followed by curly braces on same line
    before = before.replaceAll("\\$(?!\\{)", "\\\\\\$");
    // escape all regex -> ${~
    before = before.replaceAll("\\$\\{~", "\\\\\\$\\{~");
    // escape all escaped newlines
    before = before.replaceAll("\\\\n", "\\\\\\\\\\n");
    before = before.replaceAll("\\\\r", "\\\\\\\\\\r");
    // escape all escaped quotes
    before = before.replaceAll("\\\"", "\\\\\"");

    CompilerConfiguration compilerCfg = new CompilerConfiguration();
    compilerCfg.setScriptBaseClass(DelegatingScript.class.getName());
    GroovyShell shell = new GroovyShell(TestCaseScript.class.getClassLoader(), getBinding(), compilerCfg);
    DelegatingScript script = (DelegatingScript) shell.parse("return \"\"\"" + before + "\"\"\"");
    script.setDelegate(TestCaseScript.this);
    // restore escaped \$ to $ for comparison
    return script.run().toString().replaceAll("\\\\$", "\\$");
}
 
Example 5
Source File: StandaloneTestCaseRun.java    From mdw with Apache License 2.0 6 votes vote down vote up
/**
 * 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 6
Source File: ForbiddenApisPlugin.java    From forbidden-apis with Apache License 2.0 6 votes vote down vote up
private static Class<? extends DelegatingScript> loadScript() {
  final ImportCustomizer importCustomizer = new ImportCustomizer().addStarImports(ForbiddenApisPlugin.class.getPackage().getName());
  final CompilerConfiguration configuration = new CompilerConfiguration().addCompilationCustomizers(importCustomizer);
  configuration.setScriptBaseClass(DelegatingScript.class.getName());
  configuration.setSourceEncoding(StandardCharsets.UTF_8.name());
  final URL scriptUrl = ForbiddenApisPlugin.class.getResource(PLUGIN_INIT_SCRIPT);
  if (scriptUrl == null) {
    throw new RuntimeException("Cannot find resource with script: " + PLUGIN_INIT_SCRIPT);
  }
  return AccessController.doPrivileged(new PrivilegedAction<Class<? extends DelegatingScript>>() {
    @Override
    public Class<? extends DelegatingScript> run() {
      try {
        // We don't close the classloader, as we may need it later when loading other classes from inside script:
        @SuppressWarnings("resource") final GroovyClassLoader loader =
            new GroovyClassLoader(ForbiddenApisPlugin.class.getClassLoader(), configuration);
        final GroovyCodeSource csrc = new GroovyCodeSource(scriptUrl);
        @SuppressWarnings("unchecked") final Class<? extends DelegatingScript> clazz =
            loader.parseClass(csrc, false).asSubclass(DelegatingScript.class);
        return clazz;
      } catch (Exception e) {
        throw new RuntimeException("Cannot compile Groovy script: " + PLUGIN_INIT_SCRIPT);
      }
    }
  });
}
 
Example 7
Source File: GroovyScriptEngineFactory.java    From nexus-public with Eclipse Public License 1.0 6 votes vote down vote up
private GroovyScriptEngine create() {
  // custom the configuration of the compiler
  CompilerConfiguration cc = new CompilerConfiguration();
  cc.setTargetDirectory(new File(applicationDirectories.getTemporaryDirectory(), "groovy-classes"));
  cc.setSourceEncoding("UTF-8");
  cc.setScriptBaseClass(ScriptWithCleanup.class.getName());
  cc.addCompilationCustomizers(secureASTCustomizer());
  GroovyClassLoader gcl = new GroovyClassLoader(classLoader, cc);

  engine = new GroovyScriptEngine(gcl);

  // HACK: For testing
  log.info("Created engine: {}", engine);

  return engine;
}
 
Example 8
Source File: CrossmapActivity.java    From mdw with Apache License 2.0 5 votes vote down vote up
/**
 * Invokes the builder object for creating new output variable value.
 */
protected void runScript(String mapperScript, Slurper slurper, Builder builder)
        throws ActivityException, TransformerException {

    CompilerConfiguration compilerConfig = new CompilerConfiguration();
    compilerConfig.setScriptBaseClass(CrossmapScript.class.getName());

    Binding binding = new Binding();
    binding.setVariable("runtimeContext", getRuntimeContext());
    binding.setVariable(slurper.getName(), slurper.getInput());
    binding.setVariable(builder.getName(), builder);
    GroovyShell shell = new GroovyShell(getPackage().getClassLoader(), binding, compilerConfig);
    Script gScript = shell.parse(mapperScript);
    gScript.run();
}
 
Example 9
Source File: GroovyShellTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testClassLoader() {
    Binding context = new Binding();
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(DerivedScript.class.getName());
    GroovyShell shell = new GroovyShell(context, config);
    String script = "evaluate '''\n"+
                    "class XXXX{}\n"+
                    "assert evaluate('XXXX') == XXXX\n"+
                    "'''";
    shell.evaluate(script);
 
}
 
Example 10
Source File: GroovyShellTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Test for GROOVY-6615
 * @throws Exception
 */
public void testScriptWithCustomBodyMethod() throws Exception {
    Binding context = new Binding();
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(BaseScriptCustomBodyMethod.class.getName());
    GroovyShell shell = new GroovyShell(context, config);
    Object result = shell.evaluate("'I like ' + cheese");
    assertEquals("I like Cheddar", result);
}
 
Example 11
Source File: GroovyShellTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
public void testScriptWithDerivedBaseClass() throws Exception {
    Binding context = new Binding();
    CompilerConfiguration config = new CompilerConfiguration();
    config.setScriptBaseClass(DerivedScript.class.getName());
    GroovyShell shell = new GroovyShell(context, config);
    Object result = shell.evaluate("x = 'abc'; doSomething(cheese)");
    assertEquals("I like Cheddar", result);
    assertEquals("abc", context.getVariable("x"));
}
 
Example 12
Source File: TestCaseRun.java    From mdw with Apache License 2.0 5 votes vote down vote up
public void run() {
    startExecution();
    try {
        if (testCase.getAsset().getExtension().equals("postman")) {
            String runnerClass = NODE_PACKAGE + ".TestRunner";
            Package pkg = PackageCache.getPackage(testCase.getPackage());
            Class<?> testRunnerClass = CompiledJavaCache.getResourceClass(runnerClass, getClass().getClassLoader(), pkg);
            Object runner = testRunnerClass.newInstance();
            Method runMethod = testRunnerClass.getMethod("run", TestCase.class);
            runMethod.invoke(runner, testCase);
            finishExecution(null);
        }
        else {
            String groovyScript = testCase.getText();
            CompilerConfiguration compilerConfig = new CompilerConfiguration();
            compilerConfig.setScriptBaseClass(TestCaseScript.class.getName());

            Binding binding = new Binding();
            binding.setVariable("testCaseRun", this);

            ClassLoader classLoader = this.getClass().getClassLoader();
            Package testPkg = PackageCache.getPackage(testCase.getPackage());
            if (testPkg != null)
                classLoader = testPkg.getClassLoader();

            GroovyShell shell = new GroovyShell(classLoader, binding, compilerConfig);
            Script gScript = shell.parse(groovyScript);
            gScript.setProperty("out", log);
            gScript.run();
            finishExecution(null);
        }
    }
    catch (Throwable ex) {
        finishExecution(ex);
    }
}
 
Example 13
Source File: GroovyScriptController.java    From groovy-script-example with Apache License 2.0 5 votes vote down vote up
@PostConstruct
public void init(){
    GroovyClassLoader groovyClassLoader = new GroovyClassLoader(this.getClass().getClassLoader());
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
    compilerConfiguration.setSourceEncoding("utf-8");
    compilerConfiguration.setScriptBaseClass(TestScript.class.getName());

    groovyShell = new GroovyShell(groovyClassLoader, groovyBinding, compilerConfiguration);
}
 
Example 14
Source File: GroovyDirective.java    From AuTe-Framework with Apache License 2.0 4 votes vote down vote up
public GroovyDirective() {
    configuration = new CompilerConfiguration();
    configuration.setScriptBaseClass(ExtendedScript.class.getName());
}
 
Example 15
Source File: PuzzleEventDispatcher.java    From stendhal with GNU General Public License v2.0 4 votes vote down vote up
/**
 * singleton constructor
 */
private PuzzleEventDispatcher() {
	CompilerConfiguration config = new CompilerConfiguration();
	config.setScriptBaseClass(GroovyPuzzlePropertyAdapter.class.getName());
	shell = new GroovyShell(this.getClass().getClassLoader(), new Binding(), config);
}
 
Example 16
Source File: FileSystemCompiler.java    From groovy with Apache License 2.0 4 votes vote down vote up
public CompilerConfiguration toCompilerConfiguration() throws IOException {
    // Setup the configuration data
    CompilerConfiguration configuration = new CompilerConfiguration();

    if (classpath != null) {
        configuration.setClasspath(classpath);
    }

    if (targetDir != null && targetDir.getName().length() > 0) {
        configuration.setTargetDirectory(targetDir);
    }

    configuration.setParameters(parameterMetadata);
    configuration.setPreviewFeatures(previewFeatures);
    configuration.setSourceEncoding(encoding);
    configuration.setScriptBaseClass(scriptBaseClass);

    // joint compilation parameters
    if (jointCompilation) {
        Map<String, Object> compilerOptions = new HashMap<>();
        compilerOptions.put("flags", javacFlags());
        compilerOptions.put("namedValues", javacNamedValues());
        configuration.setJointCompilationOptions(compilerOptions);
    }

    final List<String> transformations = new ArrayList<>();
    if (compileStatic) {
        transformations.add("ast(groovy.transform.CompileStatic)");
    }
    if (typeChecked) {
        transformations.add("ast(groovy.transform.TypeChecked)");
    }
    if (!transformations.isEmpty()) {
        processConfigScriptText(buildConfigScriptText(transformations), configuration);
    }

    String configScripts = System.getProperty("groovy.starter.configscripts", null);
    if (configScript != null || (configScripts != null && !configScripts.isEmpty())) {
        List<String> scripts = new ArrayList<>();
        if (configScript != null) {
            scripts.add(configScript);
        }
        if (configScripts != null) {
            scripts.addAll(StringGroovyMethods.tokenize(configScripts, ','));
        }
        processConfigScripts(scripts, configuration);
    }

    return configuration;
}
 
Example 17
Source File: GroovyScriptEngine.java    From james with Apache License 2.0 4 votes vote down vote up
private GroovyShell createGroovyShell(ClassLoader classLoader, Class baseClass) {
    CompilerConfiguration compilerConfiguration = new CompilerConfiguration();
    compilerConfiguration.setScriptBaseClass(baseClass.getName());
    return new GroovyShell(classLoader, compilerConfiguration);
}
 
Example 18
Source File: OperationGroovy.java    From mts with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Execute operation: load each imported groovy class file, instantiate each
 * groovy class, inject these instances in the groovy operation script, and
 * finally execute the groovy operation script
 *
 * @param runner
 * @return Next operation or null by default
 */
@Override
public Operation execute(Runner runner) throws Exception {
    if (runner instanceof ScenarioRunner) {
        GlobalLogger.instance().getSessionLogger().info(runner, TextEvent.Topic.CORE, this);
    } else {
        GlobalLogger.instance().getApplicationLogger().info(TextEvent.Topic.CORE, this);
    }

    // retrieve the list of groovy files to load
    String groovyFiles = getRootElement().attributeValue("name");

    // retrieve the groovy operation script source
    String scriptSource = getRootElement().getText();

    try {
        // instantiate the binding which manage the exchange of variables
        // between groovy scripts and MTS runner:
        MTSBinding mtsBinding = new MTSBinding(runner);

        // instantiate the classloader in charge of groovy scripts
        CompilerConfiguration compilerConfig = new CompilerConfiguration();
        compilerConfig.setScriptBaseClass("MTSScript");

        ClassLoader mtsClassLoader = getClass().getClassLoader();
        GroovyClassLoader groovyClassLoader = new GroovyClassLoader(mtsClassLoader, compilerConfig);

        // load, instantiate and execute each groovy file,
        if (groovyFiles != null) {
            StringTokenizer st = new StringTokenizer(groovyFiles, ";");
            while (st.hasMoreTokens()) {
                String scriptName = st.nextToken();
                File file = new File(URIRegistry.MTS_TEST_HOME.resolve(scriptName));
                if (file.exists() && file.getName().endsWith(".groovy")) {
                    Class groovyClass = groovyClassLoader.parseClass(file);
                    Object obj = groovyClass.newInstance();
                    if (obj instanceof Script) {
                        // add the MTS Binding and execute the run method
                        ((Script) obj).setBinding(mtsBinding);
                        ((Script) obj).invokeMethod("run", new Object[]{});
                        prepareScriptProperties(runner, scriptName, (Script) obj);
                    }
                } else {
                    if (runner instanceof ScenarioRunner) {
                        GlobalLogger.instance().getSessionLogger().error(runner, TextEvent.Topic.CORE,
                                "invalid groovy file " + scriptName);
                    } else {
                        GlobalLogger.instance().getApplicationLogger().error(TextEvent.Topic.CORE,
                                "invalid groovy file " + scriptName);
                    }
                }
            }
        }
        groovyClassLoader.close();

        // instantiate the groovy operation script
        Class scriptClass = groovyClassLoader.parseClass(scriptSource);
        Script script = (Script) scriptClass.newInstance();
        script.setBinding(mtsBinding);

        // inject each imported groovy class as a property of the groovy
        // operation script
        injectScriptProperties(script);

        // execute the groovy operation script
        Object result = script.run();

    } catch (AssertionError pae) {
        GlobalLogger.instance().getSessionLogger().error(runner, TextEvent.Topic.CORE, pae.getMessage(), scriptSource);
        throw new ExecutionException("Error in groovy test", pae);

    } catch (Exception e) {
        GlobalLogger.instance().getSessionLogger().error(runner, TextEvent.Topic.CORE, scriptSource,
                "Exception occured\n", e);
        throw new ExecutionException("Error executing groovy operation command", e);
    }

    return null;
}