Search in sources :

Example 21 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException 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);
            }
        }
    }
}
Also used : Closure(groovy.lang.Closure) GroovyBugError(org.codehaus.groovy.GroovyBugError) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) GroovyClassLoader(groovy.lang.GroovyClassLoader) CompilerConfiguration(org.codehaus.groovy.control.CompilerConfiguration) GroovyClassLoader(groovy.lang.GroovyClassLoader) ImportCustomizer(org.codehaus.groovy.control.customizers.ImportCustomizer) Binding(groovy.lang.Binding) InputStreamReader(java.io.InputStreamReader) Constructor(java.lang.reflect.Constructor) InputStream(java.io.InputStream) SimpleMessage(org.codehaus.groovy.control.messages.SimpleMessage) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InvocationTargetException(java.lang.reflect.InvocationTargetException) GroovyShell(groovy.lang.GroovyShell)

Example 22 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException in project ratpack by ratpack.

the class TextTemplateCompiler method compile.

public CompiledTextTemplate compile(ByteBuf templateSource, String name) throws CompilationFailedException, IOException {
    ByteBuf scriptSource = byteBufAllocator.buffer(templateSource.capacity());
    parser.parse(templateSource, scriptSource);
    String scriptSourceString = scriptSource.toString(CharsetUtil.UTF_8);
    scriptSource.release();
    if (verbose && logger.isInfoEnabled()) {
        logger.info("\n-- script source --\n" + scriptSourceString + "\n-- script end --\n");
    }
    try {
        Class<DefaultTextTemplateScript> scriptClass = scriptEngine.compile(name, scriptSourceString);
        return new CompiledTextTemplate(name, scriptClass);
    } catch (Exception e) {
        throw new InvalidTemplateException(name, "compilation failure", e);
    }
}
Also used : ByteBuf(io.netty.buffer.ByteBuf) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException)

Example 23 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException in project spock by spockframework.

the class ConfigurationScriptLoader method loadScriptFromFileSystemLocation.

@Nullable
private DelegatingScript loadScriptFromFileSystemLocation(String location) {
    File file = new File(location);
    try {
        if (!file.exists())
            return null;
    } catch (AccessControlException e) {
        // so let's just assume it's not there and continue
        return null;
    }
    GroovyShell shell = createShell();
    try {
        return (DelegatingScript) shell.parse(file);
    } catch (IOException e) {
        throw new ConfigurationException("Error reading configuration script '%s'", location);
    } catch (CompilationFailedException e) {
        throw new ConfigurationException("Error compiling configuration script '%s'", location);
    }
}
Also used : ConfigurationException(spock.config.ConfigurationException) DelegatingScript(org.spockframework.builder.DelegatingScript) AccessControlException(java.security.AccessControlException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) File(java.io.File) Nullable(org.spockframework.util.Nullable)

Example 24 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException in project opennms by OpenNMS.

the class SeleniumMonitor method poll.

@Override
public PollStatus poll(MonitoredService svc, Map<String, Object> parameters) {
    PollStatus serviceStatus = PollStatus.unavailable("Poll not completed yet");
    TimeoutTracker tracker = new TimeoutTracker(parameters, DEFAULT_SEQUENCE_RETRY, DEFAULT_TIMEOUT);
    for (tracker.reset(); tracker.shouldRetry() && !serviceStatus.isAvailable(); tracker.nextAttempt()) {
        String seleniumTestFilename = getGroovyFilename(parameters);
        try {
            Map<String, Number> responseTimes = new HashMap<String, Number>();
            responseTimes.put(PollStatus.PROPERTY_RESPONSE_TIME, Double.NaN);
            tracker.startAttempt();
            Result result = runTest(getBaseUrl(parameters, svc), getTimeout(parameters), createGroovyClass(seleniumTestFilename));
            double responseTime = tracker.elapsedTimeInMillis();
            responseTimes.put(PollStatus.PROPERTY_RESPONSE_TIME, responseTime);
            if (result.wasSuccessful()) {
                serviceStatus = PollStatus.available();
                serviceStatus.setProperties(responseTimes);
            } else {
                serviceStatus = PollStatus.unavailable(getFailureMessage(result, svc));
            }
        } catch (CompilationFailedException e) {
            serviceStatus = PollStatus.unavailable("Selenium page sequence attempt on:" + svc.getIpAddr() + " failed : selenium-test compilation error " + e.getMessage());
            String reason = "Selenium sequence failed: CompilationFailedException" + e.getMessage();
            SeleniumMonitor.LOG.debug(reason);
            PollStatus.unavailable(reason);
        } catch (IOException e) {
            serviceStatus = PollStatus.unavailable("Selenium page sequence attempt on " + svc.getIpAddr() + " failed: IOException occurred, failed to find selenium-test: " + seleniumTestFilename);
            String reason = "Selenium sequence failed: IOException: " + e.getMessage();
            SeleniumMonitor.LOG.debug(reason);
            PollStatus.unavailable(reason);
        } catch (Exception e) {
            serviceStatus = PollStatus.unavailable("Selenium page sequence attempt on " + svc.getIpAddr() + " failed:\n" + e.getMessage());
            String reason = "Selenium sequence failed: Exception: " + e.getMessage();
            SeleniumMonitor.LOG.debug(reason);
            PollStatus.unavailable(reason);
        }
    }
    return serviceStatus;
}
Also used : PollStatus(org.opennms.netmgt.poller.PollStatus) TimeoutTracker(org.opennms.core.utils.TimeoutTracker) HashMap(java.util.HashMap) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) IOException(java.io.IOException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) Result(org.junit.runner.Result)

Example 25 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException in project indy by Commonjava.

the class ScriptEngine method parseStandardScriptInstance.

/**
     * Provide a standard set of places to store common types of scripts used throughout Indy, such as
     * {@link org.commonjava.indy.model.core.ArtifactStore} creators. This is better from a config maintenance
     * perspective than having these spread out across the whole data/ subdirectory structure, particularly since it's
     * likely if one script needs to be revised, they all will.
     *
     * If the script doesn't exist in the data/scripts directory structure, this method will search the classpath
     * for the same path (scripts/[type]/[name]).
     */
public <T> T parseStandardScriptInstance(final StandardScriptType scriptType, final String name, final Class<T> type, boolean processCdiInjections) throws IndyGroovyException {
    DataFile dataFile = dataFileManager.getDataFile(SCRIPTS_SUBDIR, scriptType.subdir(), name);
    String script = null;
    if (dataFile == null || !dataFile.exists() || dataFile.isDirectory()) {
        URL resource = Thread.currentThread().getContextClassLoader().getResource(Paths.get(SCRIPTS_SUBDIR, scriptType.subdir(), name).toString());
        if (resource == null) {
            throw new IndyGroovyException("Cannot read standard script from: %s/%s/%s", SCRIPTS_SUBDIR, scriptType.subdir(), name);
        } else {
            Logger logger = LoggerFactory.getLogger(getClass());
            logger.debug("Loading script: {}/{}/{} for class: {} from classpath resource: {}", SCRIPTS_SUBDIR, scriptType, name, type.getName(), resource);
            try (InputStream in = resource.openStream()) {
                script = IOUtils.toString(in);
            } catch (IOException e) {
                throw new IndyGroovyException("Cannot read standard script from classpath: %s/%s/%s. Reason: %s", e, SCRIPTS_SUBDIR, scriptType.subdir(), name, e.getMessage());
            }
        }
    } else {
        try {
            script = dataFile.readString();
        } catch (IOException e) {
            throw new IndyGroovyException("Failed to read standard script from: %s/%s. Reason: %s", e, scriptType.subdir(), name, e.getMessage());
        }
    }
    Object instance = null;
    try {
        final Class<?> clazz = groovyClassloader.parseClass(script);
        instance = clazz.newInstance();
        T result = type.cast(instance);
        return processCdiInjections ? inject(result) : result;
    } catch (final CompilationFailedException e) {
        throw new IndyGroovyException("Failed to compile groovy script: '%s'. Reason: %s", e, script, e.getMessage());
    } catch (final InstantiationException | IllegalAccessException e) {
        throw new IndyGroovyException("Cannot instantiate class parsed from script: '%s'. Reason: %s", e, script, e.getMessage());
    } catch (final ClassCastException e) {
        throw new IndyGroovyException("Script: '%s' instance: %s cannot be cast as: %s", e, script, instance, type.getName());
    }
}
Also used : InputStream(java.io.InputStream) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) Logger(org.slf4j.Logger) URL(java.net.URL) DataFile(org.commonjava.indy.subsys.datafile.DataFile)

Aggregations

CompilationFailedException (org.codehaus.groovy.control.CompilationFailedException)26 IOException (java.io.IOException)14 GroovyClassLoader (groovy.lang.GroovyClassLoader)7 Script (groovy.lang.Script)5 ClassNode (org.codehaus.groovy.ast.ClassNode)5 CompilationUnit (org.codehaus.groovy.control.CompilationUnit)5 File (java.io.File)4 GeneratorContext (org.codehaus.groovy.classgen.GeneratorContext)4 SourceUnit (org.codehaus.groovy.control.SourceUnit)4 GroovyShell (groovy.lang.GroovyShell)3 InputStream (java.io.InputStream)3 URL (java.net.URL)3 CompilerConfiguration (org.codehaus.groovy.control.CompilerConfiguration)3 Binding (groovy.lang.Binding)2 Closure (groovy.lang.Closure)2 GroovyObject (groovy.lang.GroovyObject)2 GroovyRuntimeException (groovy.lang.GroovyRuntimeException)2 MissingMethodException (groovy.lang.MissingMethodException)2 Node (groovy.util.Node)2 InputStreamReader (java.io.InputStreamReader)2