groovy.lang.GroovyClassLoader Java Examples

The following examples show how to use groovy.lang.GroovyClassLoader. 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: 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 #2
Source File: DefaultRunners.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Run the specified class extending TestCase as a unit test.
 * This is done through reflection, to avoid adding a dependency to the JUnit framework.
 * Otherwise, developers embedding Groovy and using GroovyShell to load/parse/compile
 * groovy scripts and classes would have to add another dependency on their classpath.
 *
 * @param scriptClass the class to be run as a unit test
 * @param loader the class loader
 */
@Override
public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
    try {
        Class<?> junitCoreClass = loader.loadClass("org.junit.runner.JUnitCore");
        Object result = InvokerHelper.invokeStaticMethod(junitCoreClass,
                "runClasses", new Object[]{scriptClass});
        System.out.print("JUnit 4 Runner, Tests: " + InvokerHelper.getProperty(result, "runCount"));
        System.out.print(", Failures: " + InvokerHelper.getProperty(result, "failureCount"));
        System.out.println(", Time: " + InvokerHelper.getProperty(result, "runTime"));
        List<?> failures = (List<?>) InvokerHelper.getProperty(result, "failures");
        for (Object f : failures) {
            System.out.println("Test Failure: " + InvokerHelper.getProperty(f, "description"));
            System.out.println(InvokerHelper.getProperty(f, "trace"));
        }
        return result;
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Error running JUnit 4 test.", e);
    }
}
 
Example #3
Source File: JUnit5Runner.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to check via reflection if the parsed class appears to be a JUnit5
 * test, i.e. checks whether it appears to be using the relevant annotations.
 *
 * @param scriptClass the class we want to check
 * @param loader the GroovyClassLoader to use to find classes
 * @return true if the class appears to be a compatible test
 */
@Override
public boolean canRun(Class<?> scriptClass, GroovyClassLoader loader) {
    if (!tryLoadClass("org.junit.jupiter.api.Test", loader)) {
        return false;
    }
    if (isJUnit5AnnotationPresent(scriptClass.getAnnotations(), loader)) {
        return true;
    }
    Method[] methods = scriptClass.getMethods();
    for (Method method : methods) {
        if (isJUnit5AnnotationPresent(method.getAnnotations(), loader)) {
            return true;
        }
    }
    return false;
}
 
Example #4
Source File: Groovys.java    From incubator-batchee with Apache License 2.0 6 votes vote down vote up
public static <T> GroovyInstance<T> newInstance(final Class<T> expected, final String path, final JobContext jobContext, final StepContext stepContext)
        throws IllegalAccessException, InstantiationException {
    if (path == null) {
        throw new BatchRuntimeException("no script configured expected");
    }
    final File script = new File(path);
    if (!script.exists()) {
        throw new BatchRuntimeException("Can't find script: " + path);
    }

    final ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    final GroovyClassLoader loader = new GroovyClassLoader(tccl);

    final Class<?> clazz;
    try {
        clazz = loader.parseClass(script);
    } catch (final IOException e) {
        throw new BatchRuntimeException(e);
    }

    final T delegate = expected.cast(clazz.newInstance());
    injectIfBatcheeIfAvailable(tccl, delegate, jobContext, stepContext);
    return new GroovyInstance<T>(loader, delegate);
}
 
Example #5
Source File: ClassNodeResolver.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * try to find a script using the compilation unit class loader.
 */
private static LookupResult tryAsScript(String name, CompilationUnit compilationUnit, ClassNode oldClass) {
    LookupResult lr = null;
    if (oldClass!=null) {
        lr = new LookupResult(null, oldClass);
    }
    
    if (name.startsWith("java.")) return lr;
    //TODO: don't ignore inner static classes completely
    if (name.indexOf('$') != -1) return lr;
    
    // try to find a script from classpath*/
    GroovyClassLoader gcl = compilationUnit.getClassLoader();
    URL url = null;
    try {
        url = gcl.getResourceLoader().loadGroovySource(name);
    } catch (MalformedURLException e) {
        // fall through and let the URL be null
    }
    if (url != null && ( oldClass==null || isSourceNewer(url, oldClass))) {
        SourceUnit su = compilationUnit.addSource(url);
        return new LookupResult(su,null);
    }
    return lr;
}
 
Example #6
Source File: JUnit5Runner.java    From groovy with Apache License 2.0 6 votes vote down vote up
private boolean isJUnit5AnnotationPresent(Annotation[] annotations, GroovyClassLoader loader) {
    for (Annotation annotation : annotations) {
        Class<? extends Annotation> type = annotation.annotationType();
        String name = type.getName();
        if (name.startsWith("org.junit.jupiter.api.") && tryLoadClass(name, loader)) {
            return true;
        }
        // it might directly annotate a class, e.g. Specification in Spock 2
        if (name.equals("org.junit.platform.commons.annotation.Testable") && tryLoadClass(name, loader)) {
            return true;
        }
        if (isJUnit5TestableMetaAnnotationPresent(type, new HashSet<>()) && tryLoadClass(name, loader)) {
            return true;
        }
    }
    return false;
}
 
Example #7
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 #8
Source File: Controller.java    From xdat_editor with MIT License 6 votes vote down vote up
public void registerVersion(String name, String xdatClass) {
    RadioMenuItem menuItem = new RadioMenuItem(name);
    menuItem.setMnemonicParsing(false);
    menuItem.selectedProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue) {
            editor.execute(() -> {
                Class<? extends IOEntity> clazz = Class.forName(xdatClass, true, new GroovyClassLoader(getClass().getClassLoader())).asSubclass(IOEntity.class);
                Platform.runLater(() -> editor.setXdatClass(clazz));
                return null;
            }, e -> {
                String msg = String.format("%s: XDAT class load error", name);
                log.log(Level.WARNING, msg, e);
                Platform.runLater(() -> {
                    version.getToggles().remove(menuItem);
                    versionMenu.getItems().remove(menuItem);

                    Dialogs.showException(Alert.AlertType.ERROR, msg, e.getMessage(), e);
                });
            });
        }
    });
    version.getToggles().add(menuItem);
    versionMenu.getItems().add(menuItem);
}
 
Example #9
Source File: JUnit5Runner.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to run a JUnit 5 test.
 *
 * @param scriptClass the class we want to run as a test
 * @param loader the class loader to use
 * @return the result of running the test
 */
@Override
public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
    try {
        try {
            loader.loadClass("org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder");
        } catch (ClassNotFoundException ignored) {
            // subsequent steps will bomb out but try to give some more friendly information first
            System.err.println("WARNING: Required dependency: org.junit.platform:junit-platform-launcher doesn't appear to be on the classpath");
        }
        Class<?> helper = loader.loadClass("groovy.junit5.plugin.GroovyJUnitRunnerHelper");
        Throwable ifFailed = (Throwable) InvokerHelper.invokeStaticMethod(helper, "execute", new Object[]{scriptClass});
        if (ifFailed != null) {
            throw new GroovyRuntimeException(ifFailed);
        }
        return null;
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Error running JUnit 5 test.", e);
    }
}
 
Example #10
Source File: GroovyLoadUtil.java    From nh-micro with Apache License 2.0 6 votes vote down vote up
public static void loadGroovy(String name, String content) throws Exception {
	logger.info("begin load groovy name=" + name);
	logger.debug("groovy content=" + content);
	if(name.toLowerCase().contains("abstract")){
		logger.info("skip load groovy name=" + name);
		return;
	}
	ClassLoader parent = GroovyLoadUtil.class.getClassLoader();
	GroovyClassLoader loader = new GroovyClassLoader(parent);
	Class<?> groovyClass = loader.parseClass(content,name+".groovy");
	GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance();
	
	GroovyObject proxyObject=groovyObject;		
	if(pluginList!=null){
		
		int size=pluginList.size();
		for(int i=0;i<size;i++){
			IGroovyLoadPlugin plugin=(IGroovyLoadPlugin) pluginList.get(i);
			proxyObject=plugin.execPlugIn(name, groovyObject, proxyObject);
		}
	}		
	GroovyExecUtil.getGroovyMap().put(name, proxyObject);		
	//GroovyExecUtil.getGroovyMap().put(name, groovyObject);
	logger.info("finish load groovy name=" + name);
}
 
Example #11
Source File: TestNgRunner.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Utility method to run a TestNG test.
 *
 * @param scriptClass the class we want to run as a test
 * @param loader the class loader to use
 * @return the result of running the test
 */
@Override
public Object run(Class<?> scriptClass, GroovyClassLoader loader) {
    try {
        Class<?> testNGClass = loader.loadClass("org.testng.TestNG");
        Object testng = InvokerHelper.invokeConstructorOf(testNGClass, new Object[]{});
        InvokerHelper.invokeMethod(testng, "setTestClasses", new Object[]{scriptClass});
        Class<?> listenerClass = loader.loadClass("org.testng.TestListenerAdapter");
        Object listener = InvokerHelper.invokeConstructorOf(listenerClass, new Object[]{});
        InvokerHelper.invokeMethod(testng, "addListener", new Object[]{listener});
        if (OUTPUT_DIRECTORY != null) {
            InvokerHelper.invokeMethod(testng, "setOutputDirectory", new Object[]{OUTPUT_DIRECTORY});
        }
        return InvokerHelper.invokeMethod(testng, "run", new Object[]{});
    } catch (ClassNotFoundException e) {
        throw new GroovyRuntimeException("Error running TestNG test.", e);
    }
}
 
Example #12
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 #13
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 #14
Source File: GroovyScriptFactory.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return the GroovyClassLoader used by this script factory.
 */
public GroovyClassLoader getGroovyClassLoader() {
	synchronized (this.scriptClassMonitor) {
		if (this.groovyClassLoader == null) {
			this.groovyClassLoader = buildGroovyClassLoader(ClassUtils.getDefaultClassLoader());
		}
		return this.groovyClassLoader;
	}
}
 
Example #15
Source File: DownloadUtils.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
public static URI[] downloadJar(Map<String, Object> artifactMap) throws IOException {
  System.setProperty("grape.config", getIvySettingsFile().getAbsolutePath());

  Map<String, Object> args = Maps.newHashMap();
  args.put("classLoader",  AccessController.doPrivileged(new PrivilegedAction<GroovyClassLoader>() {
    @Override
    public GroovyClassLoader run() {
      return new GroovyClassLoader();
    }
  }));
  return Grape.resolve(args, artifactMap);
}
 
Example #16
Source File: CompilationUnitTest.java    From groovy with Apache License 2.0 5 votes vote down vote up
private GroovyClassLoader createGroovyClassLoaderWithExpectations(CompilerConfiguration configuration) {
    Mock mockGroovyClassLoader = mock(GroovyClassLoader.class);
    for (Iterator iterator = configuration.getClasspath().iterator(); iterator.hasNext();) {
        mockGroovyClassLoader.expects(once()).method("addClasspath").with(eq(iterator.next()));
    }
    return (GroovyClassLoader) mockGroovyClassLoader.proxy();
}
 
Example #17
Source File: ClassNodeCache.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public GroovyClassLoader createResolveLoader(
        @NonNull final ClassPath allResources,
        @NonNull final CompilerConfiguration configuration) {
    GroovyClassLoader resolveLoader = resolveLoaderRef == null ? null : resolveLoaderRef.get();
    if (resolveLoader == null) {
        LOG.log(Level.FINE,"Resolver ClassLoader created.");  //NOI18N
        resolveLoader = new ParsingClassLoader(
                allResources,
                configuration,
                this);
        resolveLoaderRef = new SoftReference<>(resolveLoader);
    }
    return resolveLoader;
}
 
Example #18
Source File: Main.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method that gets an instance of a brooklyn {@link EntitySpec}.
 * Guaranteed to be non-null result (throwing exception if app not appropriate).
 * 
 * @throws FatalConfigurationRuntimeException if class is not an {@link Application} or {@link Entity}
 */
@SuppressWarnings("unchecked")
protected EntitySpec<? extends Application> loadApplicationFromClasspathOrParse(ResourceUtils utils, GroovyClassLoader loader, String app)
        throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
    
    Class<?> clazz;
    log.debug("Loading application as class on classpath: {}", app);
    try {
        clazz = loader.loadClass(app, true, false);
    } catch (ClassNotFoundException cnfe) { // Not a class on the classpath
        throw new IllegalStateException("Unable to load app class '"+app+"'", cnfe);
    }
    
    if (Application.class.isAssignableFrom(clazz)) {
        if (clazz.isInterface()) {
            return EntitySpec.create((Class<? extends Application>)clazz);
        } else {
            return EntitySpec.create(Application.class)
                    .impl((Class<? extends Application>) clazz)
                    .additionalInterfaces(Reflections.getAllInterfaces(clazz));
        }
        
    } else if (Entity.class.isAssignableFrom(clazz)) {
        // TODO Should we really accept any entity type, and just wrap it in an app? That's not documented!
        EntitySpec<?> childSpec;
        if (clazz.isInterface()) {
            childSpec = EntitySpec.create((Class<? extends Entity>)clazz);
        } else {
            childSpec = EntitySpec.create(Entity.class)
                    .impl((Class<? extends Application>) clazz)
                    .additionalInterfaces(Reflections.getAllInterfaces(clazz));
        }
        return EntitySpec.create(BasicApplication.class).child(childSpec);
        
    } else {
        throw new FatalConfigurationRuntimeException("Application class "+clazz+" must be an Application or Entity");
    }
}
 
Example #19
Source File: CompilationUnit.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public CompileUnit(GroovyParser parser, GroovyClassLoader classLoader,
        CodeSource codeSource, CompilerConfiguration config,
        ClasspathInfo cpInfo,
        ClassNodeCache classNodeCache) {
    super(classLoader, codeSource, config);
    this.parser = parser;
    this.cache = classNodeCache;
    this.javaSource = cache.createResolver(cpInfo);
}
 
Example #20
Source File: SiteContextFactory.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
protected URLClassLoader getClassLoader(SiteContext siteContext) {
    GroovyClassLoader classLoader =
            new GroovyClassLoader(getClass().getClassLoader(), getCompilerConfiguration(enableScriptSandbox));
    ContentStoreGroovyResourceLoader resourceLoader = new ContentStoreGroovyResourceLoader(siteContext,
                                                                                           groovyClassesPath);

    classLoader.setResourceLoader(resourceLoader);

    return classLoader;
}
 
Example #21
Source File: Groovyc.java    From groovy with Apache License 2.0 5 votes vote down vote up
private void loadRegisteredScriptExtensions() {
    if (scriptExtensions.isEmpty()) {
        scriptExtensions.add(getScriptExtension().substring(2)); // first extension will be the one set explicitly on <groovyc>

        Path classpath = Optional.ofNullable(getClasspath()).orElse(new Path(getProject()));
        try (GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader())) {
            for (String element : classpath.list()) {
                loader.addClasspath(element);
            }
            scriptExtensions.addAll(SourceExtensionHandler.getRegisteredExtensions(loader));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
 
Example #22
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 #23
Source File: GroovyApplicationTest.java    From everrest with Eclipse Public License 2.0 5 votes vote down vote up
@Before
@Override
public void setUp() throws Exception {
    super.setUp();
    groovyClassLoader = new GroovyClassLoader();
    URL root = Thread.currentThread().getContextClassLoader().getResource("repo");
    DefaultGroovyResourceLoader groovyResourceLoader = new DefaultGroovyResourceLoader(root);
    groovyClassLoader.setResourceLoader(groovyResourceLoader);
    applicationPublisher = new ApplicationPublisher(resources, providers);
}
 
Example #24
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 #25
Source File: GroovyUtil.java    From scipio-erp with Apache License 2.0 5 votes vote down vote up
/**
 * @throws IOException
 * @deprecated SCIPIO: 2017-01-30: ambiguous; method specifying an explicit ClassLoader should be used instead, to ensure library loading consistency.
 */
@Deprecated
public static Class<?> parseClass(String text) throws IOException {
    if (!baseScriptInitialized) { initBaseScript(); } // SCIPIO
    GroovyClassLoader groovyClassLoader = new GroovyClassLoader();
    Class<?> classLoader = groovyClassLoader.parseClass(text);
    groovyClassLoader.close();
    return classLoader;
}
 
Example #26
Source File: SourceUnit.java    From groovy with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes the SourceUnit from existing machinery.
 */
public SourceUnit(String name, ReaderSource source, CompilerConfiguration flags,
                  GroovyClassLoader loader, ErrorCollector er) {
    super(flags, loader, er);

    this.name = name;
    this.source = source;
}
 
Example #27
Source File: StreamSetsGroovyScriptEngineFactory.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Override
public ScriptEngine getScriptEngine() {
  CompilerConfiguration conf = new CompilerConfiguration();
  Map<String, Boolean> optimizationOptions = conf.getOptimizationOptions();
  optimizationOptions.put(INVOKEDYNAMIC, useInvokeDynamic());
  conf.setOptimizationOptions(optimizationOptions);
  conf.setTargetBytecode(JDK8);

  GroovyClassLoader classLoader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader(), conf);
  return new GroovyScriptEngineImpl(classLoader);
}
 
Example #28
Source File: GroovyAutocomplete.java    From beakerx with Apache License 2.0 5 votes vote down vote up
public GroovyAutocomplete(GroovyClasspathScanner _cps,
                          GroovyClassLoader groovyClassLoader,
                          Imports imports,
                          MagicCommandAutocompletePatterns autocompletePatterns,
                          Binding scriptBinding) {
  super(autocompletePatterns);
  cps = _cps;
  this.groovyClassLoader = groovyClassLoader;
  this.imports = imports;
  this.scriptBinding = scriptBinding;
  registry = AutocompleteRegistryFactory.createRegistry(cps);
}
 
Example #29
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 #30
Source File: GroovyUtils.java    From zstack with Apache License 2.0 5 votes vote down vote up
public static Class getClass(String scriptPath, ClassLoader parent) {
    Class clz = groovyClasses.get(scriptPath);
    if (clz != null) {
        return clz;
    }

    GroovyClassLoader loader = new GroovyClassLoader(parent);
    InputStream in =  parent.getResourceAsStream(scriptPath);
    String script = StringDSL.inputStreamToString(in);
    clz = loader.parseClass(script);
    groovyClasses.put(scriptPath, clz);
    return clz;
}