下面列出了怎么用javax.annotation.processing.Processor的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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();
}
}
}
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);
}
}
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);
}
}
/**
* 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();
}
}
}
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);
}
}
/**
* 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();
}
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;
}
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;
}
@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"));
}
/**
* 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();
}
}
}
/**
* 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();
}
}
}
/**
* 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();
}
}
/** 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);
}
/**
* 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();
}
}
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);
}
public void setProcessors(Iterable<? extends Processor> processors) {
processors.getClass(); // null check
// not mt-safe
if (used.get())
throw new IllegalStateException();
this.processors = processors;
}
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));
}
/**
* 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();
}
}
/**
* 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();
}
}
static Iterable<? extends Processor> factoryProcessorsWithAdditionalTypes(String... types) {
FactoryProcessor factoryProcessor = new FactoryProcessor();
for (String type : types) {
factoryProcessor.addSupportedAnnotationType(type);
}
return Arrays.asList(factoryProcessor);
}
/** 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);
}
/**
* 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();
}
}
/**
* 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;
}
public void setProcessors(Iterable<? extends Processor> processors) {
processors.getClass(); // null check
// not mt-safe
if (used.get())
throw new IllegalStateException();
this.processors = processors;
}
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);
}
}
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);
}
}
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;
}
@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);
}
}
@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;
}
}
@Override
Processor internalNext() {
if (hasNext()) {
Processor p = nextProc;
nextProc = null;
return p;
} else {
throw new NoSuchElementException();
}
}