Java Code Examples for javax.tools.StandardLocation

The following examples show how to use javax.tools.StandardLocation. These examples are extracted from open source projects. 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
@Test
public void testBasic(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Location[] locns = {
            StandardLocation.SOURCE_PATH,
            StandardLocation.CLASS_PATH,
            StandardLocation.PLATFORM_CLASS_PATH,
        };
        // set a value
        Path out = Files.createDirectories(base.resolve("out"));
        for (Location locn : locns) {
            checkException("unsupported for location",
                    IllegalArgumentException.class,
                    "location is not an output location or a module-oriented location: " + locn,
                    () -> fm.setLocationForModule(locn, "m", List.of(out)));
        }
    }
}
 
Example 2
Source Project: hottub   Source File: JavacTemplateTestBase.java    License: GNU General Public License v2.0 6 votes vote down vote up
private File compile(List<File> classpaths, List<JavaFileObject> files, boolean generate) throws IOException {
    JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = systemJavaCompiler.getStandardFileManager(null, null, null);
    if (classpaths.size() > 0)
        fm.setLocation(StandardLocation.CLASS_PATH, classpaths);
    JavacTask ct = (JavacTask) systemJavaCompiler.getTask(null, fm, diags, compileOptions, null, files);
    if (generate) {
        File destDir = new File(root, Integer.toString(counter.incrementAndGet()));
        // @@@ Assert that this directory didn't exist, or start counter at max+1
        destDir.mkdirs();
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
        ct.generate();
        return destDir;
    }
    else {
        ct.analyze();
        return nullDir;
    }
}
 
Example 3
Source Project: openjdk-8   Source File: JNIWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** Emit a class file for a given class.
 *  @param c      The class from which a class file is generated.
 */
public FileObject write(ClassSymbol c)
    throws IOException
{
    String className = c.flatName().toString();
    FileObject outFile
        = fileManager.getFileForOutput(StandardLocation.NATIVE_HEADER_OUTPUT,
            "", className.replaceAll("[.$]", "_") + ".h", null);
    Writer out = outFile.openWriter();
    try {
        write(out, c);
        if (verbose)
            log.printVerbose("wrote.file", outFile);
        out.close();
        out = null;
    } finally {
        if (out != null) {
            // if we are propogating an exception, delete the file
            out.close();
            outFile.delete();
            outFile = null;
        }
    }
    return outFile; // may be null if write failed
}
 
Example 4
Source Project: openjdk-jdk8u   Source File: TestSuperclass.java    License: GNU General Public License v2.0 6 votes vote down vote up
int run(JavaCompiler comp, StandardJavaFileManager fm) throws IOException {
    System.err.println("test: ck:" + ck + " gk:" + gk + " sk:" + sk);
    File testDir = new File(ck + "-" + gk + "-" + sk);
    testDir.mkdirs();
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(testDir));

    JavaSource js = new JavaSource();
    System.err.println(js.getCharContent(false));
    CompilationTask t = comp.getTask(null, fm, null, null, null, Arrays.asList(js));
    if (!t.call())
        throw new Error("compilation failed");

    File testClass = new File(testDir, "Test.class");
    String out = javap(testClass);

    // Extract class sig from first line of Java source
    String expect = js.source.replaceAll("(?s)^(.* Test[^{]+?) *\\{.*", "$1");

    // Extract class sig from line from javap output
    String found = out.replaceAll("(?s).*\n(.* Test[^{]+?) *\\{.*", "$1");

    checkEqual("class signature", expect, found);

    return errors;
}
 
Example 5
@Test
public void incrementalAnnotationProcessor() {
  assertThat(
          JavaFileObjects.forResource("test/IsolatingProcessor.java"),
          JavaFileObjects.forResource("test/AggregatingProcessor.java"),
          JavaFileObjects.forResource("test/DynamicProcessor.java"),
          JavaFileObjects.forResource("test/Enclosing.java"))
      .processedWith(new IncrementalAnnotationProcessorProcessor())
      .compilesWithoutError()
      .and()
      .generatesFileNamed(
          StandardLocation.CLASS_OUTPUT,
          "",
          IncrementalAnnotationProcessorProcessor.RESOURCE_FILE)
      .withStringContents(
          StandardCharsets.UTF_8,
          String.join(
              "\n",
              "test.AggregatingProcessor,AGGREGATING",
              "test.DynamicProcessor,DYNAMIC",
              "test.Enclosing$NestedIsolatingProcessor,ISOLATING",
              "test.IsolatingProcessor,ISOLATING",
              ""));
}
 
Example 6
Source Project: TencentKona-8   Source File: JNIWriter.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** Emit a class file for a given class.
 *  @param c      The class from which a class file is generated.
 */
public FileObject write(ClassSymbol c)
    throws IOException
{
    String className = c.flatName().toString();
    FileObject outFile
        = fileManager.getFileForOutput(StandardLocation.NATIVE_HEADER_OUTPUT,
            "", className.replaceAll("[.$]", "_") + ".h", null);
    Writer out = outFile.openWriter();
    try {
        write(out, c);
        if (verbose)
            log.printVerbose("wrote.file", outFile);
        out.close();
        out = null;
    } finally {
        if (out != null) {
            // if we are propogating an exception, delete the file
            out.close();
            outFile.delete();
            outFile = null;
        }
    }
    return outFile; // may be null if write failed
}
 
Example 7
void testCreate(String relativeBase, Kind kind) {
    String relative = getRelative(relativeBase, kind);
    System.out.println("test create relative path: " + relative + ", kind: " + kind);
    try {
        switch (kind) {
            case READER_WRITER:
                try (Writer writer = filer.createResource(
                        StandardLocation.CLASS_OUTPUT, "", relative).openWriter()) {
                    writer.write(relative);
                }
                break;

            case INPUT_OUTPUT_STREAM:
                try (OutputStream out = filer.createResource(
                        StandardLocation.CLASS_OUTPUT, "", relative).openOutputStream()) {
                    out.write(relative.getBytes());
                }
                break;
        }
    } catch (Exception e) {
        messager.printMessage(Diagnostic.Kind.ERROR,
                "relative path: " + relative + ", kind: " + kind + ", unexpected exception: " + e);
    }
}
 
Example 8
Source Project: yugong   Source File: JdkCompiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
private JavaFileManagerImpl buildFileManager(JdkCompilerClassLoader classLoader, ClassLoader loader,
                                             DiagnosticCollector<JavaFileObject> diagnostics) {
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    if (loader instanceof URLClassLoader
        && (!"sun.misc.Launcher$AppClassLoader".equalsIgnoreCase(loader.getClass().getName()))) {
        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> paths = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                File file = new File(url.getFile());
                paths.add(file);
            }

            fileManager.setLocation(StandardLocation.CLASS_PATH, paths);
        } catch (Throwable e) {
            throw new YuGongException(e);
        }
    }

    return new JavaFileManagerImpl(fileManager, classLoader);
}
 
Example 9
Source Project: dubbox   Source File: JdkCompiler.java    License: Apache License 2.0 6 votes vote down vote up
public JdkCompiler(){
    options = new ArrayList<String>();
    options.add("-target");
    options.add("1.6");
    StandardJavaFileManager manager = compiler.getStandardFileManager(diagnosticCollector, null, null);
    final ClassLoader loader = Thread.currentThread().getContextClassLoader();
    if (loader instanceof URLClassLoader 
            && (! loader.getClass().getName().equals("sun.misc.Launcher$AppClassLoader"))) {
        try {
            URLClassLoader urlClassLoader = (URLClassLoader) loader;
            List<File> files = new ArrayList<File>();
            for (URL url : urlClassLoader.getURLs()) {
                files.add(new File(url.getFile()));
            }
            manager.setLocation(StandardLocation.CLASS_PATH, files);
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }
    classLoader = AccessController.doPrivileged(new PrivilegedAction<ClassLoaderImpl>() {
        public ClassLoaderImpl run() {
            return new ClassLoaderImpl(loader);
        }
    });
    javaFileManager = new JavaFileManagerImpl(manager, classLoader);
}
 
Example 10
@Override
Iterable<DocFile> list(Location location, DocPath path) {
    if (location != StandardLocation.SOURCE_PATH)
        throw new IllegalArgumentException();

    Set<DocFile> files = new LinkedHashSet<DocFile>();
    if (fileManager.hasLocation(location)) {
        for (Path f: fileManager.getLocation(location)) {
            if (Files.isDirectory(f)) {
                f = f.resolve(path.getPath());
                if (Files.exists(f))
                    files.add(new StandardDocFile(f));
            }
        }
    }
    return files;
}
 
Example 11
Source Project: picocli   Source File: AbstractGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void generate(Map<Element, CommandLine.Model.CommandSpec> allCommands) {
    if (!enabled()) {
        logInfo("is not enabled");
        return;
    }
    try {
        String path = createRelativePath(fileName());
        logInfo("writing to: " + StandardLocation.CLASS_OUTPUT + "/" + path);
        String text = generateConfig(allCommands);
        ProcessorUtil.generate(StandardLocation.CLASS_OUTPUT, path, text, processingEnv, allCommands.keySet().toArray(new Element[0]));
    } catch (Exception e) {
        // We don't allow exceptions of any kind to propagate to the compiler
        fatalError(ProcessorUtil.stacktrace(e));
    }
}
 
Example 12
Source Project: netbeans   Source File: PatchModuleFileManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Location getLocationForModule(Location location, JavaFileObject fo) throws IOException {
    if (location == StandardLocation.PATCH_MODULE_PATH) {
        final URL url = fo.toUri().toURL();
        for (Map.Entry<URL,String> root : roots.entrySet()) {
            if (FileObjects.isParentOf(root.getKey(), url)) {
                String modName = root.getValue();
                return moduleLocations(location).stream()
                        .filter((ml) -> modName.equals(ml.getModuleName()))
                        .findFirst()
                        .orElse(null);
            }
        }
    }
    return null;
}
 
Example 13
void compileWithJSR199() throws IOException {
    String cpath = "C2.jar";
    File clientJarFile = new File(cpath);
    File sourceFileToCompile = new File("C3.java");


    javax.tools.JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager stdFileManager = javac.getStandardFileManager(diagnostics, null, null);

    List<File> files = new ArrayList<>();
    files.add(clientJarFile);

    stdFileManager.setLocation(StandardLocation.CLASS_PATH, files);

    Iterable<? extends JavaFileObject> sourceFiles = stdFileManager.getJavaFileObjects(sourceFileToCompile);

    if (!javac.getTask(null, stdFileManager, diagnostics, null, null, sourceFiles).call()) {
        throw new AssertionError("compilation failed");
    }
}
 
Example 14
Source Project: jdk8u60   Source File: T6418694.java    License: GNU General Public License v2.0 6 votes vote down vote up
void test(String... args) {
    for (StandardLocation loc : StandardLocation.values()) {
        switch (loc) {
        case CLASS_PATH:
        case SOURCE_PATH:
        case CLASS_OUTPUT:
        case PLATFORM_CLASS_PATH:
            if (!fm.hasLocation(loc))
                throw new AssertionError("Missing location " + loc);
            break;
        default:
            if (fm.hasLocation(loc))
                throw new AssertionError("Extra location " + loc);
            break;
        }
    }
}
 
Example 15
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse) throws IOException {
    if (location != StandardLocation.PLATFORM_CLASS_PATH || !kinds.contains(Kind.CLASS))
        return Collections.emptyList();

    if (!packageName.isEmpty())
        packageName += ".";

    List<JavaFileObject> result = new ArrayList<>();

    for (Entry<String, JavaFileObject> e : className2File.entrySet()) {
        String currentPackage = e.getKey().substring(0, e.getKey().lastIndexOf(".") + 1);
        if (recurse ? currentPackage.startsWith(packageName) : packageName.equals(currentPackage))
            result.add(e.getValue());
    }

    return result;
}
 
Example 16
Source Project: j2objc   Source File: JavacParser.java    License: Apache License 2.0 6 votes vote down vote up
private StandardJavaFileManager getFileManager(JavaCompiler compiler,
    DiagnosticCollector<JavaFileObject> diagnostics) throws IOException {
  fileManager =
      compiler.getStandardFileManager(diagnostics, null, options.fileUtil().getCharset());
  addPaths(StandardLocation.CLASS_PATH, classpathEntries, fileManager);
  addPaths(StandardLocation.SOURCE_PATH, sourcepathEntries, fileManager);
  addPaths(StandardLocation.PLATFORM_CLASS_PATH, options.getBootClasspath(), fileManager);
  List<String> processorPathEntries = options.getProcessorPathEntries();
  if (!processorPathEntries.isEmpty()) {
    addPaths(StandardLocation.ANNOTATION_PROCESSOR_PATH, processorPathEntries, fileManager);
  }
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
      Lists.newArrayList(options.fileUtil().getOutputDirectory()));
  fileManager.setLocation(StandardLocation.SOURCE_OUTPUT,
      Lists.newArrayList(FileUtil.createTempDir("annotations")));
  return fileManager;
}
 
Example 17
Source Project: openjdk-jdk8u   Source File: T6410706.java    License: GNU General Public License v2.0 6 votes vote down vote up
public static void main(String... args) throws IOException {
    String testSrc = System.getProperty("test.src", ".");
    String testClasses = System.getProperty("test.classes", ".");
    JavacTool tool = JavacTool.create();
    MyDiagListener dl = new MyDiagListener();
    StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(testClasses)));
    Iterable<? extends JavaFileObject> files =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrc, T6410706.class.getName()+".java")));
    JavacTask task = tool.getTask(null, fm, dl, null, null, files);
    task.parse();
    task.analyze();
    task.generate();

    // expect 2 notes:
    // Note: T6410706.java uses or overrides a deprecated API.
    // Note: Recompile with -Xlint:deprecation for details.

    if (dl.notes != 2)
        throw new AssertionError(dl.notes + " notes given");
}
 
Example 18
Source Project: netbeans   Source File: BootClassPathUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<JavaFileObject.Kind> kinds, boolean recurse) throws IOException {
    if (location == StandardLocation.CLASS_OUTPUT) {
        List<JavaFileObject> result = new ArrayList<>();
        FileObject pack = output.getFileObject(packageName.replace('.', '/'));

        if (pack != null) {
            Enumeration<? extends FileObject> c = pack.getChildren(recurse);

            while (c.hasMoreElements()) {
                FileObject file = c.nextElement();
                if (!file.hasExt("class"))
                    continue;
                result.add(new InferableJavaFileObject(file, JavaFileObject.Kind.CLASS));
            }
        }

        return result;
    }
    return super.list(location, packageName, kinds, recurse);
}
 
Example 19
Source Project: dubbo-2.6.5   Source File: JdkCompiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Class<?> doCompile(String name, String sourceCode) throws Throwable {
    int i = name.lastIndexOf('.');
    String packageName = i < 0 ? "" : name.substring(0, i);
    String className = i < 0 ? name : name.substring(i + 1);
    JavaFileObjectImpl javaFileObject = new JavaFileObjectImpl(className, sourceCode);
    javaFileManager.putFileForInput(StandardLocation.SOURCE_PATH, packageName,
            className + ClassUtils.JAVA_EXTENSION, javaFileObject);
    Boolean result = compiler.getTask(null, javaFileManager, diagnosticCollector, options,
            null, Arrays.asList(javaFileObject)).call();
    if (result == null || !result) {
        throw new IllegalStateException("Compilation failed. class: " + name + ", diagnostics: " + diagnosticCollector);
    }
    return classLoader.loadClass(name);
}
 
Example 20
Source Project: javaide   Source File: TestJavacParser.java    License: GNU General Public License v3.0 5 votes vote down vote up
public void test2() {
    Context context = new Context();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    context.put(DiagnosticListener.class, diagnostics);
    Options.instance(context).put("allowStringFolding", "false");
    JCTree.JCCompilationUnit unit;
    JavacFileManager fileManager = new JavacFileManager(context, true, UTF_8);
    try {
        fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, ImmutableList.<File>of());
    } catch (IOException e) {
        // impossible
        throw new IOError(e);
    }
    SimpleJavaFileObject source =
            new SimpleJavaFileObject(URI.create("source"), JavaFileObject.Kind.SOURCE) {
                @Override
                public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
                    return src;
                }
            };
    Log.instance(context).useSource(source);
    ParserFactory parserFactory = ParserFactory.instance(context);
    Parser parser =
            parserFactory.newParser(
                    src,
        /*keepDocComments=*/ true,
        /*keepEndPos=*/ true,
        /*keepLineMap=*/ true);
    unit = parser.parseCompilationUnit();
    unit.sourcefile = source;
}
 
Example 21
Source Project: buck   Source File: AnnotationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (!roundEnv.processingOver() && !generated) {
    try {
      Filer filer = processingEnv.getFiler();

      JavaFileObject cSource = filer.createSourceFile("ImmutableC");
      try (OutputStream outputStream = cSource.openOutputStream()) {
        outputStream.write("public class ImmutableC { }".getBytes());
      }

      JavaFileObject dSource = filer.createSourceFile("RemovableD");
      try (OutputStream outputStream = dSource.openOutputStream()) {
        outputStream.write("public class RemovableD { }".getBytes());
      }

      FileObject dResource =
          filer.createResource(StandardLocation.CLASS_OUTPUT, "", "RemovableD");
      try (OutputStream outputStream = dResource.openOutputStream()) {
        outputStream.write("foo".getBytes());
      }

      generated = true;
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  return true;
}
 
Example 22
Source Project: jlibs   Source File: BundleAnnotationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
public Info(Element element, AnnotationMirror mirror) throws IOException{
    pakage = ModelUtil.getPackage(element);
    if(ModelUtil.exists(pakage, basename+".properties"))
        throw new AnnotationError(element, mirror, basename+".properties in package "+pakage+" already exists in source path");

    FileObject resource = Environment.get().getFiler().createResource(StandardLocation.CLASS_OUTPUT, pakage, basename+".properties");
    props = new BufferedWriter(resource.openWriter());
}
 
Example 23
Source Project: oxygen   Source File: DynamicJavaFileManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind,
    FileObject sibling) throws IOException {
  if (kind == Kind.CLASS && location == StandardLocation.CLASS_OUTPUT) {
    ByteCode byteCode = byteCodes.get(className);
    if (byteCode == null) {
      byteCode = new ByteCode(className, kind);
      byteCodes.put(className, byteCode);
    }
    return byteCode;
  }
  return super.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example 24
@Test
public void testGenerateReflectJava8ApiOptionProject() {
    NativeImageConfigGeneratorProcessor processor = new NativeImageConfigGeneratorProcessor();
    Compilation compilation =
            javac()
                    .withProcessors(processor)
                    .withOptions("-A" + OPTION_PROJECT + "=example/full")
                    .compile(JavaFileObjects.forSourceLines(
                            "picocli.codegen.graalvm.example.ExampleFull",
                            slurp("/picocli/codegen/graalvm/example/ExampleFull.java")));
    assertThat(compilation).succeeded();
    assertThat(compilation)
            .generatedFile(StandardLocation.CLASS_OUTPUT, "META-INF/native-image/picocli-generated/example/full/reflect-config.json")
            .contentsAsUtf8String().isEqualTo(slurp("/picocli/codegen/graalvm/example/FullExample-reflect-config.json"));
}
 
Example 25
Source Project: takari-lifecycle   Source File: FilerImplTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void testGetResource_location_classpath() throws Exception {
  EclipseFileManager fileManager = new EclipseFileManager(null, Charsets.UTF_8);

  List<File> classpath = new ArrayList<>();
  classpath.add(new File("src/test/projects/compile-jdt-proc/getresource-location-classpath/classes"));
  classpath.add(new File("src/test/projects/compile-jdt-proc/getresource-location-classpath/dependency.zip"));
  fileManager.setLocation(StandardLocation.CLASS_PATH, classpath);

  FilerImpl filer = new FilerImpl(null /* context */, fileManager, null /* compiler */, null /* env */);

  Assert.assertEquals("dir resource", toString(filer.getResource(StandardLocation.CLASS_PATH, "", "dirresource.txt")));
  // Assert.assertEquals("jar resource", toString(filer.getResource(StandardLocation.CLASS_PATH, "", "jarresource.txt")));
  Assert.assertEquals("pkg jar resource", toString(filer.getResource(StandardLocation.CLASS_PATH, "pkg", "jarresource.txt")));
}
 
Example 26
public OutputStream openBinary(JPackage pkg, String fileName) throws IOException {
    StandardLocation loc;
    if(fileName.endsWith(".java")) {
        // Annotation Processing doesn't do the proper Unicode escaping on Java source files,
        // so we can't rely on Filer.createSourceFile.
        loc = SOURCE_PATH;
    } else {
        // put non-Java files directly to the output folder
        loc = CLASS_PATH;
    }
    return filer.createResource(loc, pkg.name(), fileName).openOutputStream();
}
 
Example 27
Source Project: droitatedDB   Source File: JavaFileWriter.java    License: Apache License 2.0 5 votes vote down vote up
private void clearOldVersions(final String packageName, final String fileName) {
 try {
	 FileObject schema = processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT, packageName, fileName);
	 String schemaFile = schema.toUri().toASCIIString();
	 String withoutFile = schemaFile.replace("file:", "") + ".java";
	 if (new File(withoutFile).exists()) {
		 new File(withoutFile).delete();
	 }
 } catch (IOException e) {
	 // ignore
 }
}
 
Example 28
Source Project: netbeans   Source File: TreeShimsCopier.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annos, RoundEnvironment roundEnv) {
    for (Element el : roundEnv.getRootElements()) {
        if (el.getKind() != ElementKind.CLASS)
            continue;
        TypeElement type = (TypeElement) el;
        String qualName = type.getQualifiedName().toString();
        String targetPackage = ALLOWED_CLASSES2TARGET_PACKAGE.get(qualName);
        if (targetPackage != null) {
            try {
                Filer filer = processingEnv.getFiler();
                FileObject fo = filer.getResource(StandardLocation.SOURCE_PATH, ((PackageElement) type.getEnclosingElement()).getQualifiedName().toString(), type.getSimpleName() + ".java");
                URI source = fo.toUri();
                StringBuilder path2Shims = new StringBuilder();
                int p = qualName.split("\\.").length;
                for (int i = 0; i < p; i++) {
                    path2Shims.append("../");
                }
                path2Shims.append("../java.source.base/src/org/netbeans/modules/java/source/TreeShims.java");
                URI treeShims = source.resolve(path2Shims.toString());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try (InputStream in = treeShims.toURL().openStream()) {
                    int r;

                    while ((r = in.read()) != (-1)) {
                        baos.write(r);
                    }
                }
                String content = new String(baos.toByteArray(), "UTF-8");
                content = content.replace("package org.netbeans.modules.java.source;", "package " + targetPackage + ";");
                try (OutputStream out = filer.createSourceFile(targetPackage + ".TreeShims", type).openOutputStream()) {
                    out.write(content.getBytes("UTF-8"));
                }
            } catch (IOException ex) {
                throw new IllegalStateException(ex);
            }
        }
    }
    return false;
}
 
Example 29
Source Project: quarkus   Source File: ExtensionAnnotationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void processBuildStep(RoundEnvironment roundEnv, TypeElement annotation) {
    final Set<String> processorClassNames = new HashSet<>();

    for (ExecutableElement i : methodsIn(roundEnv.getElementsAnnotatedWith(annotation))) {
        final TypeElement clazz = getClassOf(i);
        if (clazz == null) {
            continue;
        }

        final PackageElement pkg = processingEnv.getElementUtils().getPackageOf(clazz);
        if (pkg == null) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "Element " + clazz + " has no enclosing package");
            continue;
        }

        final String binaryName = processingEnv.getElementUtils().getBinaryName(clazz).toString();
        if (processorClassNames.add(binaryName)) {
            recordConfigJavadoc(clazz);
            generateAccessor(clazz);
            final StringBuilder rbn = getRelativeBinaryName(clazz, new StringBuilder());
            try {
                final FileObject itemResource = processingEnv.getFiler().createResource(
                        StandardLocation.SOURCE_OUTPUT,
                        pkg.getQualifiedName().toString(),
                        rbn.toString() + ".bsc",
                        clazz);
                writeResourceFile(binaryName, itemResource);
            } catch (IOException e1) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "Failed to create " + rbn + " in " + pkg + ": " + e1, clazz);
            }
        }
    }
}
 
Example 30
@Override
public void configure(Object batchCompiler, String[] commandLineArguments) {
	if (null != _processingEnv) {
		throw new IllegalStateException(
				"Calling configure() more than once on an AnnotationProcessorManager is not supported"); //$NON-NLS-1$
	}
	BatchProcessingEnvImpl processingEnv = new BatchProcessingEnvImpl(this, (Main) batchCompiler, commandLineArguments);
	_processingEnv = processingEnv;
	_procLoader = processingEnv.getFileManager().getClassLoader(StandardLocation.ANNOTATION_PROCESSOR_PATH);
	parseCommandLine(commandLineArguments);
	_round = 0;
}