use of groovy.lang.GroovyClassLoader in project groovy by apache.
the class GroovyTypeCheckingExtensionSupport method setup.
@Override
public void setup() {
CompilerConfiguration config = new CompilerConfiguration();
config.setScriptBaseClass("org.codehaus.groovy.transform.stc.GroovyTypeCheckingExtensionSupport.TypeCheckingDSL");
ImportCustomizer ic = new ImportCustomizer();
ic.addStarImports("org.codehaus.groovy.ast.expr");
ic.addStaticStars("org.codehaus.groovy.ast.ClassHelper");
ic.addStaticStars("org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport");
config.addCompilationCustomizers(ic);
final GroovyClassLoader transformLoader = compilationUnit != null ? compilationUnit.getTransformLoader() : typeCheckingVisitor.getSourceUnit().getClassLoader();
// since Groovy 2.2, it is possible to use FQCN for type checking extension scripts
TypeCheckingDSL script = null;
try {
Class<?> clazz = transformLoader.loadClass(scriptPath, false, true);
if (TypeCheckingDSL.class.isAssignableFrom(clazz)) {
script = (TypeCheckingDSL) clazz.newInstance();
} else if (TypeCheckingExtension.class.isAssignableFrom(clazz)) {
// since 2.4, we can also register precompiled type checking extensions which are not scripts
try {
Constructor<?> declaredConstructor = clazz.getDeclaredConstructor(StaticTypeCheckingVisitor.class);
TypeCheckingExtension extension = (TypeCheckingExtension) declaredConstructor.newInstance(typeCheckingVisitor);
typeCheckingVisitor.addTypeCheckingExtension(extension);
extension.setup();
return;
} catch (InstantiationException e) {
addLoadingError(config);
} catch (IllegalAccessException e) {
addLoadingError(config);
} catch (NoSuchMethodException e) {
context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' could not be loaded because it doesn't have a constructor accepting StaticTypeCheckingVisitor.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
} catch (InvocationTargetException e) {
addLoadingError(config);
}
}
} catch (ClassNotFoundException e) {
// silent
} catch (InstantiationException e) {
addLoadingError(config);
} catch (IllegalAccessException e) {
addLoadingError(config);
}
if (script == null) {
ClassLoader cl = typeCheckingVisitor.getSourceUnit().getClassLoader();
// cast to prevent incorrect @since 1.7 warning
InputStream is = ((ClassLoader) transformLoader).getResourceAsStream(scriptPath);
if (is == null) {
// fallback to the source unit classloader
is = cl.getResourceAsStream(scriptPath);
}
if (is == null) {
// fallback to the compiler classloader
cl = GroovyTypeCheckingExtensionSupport.class.getClassLoader();
is = cl.getResourceAsStream(scriptPath);
}
if (is == null) {
// if the input stream is still null, we've not found the extension
context.getErrorCollector().addFatalError(new SimpleMessage("Static type checking extension '" + scriptPath + "' was not found on the classpath.", config.getDebug(), typeCheckingVisitor.getSourceUnit()));
}
try {
GroovyShell shell = new GroovyShell(transformLoader, new Binding(), config);
script = (TypeCheckingDSL) shell.parse(new InputStreamReader(is, typeCheckingVisitor.getSourceUnit().getConfiguration().getSourceEncoding()));
} catch (CompilationFailedException e) {
throw new GroovyBugError("An unexpected error was thrown during custom type checking", e);
} catch (UnsupportedEncodingException e) {
throw new GroovyBugError("Unsupported encoding found in compiler configuration", e);
}
}
if (script != null) {
script.extension = this;
script.run();
List<Closure> list = eventHandlers.get("setup");
if (list != null) {
for (Closure closure : list) {
safeCall(closure);
}
}
}
}
use of groovy.lang.GroovyClassLoader in project engine by craftercms.
the class SiteContextFactory method getClassLoader.
protected URLClassLoader getClassLoader(SiteContext siteContext) {
ContentStoreGroovyResourceLoader resourceLoader = new ContentStoreGroovyResourceLoader(siteContext, groovyClassesPath);
GroovyClassLoader classLoader = new GroovyClassLoader(getClass().getClassLoader());
classLoader.setResourceLoader(resourceLoader);
return classLoader;
}
use of groovy.lang.GroovyClassLoader in project cas by apereo.
the class CoreAuthenticationUtils method newCredentialSelectionPredicate.
/**
* Gets credential selection predicate.
*
* @param selectionCriteria the selection criteria
* @return the credential selection predicate
*/
public static Predicate<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.getDeclaredConstructor().newInstance();
}
}
final Class predicateClazz = ClassUtils.getClass(selectionCriteria);
return (Predicate<org.apereo.cas.authentication.Credential>) predicateClazz.getDeclaredConstructor().newInstance();
} catch (final Exception e) {
final Predicate<String> predicate = Pattern.compile(selectionCriteria).asPredicate();
return credential -> predicate.test(credential.getId());
}
}
use of groovy.lang.GroovyClassLoader in project cas by apereo.
the class ScriptingUtils method getObjectInstanceFromGroovyResource.
/**
* Gets object instance from groovy resource.
*
* @param <T> the type parameter
* @param resource the resource
* @param constructorArgs the constructor args
* @param args the args
* @param expectedType the expected type
* @return the object instance from groovy resource
*/
public static <T> T getObjectInstanceFromGroovyResource(final Resource resource, final Class[] constructorArgs, final Object[] args, final Class<T> expectedType) {
try {
if (resource == null) {
LOGGER.debug("No groovy script is defined");
return null;
}
final String script = IOUtils.toString(resource.getInputStream(), StandardCharsets.UTF_8);
final GroovyClassLoader classLoader = new GroovyClassLoader(ScriptingUtils.class.getClassLoader(), new CompilerConfiguration(), true);
final Class<T> clazz = classLoader.parseClass(script);
LOGGER.debug("Preparing constructor arguments [{}] for resource [{}]", args, resource);
final Constructor<T> ctor = clazz.getDeclaredConstructor(constructorArgs);
final T result = ctor.newInstance(args);
if (result != null && !expectedType.isAssignableFrom(result.getClass())) {
throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + expectedType);
}
return result;
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
use of groovy.lang.GroovyClassLoader in project cas by apereo.
the class ScriptingUtils method getGroovyResult.
private static <T> T getGroovyResult(final Resource groovyScript, final String methodName, final Object[] args, final Class<T> clazz, final ClassLoader parent) {
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.getDeclaredConstructor().newInstance();
LOGGER.trace("Executing groovy script's [{}] method, with parameters [{}]", methodName, args);
final Object result = groovyObject.invokeMethod(methodName, args);
LOGGER.trace("Results returned by the groovy script are [{}]", result);
if (result != null && !clazz.isAssignableFrom(result.getClass())) {
throw new ClassCastException("Result [" + result + " is of type " + result.getClass() + " when we were expecting " + clazz);
}
return (T) result;
}
LOGGER.trace("Groovy script at [{}] does not exist", groovyScript);
} catch (final Exception e) {
LOGGER.error(e.getMessage(), e);
}
return null;
}
Aggregations