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