Java Code Examples for javax.tools.JavaFileObject.Kind

The following examples show how to use javax.tools.JavaFileObject.Kind. 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
Source Project: kan-java   Source File: DynaFileManager.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    if (Kind.CLASS != kind && Kind.SOURCE != kind)
        throw new IOException("Unsupported output kind: " + kind);
    if (!(location instanceof StandardLocation))
        throw new IOException("Unsupported output location: " + location);
    switch ((StandardLocation) location) {
    case CLASS_OUTPUT:
        return getOrCreateMemFileByClassName(className, this.classes, JavaClassFile.class);
    case SOURCE_OUTPUT:
        return getOrCreateMemFileByClassName(className, this.srcs, JavaSourceFile.class);
    case CLASS_PATH:
    case SOURCE_PATH:
    case ANNOTATION_PROCESSOR_PATH:
    case PLATFORM_CLASS_PATH:
    default:
        throw new IOException("Unsupported output location: " + location);
    }
}
 
Example 2
Source Project: hottub   Source File: JavacPathFileManager.java    License: 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 {
    // validatePackageName(packageName);
    nullCheck(packageName);
    nullCheck(kinds);

    Iterable<? extends Path> paths = getLocation(location);
    if (paths == null)
        return List.nil();
    ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();

    for (Path path : paths)
        list(path, packageName, kinds, recurse, results);

    return results.toList();
}
 
Example 3
@Override
public Iterable<JavaFileObject> list(Location location, String packageName, Set<Kind> kinds, boolean recurse)
		throws IOException {
	
	Iterable<? extends File> allFilesInLocations = getLocation(location);
	if (allFilesInLocations == null) {
		throw new IllegalArgumentException("Unknown location : " + location);//$NON-NLS-1$
	}
	
	ArrayList<JavaFileObject> collector = new ArrayList<JavaFileObject>();
	String normalizedPackageName = normalized(packageName);
	for (File file : allFilesInLocations) {
		collectAllMatchingFiles(file, normalizedPackageName, kinds, recurse, collector);
	}
	return collector;
}
 
Example 4
@Override
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    // Acquire the list of files.
    Iterable<JavaFileObject> files = super.list(location, packageName, kinds, recurse);
    if (visibleSources.isEmpty()) {
        return files;
    }
    // Now filter!
    ListBuffer<JavaFileObject> filteredFiles = new ListBuffer<JavaFileObject>();
    for (JavaFileObject f : files) {
        URI uri = f.toUri();
        String t = uri.toString();
        if (t.startsWith("jar:")
            || t.endsWith(".class")
            || visibleSources.contains(uri))
        {
            filteredFiles.add(f);
        }
    }
    return filteredFiles;
}
 
Example 5
Source Project: openjdk-8   Source File: SmartFileManager.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location,
                                           String className,
                                           Kind kind,
                                           FileObject sibling)
    throws IOException
{
    JavaFileObject file = super.getJavaFileForOutput(location, className, kind, sibling);
    if (file == null) return file;
    int dp = className.lastIndexOf('.');
    String pkg_name = "";
    if (dp != -1) {
        pkg_name = className.substring(0, dp);
    }
    // When modules are in use, then the mod_name might be something like "jdk_base"
    String mod_name = "";
    addArtifact(mod_name+":"+pkg_name, file.toUri());
    return file;
}
 
Example 6
Source Project: dremio-oss   Source File: TestClassCompilers.java    License: Apache License 2.0 6 votes vote down vote up
@BeforeClass
public static void compileDependencyClass() throws IOException, ClassNotFoundException {
  JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
  Assume.assumeNotNull(javaCompiler);

  classes = temporaryFolder.newFolder("classes");;

  StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, Locale.ROOT, UTF_8);
  fileManager.setLocation(StandardLocation.CLASS_OUTPUT, ImmutableList.of(classes));

  SimpleJavaFileObject compilationUnit = new SimpleJavaFileObject(URI.create("FooTest.java"), Kind.SOURCE) {
    String fooTestSource = Resources.toString(Resources.getResource("com/dremio/exec/compile/FooTest.java"), UTF_8);
    @Override
    public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
      return fooTestSource;
    }
  };

  CompilationTask task = javaCompiler.getTask(null, fileManager, null, Collections.<String>emptyList(), null, ImmutableList.of(compilationUnit));
  assertTrue(task.call());
}
 
Example 7
@Override
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    // Acquire the list of files.
    Iterable<JavaFileObject> files = super.list(location, packageName, kinds, recurse);
    if (visibleSources.isEmpty()) {
        return files;
    }
    // Now filter!
    ListBuffer<JavaFileObject> filteredFiles = new ListBuffer<JavaFileObject>();
    for (JavaFileObject f : files) {
        URI uri = f.toUri();
        String t = uri.toString();
        if (t.startsWith("jar:")
            || t.endsWith(".class")
            || visibleSources.contains(uri))
        {
            filteredFiles.add(f);
        }
    }
    return filteredFiles;
}
 
Example 8
@Override
public Iterable<JavaFileObject> list(Location location,
        String packageName, Set<Kind> kinds, boolean recurse)
        throws IOException {
    // validatePackageName(packageName);
    nullCheck(packageName);
    nullCheck(kinds);

    Iterable<? extends Path> paths = getLocation(location);
    if (paths == null)
        return List.nil();
    ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();

    for (Path path : paths)
        list(path, packageName, kinds, recurse, results);

    return results.toList();
}
 
Example 9
@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 10
@Override
public Iterable<JavaFileObject> list(Location location,
        String packageName, Set<Kind> kinds, boolean recurse)
        throws IOException {
    // validatePackageName(packageName);
    nullCheck(packageName);
    nullCheck(kinds);

    Iterable<? extends Path> paths = getLocation(location);
    if (paths == null)
        return List.nil();
    ListBuffer<JavaFileObject> results = new ListBuffer<JavaFileObject>();

    for (Path path : paths)
        list(path, packageName, kinds, recurse, results);

    return results.toList();
}
 
Example 11
Source Project: JReFrameworker   Source File: JavaFile.java    License: MIT License 6 votes vote down vote up
public JavaFileObject toJavaFileObject() {
  URI uri = URI.create((packageName.isEmpty()
      ? typeSpec.name
      : packageName.replace('.', '/') + '/' + typeSpec.name)
      + Kind.SOURCE.extension);
  return new SimpleJavaFileObject(uri, Kind.SOURCE) {
    private final long lastModified = System.currentTimeMillis();
    @Override public String getCharContent(boolean ignoreEncodingErrors) {
      return JavaFile.this.toString();
    }
    @Override public InputStream openInputStream() throws IOException {
      return new ByteArrayInputStream(getCharContent(true).getBytes(UTF_8));
    }
    @Override public long getLastModified() {
      return lastModified;
    }
  };
}
 
Example 12
Source Project: openjdk-jdk9   Source File: JavaCompiler.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** Emit plain Java source for a class.
 *  @param env    The attribution environment of the outermost class
 *                containing this class.
 *  @param cdef   The class definition to be printed.
 */
JavaFileObject printSource(Env<AttrContext> env, JCClassDecl cdef) throws IOException {
    JavaFileObject outFile
       = fileManager.getJavaFileForOutput(CLASS_OUTPUT,
                                           cdef.sym.flatname.toString(),
                                           JavaFileObject.Kind.SOURCE,
                                           null);
    if (inputFiles.contains(outFile)) {
        log.error(cdef.pos(), "source.cant.overwrite.input.file", outFile);
        return null;
    } else {
        try (BufferedWriter out = new BufferedWriter(outFile.openWriter())) {
            new Pretty(out, true).printUnit(env.toplevel, cdef);
            if (verbose)
                log.printVerbose("wrote.file", outFile);
        }
        return outFile;
    }
}
 
Example 13
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException {
    try {
        return new SimpleJavaFileObject(new URI("mem://" + className.replace('.', '/') + kind.extension), kind) {
            @Override public OutputStream openOutputStream() throws IOException {
                return new ByteArrayOutputStream() {
                    @Override public void close() throws IOException {
                        super.close();
                        name2Content.put(className, toByteArray());
                    }
                };
            }
        };
    } catch (URISyntaxException ex) {
        throw new AssertionError(ex);
    }
}
 
Example 14
/**
 * @throws IllegalArgumentException {@inheritDoc}
 * @throws IllegalStateException {@inheritDoc}
 */
public JavaFileObject getJavaFileForOutput(Location location,
                                           String className,
                                           Kind kind,
                                           FileObject sibling)
    throws IOException
{
    return fileManager.getJavaFileForOutput(location, className, kind, sibling);
}
 
Example 15
public static Kind getKind(String name) {
    if (name.endsWith(Kind.CLASS.extension))
        return Kind.CLASS;
    else if (name.endsWith(Kind.SOURCE.extension))
        return Kind.SOURCE;
    else if (name.endsWith(Kind.HTML.extension))
        return Kind.HTML;
    else
        return Kind.OTHER;
}
 
Example 16
Source Project: openjdk-jdk9   Source File: JavacTrees.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public void printMessage(Diagnostic.Kind kind, CharSequence msg,
        com.sun.source.doctree.DocTree t,
        com.sun.source.doctree.DocCommentTree c,
        com.sun.source.tree.CompilationUnitTree root) {
    printMessage(kind, msg, ((DCTree) t).pos((DCDocComment) c), root);
}
 
Example 17
public List<CompilationMessage> addAndResolveDependencies(String[] dependencies) {
	List<CompilationMessage> resolutionMessages = new ArrayList<>();
	for (String dependency : dependencies) {
		if (dependency.startsWith("maven:")) {
			// Resolving an explicit external archive
			String coordinates = dependency.replaceFirst("maven:\\/*", "");
			DependencyResolver engine = DependencyResolver.instance();
			try {
				File resolved = engine.resolve(
						new Dependency(new DefaultArtifact(coordinates), "runtime"));
				// Example:
				// dependency =
				// maven://org.springframework:spring-expression:4.3.9.RELEASE
				// resolved.toURI() =
				// file:/Users/aclement/.m2/repository/
				// org/springframework/spring-expression/4.3.9.RELEASE/spring-expression-4.3.9.RELEASE.jar
				this.resolvedAdditionalDependencies.put(dependency, resolved);
			}
			catch (RuntimeException re) {
				CompilationMessage compilationMessage = new CompilationMessage(
						CompilationMessage.Kind.ERROR, re.getMessage(), null, 0, 0);
				resolutionMessages.add(compilationMessage);
			}
		}
		else if (dependency.startsWith("file:")) {
			this.resolvedAdditionalDependencies.put(dependency,
					new File(URI.create(dependency)));
		}
		else {
			resolutionMessages.add(new CompilationMessage(
					CompilationMessage.Kind.ERROR,
					"Unrecognized dependency: " + dependency
							+ " (expected something of the form: maven://groupId:artifactId:version)",
					null, 0, 0));
		}
	}
	return resolutionMessages;
}
 
Example 18
Source Project: dubbo3   Source File: JdkCompiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String qualifiedName, Kind kind, FileObject outputFile)
        throws IOException {
    JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind);
    classLoader.add(qualifiedName, file);
    return file;
}
 
Example 19
Source Project: dremio-oss   Source File: DremioJavaFileManager.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 {
  logger.trace("Creating [email protected](location:{}, className:{}, kinds:{})", location, className, kind);
  if (sibling != null && sibling instanceof DremioJavaFileObject) {
    return ((DremioJavaFileObject)sibling).addOutputJavaFile(className);
  }
  throw new IOException("The source file passed to getJavaFileForOutput() is not a DremioJavaFileObject: " + sibling);
}
 
Example 20
Source Project: Akatsuki   Source File: InMemoryJavaFileManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind)
		throws IOException {
	if (location.isOutputLocation()) {
		return inMemoryFileObjects
				.getIfPresent(uriForJavaFileObject(location, className, kind));
	} else {
		return super.getJavaFileForInput(location, className, kind);
	}
}
 
Example 21
/** Implement policy to choose to derive information from a source
 *  file or a class file when both are present.  May be overridden
 *  by subclasses.
 */
protected JavaFileObject preferredFileObject(JavaFileObject a,
                                       JavaFileObject b) {

    if (preferSource)
        return (a.getKind() == JavaFileObject.Kind.SOURCE) ? a : b;
    else {
        long adate = a.getLastModified();
        long bdate = b.getLastModified();
        // 6449326: policy for bad lastModifiedTime in ClassReader
        //assert adate >= 0 && bdate >= 0;
        return (adate > bdate) ? a : b;
    }
}
 
Example 22
Source Project: openjdk-jdk9   Source File: ToolBox.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Constructs a memory file object.
 * @param name binary name of the class to be stored in this file object
 */
MemoryFileObject(Location location, String name, JavaFileObject.Kind kind) {
    super(URI.create("mfm:///" + name.replace('.','/') + kind.extension),
          Kind.CLASS);
    this.location = location;
    this.name = name;
}
 
Example 23
/**
 * @throws IllegalArgumentException {@inheritDoc}
 * @throws UnsupportedOperationException {@inheritDoc}
 * @throws IllegalStateException {@inheritDoc}
 */
@DefinedBy(Api.COMPILER)
public JavaFileObject getJavaFileForOutput(Location location,
                                           String className,
                                           Kind kind,
                                           FileObject sibling)
    throws IOException
{
    return wrap(super.getJavaFileForOutput(location, className, kind, unwrap(sibling)));
}
 
Example 24
/**
 * Construct a SimpleJavaFileObject of the given kind and with the
 * given URI.
 *
 * @param uri  the URI for this file object
 * @param kind the kind of this file object
 */
protected SimpleJavaFileObject(URI uri, Kind kind) {
    Objects.requireNonNull(uri);
    Objects.requireNonNull(kind);
    if (uri.getPath() == null)
        throw new IllegalArgumentException("URI must have a path: " + uri);
    this.uri = uri;
    this.kind = kind;
}
 
Example 25
Source Project: openjdk-8   Source File: ScopeTest.java    License: GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example 26
Source Project: dubbox   Source File: JdkCompiler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(Location location, String qualifiedName, Kind kind, FileObject outputFile)
        throws IOException {
    JavaFileObject file = new JavaFileObjectImpl(qualifiedName, kind);
    classLoader.add(qualifiedName, file);
    return file;
}
 
Example 27
/**
 * @throws IllegalStateException {@inheritDoc}
 */
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    return wrap(super.list(location, packageName, kinds, recurse));
}
 
Example 28
/**
 * @throws IllegalStateException {@inheritDoc}
 */
public Iterable<JavaFileObject> list(Location location,
                                     String packageName,
                                     Set<Kind> kinds,
                                     boolean recurse)
    throws IOException
{
    return wrap(super.list(location, packageName, kinds, recurse));
}
 
Example 29
@Override
public JavaFileObject getJavaFileForOutput(Location location, String className,
                                           Kind kind, FileObject sibling)
    throws IOException {
    if (!file.getClassName().equals(className)) {
        throw new IOException("Expected class with name " + file.getClassName() +
                              ", but got " + className);
    }
    return file;
}
 
Example 30
Source Project: spring-init   Source File: MemoryBasedJavaFileManager.java    License: Apache License 2.0 5 votes vote down vote up
public Key(Location location, String classpath, String packageName, Set<Kind> kinds, boolean recurse) {
	this.location = location;
	this.classpath = classpath;
	this.packageName = packageName;
	this.kinds = kinds;
	this.recurse = recurse;
}