/** * Gets credential selection predicate. * * @param selectionCriteria the selection criteria * @return the credential selection predicate */ public static Predicate<org.apereo.cas.authentication.Credential> newCredentialSelectionPredicate(final String selectionCriteria) { try { if (StringUtils.isBlank(selectionCriteria)) { return credential -> true; } if (selectionCriteria.endsWith(".groovy")) { final ResourceLoader loader = new DefaultResourceLoader(); final Resource resource = loader.getResource(selectionCriteria); if (resource != null) { final String script = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8); final GroovyClassLoader classLoader = new GroovyClassLoader(Beans.class.getClassLoader(), new CompilerConfiguration(), true); final Class<Predicate> clz = classLoader.parseClass(script); return clz.newInstance(); } } final Class predicateClazz = ClassUtils.getClass(selectionCriteria); return (Predicate<org.apereo.cas.authentication.Credential>) predicateClazz.newInstance(); } catch (final Exception e) { final Predicate<String> predicate = Pattern.compile(selectionCriteria).asPredicate(); return credential -> predicate.test(credential.getId()); } }
/** * 执行几串简单的命令 * * @param importList * @param commandLines * @return * @throws InstantiationException * @throws IllegalAccessException * @throws IOException * @throws ScriptException * @throws IllegalArgumentException * @throws InvocationTargetException */ public AbstractScriptLoader<KEY> executeCommand(List<String> importList, String commandLines) throws InstantiationException, IllegalAccessException, IOException, ScriptException, IllegalArgumentException, InvocationTargetException { StringBuilder importBuffer = new StringBuilder(); if (importList != null) { for (String temp : importList) { importBuffer.append("import " + temp + ";"); } } String result = importBuffer.toString() + "import com.limitart.script.IDynamicCode; public class DynamicCodeProxy" + dynamicCodeCount.getAndIncrement() + " extends IDynamicCode {" + " public void execute() {" + commandLines + "}" + "}"; try (GroovyClassLoader loader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader())) { @SuppressWarnings("rawtypes") Class parseClass = loader.parseClass(result); IDynamicCode newInstance = (IDynamicCode) parseClass.newInstance(); log.info("compile code success,start executing..."); newInstance.execute(); log.info("done!"); } return this; }
/** * 重载脚本 * * @param scriptId * @throws IOException * @throws CompilationFailedException * @throws IllegalAccessException * @throws InstantiationException * @throws ScriptException */ public AbstractScriptLoader<KEY> reloadScript(KEY scriptId) throws CompilationFailedException, IOException, InstantiationException, IllegalAccessException, ScriptException { File file = scriptPath.get(scriptId); Objects.requireNonNull(file, "script id:" + scriptId + " does not exist!"); try (GroovyClassLoader loader = new GroovyClassLoader(ClassLoader.getSystemClassLoader())) { Class<?> parseClass = loader.parseClass(file); Object newInstance = parseClass.newInstance(); if (!(newInstance instanceof IScript)) { throw new ScriptException("script file must implement IScript:" + file.getName()); } @SuppressWarnings("unchecked") IScript<KEY> newScript = (IScript<KEY>) newInstance; scriptMap.put(scriptId, newScript); log.info("reload script success:" + file.getName()); } return this; }
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); }
private void initGroovyTransformer(String code, List<String> extraPackage) { GroovyClassLoader loader = new GroovyClassLoader(GroovyTransformer.class.getClassLoader()); String groovyRule = getGroovyRule(code, extraPackage); Class groovyClass; try { groovyClass = loader.parseClass(groovyRule); } catch (CompilationFailedException cfe) { throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_GROOVY_INIT_EXCEPTION, cfe); } try { Object t = groovyClass.newInstance(); if (!(t instanceof Transformer)) { throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_GROOVY_INIT_EXCEPTION, "datax bug! contact askdatax"); } this.groovyTransformer = (Transformer) t; } catch (Throwable ex) { throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_GROOVY_INIT_EXCEPTION, ex); } }
@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); }
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); }
public static AetherGrapeEngine create(GroovyClassLoader classLoader, List<RepositoryConfiguration> repositoryConfigurations, DependencyResolutionContext dependencyResolutionContext) { RepositorySystem repositorySystem = createServiceLocator() .getService(RepositorySystem.class); DefaultRepositorySystemSession repositorySystemSession = MavenRepositorySystemUtils .newSession(); ServiceLoader<RepositorySystemSessionAutoConfiguration> autoConfigurations = ServiceLoader .load(RepositorySystemSessionAutoConfiguration.class); for (RepositorySystemSessionAutoConfiguration autoConfiguration : autoConfigurations) { autoConfiguration.apply(repositorySystemSession, repositorySystem); } new DefaultRepositorySystemSessionAutoConfiguration() .apply(repositorySystemSession, repositorySystem); return new AetherGrapeEngine(classLoader, repositorySystem, repositorySystemSession, createRepositories(repositoryConfigurations), dependencyResolutionContext); }
public AetherGrapeEngine(GroovyClassLoader classLoader, RepositorySystem repositorySystem, DefaultRepositorySystemSession repositorySystemSession, List<RemoteRepository> remoteRepositories, DependencyResolutionContext resolutionContext) { this.classLoader = classLoader; this.repositorySystem = repositorySystem; this.session = repositorySystemSession; this.resolutionContext = resolutionContext; this.repositories = new ArrayList<RemoteRepository>(); List<RemoteRepository> remotes = new ArrayList<RemoteRepository>( remoteRepositories); Collections.reverse(remotes); // priority is reversed in addRepository for (RemoteRepository repository : remotes) { addRepository(repository); } this.progressReporter = getProgressReporter(this.session); }
@Before public void setUp() { MockitoAnnotations.initMocks(this); given(this.resolver.getGroupId("spring-boot-starter-logging")) .willReturn("org.springframework.boot"); given(this.resolver.getArtifactId("spring-boot-starter-logging")) .willReturn("spring-boot-starter-logging"); this.moduleNode.addClass(this.classNode); this.dependencyCustomizer = new DependencyCustomizer( new GroovyClassLoader(getClass().getClassLoader()), this.moduleNode, new DependencyResolutionContext() { @Override public ArtifactCoordinatesResolver getArtifactCoordinatesResolver() { return DependencyCustomizerTests.this.resolver; } }); }
@SuppressWarnings("resource") private static final GroovyObject getGroovyObject(String rule) throws IllegalAccessException, InstantiationException { if (!RULE_CLASS_CACHE.containsKey(rule)) { synchronized (GroovyRuleEngine.class) { if (!RULE_CLASS_CACHE.containsKey(rule)) { Matcher matcher = DimensionRule.RULE_COLUMN_PATTERN.matcher(rule); StringBuilder engineClazzImpl = new StringBuilder(200) .append("class RuleEngineBaseImpl extends " + RuleEngineBase.class.getName() + "{") .append("Object execute(Map context) {").append(matcher.replaceAll("context.get(\"$1\")")) .append("}").append("}"); GroovyClassLoader loader = new GroovyClassLoader(AbstractDimensionRule.class.getClassLoader()); Class<?> engineClazz = loader.parseClass(engineClazzImpl.toString()); RULE_CLASS_CACHE.put(rule, engineClazz); } } } return (GroovyObject) RULE_CLASS_CACHE.get(rule).newInstance(); }
/** * 将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); } } }
protected HashMap<String, Object> generateDefaultVariableValues() { HashMap<String, Object> result = new HashMap<>(); try { Map<String, Variable> variableInstances = HybridbpmUI.getBpmAPI().createFirstVariables(processModel); for (String name : variableInstances.keySet()) { Variable vi = variableInstances.get(name); if (FieldModelUtil.isSimple(vi.getClassName())) { } else { GroovyClassLoader groovyClassLoader = HybridbpmUI.getDevelopmentAPI().getGroovyClassLoader(); Class clazz = groovyClassLoader.loadClass(vi.getClassName()); Object object = clazz.newInstance(); System.out.println("object = " + object); result.put(name, object); } } } catch (Exception ex) { logger.log(Level.SEVERE, ex.getMessage(), ex); } return result; }
@SuppressWarnings({ "unchecked", "resource" }) public static void main(String[] args) throws InstantiationException, IllegalAccessException { String classCode = ""+ "import java.util.Map; "+ "class GroovyServiceImpl2 implements IGroovyService{"+ " @Override"+ " public Object execute(Map<String, Object> param) {"+ " return 1656565;"+ " }"+ "}"+ ";"; GroovyClassLoader groovyClassLoader = new GroovyClassLoader(); Class<IGroovyService> clazz = groovyClassLoader.parseClass(classCode); IGroovyService service = clazz.newInstance(); System.out.println(service.execute(null)); }
protected CompilationUnit makeCompileUnit(GroovyClassLoader loader) { Map<String, Object> options = configuration.getJointCompilationOptions(); if (options != null) { if (keepStubs) { options.put("keepStubs", Boolean.TRUE); } if (stubDir != null) { options.put("stubDir", stubDir); } else { try { File tempStubDir = DefaultGroovyStaticMethods.createTempDir(null, "groovy-generated-", "-java-source"); temporaryFiles.add(tempStubDir); options.put("stubDir", tempStubDir); } catch (IOException ioe) { throw new BuildException(ioe); } } return new JavaAwareCompilationUnit(configuration, loader); } else { return new CompilationUnit(configuration, null, loader); } }
private void loadRegisteredScriptExtensions() { if (scriptExtensions.isEmpty()) { scriptExtensions.add(getScriptExtension().substring(2)); // first extension will be the one set explicitly on <groovyc> Path classpath = getClasspath() != null ? getClasspath() : new Path(getProject()); final String[] pe = classpath.list(); try (GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader())) { for (String file : pe) { loader.addClasspath(file); } scriptExtensions.addAll(SourceExtensionHandler.getRegisteredExtensions(loader)); } catch (IOException e) { throw new RuntimeException(e); } } }
public ModuleNode parse(File file) { if (null == file || !file.exists()) { throw new IllegalArgumentException(file + " does not exist."); } CompilerConfiguration configuration = this.getCompilerConfiguration(); SourceUnit sourceUnit = new SourceUnit( file, configuration, AccessController.doPrivileged( new PrivilegedAction<GroovyClassLoader>() { @Override public GroovyClassLoader run() { return new GroovyClassLoader(); } }), new ErrorCollector(configuration) ); return this.parse(sourceUnit); }
/** * Utility method to check via reflection if the parsed class appears to be a TestNG * test, i.e. checks whether it appears to be using the relevant TestNG 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 test */ @Override public boolean canRun(Class<?> scriptClass, GroovyClassLoader loader) { try { @SuppressWarnings("unchecked") Class<? extends Annotation> testAnnotationClass = (Class<? extends Annotation>) loader.loadClass("org.testng.annotations.Test"); if (scriptClass.isAnnotationPresent(testAnnotationClass)) { return true; } else { Method[] methods = scriptClass.getMethods(); for (Method method : methods) { if (method.isAnnotationPresent(testAnnotationClass)) { return true; } } } } catch (Throwable e) { // fall through } return false; }
private ImmutableList<BaseListener> buildClasses() { List<BaseListener> listeners = new ArrayList<>(); CompilerConfiguration compiler = new CompilerConfiguration(); compiler.setScriptBaseClass(BaseListener.class.getName()); GroovyClassLoader loader = new GroovyClassLoader(this.getClass().getClassLoader(), compiler); paths.forEach(path -> { try { final Class clazz = loader.parseClass(path.toFile()); BaseListener listener = (BaseListener) clazz.newInstance(); listener.run(); listener.init(); listeners.add(listener); } catch (Exception e) { log.error("Error building or initializing groovy script " + path, e); } }); return ImmutableList.copyOf(listeners); }
/** * This method is used to realize the lookup of a class using the compilation * unit class loader. Should no class be found we fall back to a script lookup. * If a class is found we check if there is also a script and maybe use that * one in case it is newer.<p/> * * Two class search strategies are possible: by ASM decompilation or by usual Java classloading. * The latter is slower but is unavoidable for scripts executed in dynamic environments where * the referenced classes might only be available in the classloader, not on disk. */ private LookupResult tryAsLoaderClassOrScript(String name, CompilationUnit compilationUnit) { GroovyClassLoader loader = compilationUnit.getClassLoader(); Map<String, Boolean> options = compilationUnit.configuration.getOptimizationOptions(); boolean useAsm = !Boolean.FALSE.equals(options.get("asmResolving")); boolean useClassLoader = !Boolean.FALSE.equals(options.get("classLoaderResolving")); LookupResult result = useAsm ? findDecompiled(name, compilationUnit, loader) : null; if (result != null) { return result; } if (!useClassLoader) { return tryAsScript(name, compilationUnit, null); } return findByClassLoading(name, compilationUnit, loader); }
/** * 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; }
private BuilderStrategy createBuilderStrategy(AnnotationNode anno, GroovyClassLoader loader) { ClassNode strategyClass = getMemberClassValue(anno, "builderStrategy", ClassHelper.make(DefaultStrategy.class)); if (strategyClass == null) { addError("Couldn't determine builderStrategy class", anno); return null; } String className = strategyClass.getName(); try { Object instance = loader.loadClass(className).newInstance(); if (instance == null) { addError("Can't load builderStrategy '" + className + "'", anno); return null; } if (!BuilderStrategy.class.isAssignableFrom(instance.getClass())) { addError("The builderStrategy class '" + strategyClass.getName() + "' on " + MY_TYPE_NAME + " is not a builderStrategy", anno); return null; } return (BuilderStrategy) instance; } catch (Exception e) { addError("Can't load builderStrategy '" + className + "' " + e, anno); return null; } }
public static long getTimestamp(Class clazz) { if (clazz.getClassLoader() instanceof GroovyClassLoader.InnerLoader) { GroovyClassLoader.InnerLoader innerLoader = (GroovyClassLoader.InnerLoader) clazz.getClassLoader(); return innerLoader.getTimeStamp(); } final Field[] fields = clazz.getFields(); for (int i = 0; i != fields.length; ++i) { if (isStatic(fields[i].getModifiers())) { Long timestamp = getTimestampFromFieldName(fields[i].getName()); if (timestamp != null) { return timestamp; } } } return Long.MAX_VALUE; }
protected void ensureInitializedOrReloaded() { if (groovyClassLoader == null) { compilerConfiguration = new CompilerConfiguration(getCompilerConfigurationFactory().getCompilerConfiguration()); if (getScriptBaseClass() != null) { compilerConfiguration.setScriptBaseClass(getScriptBaseClass()); } groovyClassLoader = AccessController.doPrivileged((PrivilegedAction<GroovyClassLoader>) () -> new GroovyClassLoader(getParentClassLoaderFactory().getClassLoader(), compilerConfiguration)); if (!scriptCache.isEmpty()) { // de-serialized: need to re-generate all previously compiled scripts (this can cause a hick-up...): for (ScriptCacheElement element : scriptCache.keySet()) { element.setScriptClass(compileScript(element.getBaseClass(), element.getScriptSource(), element.getScriptName())); } } } }
/** * Utility method to run a JUnit4 test. * * @param scriptClass the class we want to run as a test * @return the result of running the test */ static Object realRunJUnit4Test(Class scriptClass, GroovyClassLoader loader) { // invoke through reflection to eliminate mandatory JUnit 4 jar dependency 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 (int i = 0; i < failures.size(); i++) { Object f = failures.get(i); 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); } }
public CustomCompilationUnit(CompilerConfiguration compilerConfiguration, CodeSource codeSource, final Action<? super ClassNode> customVerifier, GroovyClassLoader groovyClassLoader) { super(compilerConfiguration, codeSource, groovyClassLoader); this.verifier = new Verifier() { public void visitClass(ClassNode node) { customVerifier.execute(node); super.visitClass(node); } }; this.resolveVisitor = new GradleResolveVisitor(this, defaultImportPackages, simpleNameToFQN); }
public void test_groovy() throws Exception { ClassLoader parent = Thread.currentThread().getContextClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); // A类 Class AClass = loader.parseClass("class A {\n" + // " int id\n" + // "}"); // A实例 GroovyObject a = (GroovyObject) AClass.newInstance(); a.setProperty("id", 33); String textA = JSON.toJSONString(a); GroovyObject aa = (GroovyObject) JSON.parseObject(textA, AClass); Assert.assertEquals(a.getProperty("id"), aa.getProperty("id")); System.out.println(a); // B类,继承于A Class BClass = loader.parseClass("class B extends A {\n" + // " String name\n" + // "}"); // B实例 GroovyObject b = (GroovyObject) BClass.newInstance(); b.setProperty("name", "jobs"); String textB = JSON.toJSONString(b); GroovyObject bb = (GroovyObject) JSON.parseObject(textB, BClass); Assert.assertEquals(b.getProperty("id"), bb.getProperty("id")); Assert.assertEquals(b.getProperty("name"), bb.getProperty("name")); // 序列化失败 System.out.println(JSON.toJSONString(b, true)); }
/** * Execute groovy script t. * * @param <T> the type parameter * @param groovyScript the groovy script * @param methodName the method name * @param args the args * @param clazz the clazz * @return the t */ public static <T> T executeGroovyScript(final Resource groovyScript, final String methodName, final Object[] args, final Class<T> clazz) { if (groovyScript == null || StringUtils.isBlank(methodName)) { return null; } final ClassLoader parent = ScriptingUtils.class.getClassLoader(); try (GroovyClassLoader loader = new GroovyClassLoader(parent)) { final File groovyFile = groovyScript.getFile(); if (groovyFile.exists()) { final Class<?> groovyClass = loader.parseClass(groovyFile); LOGGER.trace("Creating groovy object instance from class [{}]", groovyFile.getCanonicalPath()); final GroovyObject groovyObject = (GroovyObject) groovyClass.newInstance(); LOGGER.trace("Executing groovy script's [{}] method, with parameters [{}]", methodName, args); final T result = (T) groovyObject.invokeMethod(methodName, args); LOGGER.trace("Results returned by the groovy script are [{}]", result); if (!clazz.isAssignableFrom(result.getClass())) { throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz); } return result; } else { LOGGER.trace("Groovy script at [{}] does not exist", groovyScript); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } return null; }
@Override protected Set<Event> resolveMultifactorProviderViaPredicate(final RequestContext context, final RegisteredService service, final Principal principal, final Collection<MultifactorAuthenticationProvider> providers) { try { if (predicateResource == null || !ResourceUtils.doesResourceExist(predicateResource)) { LOGGER.debug("No groovy script predicate is defined to decide which multifactor authentication provider should be chosen"); return null; } final String script = IOUtils.toString(predicateResource.getInputStream(), StandardCharsets.UTF_8); final GroovyClassLoader classLoader = new GroovyClassLoader(getClass().getClassLoader(), new CompilerConfiguration(), true); final Class<Predicate> predicateClass = classLoader.parseClass(script); final Object[] args = {service, principal, providers, LOGGER}; final Class[] types = {Object.class, Object.class, Object.class, Object.class}; final Constructor<Predicate> ctor = predicateClass.getDeclaredConstructor(types); final Predicate<MultifactorAuthenticationProvider> predicate = ctor.newInstance(args); return resolveEventViaPrincipalAttribute(principal, attributeNames, service, context, providers, input -> providers.stream() .filter(predicate) .findFirst() .isPresent()); } catch (final Exception e) { throw Throwables.propagate(e); } }
@Inject public GroovyFactory( GroovyClassLoader groovyClassLoader, SelectClauseParser selectClauseParser, WhereClauseParser whereClauseParser) { this.groovyClassLoader = groovyClassLoader; this.selectClauseParser = selectClauseParser; this.whereClauseParser = whereClauseParser; this.cache = CacheBuilder.newBuilder() .maximumSize(2000) .initialCapacity(1000) .expireAfterWrite(1, TimeUnit.HOURS) .build(); }
/** * 执行一段继承了IDynamicCode的代码 * * @param path * @return * @throws ScriptException * @throws IOException * @throws IllegalAccessException * @throws InstantiationException * @see IDynamicCode */ public AbstractScriptLoader<KEY> executeCommand(String path) throws ScriptException, IOException, InstantiationException, IllegalAccessException { File file = new File(path); if (!file.exists()) { throw new FileNotFoundException("file not exist!"); } if (file.isDirectory()) { throw new ScriptException("script file is directory!"); } String[] split = file.getName().split("[.]"); if (split.length < 2) { throw new ScriptException("file name must has extension,like .java .groovy,yours:" + file.getName()); } String type = split[1]; ScriptFileType typeByValue = ScriptFileType.getTypeByValue(type); if (typeByValue == null) { throw new ScriptException("script type not supported:" + type); } try (GroovyClassLoader loader = new GroovyClassLoader(Thread.currentThread().getContextClassLoader())) { @SuppressWarnings("rawtypes") Class parseClass = loader.parseClass(file); Object newInstance = parseClass.newInstance(); if (!(newInstance instanceof IDynamicCode)) { throw new ScriptException("class must extends IDynamicCode"); } IDynamicCode temp = (IDynamicCode) newInstance; log.info("compile code success,start executing..."); temp.execute(); log.info("done!"); } return this; }
/** * 加载一个目录下对应的全部脚本(不会加载IDynamicCode相关) * * @param dir * @param scriptTypes * @return * @throws IOException * @throws InstantiationException * @throws IllegalAccessException * @throws ScriptException */ public AbstractScriptLoader<KEY> loadScriptsBySourceDir(String dir, ScriptFileType... scriptTypes) throws IOException, InstantiationException, IllegalAccessException, ScriptException { ConcurrentHashMap<KEY, IScript<KEY>> scriptMap_new = new ConcurrentHashMap<>(); ConcurrentHashMap<KEY, File> scriptPath_new = new ConcurrentHashMap<>(); try (GroovyClassLoader loader = new GroovyClassLoader(ClassLoader.getSystemClassLoader());) { File dir_root = new File(dir); if (!dir_root.exists()) { throw new IOException("scripts root dir does not exist:" + dir); } if (!dir_root.isDirectory()) { throw new IOException("file is not dir:" + dir); } String[] types = null; if (scriptTypes != null && scriptTypes.length > 0) { types = new String[scriptTypes.length]; for (int i = 0; i < scriptTypes.length; ++i) { types[i] = scriptTypes[i].getValue(); } } List<File> result = FileUtil.getFiles(dir_root, types); for (File file : result) { Class<?> parseClass = loader.parseClass(file); Object newInstance = parseClass.newInstance(); if (newInstance instanceof IScript) { if (newInstance instanceof IDynamicCode) { continue; } @SuppressWarnings("unchecked") IScript<KEY> script = (IScript<KEY>) newInstance; KEY scriptId = script.getScriptId(); if (scriptMap_new.containsKey(scriptId)) { log.error("script id duplicated,source:" + scriptPath.get(scriptId).getName() + ",yours:" + file.getName()); } else { scriptMap_new.put(scriptId, script); scriptPath_new.put(scriptId, file); log.info("compile script success:" + file.getName()); } } else { throw new ScriptException("script file must implement IScript:" + file.getName()); } } this.scriptMap = scriptMap_new; this.scriptPath = scriptPath_new; } return this; }
/** * Compile a Groovy expression. * For example, {@code 1 + 1} will be {@code 2} on evaluated. * @param expression Groovy expression * @return compiled */ @SuppressWarnings("unchecked") public CompiledExpression compileExpression(String expression, RouteSource source) { if (expression == null) { return null; } try { val clazz = new GroovyClassLoader().parseClass(expression, source.getName()); return new CompiledExpression((Class<Script>) clazz); } catch (GroovyRuntimeException e) { throw new IllegalRuleException("Invalid expression: " + expression, source, e); } }