javax.tools.StandardLocation Java Examples

The following examples show how to use javax.tools.StandardLocation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JNIWriter.java    From openjdk-8 with 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 #2
Source File: IncrementalAnnotationProcessorProcessorTest.java    From gradle-incap-helper with Apache License 2.0 6 votes vote down vote up
@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 #3
Source File: JNIWriter.java    From TencentKona-8 with 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 File: PathDocFileFactory.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@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 #5
Source File: PatchModuleFileManager.java    From netbeans with 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 #6
Source File: JdkCompiler.java    From dubbox with 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 #7
Source File: T6418694.java    From jdk8u60 with 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 #8
Source File: ElementStructureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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 #9
Source File: JavacParser.java    From j2objc with 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 #10
Source File: TestSuperclass.java    From openjdk-jdk8u with 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 #11
Source File: TestValidRelativeNames.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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 #12
Source File: JavacTemplateTestBase.java    From hottub with 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 #13
Source File: T6410706.java    From openjdk-jdk8u with 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 #14
Source File: TestCompileJARInClassPath.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 #15
Source File: BootClassPathUtil.java    From netbeans with 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 #16
Source File: AbstractGenerator.java    From picocli with 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 #17
Source File: JdkCompiler.java    From yugong with 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 #18
Source File: SetLocationForModule.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@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 #19
Source File: TestSearchPaths.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void testNativeHeaderOutput() throws IOException {
    String test = "testNativeHeaderOutput";
    System.err.println("test: " + test);

    for (int i = 1; i <= 5; i++) {
        File classes = createDir(test + "/" + i + "/classes");
        File headers = createDir(test + "/" + i + "/hdrs");
        List<String> options;
        switch (i) {
            default:
                options = getOptions("-d", classes.getPath(), "-h", headers.getPath());
                break;

            case 3:
                setLocation(NATIVE_HEADER_OUTPUT, headers);
                options = getOptions("-d", classes.getPath());
                break;
        }
        List<JavaFileObject> sources = getSources("class C" + i + " { native void m(); }");
        callTask(options, sources);
        checkPath(NATIVE_HEADER_OUTPUT, Mode.EQUALS, headers);
        checkFile(NATIVE_HEADER_OUTPUT, "C" + i + ".h");
    }

    tested.add(StandardLocation.NATIVE_HEADER_OUTPUT);
    System.err.println();
}
 
Example #20
Source File: Locations.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void initHandlers() {
    handlersForLocation = new HashMap<>();
    handlersForOption = new EnumMap<>(Option.class);

    BasicLocationHandler[] handlers = {
        new BootClassPathLocationHandler(),
        new ClassPathLocationHandler(),
        new SimpleLocationHandler(StandardLocation.SOURCE_PATH, Option.SOURCE_PATH),
        new SimpleLocationHandler(StandardLocation.ANNOTATION_PROCESSOR_PATH, Option.PROCESSOR_PATH),
        new SimpleLocationHandler(StandardLocation.ANNOTATION_PROCESSOR_MODULE_PATH, Option.PROCESSOR_MODULE_PATH),
        new OutputLocationHandler(StandardLocation.CLASS_OUTPUT, Option.D),
        new OutputLocationHandler(StandardLocation.SOURCE_OUTPUT, Option.S),
        new OutputLocationHandler(StandardLocation.NATIVE_HEADER_OUTPUT, Option.H),
        new ModuleSourcePathLocationHandler(),
        new PatchModulesLocationHandler(),
        new ModulePathLocationHandler(StandardLocation.UPGRADE_MODULE_PATH, Option.UPGRADE_MODULE_PATH),
        new ModulePathLocationHandler(StandardLocation.MODULE_PATH, Option.MODULE_PATH),
        new SystemModulesLocationHandler(),
    };

    for (BasicLocationHandler h : handlers) {
        handlersForLocation.put(h.location, h);
        for (Option o : h.options) {
            handlersForOption.put(o, h);
        }
    }
}
 
Example #21
Source File: DynaFileManager.java    From kan-java with Eclipse Public License 1.0 5 votes vote down vote up
public String inferBinaryName(Location location, JavaFileObject file) {
    if (StandardLocation.CLASS_OUTPUT.equals(location) || StandardLocation.CLASS_PATH.equals(location)
            || StandardLocation.SOURCE_OUTPUT.equals(location) || StandardLocation.SOURCE_PATH.equals(location)) {
        if (file instanceof JavaSourceFile) {
            return null;
        } else if (file instanceof JavaClassFile) {
            return ((JavaClassFile) file).getBinaryClassName();
        }
    }
    return super.inferBinaryName(location, file);
}
 
Example #22
Source File: AbstractAnnotationProcessor.java    From dekorate with Apache License 2.0 5 votes vote down vote up
/**
 * Get the output directory of the processor.
 * @return  The directroy.
 */
public Path getOutputDirectory() {
  try {
    FileObject project = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, PACKAGE, String.format(PROJECT, TMP));
    return Paths.get(Urls.toFile(project.toUri().toURL()).getParentFile().getAbsolutePath());
  } catch (IOException e) {
    throw DekorateException.launderThrowable(e);
  }
}
 
Example #23
Source File: NativeHeaderTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * The worker method for each test case.
 * Compile the files and verify that exactly the expected set of header files
 * is generated.
 */
void test(RunKind rk, GenKind gk, List<File> files, Set<String> expect) throws Exception {
    List<String> args = new ArrayList<String>();
    if (gk == GenKind.FULL)
        args.add("-XDjavah:full");

    switch (rk) {
        case CMD:
            args.add("-d");
            args.add(classesDir.getPath());
            args.add("-h");
            args.add(headersDir.getPath());
            for (File f: files)
                args.add(f.getPath());
            int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()]));
            if (rc != 0)
                throw new Exception("compilation failed, rc=" + rc);
            break;

        case API:
            fm.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(srcDir));
            fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(classesDir));
            fm.setLocation(StandardLocation.NATIVE_HEADER_OUTPUT, Arrays.asList(headersDir));
            JavacTask task = javac.getTask(null, fm, null, args, null,
                    fm.getJavaFileObjectsFromFiles(files));
            if (!task.call())
                throw new Exception("compilation failed");
            break;
    }

    Set<String> found = createSet(headersDir.list());
    checkEqual("header files", expect, found);
}
 
Example #24
Source File: AnnotationUtils.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
public static boolean fileExists(Filer filer, String c){
    String outputFile = "META-INF/konduit-serving/" + c;
    try {
        FileObject file = filer.getResource(StandardLocation.CLASS_OUTPUT, "", outputFile);
        return file != null;
    } catch (IOException e){
        return false;
    }
}
 
Example #25
Source File: AnnotationUtils.java    From konduit-serving with Apache License 2.0 5 votes vote down vote up
public static void writeFile(Filer filer, String c, List<String> lines){
    if(lines.isEmpty())
        return;
    try {
        String outputFile = "META-INF/konduit-serving/" + c;
        FileObject file = filer.createResource(StandardLocation.CLASS_OUTPUT, "", outputFile);

        try (Writer w = file.openWriter()) {
            w.write(String.join("\n", lines));
        }

    } catch (Throwable t) {
        throw new RuntimeException("Error in annotation processing", t);
    }
}
 
Example #26
Source File: AptSourceFileManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput (Location l, String className, JavaFileObject.Kind kind, javax.tools.FileObject sibling)
    throws IOException, UnsupportedOperationException, IllegalArgumentException {
    URL aptRoot = getAptRoot(sibling);
    if (ModuleLocation.isInstance(l)) {
        ModuleLocation mloc = ModuleLocation.cast(l);
        l = mloc.getBaseLocation();
        if (aptRoot == null) {
            final Iterator<? extends URL> it = mloc.getModuleRoots().iterator();
            aptRoot = it.hasNext() ? it.next() : null;
        } else if (!mloc.getModuleRoots().contains(aptRoot)) {
            throw new UnsupportedOperationException("ModuleLocation's APT root differs from the sibling's APT root");
        }
    }
    final Location location = l;
    if (StandardLocation.SOURCE_OUTPUT != location) {
        throw new UnsupportedOperationException("Only apt output is supported."); // NOI18N
    }
    if (aptRoot == null) {
        throw new UnsupportedOperationException(noAptRootDebug(sibling));
    }
    final String nameStr = className.replace('.', File.separatorChar) + kind.extension;    //NOI18N
    //Always on master fs -> file is save.
    return Optional.ofNullable(URLMapper.findFileObject(aptRoot))
            .map(fo -> {
                File f = FileUtil.toFile(fo);
                return fileTx.createFileObject(location, new File(f, nameStr), f, null, null);
            }).get();
}
 
Example #27
Source File: TransportProcessorTest.java    From transport with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void overloadedUDF() throws IOException {
  assertThat(
      forResource("udfs/OverloadedUDF1.java"),
      forResource("udfs/OverloadedUDFInt.java"),
      forResource("udfs/OverloadedUDFString.java")
  ).processedWith(new TransportProcessor())
      .compilesWithoutError()
      .and()
      .generatesFileNamed(StandardLocation.CLASS_OUTPUT, "", Constants.UDF_RESOURCE_FILE_PATH)
      .withStringContents(Charset.defaultCharset(), asString(forResource("outputs/overloadedUDF.json")));
}
 
Example #28
Source File: NativeImageConfigGeneratorProcessorTest.java    From picocli with Apache License 2.0 5 votes vote down vote up
@Test
public void testGenerateReflectForNestedInnerEnum() {
    NativeImageConfigGeneratorProcessor processor = new NativeImageConfigGeneratorProcessor();
    Compilation compilation =
            javac()
                    .withProcessors(processor)
                    .withOptions("-A" + OPTION_PROJECT + "=nested/enum")
                    .compile(JavaFileObjects.forSourceLines(
                            "picocli.ls.FileList",
                            slurp("/picocli/ls/FileList.java")));
    assertThat(compilation).succeeded();
    assertThat(compilation)
            .generatedFile(StandardLocation.CLASS_OUTPUT, "META-INF/native-image/picocli-generated/nested/enum/reflect-config.json")
            .contentsAsUtf8String().isEqualTo(slurp("/picocli/ls/expected-reflect.json"));
}
 
Example #29
Source File: Test.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
/** Doc comment: run */
void run() throws Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisFile = new File(testSrc, getClass().getName() + ".java");
    JavacTool javac = JavacTool.create();
    StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
    Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjects(thisFile);
    testAnnoProcessor(javac, fm, fos, out, EXPECT_DOC_COMMENTS);
    testTaskListener(javac, fm, fos, out, EXPECT_DOC_COMMENTS);

    if (errors > 0)
        throw new Exception(errors + " errors occurred");
}
 
Example #30
Source File: TestJavacParser.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public void test4() {
    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;
}