Search in sources :

Example 11 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException in project groovy-core by groovy.

the class XmlTemplateEngine method createTemplate.

public Template createTemplate(Reader reader) throws CompilationFailedException, ClassNotFoundException, IOException {
    Node root;
    try {
        root = xmlParser.parse(reader);
    } catch (SAXException e) {
        throw new RuntimeException("Parsing XML source failed.", e);
    }
    if (root == null) {
        throw new IOException("Parsing XML source failed: root node is null.");
    }
    StringWriter writer = new StringWriter(1024);
    writer.write("/* Generated by XmlTemplateEngine */\n");
    new GspPrinter(new PrintWriter(writer), indentation).print(root);
    Script script;
    try {
        script = groovyShell.parse(writer.toString(), "XmlTemplateScript" + counter++ + ".groovy");
    } catch (Exception e) {
        throw new GroovyRuntimeException("Failed to parse template script (your template may contain an error or be trying to use expressions not currently supported): " + e.getMessage());
    }
    return new XmlTemplate(script);
}
Also used : Script(groovy.lang.Script) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) StringWriter(java.io.StringWriter) Node(groovy.util.Node) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) IOException(java.io.IOException) GroovyRuntimeException(groovy.lang.GroovyRuntimeException) IOException(java.io.IOException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) SAXException(org.xml.sax.SAXException) PrintWriter(java.io.PrintWriter)

Example 12 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException in project intellij-community by JetBrains.

the class ScriptSupport method checkValidScript.

public static String checkValidScript(String scriptText) {
    try {
        final File scriptFile = new File(scriptText);
        final GroovyShell shell = new GroovyShell();
        final Script script = scriptFile.exists() ? shell.parse(scriptFile) : shell.parse(scriptText);
        return null;
    } catch (IOException e) {
        return e.getMessage();
    } catch (MultipleCompilationErrorsException e) {
        final ErrorCollector errorCollector = e.getErrorCollector();
        final List<Message> errors = errorCollector.getErrors();
        for (Message error : errors) {
            if (error instanceof SyntaxErrorMessage) {
                final SyntaxErrorMessage errorMessage = (SyntaxErrorMessage) error;
                final SyntaxException cause = errorMessage.getCause();
                return cause.getMessage();
            }
        }
        return e.getMessage();
    } catch (CompilationFailedException ex) {
        return ex.getLocalizedMessage();
    }
}
Also used : Script(groovy.lang.Script) Message(org.codehaus.groovy.control.messages.Message) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) SyntaxErrorMessage(org.codehaus.groovy.control.messages.SyntaxErrorMessage) SyntaxException(org.codehaus.groovy.syntax.SyntaxException) ErrorCollector(org.codehaus.groovy.control.ErrorCollector) ArrayList(java.util.ArrayList) List(java.util.List) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) MultipleCompilationErrorsException(org.codehaus.groovy.control.MultipleCompilationErrorsException) File(java.io.File) GroovyShell(groovy.lang.GroovyShell)

Example 13 with CompilationFailedException

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

the class TemplatingEngine method getTemplate.

// TODO Cache these...though this will hurt hot-reloading. Perhaps a debug mode configuration?
private Template getTemplate(final String acceptHeader, final String templateKey) throws IndyGroovyException {
    final String accept = (acceptHeader == null ? "" : acceptHeader.replace('/', '_') + "/");
    try {
        final String filename = accept + templateKey + ".groovy";
        final DataFile templateFile = manager.getDataFile(TEMPLATES, filename);
        logger.info("Looking for template: {} for ACCEPT header: {} in: {}", templateKey, acceptHeader, templateFile);
        Template template;
        if (templateFile.exists() && !templateFile.isDirectory()) {
            template = engine.createTemplate(templateFile.readString());
        } else {
            final String urlpath = TEMPLATES + "/" + accept + templateKey + ".groovy";
            logger.info("Looking for template: {} for ACCEPT header: {} in: {}", templateKey, acceptHeader, urlpath);
            final URL u = Thread.currentThread().getContextClassLoader().getResource(urlpath);
            template = u == null ? null : engine.createTemplate(u);
        }
        if (template == null) {
            throw new IndyGroovyException("Failed to locate template: %s (with ACCEPT header: %s)", templateKey, acceptHeader);
        }
        return template;
    } catch (final CompilationFailedException e) {
        throw new IndyGroovyException("Failed to compile template: %s. Reason: %s", e, templateKey, e.getMessage());
    } catch (final ClassNotFoundException e) {
        throw new IndyGroovyException("Failed to compile template: %s. Reason: %s", e, templateKey, e.getMessage());
    } catch (final IOException e) {
        throw new IndyGroovyException("Failed to read template: %s. Reason: %s", e, templateKey, e.getMessage());
    }
}
Also used : DataFile(org.commonjava.indy.subsys.datafile.DataFile) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException) IOException(java.io.IOException) URL(java.net.URL) Template(groovy.text.Template)

Example 14 with CompilationFailedException

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

the class SubsetScriptTransformer method call.

public void call(SourceUnit source) throws CompilationFailedException {
    AstUtils.filterAndTransformStatements(source, transformer);
    // Filter imported classes which are not available yet
    Iterator<ImportNode> iter = source.getAST().getImports().iterator();
    while (iter.hasNext()) {
        ImportNode importedClass = iter.next();
        if (!AstUtils.isVisible(source, importedClass.getClassName())) {
            try {
                Field field = ModuleNode.class.getDeclaredField("imports");
                field.setAccessible(true);
                Map value = (Map) field.get(source.getAST());
                value.remove(importedClass.getAlias());
            } catch (Exception e) {
                throw UncheckedException.throwAsUncheckedException(e);
            }
        }
    }
    iter = source.getAST().getStaticImports().values().iterator();
    while (iter.hasNext()) {
        ImportNode importedClass = iter.next();
        if (!AstUtils.isVisible(source, importedClass.getClassName())) {
            iter.remove();
        }
    }
    iter = source.getAST().getStaticStarImports().values().iterator();
    while (iter.hasNext()) {
        ImportNode importedClass = iter.next();
        if (!AstUtils.isVisible(source, importedClass.getClassName())) {
            iter.remove();
        }
    }
    ClassNode scriptClass = AstUtils.getScriptClass(source);
    // Remove all the classes other than the main class
    Iterator<ClassNode> classes = source.getAST().getClasses().iterator();
    while (classes.hasNext()) {
        ClassNode classNode = classes.next();
        if (classNode != scriptClass) {
            classes.remove();
        }
    }
    // Remove all the methods from the main class
    if (scriptClass != null) {
        for (MethodNode methodNode : new ArrayList<MethodNode>(scriptClass.getMethods())) {
            if (!methodNode.getName().equals("run")) {
                AstUtils.removeMethod(scriptClass, methodNode);
            }
        }
    }
    source.getAST().getMethods().clear();
}
Also used : Field(java.lang.reflect.Field) ClassNode(org.codehaus.groovy.ast.ClassNode) MethodNode(org.codehaus.groovy.ast.MethodNode) ArrayList(java.util.ArrayList) ImportNode(org.codehaus.groovy.ast.ImportNode) Map(java.util.Map) UncheckedException(org.gradle.internal.UncheckedException) CompilationFailedException(org.codehaus.groovy.control.CompilationFailedException)

Example 15 with CompilationFailedException

use of org.codehaus.groovy.control.CompilationFailedException in project groovy-core by groovy.

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)

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