javax.annotation.processing.Processor Java Examples

The following examples show how to use javax.annotation.processing.Processor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: hottub   Author: dsrg-uoft   File: JavaCompiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if we should process annotations.
 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
 * to catch doc comments, and set keepComments so the parser records them in
 * the compilation unit.
 *
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void initProcessAnnotations(Iterable<? extends Processor> processors) {
    // Process annotations if processing is not disabled and there
    // is at least one Processor available.
    if (options.isSet(PROC, "none")) {
        processAnnotations = false;
    } else if (procEnvImpl == null) {
        procEnvImpl = JavacProcessingEnvironment.instance(context);
        procEnvImpl.setProcessors(processors);
        processAnnotations = procEnvImpl.atLeastOneProcessor();

        if (processAnnotations) {
            options.put("save-parameter-names", "save-parameter-names");
            reader.saveParameterNames = true;
            keepComments = true;
            genEndPos = true;
            if (!taskListener.isEmpty())
                taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
            deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
        } else { // free resources
            procEnvImpl.close();
        }
    }
}
 
Example #2
Source Project: TencentKona-8   Author: Tencent   File: MalformedAnnotationProcessorTests.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testBadAnnotationProcessor(Path base) throws Exception {
    Path apDir = base.resolve("annoprocessor");
    ToolBox.writeFile(apDir.resolve("META-INF").resolve("services")
                      .resolve(Processor.class.getCanonicalName()), "BadAnnoProcessor");
    ToolBox.writeFile(apDir.resolve("BadAnnoProcessor.class"), "badannoprocessor");

    Path classes = base.resolve("classes");
    Files.createDirectories(classes);

    List<String> actualErrors = new ArrayList<>();
    ToolBox.JavaToolArgs args = new ToolBox.JavaToolArgs();
    args.setSources("package test; public class Test {}")
        .appendArgs("-XDrawDiagnostics",
                    "-d", classes.toString(),
                    "-classpath", "",
                    "-processorpath", apDir.toString())
        .set(ToolBox.Expect.FAIL)
        .setErrOutput(actualErrors);
    ToolBox.javac(args);

    System.out.println(actualErrors.get(0));
    if (!actualErrors.get(0).contains("- compiler.err.proc.cant.load.class: " +
                                      "Incompatible magic value")) {
        throw new AssertionError("Unexpected errors reported: " + actualErrors);
    }
}
 
Example #3
Source Project: TencentKona-8   Author: Tencent   File: MalformedAnnotationProcessorTests.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testMissingAnnotationProcessor(Path base) throws Exception {
    Path apDir = base.resolve("annoprocessor");
    ToolBox.writeFile(apDir.resolve("META-INF").resolve("services").resolve(Processor.class.getCanonicalName()),
                 "MissingAnnoProcessor");

    Path classes = base.resolve("classes");
    Files.createDirectories(classes);

    List<String> actualErrors = new ArrayList<>();
    ToolBox.JavaToolArgs args = new ToolBox.JavaToolArgs();
    args.setSources("package test; public class Test {}")
        .appendArgs("-XDrawDiagnostics",
                    "-d", classes.toString(),
                    "-classpath", "",
                    "-processorpath", apDir.toString())
        .set(ToolBox.Expect.FAIL)
        .setErrOutput(actualErrors);
    ToolBox.javac(args);

    if (!actualErrors.get(0).contains("- compiler.err.proc.bad.config.file: " +
        "javax.annotation.processing.Processor: Provider MissingAnnoProcessor not found")) {
        throw new AssertionError("Unexpected errors reported: " + actualErrors);
    }
}
 
Example #4
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: JavaCompiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if we should process annotations.
 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
 * to catch doc comments, and set keepComments so the parser records them in
 * the compilation unit.
 *
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void initProcessAnnotations(Iterable<? extends Processor> processors) {
    // Process annotations if processing is not disabled and there
    // is at least one Processor available.
    if (options.isSet(PROC, "none")) {
        processAnnotations = false;
    } else if (procEnvImpl == null) {
        procEnvImpl = JavacProcessingEnvironment.instance(context);
        procEnvImpl.setProcessors(processors);
        processAnnotations = procEnvImpl.atLeastOneProcessor();

        if (processAnnotations) {
            options.put("save-parameter-names", "save-parameter-names");
            reader.saveParameterNames = true;
            keepComments = true;
            genEndPos = true;
            if (!taskListener.isEmpty())
                taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
            deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
        } else { // free resources
            procEnvImpl.close();
        }
    }
}
 
Example #5
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: MalformedAnnotationProcessorTests.java    License: GNU General Public License v2.0 6 votes vote down vote up
public void testMissingAnnotationProcessor(Path base) throws Exception {
    Path apDir = base.resolve("annoprocessor");
    ToolBox.writeFile(apDir.resolve("META-INF").resolve("services").resolve(Processor.class.getCanonicalName()),
                 "MissingAnnoProcessor");

    Path classes = base.resolve("classes");
    Files.createDirectories(classes);

    List<String> actualErrors = new ArrayList<>();
    ToolBox.JavaToolArgs args = new ToolBox.JavaToolArgs();
    args.setSources("package test; public class Test {}")
        .appendArgs("-XDrawDiagnostics",
                    "-d", classes.toString(),
                    "-classpath", "",
                    "-processorpath", apDir.toString())
        .set(ToolBox.Expect.FAIL)
        .setErrOutput(actualErrors);
    ToolBox.javac(args);

    if (!actualErrors.get(0).contains("- compiler.err.proc.bad.config.file: " +
        "javax.annotation.processing.Processor: Provider MissingAnnoProcessor not found")) {
        throw new AssertionError("Unexpected errors reported: " + actualErrors);
    }
}
 
Example #6
/**
 * 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) {
    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(Option.PROCESSOR), workingPath) )
            handleException(key, e);

    } else {
        handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
}
 
Example #7
private boolean needClassLoader(String procNames, Iterable<? extends File> workingpath) {
    if (procNames != null)
        return true;

    URL[] urls = new URL[1];
    for(File pathElement : workingpath) {
        try {
            urls[0] = pathElement.toURI().toURL();
            if (ServiceProxy.hasService(Processor.class, urls))
                return true;
        } catch (MalformedURLException ex) {
            throw new AssertionError(ex);
        }
        catch (ServiceProxy.ServiceConfigurationError e) {
            log.error(Errors.ProcBadConfigFile(e.getLocalizedMessage()));
            return true;
        }
    }

    return false;
}
 
Example #8
Source Project: netbeans   Author: apache   File: APTUtils.java    License: Apache License 2.0 6 votes vote down vote up
private Collection<Processor> lookupProcessors(ClassLoader cl, boolean onScan, boolean isModule) {
    Iterable<? extends String> processorNames = aptOptions.annotationProcessorsToRun();
    if (processorNames == null) {
        processorNames = getProcessorNames(cl, isModule);
    }
    List<Processor> result = new LinkedList<Processor>();
    for (String name : processorNames) {
        try {
            Class<?> clazz = Class.forName(name, true, cl);
            Object instance = clazz.newInstance();
            if (instance instanceof Processor) {
                result.add(new ErrorToleratingProcessor((Processor) instance));
            }
        } catch (ThreadDeath td) {
            throw td;
        } catch (Throwable t) {
            LOG.log(Level.FINE, null, t);
        }
    }
    if (!onScan)
        result.addAll(HARDCODED_PROCESSORS.lookupAll(Processor.class));
    return result;
}
 
Example #9
Source Project: toothpick   Author: stephanenicolas   File: FactoryOriginatingElementTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testOriginatingElement() {
  JavaFileObject source =
      JavaFileObjects.forSourceString(
          "test.TestOriginatingElement",
          Joiner.on('\n')
              .join( //
                  "package test;", //
                  "import javax.inject.Inject;", //
                  "public class TestOriginatingElement {", //
                  "  @Inject public TestOriginatingElement() {}", //
                  "}" //
                  ));

  Iterable<? extends Processor> processors = ProcessorTestUtilities.factoryProcessors();

  assert_().about(javaSource()).that(source).processedWith(processors).compilesWithoutError();

  FactoryProcessor factoryProcessor = (FactoryProcessor) processors.iterator().next();
  TypeElement enclosingElement =
      factoryProcessor.getOriginatingElement("test.TestOriginatingElement__Factory");
  assertTrue(enclosingElement.getQualifiedName().contentEquals("test.TestOriginatingElement"));
}
 
Example #10
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: JavaCompiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if we should process annotations.
 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
 * to catch doc comments, and set keepComments so the parser records them in
 * the compilation unit.
 *
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void initProcessAnnotations(Iterable<? extends Processor> processors) {
    // Process annotations if processing is not disabled and there
    // is at least one Processor available.
    if (options.isSet(PROC, "none")) {
        processAnnotations = false;
    } else if (procEnvImpl == null) {
        procEnvImpl = JavacProcessingEnvironment.instance(context);
        procEnvImpl.setProcessors(processors);
        processAnnotations = procEnvImpl.atLeastOneProcessor();

        if (processAnnotations) {
            options.put("save-parameter-names", "save-parameter-names");
            reader.saveParameterNames = true;
            keepComments = true;
            genEndPos = true;
            if (!taskListener.isEmpty())
                taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
            deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
        } else { // free resources
            procEnvImpl.close();
        }
    }
}
 
Example #11
Source Project: openjdk-8   Author: bpupadhyaya   File: JavaCompiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Check if we should process annotations.
 * If so, and if no scanner is yet registered, then set up the DocCommentScanner
 * to catch doc comments, and set keepComments so the parser records them in
 * the compilation unit.
 *
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void initProcessAnnotations(Iterable<? extends Processor> processors) {
    // Process annotations if processing is not disabled and there
    // is at least one Processor available.
    if (options.isSet(PROC, "none")) {
        processAnnotations = false;
    } else if (procEnvImpl == null) {
        procEnvImpl = JavacProcessingEnvironment.instance(context);
        procEnvImpl.setProcessors(processors);
        processAnnotations = procEnvImpl.atLeastOneProcessor();

        if (processAnnotations) {
            options.put("save-parameter-names", "save-parameter-names");
            reader.saveParameterNames = true;
            keepComments = true;
            genEndPos = true;
            if (!taskListener.isEmpty())
                taskListener.started(new TaskEvent(TaskEvent.Kind.ANNOTATION_PROCESSING));
            deferredDiagnosticHandler = new Log.DeferredDiagnosticHandler(log);
        } else { // free resources
            procEnvImpl.close();
        }
    }
}
 
Example #12
Source Project: TencentKona-8   Author: Tencent   File: JavaCompiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Main method: compile a list of files, return all compiled classes
 *
 * @param sourceFileObjects file objects to be compiled
 * @param classnames class names to process for annotations
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void compile(List<JavaFileObject> sourceFileObjects,
                    List<String> classnames,
                    Iterable<? extends Processor> processors)
{
    if (processors != null && processors.iterator().hasNext())
        explicitAnnotationProcessingRequested = true;
    // as a JavaCompiler can only be used once, throw an exception if
    // it has been used before.
    if (hasBeenUsed)
        throw new AssertionError("attempt to reuse JavaCompiler");
    hasBeenUsed = true;

    // forcibly set the equivalent of -Xlint:-options, so that no further
    // warnings about command line options are generated from this point on
    options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
    options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);

    start_msec = now();

    try {
        initProcessAnnotations(processors);

        // These method calls must be chained to avoid memory leaks
        delegateCompiler =
            processAnnotations(
                enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
                classnames);

        delegateCompiler.compile2();
        delegateCompiler.close();
        elapsed_msec = delegateCompiler.elapsed_msec;
    } catch (Abort ex) {
        if (devVerbose)
            ex.printStackTrace(System.err);
    } finally {
        if (procEnvImpl != null)
            procEnvImpl.close();
    }
}
 
Example #13
Source Project: openjdk-8   Author: bpupadhyaya   File: Main.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Programmatic interface for main function.
 * @param args    The command line parameters.
 */
public Result compile(String[] args,
                   Context context,
                   List<JavaFileObject> fileObjects,
                   Iterable<? extends Processor> processors)
{
    return compile(args,  null, context, fileObjects, processors);
}
 
Example #14
Source Project: openjdk-8-source   Author: keerath   File: JavaCompiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Main method: compile a list of files, return all compiled classes
 *
 * @param sourceFileObjects file objects to be compiled
 * @param classnames class names to process for annotations
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void compile(List<JavaFileObject> sourceFileObjects,
                    List<String> classnames,
                    Iterable<? extends Processor> processors)
{
    if (processors != null && processors.iterator().hasNext())
        explicitAnnotationProcessingRequested = true;
    // as a JavaCompiler can only be used once, throw an exception if
    // it has been used before.
    if (hasBeenUsed)
        throw new AssertionError("attempt to reuse JavaCompiler");
    hasBeenUsed = true;

    // forcibly set the equivalent of -Xlint:-options, so that no further
    // warnings about command line options are generated from this point on
    options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
    options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);

    start_msec = now();

    try {
        initProcessAnnotations(processors);

        // These method calls must be chained to avoid memory leaks
        delegateCompiler =
            processAnnotations(
                enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
                classnames);

        delegateCompiler.compile2();
        delegateCompiler.close();
        elapsed_msec = delegateCompiler.elapsed_msec;
    } catch (Abort ex) {
        if (devVerbose)
            ex.printStackTrace(System.err);
    } finally {
        if (procEnvImpl != null)
            procEnvImpl.close();
    }
}
 
Example #15
Source Project: RADL   Author: restful-api-description-language   File: Project.java    License: Apache License 2.0 5 votes vote down vote up
public boolean apply(Processor processor) {
  ProcessingEnvironment processingEnvironment = mock(ProcessingEnvironment.class);
  when(processingEnvironment.getOptions()).thenReturn(options);
  when(processingEnvironment.getTypeUtils()).thenReturn(types);
  when(processingEnvironment.getElementUtils()).thenReturn(elements);
  processor.init(processingEnvironment);

  return processor.process(environment.getAnnotations(), environment);
}
 
Example #16
Source Project: jdk8u60   Author: chenghanpeng   File: JavacTaskImpl.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void setProcessors(Iterable<? extends Processor> processors) {
    processors.getClass(); // null check
    // not mt-safe
    if (used.get())
        throw new IllegalStateException();
    this.processors = processors;
}
 
Example #17
Source Project: helidon-build-tools   Author: oracle   File: SnakeYAMLMojo.java    License: Apache License 2.0 5 votes vote down vote up
private void analyzeClasses(Map<String, Type> types, Set<Import> imports, Map<String, List<String>> interfaces,
        Collection<Path> pathsToCommpile, String note) {
    /*
     * There should not be compilation errors, but without our own diagnostic listener any compilation errors will
     * appear in the build output. We want to suppress those because we want to gather information about the interfaces
     * and classes, not actually compile them into .class files.
     */
    DiagnosticListener<JavaFileObject> diagListener = diagnostic -> {
        debugLog(() -> diagnostic.toString());
    };

    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null);

    JavaCompiler.CompilationTask task = jc.getTask(null, fm, diagListener, null, null,
            javaFilesToCompile(fm, pathsToCommpile));
    List<Processor> procs = new ArrayList<>();
    EndpointProcessor ep = new EndpointProcessor(new EndpointScanner(types, imports, interfaces));
    procs.add(ep);
    task.setProcessors(procs);
    task.call();

    getLog().info(String.format("Types prepared for %s: %d", note, types.size()));
    debugLog(() -> String.format("Types prepared for %s: %s", note, types));
    debugLog(() -> String.format("Imports after analyzing %s: %s", note,
            imports.stream().sorted().map(Import::toString).collect(Collectors.joining(","))));
    debugLog(() -> String.format("Interface impls after analyzing %s: %s", note, interfaces));
}
 
Example #18
Source Project: hottub   Author: dsrg-uoft   File: JavaCompiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Main method: compile a list of files, return all compiled classes
 *
 * @param sourceFileObjects file objects to be compiled
 * @param classnames class names to process for annotations
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void compile(List<JavaFileObject> sourceFileObjects,
                    List<String> classnames,
                    Iterable<? extends Processor> processors)
{
    if (processors != null && processors.iterator().hasNext())
        explicitAnnotationProcessingRequested = true;
    // as a JavaCompiler can only be used once, throw an exception if
    // it has been used before.
    if (hasBeenUsed)
        throw new AssertionError("attempt to reuse JavaCompiler");
    hasBeenUsed = true;

    // forcibly set the equivalent of -Xlint:-options, so that no further
    // warnings about command line options are generated from this point on
    options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
    options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);

    start_msec = now();

    try {
        initProcessAnnotations(processors);

        // These method calls must be chained to avoid memory leaks
        delegateCompiler =
            processAnnotations(
                enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
                classnames);

        delegateCompiler.compile2();
        delegateCompiler.close();
        elapsed_msec = delegateCompiler.elapsed_msec;
    } catch (Abort ex) {
        if (devVerbose)
            ex.printStackTrace(System.err);
    } finally {
        if (procEnvImpl != null)
            procEnvImpl.close();
    }
}
 
Example #19
Source Project: java-n-IDE-for-Android   Author: shenghuntianlang   File: JavaCompiler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Main method: compile a list of files, return all compiled classes
 *
 * @param sourceFileObjects file objects to be compiled
 * @param classnames        class names to process for annotations
 * @param processors        user provided annotation processors to bypass
 *                          discovery, {@code null} means that no processors were provided
 */
public void compile(List<JavaFileObject> sourceFileObjects,
                    List<String> classnames,
                    Iterable<? extends Processor> processors) {
    if (processors != null && processors.iterator().hasNext())
        explicitAnnotationProcessingRequested = true;
    // as a JavaCompiler can only be used once, throw an exception if
    // it has been used before.
    if (hasBeenUsed)
        throw new AssertionError("attempt to reuse JavaCompiler");
    hasBeenUsed = true;

    // forcibly set the equivalent of -Xlint:-options, so that no further
    // warnings about command line options are generated from this point on
    options.put(XLINT_CUSTOM + "-" + LintCategory.OPTIONS.option, "true");
    options.remove(XLINT_CUSTOM + LintCategory.OPTIONS.option);

    start_msec = now();

    try {
        initProcessAnnotations(processors);

        // These method calls must be chained to avoid memory leaks
        delegateCompiler =
                processAnnotations(
                        enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
                        classnames);

        delegateCompiler.compile2();
        delegateCompiler.close();
        elapsed_msec = delegateCompiler.elapsed_msec;
    } catch (Abort ex) {
        if (devVerbose)
            ex.printStackTrace(System.err);
    } finally {
        if (procEnvImpl != null)
            procEnvImpl.close();
    }
}
 
Example #20
Source Project: toothpick   Author: stephanenicolas   File: ProcessorTestUtilities.java    License: Apache License 2.0 5 votes vote down vote up
static Iterable<? extends Processor> factoryProcessorsWithAdditionalTypes(String... types) {
  FactoryProcessor factoryProcessor = new FactoryProcessor();
  for (String type : types) {
    factoryProcessor.addSupportedAnnotationType(type);
  }

  return Arrays.asList(factoryProcessor);
}
 
Example #21
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: Main.java    License: GNU General Public License v2.0 5 votes vote down vote up
/** Programmatic interface for main function.
 * @param args    The command line parameters.
 */
public Result compile(String[] args,
                   Context context,
                   List<JavaFileObject> fileObjects,
                   Iterable<? extends Processor> processors)
{
    return compile(args,  null, context, fileObjects, processors);
}
 
Example #22
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: JavaCompiler.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Main method: compile a list of files, return all compiled classes
 *
 * @param sourceFileObjects file objects to be compiled
 * @param classnames class names to process for annotations
 * @param processors user provided annotation processors to bypass
 * discovery, {@code null} means that no processors were provided
 */
public void compile(List<JavaFileObject> sourceFileObjects,
                    List<String> classnames,
                    Iterable<? extends Processor> processors)
{
    if (processors != null && processors.iterator().hasNext())
        explicitAnnotationProcessingRequested = true;
    // as a JavaCompiler can only be used once, throw an exception if
    // it has been used before.
    if (hasBeenUsed)
        throw new AssertionError("attempt to reuse JavaCompiler");
    hasBeenUsed = true;

    // forcibly set the equivalent of -Xlint:-options, so that no further
    // warnings about command line options are generated from this point on
    options.put(XLINT_CUSTOM.text + "-" + LintCategory.OPTIONS.option, "true");
    options.remove(XLINT_CUSTOM.text + LintCategory.OPTIONS.option);

    start_msec = now();

    try {
        initProcessAnnotations(processors);

        // These method calls must be chained to avoid memory leaks
        delegateCompiler =
            processAnnotations(
                enterTrees(stopIfError(CompileState.PARSE, parseFiles(sourceFileObjects))),
                classnames);

        delegateCompiler.compile2();
        delegateCompiler.close();
        elapsed_msec = delegateCompiler.elapsed_msec;
    } catch (Abort ex) {
        if (devVerbose)
            ex.printStackTrace(System.err);
    } finally {
        if (procEnvImpl != null)
            procEnvImpl.close();
    }
}
 
Example #23
Source Project: Eclipse-Postfix-Code-Completion   Author: trylimits   File: ProcessorInfo.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Create a ProcessorInfo wrapping a particular Processor. The Processor must already have been
 * initialized (that is,
 * {@link Processor#init(javax.annotation.processing.ProcessingEnvironment)} must already have
 * been called). Its getSupportedXXX() methods will be called and the results will be cached.
 */
public ProcessorInfo(Processor p) 
{
	_processor = p;
	_hasBeenCalled = false;
	_supportedSourceVersion = p.getSupportedSourceVersion();
	_supportedOptions = p.getSupportedOptions();
	Set<String> supportedAnnotationTypes = p.getSupportedAnnotationTypes();
	
	boolean supportsStar = false;
	if (null != supportedAnnotationTypes && !supportedAnnotationTypes.isEmpty()) {
		StringBuilder regex = new StringBuilder();
		Iterator<String> iName = supportedAnnotationTypes.iterator();
		while (true) {
			String name = iName.next();
			supportsStar |= "*".equals(name);  //$NON-NLS-1$
			String escapedName1 = name.replace(".", "\\."); //$NON-NLS-1$ //$NON-NLS-2$
			String escapedName2 = escapedName1.replace("*", ".*"); //$NON-NLS-1$ //$NON-NLS-2$
			regex.append(escapedName2);
			if (!iName.hasNext()) {
				break;
			}
			regex.append('|');
		}
		_supportedAnnotationTypesPattern = Pattern.compile(regex.toString());
	}
	else {
		_supportedAnnotationTypesPattern = null;
	}
	_supportsStar = supportsStar;
}
 
Example #24
Source Project: javaide   Author: tranleduy2000   File: JavacTaskImpl.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void setProcessors(Iterable<? extends Processor> processors) {
    processors.getClass(); // null check
    // not mt-safe
    if (used.get())
        throw new IllegalStateException();
    this.processors = processors;
}
 
Example #25
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: MalformedAnnotationProcessorTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void testWrongClassFileVersion(Path base) throws Exception {
    Path apDir = base.resolve("annoprocessor");
    ToolBox.writeFile(apDir.resolve("META-INF").resolve("services").resolve(Processor.class.getCanonicalName()),
                 "WrongClassFileVersion");

    ToolBox.JavaToolArgs args = new ToolBox.JavaToolArgs();
    args.setSources("class WrongClassFileVersion {}")
        .appendArgs("-d", apDir.toString())
        .set(ToolBox.Expect.SUCCESS);
    ToolBox.javac(args);

    increaseMajor(apDir.resolve("WrongClassFileVersion.class"), 1);

    Path classes = base.resolve("classes");
    Files.createDirectories(classes);

    List<String> actualErrors = new ArrayList<>();
    args = new ToolBox.JavaToolArgs();
    args.setSources("package test; public class Test {}")
        .appendArgs("-XDrawDiagnostics",
                    "-d", classes.toString(),
                    "-classpath", "",
                    "-processorpath", apDir.toString())
        .set(ToolBox.Expect.FAIL)
        .setErrOutput(actualErrors);
    ToolBox.javac(args);

    if (!actualErrors.get(0).contains("- compiler.err.proc.cant.load.class: " +
        "WrongClassFileVersion has been compiled by a more recent version")) {
        throw new AssertionError("Unexpected errors reported: " + actualErrors);
    }
}
 
Example #26
ServiceIterator(ClassLoader classLoader, Log log) {
    this.log = log;
    try {
        try {
            loader = ServiceLoader.load(Processor.class, classLoader);
            this.iterator = loader.iterator();
        } catch (Exception e) {
            // Fail softly if a loader is not actually needed.
            this.iterator = handleServiceLoaderUnavailability("proc.no.service", null);
        }
    } catch (Throwable t) {
        log.error(Errors.ProcServiceProblem);
        throw new Abort(t);
    }
}
 
Example #27
Source Project: FreeBuilder   Author: inferred   File: SharedBehaviorTesting.java    License: Apache License 2.0 5 votes vote down vote up
public CompilationSubject compiles() {
  if (compilationException != null) {
    throw compilationException;
  }
  if (subject == null) {
    SingleBehaviorTester tester = new SingleBehaviorTester(features);
    for (Processor processor : processors) {
      tester.with(processor);
    }
    processors = null;  // Allow compilers to be reclaimed by GC (processors retain a reference)
    for (JavaFileObject compilationUnit : compilationUnits.values()) {
      tester.with(compilationUnit);
    }
    for (TestSource testSource : testSources) {
      tester.with(testSource);
    }
    for (Package pkg : permittedPackages) {
      tester.withPermittedPackage(pkg);
    }
    try {
      subject = tester.compiles();
    } catch (RuntimeException e) {
      compilationException = e;
      throw e;
    }
  }
  return subject;
}
 
Example #28
@Override
public Processor next() {
    try {
        return internalNext();
    } catch (ServiceConfigurationError sce) {
        log.error(Errors.ProcBadConfigFile(sce.getLocalizedMessage()));
        throw new Abort(sce);
    } catch (Throwable t) {
        throw new Abort(t);
    }
}
 
Example #29
@Override
boolean internalHasNext() {
    if (nextProc != null) {
        return true;
    }
    if (!processorNames.hasNext()) {
        namedProcessorsMap = null;
        return false;
    }
    String processorName = processorNames.next();
    Processor theProcessor = namedProcessorsMap.get(processorName);
    if (theProcessor != null) {
        namedProcessorsMap.remove(processorName);
        nextProc = theProcessor;
        return true;
    } else {
        while (iterator.hasNext()) {
            theProcessor = iterator.next();
            String name = theProcessor.getClass().getName();
            if (name.equals(processorName)) {
                nextProc = theProcessor;
                return true;
            } else {
                namedProcessorsMap.put(name, theProcessor);
            }
        }
        log.error(Errors.ProcProcessorNotFound(processorName));
        return false;
    }
}
 
Example #30
@Override
Processor internalNext() {
    if (hasNext()) {
        Processor p = nextProc;
        nextProc = null;
        return p;
    } else {
        throw new NoSuchElementException();
    }
}