Java Code Examples for groovy.lang.GroovyClassLoader#parseClass()

The following examples show how to use groovy.lang.GroovyClassLoader#parseClass() . 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: GroovyClassLoadingTests.java    From spring4-understanding with Apache License 2.0 8 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void classLoading() throws Exception {
	StaticApplicationContext context = new StaticApplicationContext();

	GroovyClassLoader gcl = new GroovyClassLoader();
	Class<?> class1 = gcl.parseClass("class TestBean { def myMethod() { \"foo\" } }");
	Class<?> class2 = gcl.parseClass("class TestBean { def myMethod() { \"bar\" } }");

	context.registerBeanDefinition("testBean", new RootBeanDefinition(class1));
	Object testBean1 = context.getBean("testBean");
	Method method1 = class1.getDeclaredMethod("myMethod", new Class<?>[0]);
	Object result1 = ReflectionUtils.invokeMethod(method1, testBean1);
	assertEquals("foo", result1);

	context.removeBeanDefinition("testBean");
	context.registerBeanDefinition("testBean", new RootBeanDefinition(class2));
	Object testBean2 = context.getBean("testBean");
	Method method2 = class2.getDeclaredMethod("myMethod", new Class<?>[0]);
	Object result2 = ReflectionUtils.invokeMethod(method2, testBean2);
	assertEquals("bar", result2);
}
 
Example 2
Source File: GroovyEngine.java    From light-task-scheduler with Apache License 2.0 8 votes vote down vote up
/**
 * 将groovy源码解析为Class
 */
public static Class parseClass(String groovySource) throws GroovyException {

    GroovyClassLoader loader = new GroovyClassLoader();

    ClassLoader contextClassLoader = null;

    try {
        contextClassLoader = Thread.currentThread().getContextClassLoader();
        if (contextClassLoader != null) {
            Thread.currentThread().setContextClassLoader(null);
        }
        return loader.parseClass(groovySource);
    } catch (Throwable t) {
        throw new GroovyException("parseClass error:", t);
    } finally {
        if (contextClassLoader != null) {
            Thread.currentThread().setContextClassLoader(contextClassLoader);
        }
    }
}
 
Example 3
Source File: GroovyScriptEngine.java    From chaosblade-exec-jvm with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: GroovyClassLoadingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void classLoading() throws Exception {
	StaticApplicationContext context = new StaticApplicationContext();

	GroovyClassLoader gcl = new GroovyClassLoader();
	Class<?> class1 = gcl.parseClass("class TestBean { def myMethod() { \"foo\" } }");
	Class<?> class2 = gcl.parseClass("class TestBean { def myMethod() { \"bar\" } }");

	context.registerBeanDefinition("testBean", new RootBeanDefinition(class1));
	Object testBean1 = context.getBean("testBean");
	Method method1 = class1.getDeclaredMethod("myMethod", new Class<?>[0]);
	Object result1 = ReflectionUtils.invokeMethod(method1, testBean1);
	assertEquals("foo", result1);

	context.removeBeanDefinition("testBean");
	context.registerBeanDefinition("testBean", new RootBeanDefinition(class2));
	Object testBean2 = context.getBean("testBean");
	Method method2 = class2.getDeclaredMethod("myMethod", new Class<?>[0]);
	Object result2 = ReflectionUtils.invokeMethod(method2, testBean2);
	assertEquals("bar", result2);
}
 
Example 5
Source File: GroovyClassLoadingTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("resource")
public void classLoading() throws Exception {
	StaticApplicationContext context = new StaticApplicationContext();

	GroovyClassLoader gcl = new GroovyClassLoader();
	Class<?> class1 = gcl.parseClass("class TestBean { def myMethod() { \"foo\" } }");
	Class<?> class2 = gcl.parseClass("class TestBean { def myMethod() { \"bar\" } }");

	context.registerBeanDefinition("testBean", new RootBeanDefinition(class1));
	Object testBean1 = context.getBean("testBean");
	Method method1 = class1.getDeclaredMethod("myMethod", new Class<?>[0]);
	Object result1 = ReflectionUtils.invokeMethod(method1, testBean1);
	assertEquals("foo", result1);

	context.removeBeanDefinition("testBean");
	context.registerBeanDefinition("testBean", new RootBeanDefinition(class2));
	Object testBean2 = context.getBean("testBean");
	Method method2 = class2.getDeclaredMethod("myMethod", new Class<?>[0]);
	Object result2 = ReflectionUtils.invokeMethod(method2, testBean2);
	assertEquals("bar", result2);
}
 
Example 6
Source File: InvokerHelperTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
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 7
Source File: GroovyMacroCompiler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Macro compileMacro(String macroSource) {
  Macro macro = null;
  try {
    GroovyClassLoader gcl = new GroovyClassLoader();
    InputStream is = new ByteArrayInputStream(
        macroSource.getBytes());
    Class clazz = gcl.parseClass(is, "Macro.groovy");
    Object aScript = clazz.newInstance();
    macro = (Macro) aScript;
  } catch (Exception e) {
    log.error("Cannot compile groovy macro.");
  }
  return macro;
}
 
Example 8
Source File: GroovyMacroCompiler.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public Macro compileMacro(String macroSource) {
  Macro macro = null;
  try {
    GroovyClassLoader gcl = new GroovyClassLoader();
    InputStream is = new ByteArrayInputStream(
        macroSource.getBytes());
    Class clazz = gcl.parseClass(is, "Macro.groovy");
    Object aScript = clazz.newInstance();
    macro = (Macro) aScript;
  } catch (Exception e) {
    log.error("Cannot compile groovy macro.");
  }
  return macro;
}
 
Example 9
Source File: GeoscriptConsole.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
public GeoscriptConsole() throws Exception {
    InputStream groovyClassIS = GeoscriptConsole.class.getResourceAsStream("Console.groovy");

    String classString = FileUtilities.readInputStreamToString(groovyClassIS);

    GroovyClassLoader gcl = new GroovyClassLoader();
    Class< ? > clazz = gcl.parseClass(classString);
    gcl.close();
    Object obj = clazz.getDeclaredConstructor().newInstance();
    Method method = obj.getClass().getMethod("run");
    method.invoke(obj);
}
 
Example 10
Source File: ClosureFactory.java    From atlas with Apache License 2.0 5 votes vote down vote up
public static Closure<?> buildClosure(String... strings) throws IOException {

        Closure<?> closure = null;

        // Create a method returning a closure
        StringBuilder sb = new StringBuilder("def closure() { { script -> ");
        sb.append(StringUtils.join(strings, "\n"));
        sb.append(" } }");

        // Create an anonymous class for the method
        GroovyClassLoader loader = new GroovyClassLoader();
        Class<?> groovyClass = loader.parseClass(sb.toString());

        try {
            // Create an instance of the class
            GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();

            // Invoke the object's method and thus obtain the closure
            closure = (Closure<?>) groovyObject.invokeMethod("closure", null);
        } catch (Throwable e) {
            throw new RuntimeException(e);
        } finally {
            loader.close();
        }

        return closure;
    }
 
Example 11
Source File: GroovyRule.java    From tddl with Apache License 2.0 5 votes vote down vote up
private void initGroovy() {
    if (expression == null) {
        throw new IllegalArgumentException("未指定 expression");
    }
    GroovyClassLoader loader = new GroovyClassLoader(GroovyRule.class.getClassLoader());
    String groovyRule = getGroovyRule(expression, extraPackagesStr);
    Class<?> c_groovy;
    try {
        c_groovy = loader.parseClass(groovyRule);
    } catch (CompilationFailedException e) {
        throw new IllegalArgumentException(groovyRule, e);
    }

    try {
        // 新建类实例
        Object ruleObj = c_groovy.newInstance();
        if (ruleObj instanceof ShardingFunction) {
            shardingFunction = (ShardingFunction) ruleObj;
        } else {
            throw new IllegalArgumentException("should not be here");
        }
        // 获取方法

    } catch (Throwable t) {
        throw new IllegalArgumentException("实例化规则对象失败", t);
    }
}
 
Example 12
Source File: GroovyRule.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
private void initGroovy() {
    if (expression == null) {
        throw new IllegalArgumentException("未指定 expression");
    }
    GroovyClassLoader loader = new GroovyClassLoader(GroovyRule.class.getClassLoader());
    String groovyRule = getGroovyRule(expression, extraPackagesStr);
    Class<?> c_groovy;
    try {
        c_groovy = loader.parseClass(groovyRule);
    } catch (CompilationFailedException e) {
        throw new IllegalArgumentException(groovyRule, e);
    }

    try {
        // 新建类实例
        Object ruleObj = c_groovy.newInstance();
        if (ruleObj instanceof ShardingFunction) {
            shardingFunction = (ShardingFunction) ruleObj;
        } else {
            throw new IllegalArgumentException("should not be here");
        }
        // 获取方法

    } catch (Throwable t) {
        throw new IllegalArgumentException("实例化规则对象失败", t);
    }
}
 
Example 13
Source File: GroovyScriptEngine.java    From james with Apache License 2.0 4 votes vote down vote up
private GroovyShell createGroovyShell(ClassLoader classLoader, String baseClassScript) {
    GroovyClassLoader groovyClassLoader = new GroovyClassLoader(classLoader);
    Class baseClass = groovyClassLoader.parseClass(baseClassScript);
    return createGroovyShell(groovyClassLoader, baseClass);
}
 
Example 14
Source File: FilterVerifier.java    From zuul with Apache License 2.0 4 votes vote down vote up
/**
 * compiles the Groovy source code
 *
 */
public Class<?> compileGroovy(String sFilterCode)
        throws CompilationFailedException {
    GroovyClassLoader loader = new GroovyClassLoader();
    return loader.parseClass(sFilterCode);
}
 
Example 15
Source File: GroovyUtil.java    From scipio-erp with Apache License 2.0 4 votes vote down vote up
public static Class<?> parseClass(String text, GroovyClassLoader groovyClassLoader) throws IOException { // SCIPIO: added 2017-01-27
    if (!baseScriptInitialized) { initBaseScript(); } // SCIPIO
    return groovyClassLoader.parseClass(text);
}
 
Example 16
Source File: GroovyCompiler.java    From zuul with Apache License 2.0 4 votes vote down vote up
/**
 * Compiles groovy class from a file
 *
 */
public Class<?> compile(File file) throws IOException {
    GroovyClassLoader loader = getGroovyClassLoader();
    Class<?> groovyClass = loader.parseClass(file);
    return groovyClass;
}
 
Example 17
Source File: GroovyCompiler.java    From zuul-netty with Apache License 2.0 3 votes vote down vote up
/**
 * Compiles Groovy code and returns the Class of the compiles code.
 *
 * @param sCode
 * @param sName
 * @return
 */
public Class compile(String sCode, String sName) {
    GroovyClassLoader loader = getGroovyClassLoader();
    LOG.warn("Compiling filter: " + sName);
    Class groovyClass = loader.parseClass(sCode, sName);
    return groovyClass;
}
 
Example 18
Source File: GroovyCompiler.java    From s2g-zuul with MIT License 2 votes vote down vote up
/**
 * Compiles groovy class from a file
 *
 * @param file
 * @return
 * @throws java.io.IOException
 */
public Class compile(File file) throws IOException {
    GroovyClassLoader loader = getGroovyClassLoader();
    Class groovyClass = loader.parseClass(file);
    return groovyClass;
}
 
Example 19
Source File: GroovyCompiler.java    From zuul-netty with Apache License 2.0 2 votes vote down vote up
/**
 * Compiles groovy class from a file
 *
 * @param file
 * @return
 * @throws java.io.IOException
 */
public Class compile(File file) throws IOException {
    GroovyClassLoader loader = getGroovyClassLoader();
    Class groovyClass = loader.parseClass(file);
    return groovyClass;
}
 
Example 20
Source File: GroovyCompiler.java    From alchemy with Apache License 2.0 2 votes vote down vote up
/**
 * Compiles Groovy code and returns the Class of the compiles code.
 *
 * @param sCode
 * @param sName
 * @return
 */
public static Class compile(String sCode, String sName) {
    GroovyClassLoader loader = getGroovyClassLoader();
    Class groovyClass = loader.parseClass(sCode, sName);
    return groovyClass;
}