Java 类javax.tools.StandardLocation 实例源码

项目:incubator-netbeans    文件:MRJARCachingFileManagerTest.java   
public void testJavac() throws Exception {
    final JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fm = jc.getStandardFileManager(
            null,
            Locale.ENGLISH,
            Charset.forName("UTF-8"));  //NOI18N
    fm.setLocation(
            StandardLocation.CLASS_PATH,
            Collections.singleton(FileUtil.archiveOrDirForURL(mvCp.entries().get(0).getURL())));
    Iterable<JavaFileObject> res = fm.list(
            StandardLocation.CLASS_PATH,
            "", //NOI18N
            EnumSet.of(JavaFileObject.Kind.CLASS),
            true);
    assertEquals(3, StreamSupport.stream(res.spliterator(), false).count());
}
项目:OpenJSharp    文件:JNIWriter.java   
/** 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
}
项目:openjdk-jdk10    文件:Test.java   
void testAPI(String opt, List<String> ref) throws Exception {
    File identifiers = new File(testSrc, "Identifiers.java");
    fm.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH, Arrays.asList(pluginJar));
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
    List<String> options = Arrays.asList(opt);
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(identifiers);

    System.err.println("test api: " + options + " " + files);
    Task.Result result = new JavacTask(tb, Task.Mode.API)
                              .fileManager(fm)
                              .options(opt)
                              .files(identifiers.toPath())
                              .run(Task.Expect.SUCCESS)
                              .writeAll();
    String out = result.getOutput(Task.OutputKind.DIRECT);
    checkOutput(out, ref);
}
项目:GitHub    文件:Output.java   
private boolean identicalFileIsAlreadyGenerated(CharSequence sourceCode) {
  try {
    String existingContent = new CharSource() {
      final String packagePath = !key.packageName.isEmpty() ? (key.packageName.replace('.', '/') + '/') : "";
      final String filename = key.relativeName + ".java";

      @Override
      public Reader openStream() throws IOException {
        return getFiler()
            .getResource(StandardLocation.SOURCE_OUTPUT,
                "", packagePath + filename)
            .openReader(true);
      }
    }.read();

    if (existingContent.contentEquals(sourceCode)) {
      // We are ok, for some reason the same file is already generated,
      // happens in Eclipse for example.
      return true;
    }
  } catch (Exception ignoredAttemptToGetExistingFile) {
    // we have some other problem, not an existing file
  }
  return false;
}
项目:openjdk-jdk10    文件:ModuleSourcePathTest.java   
@Test
public void getLocation_ISA(Path base) throws Exception {
    Path src1 = base.resolve("src1");
    tb.writeJavaFiles(src1.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path src2 = base.resolve("src2");
    tb.writeJavaFiles(src2.resolve("m2x").resolve("extra"), "module m2x { }", "package b; class B { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    String FS = File.separator;
    String PS = File.pathSeparator;
    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.handleOption("--module-source-path",
                List.of(src1 + PS + src2 + FS + "*" + FS + "extra").iterator());

        try {
            Iterable<? extends Path> paths = fm.getLocationAsPaths(StandardLocation.MODULE_SOURCE_PATH);
            out.println("result: " + asList(paths));
            throw new Exception("expected IllegalStateException not thrown");
        } catch (IllegalStateException e) {
            out.println("Exception thrown, as expected: " + e);
        }

        // even if we can't do getLocation for the MODULE_SOURCE_PATH, we should be able
        // to do getLocation for the modules, which will additionally confirm the option
        // was effective as intended.
        Location locn1 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m1x");
        checkLocation(fm.getLocationAsPaths(locn1), List.of(src1.resolve("m1x")));
        Location locn2 = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, "m2x");
        checkLocation(fm.getLocationAsPaths(locn2), List.of(src2.resolve("m2x").resolve("extra")));
    }
}
项目:jtsgen    文件:TsGenProcessorTest.java   
@Test
public void test_simple_interface_no_package() {
    JavaFileObject[] files = {JavaFileObjects.forResource("InterFaceTestNoPackage.java")};
    Compilation c = javac()
            .withProcessors(new TsGenProcessor())
            .compile(files);

    assertEquals(0, c.errors().size());

    // using default packages issues a warning
    assertEquals(c.diagnostics().asList().stream().filter(x -> x.getKind().equals(Diagnostic.Kind.WARNING)).count(), 1);

    // module name has to be is unknown
    assertTrue(c.generatedFile(StandardLocation.SOURCE_OUTPUT, JTSGEN_UNKNOWN, PACKAGE_JSON).isPresent());
    assertTrue(c.generatedFile(StandardLocation.SOURCE_OUTPUT, JTSGEN_UNKNOWN, "unknown.d.ts").isPresent());
}
项目:openjdk-jdk10    文件:CompilerUtils.java   
/**
 * Compile all the java sources in {@code <source>/**} to
 * {@code <destination>/**}. The destination directory will be created if
 * it doesn't exist.
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException if there is an I/O error scanning the source tree or
 *                     creating the destination directory
 */
public static boolean compile(Path source, Path destination, String ... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    List<Path> sources
        = Files.find(source, Integer.MAX_VALUE,
            (file, attrs) -> (file.toString().endsWith(".java")))
            .collect(Collectors.toList());

    Files.createDirectories(destination);
    jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                             Arrays.asList(destination));

    List<String> opts = Arrays.asList(options);
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, opts, null,
            jfm.getJavaFileObjectsFromPaths(sources));

    return task.call();
}
项目:openjdk-jdk10    文件:SetLocationForModule.java   
@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)));
        }
    }
}
项目:openjdk-jdk10    文件:TestSuperclass.java   
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;
}
项目:openjdk-jdk10    文件:TestCompileJARInClassPath.java   
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<>();
    try (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");
        }
    }
}
项目:incubator-netbeans    文件:ModuleSourceFileManager.java   
@Override
@CheckForNull
public Location getLocationForModule(Location location, JavaFileObject jfo) throws IOException {
    if (location != StandardLocation.MODULE_SOURCE_PATH) {
        throw new IllegalStateException(String.format("Unsupported location: %s", location));
    }
    final FileObject fo = URLMapper.findFileObject(jfo.toUri().toURL());
    if (fo != null) {
        for (ModuleLocation.WithExcludes moduleLocation : sourceModuleLocationsRemovedPatches()) {
            for (ClassPath.Entry moduleEntry : moduleLocation.getModuleEntries()) {
                final FileObject root = moduleEntry.getRoot();
                if (root != null && FileUtil.isParentOf(root, fo)) {
                    return moduleLocation;
                }
            }
        }
    }
    return null;
}
项目:incubator-netbeans    文件:ProxyFileManager.java   
@Override
@CheckForNull
public FileObject getFileForOutput(
        @NonNull final Location l,
        @NonNull final String packageName,
        @NonNull final String relativeName,
        @NullAllowed final FileObject sibling)
    throws IOException, UnsupportedOperationException, IllegalArgumentException {
    checkSingleOwnerThread();
    try {
        JavaFileManager[] fms = cfg.getFileManagers(
                l == StandardLocation.SOURCE_PATH ?
                    SOURCE_PATH_WRITE : l,
                null);
        if (fms.length == 0) {
            throw new UnsupportedOperationException("No JavaFileManager for location: " + l);  //NOI18N
        } else {
            return mark(
                    fms[0].getFileForOutput(l, packageName, relativeName, sibling),
                    l);
        }
    } finally {
        clearOwnerThread();
    }
}
项目:openjdk-jdk10    文件:StandardDocFileFactory.java   
@Override
Iterable<DocFile> list(Location location, DocPath path) {
    Location l = ((location == StandardLocation.SOURCE_PATH)
            && !fileManager.hasLocation(StandardLocation.SOURCE_PATH))
            ? StandardLocation.CLASS_PATH
            : location;

    Set<DocFile> files = new LinkedHashSet<>();
    for (Path f: fileManager.getLocationAsPaths(l)) {
        if (Files.isDirectory(f)) {
            f = f.resolve(path.getPath());
            if (Files.exists(f))
                files.add(new StandardDocFile(f));
        }
    }
    return files;
}
项目:openjdk-jdk10    文件:T8068517.java   
void runTest(String aJava, String bJava) throws Exception {
    try (JavaFileManager fm = ToolProvider.getSystemJavaCompiler().getStandardFileManager(null, null, null)) {
        ToolBox tb = new ToolBox();
        ToolBox.MemoryFileManager memoryFM1 = new ToolBox.MemoryFileManager(fm);
        new JavacTask(tb).fileManager(memoryFM1)
                          .sources(aJava, bJava)
                          .run();
        ToolBox.MemoryFileManager memoryFM2 = new ToolBox.MemoryFileManager(fm);
        new JavacTask(tb).fileManager(memoryFM2)
                          .sources(bJava, aJava)
                          .run();

        Assert.check(Arrays.equals(memoryFM1.getFileBytes(StandardLocation.CLASS_OUTPUT, "B"),
                                   memoryFM2.getFileBytes(StandardLocation.CLASS_OUTPUT, "B")));
    }
}
项目:openjdk-jdk10    文件:SetLocationForModule.java   
@Test
public void testOutput_nested(Path base) throws IOException {
    try (StandardJavaFileManager fm = comp.getStandardFileManager(null, null, null)) {
        Location locn = StandardLocation.CLASS_OUTPUT;

        Path out1 = Files.createDirectories(base.resolve("out1"));
        fm.setLocationForModule(locn, "m", List.of(out1));

        Location m = fm.getLocationForModule(locn, "m");
        checkEqual("initial setting",
                fm.getLocationAsPaths(m), out1);

        Path out2 = Files.createDirectories(base.resolve("out2"));
        checkException("create nested module",
                UnsupportedOperationException.class, "not supported for CLASS_OUTPUT[m]",
                () -> fm.setLocationForModule(m, "x", List.of(out2)));
    }
}
项目:incubator-netbeans    文件:CachingFileManagerTest.java   
private void doTestGetFileForInput(
        final ClassPath cp,
        final List<? extends Pair<Pair<String,String>,URI>> testCases) throws IOException, URISyntaxException {
    final CachingArchiveProvider provider = CachingArchiveProvider.getDefault();
    final CachingFileManager manager = new CachingFileManager(provider, cp, null, false, true);
    for (Pair<Pair<String,String>,URI> testCase : testCases) {
        final Pair<String,String> name = testCase.first();
        final URI expectedURI = testCase.second();
        FileObject fo = manager.getFileForInput(StandardLocation.CLASS_PATH, name.first(), name.second());
        if (expectedURI == null) {
            assertNull(
                String.format("Lookup: %s/%s expected: null",
                name.first(),
                name.second()),
                fo);
        } else {
            assertEquals(
                String.format("Lookup: %s/%s expected: %s",
                name.first(),
                name.second(),
                expectedURI),
                expectedURI,
                fo.toUri());
        }
    }        
}
项目:openjdk-jdk10    文件:CompilerUtils.java   
/**
 * Compile the specified module from the given module sourcepath
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException if there is an I/O error scanning the source tree or
 *                     creating the destination directory
 */
public static boolean compileModule(Path source, Path destination,
                                    String moduleName, String... options) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    try {
        Files.createDirectories(destination);
        jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                                 Arrays.asList(destination));
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    Stream<String> opts = Arrays.stream(new String[] {
        "--module-source-path", source.toString(), "-m", moduleName
    });
    List<String> javacOpts = Stream.concat(opts, Arrays.stream(options))
                                    .collect(Collectors.toList());
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, javacOpts, null, null);
    return task.call();
}
项目:openjdk-jdk10    文件:CompilerUtils.java   
/**
 * Compile all the java sources in {@code <source>/**} to
 * {@code <destination>/**}. The destination directory will be created if
 * it doesn't exist.
 *
 * All warnings/errors emitted by the compiler are output to System.out/err.
 *
 * @return true if the compilation is successful
 *
 * @throws IOException if there is an I/O error scanning the source tree or
 *                     creating the destination directory
 */
public static boolean compile(Path source, Path destination, String... options)
    throws IOException
{
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null);

    List<Path> sources
        = Files.find(source, Integer.MAX_VALUE,
                     (file, attrs) -> (file.toString().endsWith(".java")))
               .collect(Collectors.toList());

    Files.createDirectories(destination);
    jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT,
                             Arrays.asList(destination));

    List<String> opts = Arrays.asList(options);
    JavaCompiler.CompilationTask task
        = compiler.getTask(null, jfm, null, opts, null,
                           jfm.getJavaFileObjectsFromPaths(sources));

    return task.call();
}
项目:incubator-netbeans    文件:PatchedPublicProcessor.java   
private void flush(RoundEnvironment roundEnv) {
    if (!originatingElements.isEmpty()) {
        try (OutputStream os = processingEnv.getFiler().createResource(
                StandardLocation.CLASS_OUTPUT,
                "", "META-INF/.bytecodePatched",
                originatingElements.toArray(new Element[originatingElements.size()])).openOutputStream()) {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            for (Map.Entry<String, String> exEntry : superclasses.entrySet()) {
                String api = exEntry.getKey();
                String sup = exEntry.getValue();

                bw.append("extend.").append(api).append("=").append(sup);
                bw.newLine();
            }
            bw.flush();
        } catch (IOException x) {
            processingEnv.getMessager().printMessage(Kind.ERROR, x.getMessage());
        }
    }
}
项目:dubbo2    文件:JdkCompiler.java   
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);
}
项目:openjdk-jdk10    文件:ModuleSourcePathTest.java   
@Test
public void setLocation(Path base) throws Exception {
    Path src = base.resolve("src");
    tb.writeJavaFiles(src.resolve("m1x"), "module m1x { }", "package a; class A { }");
    Path modules = base.resolve("modules");
    tb.createDirectories(modules);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
        fm.setLocationFromPaths(StandardLocation.MODULE_SOURCE_PATH, List.of(src));
        new JavacTask(tb)
                .options("-XDrawDiagnostics")
                .fileManager(fm)
                .outdir(modules)
                .files(findJavaFiles(src))
                .run()
                .writeAll();

        checkFiles(modules.resolve("m1x/module-info.class"), modules.resolve("m1x/a/A.class"));
    }
}
项目:syndesis    文件:SyndesisExtensionActionProcessorTest.java   
@Test
public void test() throws URISyntaxException, MalformedURLException {
    Compilation compilation = Compiler.javac()
        .withProcessors(new SyndesisExtensionActionProcessor())
        .compile(JavaFileObjects.forSourceString(
            "test.AnnotatedClassTest",
            "package test;\n" +
            "\n" +
            "@io.syndesis.integration.runtime.api.SyndesisExtensionAction(\n" +
            "    id = \"action-id\",\n" +
            "    name = \"action-name\",\n" +
            "    description = \"action-description\"\n" +
            ")\n" +
            "public class AnnotatedClassTest {\n" +
            "}"
        )
    );

    assertTrue(compilation.generatedFile(StandardLocation.SOURCE_OUTPUT, "test/AnnotatedClassTest-action-id.properties").isPresent());
}
项目:openjdk-jdk10    文件:JavadocHelper.java   
private Pair<JavacTask, CompilationUnitTree> findSource(String moduleName,
                                                        String binaryName) throws IOException {
    JavaFileObject jfo = fm.getJavaFileForInput(StandardLocation.SOURCE_PATH,
                                                binaryName,
                                                JavaFileObject.Kind.SOURCE);

    if (jfo == null)
        return null;

    List<JavaFileObject> jfos = Arrays.asList(jfo);
    JavaFileManager patchFM = moduleName != null
            ? new PatchModuleFileManager(baseFileManager, jfo, moduleName)
            : baseFileManager;
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, patchFM, d -> {}, null, null, jfos);
    Iterable<? extends CompilationUnitTree> cuts = task.parse();

    task.enter();

    return Pair.of(task, cuts.iterator().next());
}
项目:beaker-notebook-archive    文件:URIUtil.java   
/**
 * Builds url for a given location, class or internal name
 *
 * @param location java file manager location
 * @param name     name
 * @return URI
 */
public static URI buildUri(JavaFileManager.Location location, String name) {
    String extension = "";
    String template = location.getName().toLowerCase().replace("_", "") + ":///%s%s";
    if (location == StandardLocation.CLASS_OUTPUT) {
        extension = JavaFileObject.Kind.CLASS.extension;
        template = CLASS_CODE_URI_TEMPLATE;
    } else if (location == StandardLocation.SOURCE_OUTPUT) {
        extension = JavaFileObject.Kind.SOURCE.extension;
        template = SOURCE_CODE_URI_TEMPLATE;
    }
    int dotLastPosition = name.lastIndexOf('.');
    if (dotLastPosition != -1) {
        name = name.replace('.', '/');
    }
    return buildUri(String.format(template, name, extension));
}
项目:beaker-notebook-archive    文件:SimpleClassLoader.java   
protected Class<?> findClassInJarFile(String qualifiedClassName) throws ClassNotFoundException {
    URI classUri = URIUtil.buildUri(StandardLocation.CLASS_OUTPUT, qualifiedClassName);
    String internalClassName = classUri.getPath().substring(1);
    JarFile jarFile = null;
    try {
        for (int i = 0; i < jarFiles.size(); i++) {
            jarFile = jarFiles.get(i);
            JarEntry jarEntry = jarFile.getJarEntry(internalClassName);
            if (jarEntry != null) {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    byte[] byteCode = new byte[(int) jarEntry.getSize()];
                    ByteStreams.read(inputStream, byteCode, 0, byteCode.length);
                    return defineClass(qualifiedClassName, byteCode, 0, byteCode.length);
                } finally {
                    Closeables.closeQuietly(inputStream);
                }
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(String.format("Failed to lookup class %s in jar file %s", qualifiedClassName, jarFile), e);
    }
    return null;
}
项目:openjdk-jdk10    文件:JavapTask.java   
private Location findModule(String moduleName) throws IOException {
    Location[] locns = {
        StandardLocation.UPGRADE_MODULE_PATH,
        StandardLocation.SYSTEM_MODULES,
        StandardLocation.MODULE_PATH
    };
    for (Location segment: locns) {
        for (Set<Location> set: fileManager.listLocationsForModules(segment)) {
            Location result = null;
            for (Location l: set) {
                String name = fileManager.inferModuleName(l);
                if (name.equals(moduleName)) {
                    if (result == null)
                        result = l;
                    else
                        throw new IOException("multiple definitions found for " + moduleName);
                }
            }
            if (result != null)
                return result;
        }
    }
    return null;
}
项目:incap    文件:Version1MappingFileFormatter.java   
public static GeneratedFile createGeneratedFile(String description) {
  String[] fields = description.split(FIELD_SEPARATOR);
  String typeString = fields[0];
  GeneratedFileType type = valueOf(typeString);
  switch (type) {
    case SOURCE:
      return new GeneratedSourceFile(fields[1]);

    case CLASS:
      return new GeneratedClassFile(fields[1]);

    case RESOURCE:
      Location location = StandardLocation.valueOf(fields[1]);
      CharSequence pkg = fields[2];
      CharSequence relativeName = fields[3];
      return new GeneratedResourceFile(location, pkg, relativeName);

    default:
      throw new IllegalStateException(
          String.format(
              "Unable to parse type %s in generated file description %s", type, description));
  }
}
项目:openjdk-jdk10    文件:JImageGenerator.java   
public static boolean compile(Path source, Path destination, String... options) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager jfm = compiler.getStandardFileManager(null, null, null)) {
        List<Path> sources
                = Files.find(source, Integer.MAX_VALUE,
                (file, attrs) -> file.toString().endsWith(".java"))
                .collect(Collectors.toList());

        Files.createDirectories(destination);
        jfm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singleton(destination));

        List<String> opts = Arrays.asList(options);
        JavaCompiler.CompilationTask task
                = compiler.getTask(null, jfm, null, opts, null,
                jfm.getJavaFileObjectsFromPaths(sources));
        List<String> list = new ArrayList<>(opts);
        list.addAll(sources.stream()
                .map(Path::toString)
                .collect(Collectors.toList()));
        System.err.println("javac options: " + optionsPrettyPrint(list.toArray(new String[list.size()])));
        return task.call();
    }
}
项目:openjdk-jdk10    文件:ElementsTable.java   
/**
 * Creates the table to manage included and excluded elements.
 *
 * @param context the context to locate commonly used objects
 * @param location the location used to locate source files
 */
ElementsTable(Context context, Map<ToolOption, Object> opts) {
    this.toolEnv = ToolEnvironment.instance(context);
    this.syms = Symtab.instance(context);
    this.names = Names.instance(context);
    this.fm = toolEnv.fileManager;
    this.modules = Modules.instance(context);
    this.opts = opts;
    this.messager = Messager.instance0(context);
    this.compiler = JavaCompiler.instance(context);
    Source source = Source.instance(context);

    List<Location> locs = new ArrayList<>();
    if (modules.multiModuleMode) {
        locs.add(StandardLocation.MODULE_SOURCE_PATH);
    } else {
        if (toolEnv.fileManager.hasLocation(StandardLocation.SOURCE_PATH))
            locs.add(StandardLocation.SOURCE_PATH);
        else
            locs.add(StandardLocation.CLASS_PATH);
    }
    if (source.allowModules() && toolEnv.fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH))
        locs.add(StandardLocation.PATCH_MODULE_PATH);
    this.locations = Collections.unmodifiableList(locs);

    getEntry("").excluded = false;

    accessFilter = new ModifierFilter(opts);
    xclasses = (boolean)opts.getOrDefault(ToolOption.XCLASSES, false);
    expandRequires = (AccessKind)opts.get(ToolOption.EXPAND_REQUIRES);
}
项目:EM    文件:ActivatorAnnotationProcessor.java   
public void generateFile() throws IOException {

        FileObject fileObject = filer.createResource(StandardLocation.SOURCE_OUTPUT, "", "em.activator.bnd");
        try (Writer writer = fileObject.openWriter()) {
            if (activator != null) {
                writer.write("Bundle-Activator: " + activator + "\n");
            }
            if (extensionActivator != null) {
                writer.write("ExtensionBundle-Activator: " + extensionActivator + "\n");
            }
        }
    }
项目:GitHub    文件:BindViewTest.java   
@Test public void bindingGeneratedView() {
  JavaFileObject source = JavaFileObjects.forSourceString("test.Test", ""
      + "package test;\n"
      + "import butterknife.BindView;\n"
      + "@PerformGeneration\n"
      + "public class Test {\n"
      + "    @BindView(1) GeneratedView thing;\n"
      + "}"
  );

  // w/o the GeneratingProcessor it can't find `class GeneratedView`
  assertAbout(javaSources()).that(ImmutableList.of(source, TestGeneratingProcessor.ANNOTATION))
      .processedWith(new ButterKnifeProcessor())
      .failsToCompile()
      .withErrorContaining("cannot find symbol");

  // now the GeneratingProcessor should let it compile
  assertAbout(javaSources()).that(ImmutableList.of(source, TestGeneratingProcessor.ANNOTATION))
      .processedWith(new ButterKnifeProcessor(), new TestGeneratingProcessor("GeneratedView",
          "package test;",
          "import android.content.Context;",
          "import android.view.View;",
          "public class GeneratedView extends View {",
          "  public GeneratedView(Context context) {",
          "    super(context);",
          "  }",
          "}"
      ))
      .compilesWithoutError()
      .withNoteContaining("@BindView field with unresolved type (GeneratedView)").and()
      .withNoteContaining("must elsewhere be generated as a View or interface").and()
      .and()
      .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "test", "Test_ViewBinding.class");
}
项目:openjdk-jdk10    文件:Modules.java   
/**
 * Determine the location for the module on the module source path
 * or source output directory which contains a given CompilationUnit.
 * If the source output directory is unset, the class output directory
 * will be checked instead.
 * {@code null} is returned if no such module can be found.
 * @param tree the compilation unit tree
 * @return the location for the enclosing module
 * @throws IOException if there is a problem while searching for the module.
 */
private Location getModuleLocation(JCCompilationUnit tree) throws IOException {
    JavaFileObject fo = tree.sourcefile;

    Location loc =
            fileManager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, fo);
    if (loc == null) {
        Location sourceOutput = fileManager.hasLocation(StandardLocation.SOURCE_OUTPUT) ?
                StandardLocation.SOURCE_OUTPUT : StandardLocation.CLASS_OUTPUT;
        loc =
            fileManager.getLocationForModule(sourceOutput, fo);
    }
    return loc;
}
项目:GitHub    文件:Compiler.java   
public void compile(JavaCompiler javaCompiler, Writer out, File sourceDirectory, File outputDirectory, List<File> classpath, DiagnosticListener<? super JavaFileObject> diagnosticListener, String targetVersion ) {
    targetVersion = targetVersion == null ? "1.6" : targetVersion;

    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);

    if (outputDirectory != null) {
        try {
            fileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                    Arrays.asList(outputDirectory));
            fileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
        } catch (IOException e) {
            throw new RuntimeException("could not set output directory", e);
        }
    }

    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(findAllSourceFiles(sourceDirectory));

    ArrayList<String> options = new ArrayList<String>();
    options.add("-source");
    options.add(targetVersion);
    options.add("-target");
    options.add(targetVersion);
    options.add("-encoding");
    options.add("UTF8");
    options.add("-Xlint:-options");
    options.add("-Xlint:unchecked");
    if (compilationUnits.iterator().hasNext()) {
        Boolean success = javaCompiler.getTask(out, fileManager, diagnosticListener, options, null, compilationUnits).call();
        assertThat("Compilation was not successful, check stdout for errors", success, is(true));
    }

}
项目:GitHub    文件:Output.java   
private void readExistingEntriesInto(Collection<String> services) {
  try {
    FileObject existing = getFiler().getResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName);
    FluentIterable.from(CharStreams.readLines(existing.openReader(true)))
        .filter(Predicates.not(Predicates.contains(SERVICE_FILE_COMMENT_LINE)))
        .copyInto(services);
  } catch (Exception ex) {
    // unable to read existing file
  }
}
项目:GitHub    文件:Output.java   
private void writeLinesFrom(Iterable<String> services) throws IOException {
  new CharSink() {
    @Override
    public Writer openStream() throws IOException {
      return getFiler()
          .createResource(StandardLocation.CLASS_OUTPUT, key.packageName, key.relativeName)
          .openWriter();
    }
  }.writeLines(services, "\n");
}
项目:GitHub    文件:Processor.java   
private String getTemplateText(
    Filer filer,
    TypeElement templateType,
    PackageElement packageElement) throws IOException {
  CharSequence relativeName = templateType.getSimpleName() + ".generator";
  CharSequence packageName = packageElement.getQualifiedName();
  List<Exception> suppressed = Lists.newArrayList();
  try {
    return filer.getResource(StandardLocation.SOURCE_PATH, packageName, relativeName)
        .getCharContent(true)
        .toString();
  } catch (Exception cannotGetFromSourcePath) {
    suppressed.add(cannotGetFromSourcePath);
    try {
      return filer.getResource(StandardLocation.CLASS_OUTPUT, packageName, relativeName)
          .getCharContent(true)
          .toString();
    } catch (Exception cannotGetFromOutputPath) {
      suppressed.add(cannotGetFromOutputPath);
      try {
        return filer.getResource(StandardLocation.CLASS_PATH,
            "",
            packageName.toString().replace('.', '/') + '/' + relativeName)
            .getCharContent(true)
            .toString();
      } catch (IOException cannotGetFromClasspath) {
        for (Exception e : suppressed) {
          cannotGetFromClasspath.addSuppressed(e);
        }
        throw cannotGetFromClasspath;
      }
    }
  }
}
项目:jsf-sdk    文件:TemplatePrecompiler.java   
@SuppressWarnings("serial")
private static void matchClassNames(List<String> ret, final String className)
        throws IOException {
    String packageName = className.substring(0, className.lastIndexOf('.'));
    String relativedName = className.substring(
            className.lastIndexOf('.') + 1, className.length());
    String patName = relativedName.replace("*", "(\\w+)");
    Pattern pat = Pattern.compile(patName);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavaFileManager fm = compiler.getStandardFileManager(
            new DiagnosticCollector<JavaFileObject>(), null, null);
    HashSet<JavaFileObject.Kind> kind = new HashSet<JavaFileObject.Kind>() {
        {
            add(JavaFileObject.Kind.CLASS);
        }
    };

    for (JavaFileObject f : fm.list(StandardLocation.PLATFORM_CLASS_PATH, packageName, kind, false)) {
        String relatived0 = f.getName();
        String name0 = relatived0.substring(0, relatived0.length() - ".class".length());
        Matcher m = pat.matcher(name0);
        if (m.matches()) {
            String name = packageName + '.' + name0;
            if (!ret.contains(name)) {
                ret.add(name);
            }
        }
    }
}
项目:openjdk-jdk10    文件:PathsTest.java   
File createJar() throws IOException {
    File f = new File("test.jar");
    try (JavaFileManager fm = ToolProvider.getSystemJavaCompiler()
            .getStandardFileManager(null, null, null)) {
        ToolBox tb = new ToolBox();
        new JarTask(tb, f.getPath())
            .files(fm, StandardLocation.PLATFORM_CLASS_PATH, "java.lang.*")
            .run();
    }
    return f;
}
项目:OpenJSharp    文件:FilerCodeWriter.java   
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();
}
项目:incubator-netbeans    文件:PatchModuleFileManager.java   
@Override
public Location getLocationForModule(Location location, String moduleName) throws IOException {
    if (location == StandardLocation.PATCH_MODULE_PATH) {
        return moduleLocations(location).stream()
                .filter((ml) -> moduleName != null && moduleName.equals(ml.getModuleName()))
                .findFirst()
                .orElse(null);
    } else if (location == StandardLocation.CLASS_OUTPUT) {
        return moduleLocations(StandardLocation.PATCH_MODULE_PATH).stream()
                .filter((pl) -> moduleName != null && moduleName.equals(pl.getModuleName()))
                .findFirst()
                .map((pl) -> {
                    final List<URL> cacheRoots = pl.getSrc() == null ?
                            Collections.emptyList() :
                            pl.getSrc().getModuleRoots().stream()
                                    .map((url) -> {
                                        try {
                                            return BaseUtilities.toURI(JavaIndex.getClassFolder(url, false, false)).toURL();
                                        } catch (IOException ioe) {
                                            LOG.log(Level.WARNING, "Cannot determine the cache URL for: {0}", url); //NOI18N
                                            return null;
                                        }
                                    })
                                    .filter((url) -> url != null)
                                    .collect(Collectors.toList());
                    return cacheRoots.isEmpty() ?
                            null :
                            new PatchLocation(
                                StandardLocation.PATCH_MODULE_PATH,
                                cacheRoots,
                                Collections.emptyList(),
                                pl.getModuleName());
                })
                .orElse(null);
    } else {
        return null;
    }
}