Search in sources :

Example 6 with JavaFileManager

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;
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) FileObject(javax.tools.FileObject) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 7 with JavaFileManager

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);
}
Also used : Log(com.sun.tools.javac.util.Log) JavaFileManager(javax.tools.JavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager)

Example 8 with JavaFileManager

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());
}
Also used : SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) JavaCompiler(javax.tools.JavaCompiler) DiagnosticCollector(javax.tools.DiagnosticCollector) CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 9 with JavaFileManager

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();
}
Also used : JavaFileManager(javax.tools.JavaFileManager) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) ArrayList(java.util.ArrayList) JavaCompiler(javax.tools.JavaCompiler) Diagnostic(javax.tools.Diagnostic) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) DiagnosticCollector(javax.tools.DiagnosticCollector)

Example 10 with JavaFileManager

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();
}
Also used : JavacFileManager(com.sun.tools.javac.file.JavacFileManager) java.util(java.util) javax.lang.model.util(javax.lang.model.util) JavaFileManager(javax.tools.JavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager) StandardJavaFileManager(javax.tools.StandardJavaFileManager)

Aggregations

JavaFileManager (javax.tools.JavaFileManager)10 JavaCompiler (javax.tools.JavaCompiler)5 JavaFileObject (javax.tools.JavaFileObject)5 StandardJavaFileManager (javax.tools.StandardJavaFileManager)5 IOException (java.io.IOException)4 ForwardingJavaFileManager (javax.tools.ForwardingJavaFileManager)4 DiagnosticCollector (javax.tools.DiagnosticCollector)3 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)3 InputStream (java.io.InputStream)2 Field (java.lang.reflect.Field)2 ArrayList (java.util.ArrayList)2 Diagnostic (javax.tools.Diagnostic)2 ImmutableList (com.google.common.collect.ImmutableList)1 BugChecker (com.google.errorprone.bugpatterns.BugChecker)1 JavacFileManager (com.sun.tools.javac.file.JavacFileManager)1 Context (com.sun.tools.javac.util.Context)1 Log (com.sun.tools.javac.util.Log)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 File (java.io.File)1 InputStreamReader (java.io.InputStreamReader)1