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 File: MalformedAnnotationProcessorTests.java    From TencentKona-8 with 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 #2
Source File: JavacProcessingEnvironment.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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 #3
Source File: APTUtils.java    From netbeans with 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 #4
Source File: JavaCompiler.java    From openjdk-jdk8u with 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 File: MalformedAnnotationProcessorTests.java    From openjdk-jdk8u with 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
Source File: JavaCompiler.java    From hottub with 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 #7
Source File: JavacProcessingEnvironment.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 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 #8
Source File: MalformedAnnotationProcessorTests.java    From TencentKona-8 with 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 #9
Source File: FactoryOriginatingElementTest.java    From toothpick with 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 File: JavaCompiler.java    From openjdk-jdk8u-backup with 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 File: JavaCompiler.java    From openjdk-8 with 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 File: JavaCompiler.java    From openjdk-8-source with 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 File: Main.java    From openjdk-8 with 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 File: Project.java    From RADL with 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 #15
Source File: JavacTaskImpl.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER)
public void setProcessors(Iterable<? extends Processor> processors) {
    Objects.requireNonNull(processors);
    // not mt-safe
    if (used.get())
        throw new IllegalStateException();
    this.processors = processors;
}
 
Example #16
Source File: SourceUtils.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of completions for an annotation attribute value suggested by
 * annotation processors.
 * 
 * @param info the CompilationInfo used to resolve annotation processors
 * @param element the element being annotated
 * @param annotation the (perhaps partial) annotation being applied to the element
 * @param member the annotation member to return possible completions for
 * @param userText source code text to be completed
 * @return suggested completions to the annotation member
 * 
 * @since 0.57
 */
public static List<? extends Completion> getAttributeValueCompletions(CompilationInfo info, Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
    List<Completion> completions = new LinkedList<>();
    if (info.getPhase().compareTo(Phase.ELEMENTS_RESOLVED) >= 0) {
        String fqn = ((TypeElement) annotation.getAnnotationType().asElement()).getQualifiedName().toString();
        Iterable<? extends Processor> processors =
                JavacParser.ProcessorHolder.instance(info.impl.getJavacTask().getContext()).getProcessors();
        if (processors != null) {
            for (Processor processor : processors) {
                boolean match = false;
                for (String sat : processor.getSupportedAnnotationTypes()) {
                    if ("*".equals(sat)) { //NOI18N
                        match = true;
                        break;
                    } else if (sat.endsWith(".*")) { //NOI18N
                        sat = sat.substring(0, sat.length() - 1);
                        if (fqn.startsWith(sat)) {
                            match = true;
                            break;
                        }
                    } else if (fqn.equals(sat)) {
                        match = true;
                        break;
                    }
                }
                if (match) {
                    try {
                        for (Completion c : processor.getCompletions(element, annotation, member, userText)) {
                            completions.add(c);
                        }
                    } catch (Exception e) {
                        Logger.getLogger(processor.getClass().getName()).log(Level.INFO, e.getMessage(), e);
                    }
                }
            }
        }
    }
    return completions;
}
 
Example #17
Source File: Main.java    From openjdk-jdk8u with 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 #18
Source File: JavaCompiler.java    From openjdk-jdk8u with 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 File: AnnotationsTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "processors")
public void processorAcceptsAnnotations(Processor p) throws ClassNotFoundException {
    for (String type : p.getSupportedAnnotationTypes()) {
        Class<?> clazz = loadType(type);
        assertTrue(Annotation.class.isAssignableFrom(clazz), "It is annotation: " + clazz);
    }
}
 
Example #20
Source File: ProcessorTestUtilities.java    From toothpick with 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 File: JavacTaskImpl.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER)
public void setProcessors(Iterable<? extends Processor> processors) {
    Objects.requireNonNull(processors);
    // not mt-safe
    if (used.get())
        throw new IllegalStateException();
    this.processors = processors;
}
 
Example #22
Source File: ProcessorInfo.java    From Eclipse-Postfix-Code-Completion with 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 #23
Source File: JavacTaskImpl.java    From javaide with 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 #24
Source File: MalformedAnnotationProcessorTests.java    From openjdk-jdk8u with 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 #25
Source File: Processing.java    From turbine with Apache License 2.0 5 votes vote down vote up
private static void reportProcessorCrash(TurbineLog log, Processor processor, Throwable t) {
  log.diagnostic(
      Diagnostic.Kind.ERROR,
      String.format(
          "An exception occurred in %s:\n%s",
          processor.getClass().getCanonicalName(), Throwables.getStackTraceAsString(t)));
  log.maybeThrow();
}
 
Example #26
Source File: JavacProcessingEnvironment.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 File: SharedBehaviorTesting.java    From FreeBuilder with 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
Source File: JavacProcessingEnvironment.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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
Source File: JavacProcessingEnvironment.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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
Source File: JavacProcessingEnvironment.java    From lua-for-android with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
Processor internalNext() {
    if (hasNext()) {
        Processor p = nextProc;
        nextProc = null;
        return p;
    } else {
        throw new NoSuchElementException();
    }
}