groovy.lang.GroovyCodeSource Java Examples
The following examples show how to use
groovy.lang.GroovyCodeSource.
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: GroovyScriptEngine.java From chaosblade-exec-jvm with Apache License 2.0 | 6 votes |
@Override public Object compile(com.alibaba.chaosblade.exec.plugin.jvm.script.base.Script script, ClassLoader classLoader, Map<String, String> configs) { String className = "groovy_script_" + script.getId(); GroovyCodeSource codeSource = new GroovyCodeSource(script.getContent(), className, UNTRUSTED_CODEBASE); codeSource.setCachable(true); CompilerConfiguration compilerConfiguration = new CompilerConfiguration() .addCompilationCustomizers( new ImportCustomizer().addStaticStars("java.lang.Math")) .addCompilationCustomizers(new GroovyBigDecimalTransformer(CompilePhase.CONVERSION)); compilerConfiguration.getOptimizationOptions().put(GROOVY_INDY_SETTING_NAME, true); GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader, compilerConfiguration); try { return groovyClassLoader.parseClass(script.getContent()); } catch (Exception ex) { throw convertToScriptException("Compile script failed:" + className, script.getId(), ex); } }
Example #2
Source File: ActionDslLoaderTest.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@Test public void testDeltaTapDslExtension() { for (DeltaTapData data : provideParams()) { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions2.groovy"))).load(network); Action deltaTapAction = actionDb.getAction(data.getTestName()); assertNotNull(deltaTapAction); assertEquals(data.getDeltaTap(), ((PhaseShifterTapTask) deltaTapAction.getTasks().get(0)).getTapDelta()); addPhaseShifter(data.getInitTapPosition()); PhaseTapChanger phaseTapChanger = network.getTwoWindingsTransformer("NGEN_NHV1").getPhaseTapChanger(); assertEquals(1, phaseTapChanger.getTapPosition()); assertTrue(phaseTapChanger.isRegulating()); assertEquals(PhaseTapChanger.RegulationMode.CURRENT_LIMITER, phaseTapChanger.getRegulationMode()); deltaTapAction.run(network, null); assertEquals(data.getExpectedTapPosition(), phaseTapChanger.getTapPosition()); assertEquals(PhaseTapChanger.RegulationMode.FIXED_TAP, phaseTapChanger.getRegulationMode()); assertFalse(phaseTapChanger.isRegulating()); } }
Example #3
Source File: ActionDslLoaderTest.java From powsybl-core with Mozilla Public License 2.0 | 6 votes |
@Test public void test() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions.groovy"))).load(network); assertEquals(2, actionDb.getContingencies().size()); Contingency contingency = actionDb.getContingency("contingency1"); ContingencyElement element = contingency.getElements().iterator().next(); assertEquals("NHV1_NHV2_1", element.getId()); contingency = actionDb.getContingency("contingency2"); element = contingency.getElements().iterator().next(); assertEquals("GEN", element.getId()); assertEquals(1, actionDb.getRules().size()); Rule rule = actionDb.getRules().iterator().next(); assertEquals("rule", rule.getId()); assertEquals("rule description", rule.getDescription()); assertTrue(rule.getActions().contains("action")); assertEquals(2, rule.getLife()); Action action = actionDb.getAction("action"); assertEquals("action", action.getId()); assertEquals("action description", action.getDescription()); assertEquals(0, action.getTasks().size()); }
Example #4
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 #5
Source File: ForbiddenApisPlugin.java From forbidden-apis with Apache License 2.0 | 6 votes |
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 #6
Source File: AstStringCompiler.java From groovy with Apache License 2.0 | 6 votes |
/** * Performs the String source to {@link java.util.List} of {@link ASTNode}. * * @param script * a Groovy script in String form * @param compilePhase * the int based CompilePhase to compile it to. * @param statementsOnly * @return {@link java.util.List} of {@link ASTNode} */ public List<ASTNode> compile(String script, CompilePhase compilePhase, boolean statementsOnly) { final String scriptClassName = makeScriptClassName(); GroovyCodeSource codeSource = new GroovyCodeSource(script, scriptClassName + ".groovy", "/groovy/script"); CompilationUnit cu = new CompilationUnit(CompilerConfiguration.DEFAULT, codeSource.getCodeSource(), AccessController.doPrivileged((PrivilegedAction<GroovyClassLoader>) GroovyClassLoader::new)); cu.addSource(codeSource.getName(), script); cu.compile(compilePhase.getPhaseNumber()); // collect all the ASTNodes into the result, possibly ignoring the script body if desired List<ASTNode> result = cu.getAST().getModules().stream().reduce(new LinkedList<>(), (acc, node) -> { BlockStatement statementBlock = node.getStatementBlock(); if (null != statementBlock) { acc.add(statementBlock); } acc.addAll( node.getClasses().stream() .filter(c -> !(statementsOnly && scriptClassName.equals(c.getName()))) .collect(Collectors.toList()) ); return acc; }, (o1, o2) -> o1); return result; }
Example #7
Source File: GroovyScriptEngine.java From groovy with Apache License 2.0 | 6 votes |
private Class<?> doParseClass(GroovyCodeSource codeSource) { // local is kept as hard reference to avoid garbage collection ThreadLocal<LocalData> localTh = getLocalData(); LocalData localData = new LocalData(); localTh.set(localData); StringSetMap cache = localData.dependencyCache; Class<?> answer = null; try { updateLocalDependencyCache(codeSource, localData); answer = super.parseClass(codeSource, false); updateScriptCache(localData); } finally { cache.clear(); localTh.remove(); } return answer; }
Example #8
Source File: GroovyScriptEngine.java From groovy with Apache License 2.0 | 6 votes |
private void updateLocalDependencyCache(GroovyCodeSource codeSource, LocalData localData) { // we put the old dependencies into local cache so createCompilationUnit // can pick it up. We put that entry under the name "." ScriptCacheEntry origEntry = scriptCache.get(codeSource.getName()); Set<String> origDep = null; if (origEntry != null) origDep = origEntry.dependencies; if (origDep != null) { Set<String> newDep = new HashSet<String>(origDep.size()); for (String depName : origDep) { ScriptCacheEntry dep = scriptCache.get(depName); if (origEntry == dep || GroovyScriptEngine.this.isSourceNewer(dep)) { newDep.add(depName); } } StringSetMap cache = localData.dependencyCache; cache.put(".", newDep); } }
Example #9
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 #10
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 #11
Source File: JsonGeneratorTest.java From everrest with Eclipse Public License 2.0 | 5 votes |
private Class<?> parseGroovyClass(String fileName) throws IOException { try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); Reader reader = new InputStreamReader(stream)) { String script = CharStreams.toString(reader); return groovyClassLoader.parseClass(new GroovyCodeSource(script, fileName, "groovy/script")); } }
Example #12
Source File: GeneratorModificationActionTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Test public void testTargetVAndQWithVoltageRegulatorOff() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); Action action = actionDb.getAction("targetV and targetQ with voltageRegulator OFF"); action.run(network, null); assertEquals(20., g.getMinP(), 0.1); assertEquals(60., g.getMaxP(), 0.1); assertEquals(50., g.getTargetP(), 0.1); assertEquals(10, g.getTargetV(), 0.1); assertEquals(25., g.getTargetQ(), 0.1); assertFalse(g.isVoltageRegulatorOn()); }
Example #13
Source File: GeneratorModificationActionTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Test public void testExceptionOnWrongGeneratorId() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/generator-modification-action.groovy"))).load(network); Action action = actionDb.getAction("unknown generator"); thrown.expect(PowsyblException.class); thrown.expectMessage("Generator 'UNKNOWN' not found"); action.run(network, null); }
Example #14
Source File: GroovyScriptAction.java From DDMQ with Apache License 2.0 | 5 votes |
@Override public Class load(String key) throws Exception { try (GroovyClassLoader groovyLoader = new GroovyClassLoader()) { GroovyCodeSource gcs = AccessController.doPrivileged((PrivilegedAction<GroovyCodeSource>) () -> new GroovyCodeSource(key, "Script" + al.getAndIncrement() + ".groovy", "/groovy/shell")); Class clazz = groovyLoader.parseClass(gcs, false); return clazz; } catch (Throwable e) { LogUtils.logErrorInfo("GroovyScript_error", "[GroovyErr]", e); return null; } }
Example #15
Source File: ActionDslLoaderTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Test public void testInvalidTransformerId() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions2.groovy"))).load(network); Action deltaTapAction = actionDb.getAction("InvalidTransformerId"); assertNotNull(deltaTapAction); assertEquals(-10, ((PhaseShifterTapTask) deltaTapAction.getTasks().get(0)).getTapDelta()); exception.expect(PowsyblException.class); exception.expectMessage("Transformer 'NHV1_NHV2_1' not found"); deltaTapAction.run(network, null); }
Example #16
Source File: ObjectBuilderTest.java From everrest with Eclipse Public License 2.0 | 5 votes |
private Class<?> parseGroovyClass(String fileName) throws IOException { try (InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); Reader reader = new InputStreamReader(stream)) { String script = CharStreams.toString(reader); return groovyClassLoader.parseClass(new GroovyCodeSource(script, fileName, "groovy/script")); } }
Example #17
Source File: ActionDslLoaderTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Test public void testTransformerWithoutPhaseShifter() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions2.groovy"))).load(network); Action deltaTapAction = actionDb.getAction("TransformerWithoutPhaseShifter"); assertNotNull(deltaTapAction); assertEquals(-10, ((PhaseShifterTapTask) deltaTapAction.getTasks().get(0)).getTapDelta()); exception.expect(PowsyblException.class); exception.expectMessage("Transformer 'NGEN_NHV1' is not a phase shifter"); deltaTapAction.run(network, null); }
Example #18
Source File: ActionDslLoaderTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Test public void testUnvalidate() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions2.groovy"))).load(network); Action someAction = actionDb.getAction("someAction"); exception.expect(ActionDslException.class); exception.expectMessage("Dsl extension task(closeSwitch) is forbidden in task script"); someAction.run(network, null); }
Example #19
Source File: ActionDslLoaderTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Test public void testUnKnownMethodInScript() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions2.groovy"))).load(network); Action someAction = actionDb.getAction("missingMethod"); exception.expect(MissingMethodException.class); someAction.run(network, null); }
Example #20
Source File: ActionDslLoaderTest.java From powsybl-core with Mozilla Public License 2.0 | 5 votes |
@Test public void testHandler() { ActionDslHandler handler = mock(ActionDslHandler.class); new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions.groovy"))).load(network, handler, null); verify(handler, times(1)).addAction(argThat(matches(a -> a.getId().equals("action")))); verify(handler, times(2)).addContingency(any()); verify(handler, times(1)).addContingency(argThat(matches(c -> c.getId().equals("contingency1")))); verify(handler, times(1)).addContingency(argThat(matches(c -> c.getId().equals("contingency2")))); verify(handler, times(1)).addRule(argThat(matches(c -> c.getId().equals("rule")))); }
Example #21
Source File: PipelineDSLGlobal.java From simple-build-for-pipeline-plugin with MIT License | 5 votes |
@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 #22
Source File: SecurityTestSupport.java From groovy with Apache License 2.0 | 5 votes |
protected Class parseClass(final GroovyCodeSource gcs) { Class clazz = null; try { clazz = loader.parseClass(gcs); } catch (Exception e) { fail(e.toString()); } return clazz; }
Example #23
Source File: ProgramTest.java From eo with MIT License | 5 votes |
/** * Creates Java code that really works. * @throws Exception If some problem inside */ @Test public void compilesExecutableJava() throws Exception { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final Program program = new Program( new InputOf( new JoinedText( "\n", "object car as Serializable:", " Integer @vin", " String name():", " \"Mercedes-Benz\"" ).asString() ), s -> new OutputTo(baos) ); program.compile(); try (final GroovyClassLoader loader = new GroovyClassLoader()) { final Class<?> type = loader.parseClass( new GroovyCodeSource( new TextOf(baos.toByteArray()).asString(), "car", GroovyShell.DEFAULT_CODE_BASE ) ); MatcherAssert.assertThat( type.getMethod("name").invoke( type.getConstructor(Integer.class).newInstance(0) ), Matchers.equalTo("Mercedes-Benz") ); } }
Example #24
Source File: MarkupTemplateEngine.java From groovy with Apache License 2.0 | 5 votes |
public Class parseClass(final GroovyCodeSource codeSource, Map<String, String> hints) throws CompilationFailedException { modelTypes.set(hints); try { return super.parseClass(codeSource); } finally { modelTypes.set(null); } }
Example #25
Source File: GroovyMain.java From groovy with Apache License 2.0 | 5 votes |
/** * Get a new GroovyCodeSource for a script which may be given as a location * (isScript is true) or as text (isScript is false). * * @param isScriptFile indicates whether the script parameter is a location or content * @param script the location or context of the script * @return a new GroovyCodeSource for the given script * @throws IOException * @throws URISyntaxException * @since 2.3.0 */ protected GroovyCodeSource getScriptSource(boolean isScriptFile, String script) throws IOException, URISyntaxException { //check the script is currently valid before starting a server against the script if (isScriptFile) { // search for the file and if it exists don't try to use URIs ... File scriptFile = huntForTheScriptFile(script); if (!scriptFile.exists() && URI_PATTERN.matcher(script).matches()) { return new GroovyCodeSource(new URI(script)); } return new GroovyCodeSource(scriptFile); } return new GroovyCodeSource(script, "script_from_command_line", GroovyShell.DEFAULT_CODE_BASE); }
Example #26
Source File: SecurityTestSupport.java From groovy with Apache License 2.0 | 5 votes |
protected void assertExecute(final String scriptStr, String codeBase, final Permission missingPermission) { if (!isSecurityAvailable()) { return; } final String effectiveCodeBase = (codeBase != null) ? codeBase : "/groovy/security/test"; // Use our privileged access in order to prevent checks lower in the call stack. Otherwise we would have // to grant access to IDE unit test runners and unit test libs. We only care about testing the call stack // higher upstream from this point of execution. AccessController.doPrivileged((PrivilegedAction<Void>) () -> { parseAndExecute(new GroovyCodeSource(scriptStr, generateClassName(), effectiveCodeBase), missingPermission); return null; }); }
Example #27
Source File: SecurityTestSupport.java From groovy with Apache License 2.0 | 5 votes |
private void parseAndExecute(final GroovyCodeSource gcs, Permission missingPermission) { Class clazz = null; try { clazz = loader.parseClass(gcs); } catch (Exception e) { fail(e.toString()); } if (TestCase.class.isAssignableFrom(clazz)) { executeTest(clazz, missingPermission); } else { executeScript(clazz, missingPermission); } }
Example #28
Source File: TestSupport.java From groovy with Apache License 2.0 | 5 votes |
protected void assertScript(final String text, final String scriptName) throws Exception { log.info("About to execute script"); log.info(text); GroovyCodeSource gcs = AccessController.doPrivileged( (PrivilegedAction<GroovyCodeSource>) () -> new GroovyCodeSource(text, scriptName, "/groovy/testSupport") ); Class groovyClass = loader.parseClass(gcs); Script script = InvokerHelper.createScript(groovyClass, new Binding()); script.run(); }
Example #29
Source File: InvokerHelperTest.java From groovy with Apache License 2.0 | 5 votes |
public void testCreateScriptWithScriptClass() { GroovyClassLoader classLoader = new GroovyClassLoader(); String controlProperty = "text"; String controlValue = "I am a script"; String code = controlProperty + " = '" + controlValue + "'"; GroovyCodeSource codeSource = new GroovyCodeSource(code, "testscript", "/groovy/shell"); Class scriptClass = classLoader.parseClass(codeSource, false); Script script = InvokerHelper.createScript(scriptClass, new Binding(bindingVariables)); assertEquals(bindingVariables, script.getBinding().getVariables()); script.run(); assertEquals(controlValue, script.getProperty(controlProperty)); }
Example #30
Source File: SecurityTest.java From groovy with Apache License 2.0 | 5 votes |
public void testCodeSource() throws IOException, CompilationFailedException { URL script = loader.getResource("groovy/ArrayTest.groovy"); try { new GroovyCodeSource(script); } catch (RuntimeException re) { assertEquals("Could not construct a GroovyCodeSource from a null URL", re.getMessage()); } }