@Before public void setUp() throws Exception { network = createNetwork(); ComputationManager computationManager = Mockito.mock(ComputationManager.class); LoadFlow loadFlow = Mockito.mock(LoadFlow.class); LoadFlowFactory loadFlowFactory = Mockito.mock(LoadFlowFactory.class); Mockito.when(loadFlowFactory.create(Mockito.any(Network.class), Mockito.any(ComputationManager.class), Mockito.anyInt())) .thenReturn(loadFlow); LoadFlowResult loadFlowResult = Mockito.mock(LoadFlowResult.class); Mockito.when(loadFlowResult.isOk()) .thenReturn(true); Mockito.when(loadFlow.getName()).thenReturn("load flow mock"); Mockito.when(loadFlow.run()) .thenReturn(loadFlowResult); LoadFlowActionSimulatorObserver observer = createObserver(); GroovyCodeSource src = new GroovyCodeSource(new InputStreamReader(getClass().getResourceAsStream(getDslFile())), "test", GroovyShell.DEFAULT_CODE_BASE); actionDb = new ActionDslLoader(src).load(network); engine = new LoadFlowActionSimulator(network, computationManager, new LoadFlowActionSimulatorConfig(LoadFlowFactory.class, 3, false), observer) { @Override protected LoadFlowFactory newLoadFlowFactory() { return loadFlowFactory; } }; }
@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()); }
/** * Standalone execution for Designer and 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); } }
@Override protected GroovyCodeSource prepareGroovyCodeSource(String dsl) { ScriptApproval.get() .configuring( dsl, GroovyLanguage.get(), ApprovalContext.create(). withCurrentUser() .withItem(source) ); try { ScriptApproval.get().using(dsl, GroovyLanguage.get()); } catch (RejectedAccessException e) { throw ScriptApproval.get().accessRejected(e, ApprovalContext.create().withItem(source)); } return super.prepareGroovyCodeSource(dsl); }
@Override public Object run(String dsl, Binding binding) { CompilerConfiguration compilerConfiguration = prepareCompilerConfiguration(); ClassLoader classLoader = prepareClassLoader(AbstractDSLLauncher.class.getClassLoader()); GroovyCodeSource groovyCodeSource = prepareGroovyCodeSource(dsl); // Groovy shell GroovyShell shell = new GroovyShell( classLoader, new Binding(), compilerConfiguration ); // Groovy script Script groovyScript = shell.parse(groovyCodeSource); // Binding groovyScript.setBinding(binding); // Runs the script return run(groovyScript); }
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; }
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); try { if (origEntry == dep || GroovyScriptEngine.this.isSourceNewer(dep)) { newDep.add(depName); } } catch (ResourceException re) { } } StringSetMap cache = localData.dependencyCache; cache.put(".", newDep); } }
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(new PrivilegedAction<Void>() { @Override public Void run() { parseAndExecute(new GroovyCodeSource(scriptStr, generateClassName(), effectiveCodeBase), missingPermission); return null; } }); }
/** * Parses a script * @param clazzName * @param sourceCode * @return */ public String parseScript(String clazzName, String sourceCode) { String compilationError = null; int lastIndexOf = clazzName.lastIndexOf("."); String codeBase = clazzName; if (lastIndexOf!=-1) { codeBase = clazzName.substring(0, lastIndexOf); } GroovyCodeSource groovyCodeSource = new GroovyCodeSource( sourceCode, clazzName, codeBase); try { Class<?> parsedClass = groovyClassLoader.parseClass(groovyCodeSource, false); availableClasses.put(clazzName, parsedClass); } catch (CompilationFailedException e) { compilationError = "Compilation for " + clazzName + " failed with " + e.getMessage(); LOGGER.warn(compilationError); } catch (Exception ex) { compilationError = "Parsing class " + clazzName + " failed with " + ex.getMessage(); LOGGER.warn(compilationError); } return compilationError; }
@SuppressWarnings("unchecked") protected Class<Script> compileScript(final String scriptBaseClass, String scriptSource, final String scriptName) { final String script = preProcessScript(scriptSource); GroovyCodeSource codeSource = AccessController.doPrivileged((PrivilegedAction<GroovyCodeSource>) () -> new GroovyCodeSource(script, scriptName, getScriptCodeBase())); String currentScriptBaseClass = compilerConfiguration.getScriptBaseClass(); try { if (scriptBaseClass != null) { compilerConfiguration.setScriptBaseClass(scriptBaseClass); } return groovyClassLoader.parseClass(codeSource, false); } finally { compilerConfiguration.setScriptBaseClass(currentScriptBaseClass); } }
@Override public void start() { try { String t_pathname = ContextUtils.getGroovyClasspath().getPath() + "/DailyWeekJob.groovy"; File file = new File(t_pathname); Class groovyClass = ContextUtils.getClassLoader().loadClass("DailyWeekJob", true, false, true); if (null == groovyClass) { groovyClass = ContextUtils.getGroovyScriptEngine().loadScriptByName("DailyWeekJob.groovy"); } if (null == groovyClass) { groovyClass = ContextUtils.getClassLoader().parseClass(new GroovyCodeSource(file)); } // GroovyObject object = (GroovyObject) groovyClass.newInstance(); object.invokeMethod("schedule", "daily.mail"); } catch (Exception e) { logger.error(e.getMessage(), e); } status = ModuleStatus.STARTED; }
@Override public List<Contingency> getContingencies(Network network) { try (Reader reader = Files.newBufferedReader(dslFile, StandardCharsets.UTF_8)) { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(reader, "script", GroovyShell.DEFAULT_CODE_BASE)) .load(network); return ImmutableList.copyOf(actionDb.getContingencies()); } catch (IOException e) { throw new UncheckedIOException(e); } }
@Test public void testGeneratorScalableStack() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/scalable.groovy"))).load(network); Action action = actionDb.getAction("actionScale"); // scale to 15000 assertEquals(607.0f, g1.getTargetP(), 0.0f); assertEquals(9999.99f, g1.getMaxP(), 0.0f); action.run(network, null); assertEquals(9999.99f, g1.getTargetP(), 0.0f); }
@Test public void testCompatible() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/scalable.groovy"))).load(network); Action action = actionDb.getAction("testCompatible"); // scale to 15000 assertEquals(607.0f, g1.getTargetP(), 0.0f); assertEquals(9999.99f, g1.getMaxP(), 0.0f); action.run(network, null); assertEquals(9999.99f, g1.getTargetP(), 0.0f); }
@Test public void testGeneratorScalableProportional() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/scalable.groovy"))).load(network); Action action = actionDb.getAction("testProportional"); // scale to 15000 assertEquals(607.0f, g1.getTargetP(), 0.0f); assertEquals(9999.99f, g1.getMaxP(), 0.0f); action.run(network, null); assertEquals(7500.0f, g1.getTargetP(), 0.0f); assertEquals(3000.0f, g2.getTargetP(), 0.0f); assertEquals(4500.0f, g3.getTargetP(), 0.0f); }
@Test public void testDslExtension() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions2.groovy"))).load(network); Action another = actionDb.getAction("anotherAction"); exception.expect(RuntimeException.class); exception.expectMessage("Switch 'switchId' not found"); another.run(network, null); }
@Test public void testFixTapDslExtension() { ActionDb actionDb = new ActionDslLoader(new GroovyCodeSource(getClass().getResource("/actions2.groovy"))).load(network); Action fixedTapAction = actionDb.getAction("fixedTap"); assertNotNull(fixedTapAction); addPhaseShifter(); PhaseTapChanger phaseTapChanger = network.getTwoWindingsTransformer("NGEN_NHV1").getPhaseTapChanger(); assertEquals(0, phaseTapChanger.getTapPosition()); assertTrue(phaseTapChanger.isRegulating()); assertEquals(PhaseTapChanger.RegulationMode.CURRENT_LIMITER, phaseTapChanger.getRegulationMode()); fixedTapAction.run(network, null); assertEquals(1, phaseTapChanger.getTapPosition()); assertEquals(PhaseTapChanger.RegulationMode.FIXED_TAP, phaseTapChanger.getRegulationMode()); assertFalse(phaseTapChanger.isRegulating()); }
@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); }
@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); }
@Override public void validate(IValidatable<String> validatable) { String script = validatable.getValue(); com.angkorteam.mbaas.server.bean.GroovyClassLoader classLoader = Spring.getBean(com.angkorteam.mbaas.server.bean.GroovyClassLoader.class); String sourceId = System.currentTimeMillis() + ""; String className = null; if (!Strings.isNullOrEmpty(script)) { GroovyCodeSource source = new GroovyCodeSource(script, sourceId, "/groovy/script"); source.setCachable(false); Class<?> groovyClass = null; try { groovyClass = classLoader.parseClass(source, false); className = groovyClass.getName(); } catch (CompilationFailedException e) { validatable.error(new ValidationError(this, "error").setVariable("reason", e.getMessage())); return; } if (!groovyClass.getName().startsWith("com.angkorteam.mbaas.server.groovy.")) { validatable.error(new ValidationError(this, "invalid").setVariable("object", groovyClass.getName())); return; } int count = 0; DSLContext context = Spring.getBean(DSLContext.class); GroovyTable table = Tables.GROOVY.as("table"); if (Strings.isNullOrEmpty(this.documentId)) { count = context.selectCount().from(table).where(table.JAVA_CLASS.eq(groovyClass.getName())).fetchOneInto(int.class); } else { count = context.selectCount().from(table).where(table.JAVA_CLASS.eq(groovyClass.getName())).and(table.GROOVY_ID.notEqual(this.documentId)).fetchOneInto(int.class); } if (count > 0) { validatable.error(new ValidationError(this, "duplicated").setVariable("object", groovyClass.getName())); } } }
/** * 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") ); } }
private RoomScript getScript(final String roomName) { final String codeBase = String.format("%s.script.groovy", roomName); final String scriptName = String.format("%s/script.groovy", roomName); try (final InputStreamReader scriptReader = new InputStreamReader( Resources.getInputStream(ROOMS_ASSETS__PATH, scriptName).openInputStream())) { final GroovyCodeSource groovyCodeSource = new GroovyCodeSource(scriptReader, codeBase, codeBase); final Class scriptClass = SCRIPT_LOADER.parseClass(groovyCodeSource); final Object roomScript = scriptClass.newInstance(); return RoomScriptProxy.build(roomScript, roomName); } catch (final Exception exception) { throw new RuntimeException(String.format("Unable to load room's [%s] script.", roomName), exception); } }
@Override public Class<? extends DelegatingScript> run() { try { 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); } }
public Class parseClass(final GroovyCodeSource codeSource, Map<String, String> hints) throws CompilationFailedException { modelTypes.set(hints); try { return super.parseClass(codeSource); } finally { modelTypes.set(null); } }
/** * 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); }
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)); }
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()); } }
protected Class parseClass(final GroovyCodeSource gcs) { Class clazz = null; try { clazz = loader.parseClass(gcs); } catch (Exception e) { fail(e.toString()); } return clazz; }
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); } }
/** * Creates an object instance from the Groovy resource * * @param resource the Groovy resource to parse * @return An Object instance */ public Object newInstance(String resource) { try { String name = resource.startsWith("/") ? resource : "/" + resource; File file = new File(this.getClass().getResource(name).toURI()); return newInstance(classLoader.parseClass(new GroovyCodeSource(file), true)); } catch (Exception e) { throw new GroovyClassInstantiationFailed(classLoader, resource, e); } }
@SuppressWarnings("unchecked") public static final <T> T parseClass(String source, Class<T> returnType, boolean singleton, GroovyClassLoader gcl) throws Exception { if (source == null || returnType == null) return null; String hashCode = String.valueOf(source.hashCode()); String cacheKey = new StringBuilder(CACHE_KEY_PREFIX_GROOVY_TYPE).append(Str.AT).append(hashCode).toString(); Object objOrClass = cache.get(cacheKey); if (objOrClass == null) { GroovyCodeSource gcs = new GroovyCodeSource(source, hashCode, CODE_BASE); Class<T> clazz = null; // Use custom GroovyClassLoader if provided. if (gcl != null) { clazz = gcl.parseClass(gcs); } else { clazz = GCL.parseClass(gcs); } T obj = clazz.newInstance(); // If we are in singleton mode, we cache the object. if (singleton) { T cachedObject = (T) cache.putIfAbsent(cacheKey, obj); if (cachedObject != null) obj = cachedObject; } // Otherwise we just cache the parsed class. else { Class<T> cachedClass = (Class<T>) cache.putIfAbsent(cacheKey, clazz); if (cachedClass != null) clazz = cachedClass; } return obj; } else { if (singleton) { return (T) objOrClass; } else { return ((Class<T>) objOrClass).newInstance(); } } }
private static Script createScript(final String scriptId, String scriptText, String targetDirectory, String... imports) { if (scriptText == null || scriptText.isEmpty()) { return null; } if (targetDirectory == null) { Script cached = cache.get(scriptText); if (cached != null) { return cached; } } StringBuilder scriptStringBuffer = StringUtil.getFSB(); for (String oneimport : imports) { scriptStringBuffer.append("import "); scriptStringBuffer.append(oneimport); scriptStringBuffer.append(";\n"); } scriptStringBuffer.append("\n"); scriptStringBuffer.append(scriptText); final String finalScriptText = scriptStringBuffer.toString(); StringUtil.freeFSB(scriptStringBuffer); GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() { public GroovyCodeSource run() { return new GroovyCodeSource(finalScriptText, scriptId+".groovy", GroovyShell.DEFAULT_CODE_BASE); } }); GroovyClassLoader loader = null; try { loader = getLoader(targetDirectory); Class<?> scriptClass = loader.parseClass(gcs, false); Script script = InvokerHelper.createScript(scriptClass, new Binding()); cache.put(scriptText, script); return script; } finally { if (loader != null) { StreamUtils.closeQuietly(loader); } } }
protected GroovyCodeSource prepareGroovyCodeSource(String dsl) { return new GroovyCodeSource(dsl, "script", DEFAULT_CODE_BASE); }
@SuppressWarnings("unchecked") public MarkupTemplateMaker(final Reader reader, String sourceName, Map<String, String> modelTypes) { String name = sourceName != null ? sourceName : "GeneratedMarkupTemplate" + counter.getAndIncrement(); templateClass = groovyClassLoader.parseClass(new GroovyCodeSource(reader, name, "x"), modelTypes); this.modeltypes = modelTypes; }
protected GroovyObject compile(String fileName) throws Exception { Class groovyClass = loader.parseClass(new GroovyCodeSource(new File(fileName))); GroovyObject object = (GroovyObject) groovyClass.newInstance(); assertTrue(object != null); return object; }
@Override public Class parseClass(GroovyCodeSource codeSource, boolean shouldCacheSource) throws CompilationFailedException { synchronized (sourceCache) { return doParseClass(codeSource); } }
private GroovyCodeSource createCodeSource(String commandText) { return new GroovyCodeSource(commandText, "UserScript", "/sandboxScript"); }
/** * This creates and starts the socket server on a new Thread. There is no need to call run or spawn * a new thread yourself. * @param groovy * The GroovyShell object that evaluates the incoming text. If you need additional classes in the * classloader then configure that through this object. * @param source * GroovyCodeSource for the Groovy script * @param autoOutput * whether output should be automatically echoed back to the client * @param port * the port to listen on * @since 2.3.0 */ public GroovySocketServer(GroovyShell groovy, GroovyCodeSource source, boolean autoOutput, int port) { this.groovy = groovy; this.source = source; this.autoOutput = autoOutput; try { url = new URL("http", InetAddress.getLocalHost().getHostAddress(), port, "/"); System.out.println("groovy is listening on port " + port); } catch (IOException e) { e.printStackTrace(); } new Thread(this).start(); }
public static void execute() throws Exception { String t_pathname = ContextUtils.getGroovyClasspath().getPath() + "/DailyWeekJob.groovy"; File file = new File(t_pathname); Class groovyClass = ContextUtils.getClassLoader().parseClass(new GroovyCodeSource(file)); GroovyObject object = (GroovyObject) groovyClass.newInstance(); object.invokeMethod("schedule", "daily.mail"); }