Java Code Examples for groovy.lang.GroovyClassLoader#loadClass()
The following examples show how to use
groovy.lang.GroovyClassLoader#loadClass() .
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: JUnit5Runner.java From groovy with Apache License 2.0 | 6 votes |
/** * 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 2
Source File: TestNgRunner.java From groovy with Apache License 2.0 | 6 votes |
/** * 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; }
Example 3
Source File: TestNgRunner.java From groovy with Apache License 2.0 | 6 votes |
/** * 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 4
Source File: DefaultRunners.java From groovy with Apache License 2.0 | 6 votes |
/** * 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 5
Source File: GroovyUtil.java From scipio-erp with Apache License 2.0 | 5 votes |
/** * @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<?> loadClass(String path) throws ClassNotFoundException, IOException { if (!baseScriptInitialized) { initBaseScript(); } // SCIPIO GroovyClassLoader groovyClassLoader = new GroovyClassLoader(); Class<?> classLoader = groovyClassLoader.loadClass(path); groovyClassLoader.close(); return classLoader; }
Example 6
Source File: JUnit5Runner.java From groovy with Apache License 2.0 | 5 votes |
private boolean tryLoadClass(String name, GroovyClassLoader loader) { try { loader.loadClass(name); return true; } catch (ClassNotFoundException ignore) { // fall through } return false; }
Example 7
Source File: DefaultRunners.java From groovy with Apache License 2.0 | 5 votes |
/** * Utility method to check through reflection if the class appears to be a * JUnit 3.8.x test, i.e. checks if it extends JUnit 3.8.x's TestCase. * * @param scriptClass the class we want to check * @param loader the class loader * @return true if the class appears to be a test */ @Override public boolean canRun(Class<?> scriptClass, GroovyClassLoader loader) { try { Class<?> testCaseClass = loader.loadClass("junit.framework.TestCase"); return testCaseClass.isAssignableFrom(scriptClass); } catch (Throwable e) { return false; } }
Example 8
Source File: DefaultRunners.java From groovy with Apache License 2.0 | 5 votes |
/** * Utility method to check through reflection if the class appears to be a * JUnit 3.8.x test suite, i.e. checks if it extends JUnit 3.8.x's TestSuite. * * @param scriptClass the class we want to check * @param loader the class loader * @return true if the class appears to be a test */ @Override public boolean canRun(Class<?> scriptClass, GroovyClassLoader loader) { try { Class<?> testSuiteClass = loader.loadClass("junit.framework.TestSuite"); return testSuiteClass.isAssignableFrom(scriptClass); } catch (Throwable e) { return false; } }
Example 9
Source File: ClassNodeResolver.java From groovy with Apache License 2.0 | 5 votes |
/** * Search for classes using class loading */ private static LookupResult findByClassLoading(String name, CompilationUnit compilationUnit, GroovyClassLoader loader) { Class cls; try { // NOTE: it's important to do no lookup against script files // here since the GroovyClassLoader would create a new CompilationUnit cls = loader.loadClass(name, false, true); } catch (ClassNotFoundException cnfe) { LookupResult lr = tryAsScript(name, compilationUnit, null); return lr; } catch (CompilationFailedException cfe) { throw new GroovyBugError("The lookup for " + name + " caused a failed compilation. There should not have been any compilation from this call.", cfe); } //TODO: the case of a NoClassDefFoundError needs a bit more research // a simple recompilation is not possible it seems. The current class // we are searching for is there, so we should mark that somehow. // Basically the missing class needs to be completely compiled before // we can again search for the current name. /*catch (NoClassDefFoundError ncdfe) { cachedClasses.put(name,SCRIPT); return false; }*/ if (cls == null) return null; //NOTE: we might return false here even if we found a class, // because we want to give a possible script a chance to // recompile. This can only be done if the loader was not // the instance defining the class. ClassNode cn = ClassHelper.make(cls); if (cls.getClassLoader() != loader) { return tryAsScript(name, compilationUnit, cn); } return new LookupResult(null,cn); }
Example 10
Source File: Main.java From brooklyn-server with Apache License 2.0 | 5 votes |
/** * 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 11
Source File: DeploymentTest.java From vertx-lang-groovy with Apache License 2.0 | 5 votes |
private Class assertScript(String script) { GroovyClassLoader loader = new GroovyClassLoader(getClass().getClassLoader()); try { return loader.loadClass(getClass().getPackage().getName() + "." + script); } catch (ClassNotFoundException e) { AssertionFailedError afe = new AssertionFailedError(); afe.initCause(e); throw afe; } }
Example 12
Source File: GroovyUtil.java From scipio-erp with Apache License 2.0 | 4 votes |
public static Class<?> loadClass(String path, GroovyClassLoader groovyClassLoader) throws ClassNotFoundException, IOException { // SCIPIO if (!baseScriptInitialized) { initBaseScript(); } // SCIPIO return groovyClassLoader.loadClass(path); }
Example 13
Source File: ASTTransformationVisitor.java From groovy with Apache License 2.0 | 4 votes |
private static void addPhaseOperationsForGlobalTransforms(CompilationUnit compilationUnit, Map<String, URL> transformNames, boolean isFirstScan) { GroovyClassLoader transformLoader = compilationUnit.getTransformLoader(); for (Map.Entry<String, URL> entry : transformNames.entrySet()) { try { Class<?> gTransClass = transformLoader.loadClass(entry.getKey(), false, true, false); GroovyASTTransformation transformAnnotation = gTransClass.getAnnotation(GroovyASTTransformation.class); if (transformAnnotation == null) { compilationUnit.getErrorCollector().addWarning(new WarningMessage( WarningMessage.POSSIBLE_ERRORS, "Transform Class " + entry.getKey() + " is specified as a global transform in " + entry.getValue().toExternalForm() + " but it is not annotated by " + GroovyASTTransformation.class.getName() + " the global transform associated with it may fail and cause the compilation to fail.", null, null)); continue; } if (ASTTransformation.class.isAssignableFrom(gTransClass)) { ASTTransformation instance = (ASTTransformation) gTransClass.getDeclaredConstructor().newInstance(); if (instance instanceof CompilationUnitAware) { ((CompilationUnitAware) instance).setCompilationUnit(compilationUnit); } CompilationUnit.ISourceUnitOperation suOp = source -> instance.visit(new ASTNode[]{source.getAST()}, source); if (isFirstScan) { compilationUnit.addPhaseOperation(suOp, transformAnnotation.phase().getPhaseNumber()); } else { compilationUnit.addNewPhaseOperation(suOp, transformAnnotation.phase().getPhaseNumber()); } } else { compilationUnit.getErrorCollector().addError(new SimpleMessage( "Transform Class " + entry.getKey() + " specified at " + entry.getValue().toExternalForm() + " is not an ASTTransformation.", null)); } } catch (Exception e) { Throwable effectiveException = e instanceof InvocationTargetException ? e.getCause() : e; compilationUnit.getErrorCollector().addError(new SimpleMessage( "Could not instantiate global transform class " + entry.getKey() + " specified at " + entry.getValue().toExternalForm() + " because of exception " + effectiveException.toString(), null)); } } }