use of javax.tools.JavaFileManager in project symmetric-ds by JumpMind.
the class SimpleClassCompiler method getCompiledClass.
public Object getCompiledClass(String javaCode) throws Exception {
Integer id = javaCode.hashCode();
Object javaObject = objectMap.get(id);
if (javaObject == null) {
String className = getNextClassName();
String origClassName = null;
Pattern pattern = Pattern.compile(REGEX_CLASS);
Matcher matcher = pattern.matcher(javaCode);
if (matcher.find()) {
origClassName = matcher.group(1);
}
javaCode = javaCode.replaceAll(REGEX_CLASS, "public class " + className);
log.info("Compiling class '" + origClassName + "'");
if (log.isDebugEnabled()) {
log.debug("Compiling code: \n" + javaCode);
}
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
if (compiler == null) {
throw new SimpleClassCompilerException("Missing Java compiler: the JDK is required for compiling classes.");
}
JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
DiagnosticCollector<JavaFileObject> diag = new DiagnosticCollector<JavaFileObject>();
List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>();
javaFiles.add(new JavaObjectFromString(className, javaCode));
Boolean success = compiler.getTask(null, fileManager, diag, null, null, javaFiles).call();
if (success) {
log.debug("Compilation has succeeded");
Class<?> clazz = fileManager.getClassLoader(null).loadClass(className);
if (clazz != null) {
javaObject = clazz.newInstance();
objectMap.put(id, javaObject);
} else {
throw new SimpleClassCompilerException("The '" + className + "' class could not be located");
}
} else {
log.error("Compilation of '" + origClassName + "' failed");
for (Diagnostic diagnostic : diag.getDiagnostics()) {
log.error(origClassName + " at line " + diagnostic.getLineNumber() + ", column " + diagnostic.getColumnNumber() + ": " + diagnostic.getMessage(null));
}
throw new SimpleClassCompilerException(diag.getDiagnostics());
}
}
return javaObject;
}
use of javax.tools.JavaFileManager in project ceylon-compiler by ceylon.
the class JavacProcessingEnvironment method initProcessorIterator.
private void initProcessorIterator(Context context, Iterable<? extends Processor> processors) {
Log log = Log.instance(context);
Iterator<? extends Processor> processorIterator;
if (options.isSet(XPRINT)) {
try {
Processor processor = PrintingProcessor.class.newInstance();
processorIterator = List.of(processor).iterator();
} catch (Throwable t) {
AssertionError assertError = new AssertionError("Problem instantiating PrintingProcessor.");
assertError.initCause(t);
throw assertError;
}
} else if (processors != null) {
processorIterator = processors.iterator();
} else {
String processorNames = options.get(PROCESSOR);
JavaFileManager fileManager = context.get(JavaFileManager.class);
try {
// If processorpath is not explicitly set, use the classpath.
processorClassLoader = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH) ? fileManager.getClassLoader(ANNOTATION_PROCESSOR_PATH) : fileManager.getClassLoader(CLASS_PATH);
/*
* If the "-processor" option is used, search the appropriate
* path for the named class. Otherwise, use a service
* provider mechanism to create the processor iterator.
*/
if (processorNames != null) {
processorIterator = new NameProcessIterator(processorNames, processorClassLoader, log);
} else {
processorIterator = new ServiceIterator(processorClassLoader, log);
}
} catch (SecurityException e) {
/*
* A security exception will occur if we can't create a classloader.
* Ignore the exception if, with hindsight, we didn't need it anyway
* (i.e. no processor was specified either explicitly, or implicitly,
* in service configuration file.) Otherwise, we cannot continue.
*/
processorIterator = handleServiceLoaderUnavailability("proc.cant.create.loader", e);
}
}
discoveredProcs = new DiscoveredProcessors(processorIterator);
}
use of javax.tools.JavaFileManager in project neo4j by neo4j.
the class DbStructureInvocationTracingAcceptanceTest method compile.
private <T> T compile(String className, String source, CompilationListener<T> listener) {
JavaCompiler systemCompiler = ToolProvider.getSystemJavaCompiler();
JavaFileManager manager = new InMemFileManager();
DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
Iterable<? extends JavaFileObject> sources = Arrays.asList(new InMemSource(className, source));
CompilationTask task = systemCompiler.getTask(null, manager, diagnosticsCollector, null, null, sources);
Boolean success = task.call();
return listener.compiled(success, manager, diagnosticsCollector.getDiagnostics());
}
use of javax.tools.JavaFileManager in project geode by apache.
the class ClassBuilder method compileClass.
/**
* Compile the provided class. The className may have a package separated by /. For example:
* my/package/myclass
*
* @param className Name of the class to compile.
* @param classCode Plain text contents of the class
* @return The byte contents of the compiled class.
* @throws IOException
*/
public byte[] compileClass(final String className, final String classCode) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
OutputStreamJavaFileManager<JavaFileManager> fileManager = new OutputStreamJavaFileManager<JavaFileManager>(javaCompiler.getStandardFileManager(null, null, null), byteArrayOutputStream);
List<JavaFileObject> fileObjects = new ArrayList<JavaFileObject>();
fileObjects.add(new JavaSourceFromString(className, classCode));
List<String> options = Arrays.asList("-classpath", this.classPath);
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
if (!javaCompiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call()) {
StringBuilder errorMsg = new StringBuilder();
for (Diagnostic d : diagnostics.getDiagnostics()) {
String err = String.format("Compilation error: Line %d - %s%n", d.getLineNumber(), d.getMessage(null));
errorMsg.append(err);
System.err.print(err);
}
throw new IOException(errorMsg.toString());
}
return byteArrayOutputStream.toByteArray();
}
use of javax.tools.JavaFileManager in project ceylon-compiler by ceylon.
the class JavacProcessingEnvironment method handleServiceLoaderUnavailability.
/**
* Returns an empty processor iterator if no processors are on the
* relevant path, otherwise if processors are present, logs an
* error. Called when a service loader is unavailable for some
* reason, either because a service loader class cannot be found
* or because a security policy prevents class loaders from being
* created.
*
* @param key The resource key to use to log an error message
* @param e If non-null, pass this exception to Abort
*/
private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
JavaFileManager fileManager = context.get(JavaFileManager.class);
if (fileManager instanceof JavacFileManager) {
StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
Iterable<? extends File> workingPath = fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH) ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH) : standardFileManager.getLocation(CLASS_PATH);
if (needClassLoader(options.get(PROCESSOR), workingPath))
handleException(key, e);
} else {
handleException(key, e);
}
java.util.List<Processor> pl = Collections.emptyList();
return pl.iterator();
}
Aggregations