use of javax.tools.JavaFileObject in project buck by facebook.
the class ClassUsageTracker method addReadFile.
private void addReadFile(FileObject fileObject) {
// Can't add after having built
Preconditions.checkState(result == null);
if (!(fileObject instanceof JavaFileObject)) {
return;
}
JavaFileObject javaFileObject = (JavaFileObject) fileObject;
URI classFileJarUri = javaFileObject.toUri();
if (!classFileJarUri.getScheme().equals(JAR_SCHEME)) {
// Not in a jar; must not have been built with java_library
return;
}
// The jar: scheme is somewhat underspecified. See the JarURLConnection docs
// for the closest thing it has to documentation.
String jarUriSchemeSpecificPart = classFileJarUri.getRawSchemeSpecificPart();
final String[] split = jarUriSchemeSpecificPart.split("!/");
Preconditions.checkState(split.length == 2);
if (isLocalOrAnonymousClass(split[1])) {
// classes so we don't need to consider them "used".
return;
}
URI jarFileUri = URI.create(split[0]);
Preconditions.checkState(jarFileUri.getScheme().equals(FILE_SCHEME) || // jimfs is used in tests
jarFileUri.getScheme().equals(JIMFS_SCHEME));
Path jarFilePath = Paths.get(jarFileUri);
// Using URI.create here for de-escaping
Path classPath = Paths.get(URI.create(split[1]).toString());
Preconditions.checkState(jarFilePath.isAbsolute());
Preconditions.checkState(!classPath.isAbsolute());
resultBuilder.put(jarFilePath, classPath);
}
use of javax.tools.JavaFileObject in project buck by facebook.
the class JavaInMemoryFileManager method list.
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException {
if (shouldDelegate(location)) {
return delegate.list(location, packageName, kinds, recurse);
}
ArrayList<JavaFileObject> results = new ArrayList<>();
for (JavaFileObject fromSuper : delegate.list(location, packageName, kinds, recurse)) {
results.add(fromSuper);
}
String packageDirPath = getPath(packageName) + '/';
for (String filepath : fileForOutputPaths.keySet()) {
if (recurse && filepath.startsWith(packageDirPath)) {
results.add(fileForOutputPaths.get(filepath));
} else if (!recurse && filepath.startsWith(packageDirPath) && filepath.substring(packageDirPath.length()).indexOf('/') < 0) {
results.add(fileForOutputPaths.get(filepath));
}
}
return results;
}
use of javax.tools.JavaFileObject in project buck by facebook.
the class Jsr199Javac method buildWithClasspath.
private int buildWithClasspath(JavacExecutionContext context, BuildTarget invokingRule, ImmutableList<String> options, ImmutableList<ResolvedJavacPluginProperties> annotationProcessors, ImmutableSortedSet<Path> javaSourceFilePaths, Path pathToSrcsList, JavaCompiler compiler, StandardJavaFileManager fileManager, Iterable<? extends JavaFileObject> compilationUnits, JavacOptions.AbiGenerationMode abiGenerationMode) {
// since we do not print them out to console in case of error
try {
context.getProjectFilesystem().writeLinesToPath(FluentIterable.from(javaSourceFilePaths).transform(Object::toString).transform(ARGFILES_ESCAPER), pathToSrcsList);
} catch (IOException e) {
context.getEventSink().reportThrowable(e, "Cannot write list of .java files to compile to %s file! Terminating compilation.", pathToSrcsList);
return 1;
}
DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
List<String> classNamesForAnnotationProcessing = ImmutableList.of();
Writer compilerOutputWriter = new PrintWriter(context.getStdErr());
JavaCompiler.CompilationTask compilationTask = compiler.getTask(compilerOutputWriter, context.getUsedClassesFileWriter().wrapFileManager(fileManager), diagnostics, options, classNamesForAnnotationProcessing, compilationUnits);
boolean isSuccess = false;
BuckTracing.setCurrentThreadTracingInterfaceFromJsr199Javac(new Jsr199TracingBridge(context.getEventSink(), invokingRule));
Object abiValidatingTaskListener = null;
if (abiGenerationMode != JavacOptions.AbiGenerationMode.CLASS) {
abiValidatingTaskListener = SourceBasedAbiStubber.newValidatingTaskListener(context.getClassLoaderCache(), compilationTask, new FileManagerBootClasspathOracle(fileManager), abiGenerationMode == JavacOptions.AbiGenerationMode.SOURCE ? Diagnostic.Kind.ERROR : Diagnostic.Kind.WARNING);
}
try {
try (// in some unusual situations
TranslatingJavacPhaseTracer tracer = TranslatingJavacPhaseTracer.setupTracing(invokingRule, context.getClassLoaderCache(), context.getEventSink(), compilationTask, abiValidatingTaskListener);
// may choke with novel errors that don't occur on the command line.
AnnotationProcessorFactory processorFactory = new AnnotationProcessorFactory(context.getEventSink(), compiler.getClass().getClassLoader(), context.getClassLoaderCache(), invokingRule)) {
compilationTask.setProcessors(processorFactory.createProcessors(annotationProcessors));
// Invoke the compilation and inspect the result.
isSuccess = compilationTask.call();
} catch (IOException e) {
LOG.warn(e, "Unable to close annotation processor class loader. We may be leaking memory.");
}
} finally {
// Clear the tracing interface so we have no chance of leaking it to code that shouldn't
// be using it.
BuckTracing.clearCurrentThreadTracingInterfaceFromJsr199Javac();
}
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
LOG.debug("javac: %s", DiagnosticPrettyPrinter.format(diagnostic));
}
List<Diagnostic<? extends JavaFileObject>> cleanDiagnostics = DiagnosticCleaner.clean(diagnostics.getDiagnostics());
if (isSuccess) {
context.getUsedClassesFileWriter().writeFile(context.getProjectFilesystem(), context.getObjectMapper());
return 0;
} else {
if (context.getVerbosity().shouldPrintStandardInformation()) {
int numErrors = 0;
int numWarnings = 0;
for (Diagnostic<? extends JavaFileObject> diagnostic : cleanDiagnostics) {
Diagnostic.Kind kind = diagnostic.getKind();
if (kind == Diagnostic.Kind.ERROR) {
++numErrors;
handleMissingSymbolError(invokingRule, diagnostic, context);
} else if (kind == Diagnostic.Kind.WARNING || kind == Diagnostic.Kind.MANDATORY_WARNING) {
++numWarnings;
}
context.getStdErr().println(DiagnosticPrettyPrinter.format(diagnostic));
}
if (numErrors > 0 || numWarnings > 0) {
context.getStdErr().printf("Errors: %d. Warnings: %d.\n", numErrors, numWarnings);
}
}
return 1;
}
}
use of javax.tools.JavaFileObject in project DeepLinkDispatch by airbnb.
the class DeepLinkProcessorTest method testNonStaticMethodCompileFail.
@Test
public void testNonStaticMethodCompileFail() {
JavaFileObject sampleActivity = JavaFileObjects.forSourceString("SampleActivity", "package com.example;" + "import com.airbnb.deeplinkdispatch.DeepLink; " + "public class SampleActivity {" + " @DeepLink(\"airbnb://host/{arbitraryNumber}\")" + " public Intent intentFromNoStatic(Context context){" + " return new Intent();" + " }" + "}");
assertAbout(javaSource()).that(sampleActivity).processedWith(new DeepLinkProcessor()).failsToCompile().withErrorContaining("Only static methods can be annotated");
}
use of javax.tools.JavaFileObject in project DeepLinkDispatch by airbnb.
the class DeepLinkProcessorTest method uppercasePackage.
@Test
public void uppercasePackage() {
JavaFileObject activityWithUppercasePackage = JavaFileObjects.forSourceString("SampleActivity", "package com.Example;" + "import com.airbnb.deeplinkdispatch.DeepLink;\n" + "import com.airbnb.deeplinkdispatch.DeepLinkHandler;\n\n" + "import com.Example.SampleModule;\n\n" + "@DeepLink(\"airbnb://example.com/deepLink\")" + "@DeepLinkHandler({ SampleModule.class })\n" + "public class SampleActivity {\n" + "}");
JavaFileObject module = JavaFileObjects.forSourceString("SampleModule", "package com.Example;" + "import com.airbnb.deeplinkdispatch.DeepLinkModule;\n\n" + "@DeepLinkModule\n" + "public class SampleModule {\n" + "}");
assertAbout(javaSources()).that(Arrays.asList(module, activityWithUppercasePackage)).processedWith(new DeepLinkProcessor()).compilesWithoutError().and().generatesSources(JavaFileObjects.forSourceString("/SOURCE_OUTPUT.com.Example.SampleModuleLoader", "package com.Example;\n" + "\n" + "import com.airbnb.deeplinkdispatch.DeepLinkEntry;\n" + "import com.airbnb.deeplinkdispatch.Parser;\n" + "import java.lang.Override;\n" + "import java.lang.String;\n" + "import java.util.Arrays;\n" + "import java.util.Collections;\n" + "import java.util.List;\n" + "\n" + "public final class SampleModuleLoader implements Parser {\n" + " public static final List<DeepLinkEntry> REGISTRY = " + "Collections.unmodifiableList(Arrays.asList(" + "new DeepLinkEntry(\"airbnb://example.com/deepLink\", DeepLinkEntry.Type" + ".CLASS, SampleActivity.class, null)));\n" + "\n" + " @Override" + " public DeepLinkEntry parseUri(String uri) {\n" + " for (DeepLinkEntry entry : REGISTRY) {\n" + " if (entry.matches(uri)) {\n" + " return entry;\n" + " }\n" + " }\n" + " return null;\n" + " }\n" + "}"));
}
Aggregations