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);
}
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();
}
}
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());
}
}
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();
}
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);
}
}
}
}
Aggregations