javax.tools.FileObject Java Examples

The following examples show how to use javax.tools.FileObject. 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: AnnotationUtils.java    From konduit-serving with Apache License 2.0 6 votes vote down vote up
public static String getContent(Filer filer, String c){
    String outputFile = "META-INF/konduit-serving/" + c;
    try {
        FileObject file = filer.getResource(StandardLocation.CLASS_OUTPUT, "", outputFile);
        InputStream is = file.openInputStream();
        StringBuilder sb = new StringBuilder();
        try (Reader r = new BufferedReader(new InputStreamReader(is))) {
            int ch = 0;
            while ((ch = r.read()) != -1) {
                sb.append((char) ch);
            }
        }
        return sb.toString();
    } catch (IOException e){
        throw new RuntimeException("ERROR READING FILE", e);
    }
}
 
Example #2
Source File: DataLoaderProcessor.java    From DataLoader with Apache License 2.0 6 votes vote down vote up
private void writeToFile(String fileName, String content) {
    if (isEmpty(fileName) || isEmpty(content)) {
        return;
    }
    System.out.println(TAG + "writeToFile fileName: " + fileName + " content: " + content);
    try {
        FileObject res = filer.createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
        OutputStream os = res.openOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os));
        writer.write(content);
        writer.flush();
        writer.close();
        os.close();
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println(TAG + e.toString());
    }
}
 
Example #3
Source File: DocImpl.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Utility for subclasses which read HTML documentation files.
 */
String readHTMLDocumentation(InputStream input, FileObject filename) throws IOException {
    byte[] filecontents = new byte[input.available()];
    try {
        DataInputStream dataIn = new DataInputStream(input);
        dataIn.readFully(filecontents);
    } finally {
        input.close();
    }
    String encoding = env.getEncoding();
    String rawDoc = (encoding!=null)
        ? new String(filecontents, encoding)
        : new String(filecontents);
    Pattern bodyPat = Pattern.compile("(?is).*<body\\b[^>]*>(.*)</body\\b.*");
    Matcher m = bodyPat.matcher(rawDoc);
    if (m.matches()) {
        return m.group(1);
    } else {
        String key = rawDoc.matches("(?is).*<body\\b.*")
                ? "javadoc.End_body_missing_from_html_file"
                : "javadoc.Body_missing_from_html_file";
        env.error(SourcePositionImpl.make(filename, Position.NOPOS, null), key);
        return "";
    }
}
 
Example #4
Source File: DocImpl.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Utility for subclasses which read HTML documentation files.
 */
String readHTMLDocumentation(InputStream input, FileObject filename) throws IOException {
    byte[] filecontents = new byte[input.available()];
    try {
        DataInputStream dataIn = new DataInputStream(input);
        dataIn.readFully(filecontents);
    } finally {
        input.close();
    }
    String encoding = env.getEncoding();
    String rawDoc = (encoding!=null)
        ? new String(filecontents, encoding)
        : new String(filecontents);
    Pattern bodyPat = Pattern.compile("(?is).*<body\\b[^>]*>(.*)</body\\b.*");
    Matcher m = bodyPat.matcher(rawDoc);
    if (m.matches()) {
        return m.group(1);
    } else {
        String key = rawDoc.matches("(?is).*<body\\b.*")
                ? "javadoc.End_body_missing_from_html_file"
                : "javadoc.Body_missing_from_html_file";
        env.error(SourcePositionImpl.make(filename, Position.NOPOS, null), key);
        return "";
    }
}
 
Example #5
Source File: DocumentationProcessor.java    From armeria with Apache License 2.0 6 votes vote down vote up
private Properties readProperties(String className) throws IOException {
    if (propertiesMap.containsKey(className)) {
        return propertiesMap.get(className);
    }
    final FileObject resource = processingEnv
            .getFiler()
            .getResource(StandardLocation.CLASS_OUTPUT,
                         "",
                         getFileName(className));
    final Properties properties = new Properties();
    if (resource.getLastModified() == 0L) {
        // returns 0 if file does not exist
        propertiesMap.put(className, properties);
        return properties;
    }
    try (Reader reader = resource.openReader(false)) {
        properties.load(reader);
        return properties;
    }
}
 
Example #6
Source File: StandardDocFileFactory.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private FileObject getFileObjectForOutput(DocPath path) throws IOException {
    // break the path into a package-part and the rest, by finding
    // the position of the last '/' before an invalid character for a
    // package name, such as the "." before an extension or the "-"
    // in filenames like package-summary.html, doc-files or src-html.
    String p = path.getPath();
    int lastSep = -1;
    for (int i = 0; i < p.length(); i++) {
        char ch = p.charAt(i);
        if (ch == '/') {
            lastSep = i;
        } else if (i == lastSep + 1 && !Character.isJavaIdentifierStart(ch)
                || !Character.isJavaIdentifierPart(ch)) {
            break;
        }
    }
    String pkg = (lastSep == -1) ? "" : p.substring(0, lastSep);
    String rest = p.substring(lastSep + 1);
    return fileManager.getFileForOutput(location, pkg, rest, null);
}
 
Example #7
Source File: CompilingClassLoader.java    From streamline with Apache License 2.0 6 votes vote down vote up
@Override
public JavaFileObject getJavaFileForOutput(
    Location location, final String className, JavaFileObject.Kind kind, FileObject sibling)
    throws IOException {
  return new SimpleJavaFileObject(EMPTY_URI, kind) {
    @Override
    public OutputStream openOutputStream() throws IOException {
      ByteArrayOutputStream outputStream = byteCodeForClasses.get(className);
      if (outputStream != null) {
        throw new IllegalStateException("Cannot write more than once");
      }
      // Reasonable size for a simple .class.
      outputStream = new ByteArrayOutputStream(256);
      byteCodeForClasses.put(className, outputStream);
      return outputStream;
    }
  };
}
 
Example #8
Source File: JavacFileManager.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public FileObject getFileForOutput(Location location,
                                   String packageName,
                                   String relativeName,
                                   FileObject sibling)
    throws IOException
{
    nullCheck(location);
    // validatePackageName(packageName);
    nullCheck(packageName);
    if (!isRelativeUri(relativeName))
        throw new IllegalArgumentException("Invalid relative name: " + relativeName);
    RelativeFile name = packageName.length() == 0
        ? new RelativeFile(relativeName)
        : new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
    return getFileForOutput(location, name, sibling);
}
 
Example #9
Source File: AbstractServiceProviderProcessor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void writeServices() {
    for (Map.Entry<Filer,Map<String,SortedSet<ServiceLoaderLine>>> outputFiles : outputFilesByProcessor.entrySet()) {
        Filer filer = outputFiles.getKey();
        for (Map.Entry<String,SortedSet<ServiceLoaderLine>> entry : outputFiles.getValue().entrySet()) {
            try {
                FileObject out = filer.createResource(StandardLocation.CLASS_OUTPUT, "", entry.getKey(),
                        originatingElementsByProcessor.get(filer).get(entry.getKey()).toArray(new Element[0]));
                OutputStream os = out.openOutputStream();
                try {
                    PrintWriter w = new PrintWriter(new OutputStreamWriter(os, "UTF-8"));
                    for (ServiceLoaderLine line : entry.getValue()) {
                        line.write(w);
                    }
                    w.flush();
                    w.close();
                } finally {
                    os.close();
                }
            } catch (IOException x) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Failed to write to " + entry.getKey() + ": " + x.toString());
            }
        }
    }
}
 
Example #10
Source File: TreeLoaderOutputFileManager.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException {
    final Pair<Location,URL> p = baseLocation(location);
    if (!hasLocation(p.first())) {
        throw new IllegalArgumentException(String.valueOf(p.first()));
    }
    final File root = new File(outputRoot);
    assert p.second() == null || p.second().equals(BaseUtilities.toURI(root).toURL()) :
            String.format("Expected: %s, Current %s", p.second(), root);
    final String path = FileObjects.resolveRelativePath(packageName, relativeName);
    final String[] names = FileObjects.getFolderAndBaseName(path, FileObjects.NBFS_SEPARATOR_CHAR);
    final javax.tools.FileObject jfo = tx.readFileObject(location, names[0], names[1]);
    if (jfo != null) {
        return (JavaFileObject) jfo;
    }
    final Archive archive = provider.getArchive(BaseUtilities.toURI(root).toURL(), false);
    return archive != null ?
        archive.getFile(path) :
        null;
}
 
Example #11
Source File: DocImpl.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Utility for subclasses which read HTML documentation files.
 */
String readHTMLDocumentation(InputStream input, FileObject filename) throws IOException {
    byte[] filecontents = new byte[input.available()];
    try {
        DataInputStream dataIn = new DataInputStream(input);
        dataIn.readFully(filecontents);
    } finally {
        input.close();
    }
    String encoding = env.getEncoding();
    String rawDoc = (encoding!=null)
        ? new String(filecontents, encoding)
        : new String(filecontents);
    Pattern bodyPat = Pattern.compile("(?is).*<body\\b[^>]*>(.*)</body\\b.*");
    Matcher m = bodyPat.matcher(rawDoc);
    if (m.matches()) {
        return m.group(1);
    } else {
        String key = rawDoc.matches("(?is).*<body\\b.*")
                ? "javadoc.End_body_missing_from_html_file"
                : "javadoc.Body_missing_from_html_file";
        env.error(SourcePositionImpl.make(filename, Position.NOPOS, null), key);
        return "";
    }
}
 
Example #12
Source File: TestingJavaFileManager.java    From doma with Apache License 2.0 6 votes vote down vote up
@Override
public FileObject getFileForInput(
    final Location location, final String packageName, final String relativeName)
    throws IOException {
  if (relativeName.endsWith(".java")) {
    return getJavaFileForInput(location, packageName + "." + relativeName, Kind.SOURCE);
  }
  if (relativeName.endsWith(".class")) {
    return getJavaFileForInput(location, packageName + "." + relativeName, Kind.CLASS);
  }
  final String key = createKey(packageName, relativeName);
  if (fileObjects.containsKey(key)) {
    return fileObjects.get(key);
  }
  return super.getFileForInput(location, packageName, relativeName);
}
 
Example #13
Source File: StandardDocFileFactory.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private FileObject getFileObjectForOutput(DocPath path) throws IOException {
    // break the path into a package-part and the rest, by finding
    // the position of the last '/' before an invalid character for a
    // package name, such as the "." before an extension or the "-"
    // in filenames like package-summary.html, doc-files or src-html.
    String p = path.getPath();
    int lastSep = -1;
    for (int i = 0; i < p.length(); i++) {
        char ch = p.charAt(i);
        if (ch == '/') {
            lastSep = i;
        } else if (i == lastSep + 1 && !Character.isJavaIdentifierStart(ch)
                || !Character.isJavaIdentifierPart(ch)) {
            break;
        }
    }
    String pkg = (lastSep == -1) ? "" : p.substring(0, lastSep);
    String rest = p.substring(lastSep + 1);
    return fileManager.getFileForOutput(location, pkg, rest, null);
}
 
Example #14
Source File: BaseFileObject.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
/** Return the last component of a presumed hierarchical URI.
 *  From the scheme specific part of the URI, it returns the substring
 *  after the last "/" if any, or everything if no "/" is found.
 */
public static String getSimpleName(FileObject fo) {
    URI uri = fo.toUri();
    String s = uri.getSchemeSpecificPart();
    return s.substring(s.lastIndexOf("/") + 1); // safe when / not found

}
 
Example #15
Source File: JavacFileManager.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public boolean isSameFile(FileObject a, FileObject b) {
    nullCheck(a);
    nullCheck(b);
    if (!(a instanceof BaseFileObject))
        throw new IllegalArgumentException("Not supported: " + a);
    if (!(b instanceof BaseFileObject))
        throw new IllegalArgumentException("Not supported: " + b);
    return a.equals(b);
}
 
Example #16
Source File: SourcePositionImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private SourcePositionImpl(FileObject file, int position,
                           Position.LineMap lineMap) {
    super();
    this.filename = file;
    this.position = position;
    this.lineMap = lineMap;
}
 
Example #17
Source File: InterceptingJavaFileManager.java    From EasyMPermission with MIT License 5 votes vote down vote up
@Override public JavaFileObject getJavaFileForOutput(Location location, String className, final Kind kind, FileObject sibling) throws IOException {
	if (className.startsWith("lombok.dummy.ForceNewRound")) {
		final String name = className.replace(".", "/") + kind.extension;
		return LombokFileObjects.createEmpty(compiler, name, kind);
	}
	JavaFileObject fileObject = fileManager.getJavaFileForOutput(location, className, kind, sibling);
	if (kind != Kind.CLASS) {
		return fileObject;
	}
	return LombokFileObjects.createIntercepting(compiler, fileObject, className, diagnostics);
}
 
Example #18
Source File: DynaFileManager.java    From kan-java with Eclipse Public License 1.0 5 votes vote down vote up
public boolean isSameFile(FileObject a, FileObject b) {
    if (a == b)
        return true;
    Class<?> ac = a.getClass();
    Class<?> bc = b.getClass();
    if (ac.equals(bc)) {
        if (JavaClassFile.class.equals(ac) || JavaSourceFile.class.equals(ac)) {
            return a.equals(b);
        } else {
            return super.isSameFile(a, b);
        }
    } else {
        return false;
    }
}
 
Example #19
Source File: CustomJavaFileObjectAndFileManeger.java    From learnjavabug with MIT License 5 votes vote down vote up
@Override
public FileObject getFileForInput(Location location, String packageName,
    String relativeName) throws IOException {
    FileObject o = fileObjects.get(uri(location, packageName, relativeName));
    if (o != null) {
        return o;
    }
    return super.getFileForInput(location, packageName, relativeName);
}
 
Example #20
Source File: ProxyFileManager.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isSameFile(FileObject fileObject, FileObject fileObject0) {
    checkSingleOwnerThread();
    try {
        final JavaFileManager[] fms = cfg.getFileManagers(ALL, null);
        for (JavaFileManager fm : fms) {
            if (fm.isSameFile(fileObject, fileObject0)) {
                return true;
            }
        }
        return fileObject.toUri().equals (fileObject0.toUri());
    } finally {
        clearOwnerThread();
    }
}
 
Example #21
Source File: InMemoryJavaCompiler.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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 #22
Source File: JavacFileManager.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
public FileObject getFileForOutput(Location location,
                                   String packageName,
                                   String relativeName,
                                   FileObject sibling)
        throws IOException {
    nullCheck(location);
    // validatePackageName(packageName);
    nullCheck(packageName);
    if (!isRelativeUri(relativeName))
        throw new IllegalArgumentException("Invalid relative name: " + relativeName);
    RelativeFile name = packageName.length() == 0
            ? new RelativeFile(relativeName)
            : new RelativeFile(RelativeDirectory.forPackage(packageName), relativeName);
    return getFileForOutput(location, name, sibling);
}
 
Example #23
Source File: DaoMetaFactory.java    From doma with Apache License 2.0 5 votes vote down vote up
private File getDir(String dirPath) {
  FileObject fileObject = getFileObject(dirPath);
  if (fileObject == null) {
    return null;
  }
  URI uri = fileObject.toUri();
  if (!uri.isAbsolute()) {
    uri = new File(".").toURI().resolve(uri);
  }
  File dir = new File(uri);
  if (dir.exists() && dir.isDirectory()) {
    return dir;
  }
  return null;
}
 
Example #24
Source File: MemoryClassLoader.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Output getJavaFileForOutput(Location location, String name, Kind kind, FileObject source) {
    Output mc = this.map.get(name);
    if (mc == null) {
        mc = new Output(name);
        this.map.put(name, mc);
    }
    return mc;
}
 
Example #25
Source File: Schema2BeansProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private FileObject createResource(String path, String pkg) throws URISyntaxException, IOException {
    // XXX LayerBuilder has standard versions of this logic now
    String abspath;
    if (path.startsWith("/")) {
        abspath = path.substring(1);
    } else {
        abspath = new URI(null, pkg.replace('.', '/') + "/", null).resolve(new URI(null, path, null)).getPath();
    }
    return processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", abspath);
}
 
Example #26
Source File: PackageDocImpl.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
/**
 * set doc path for an unzipped directory
 */
public void setDocPath(FileObject path) {
    setDocPath = true;
    if (path == null)
        return;
    if (!path.equals(docPath)) {
        docPath = path;
        checkDoc();
    }
}
 
Example #27
Source File: PDI_6976_Test.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyNoPreviousStep() {
  LoadFileInputMeta spy = spy( new LoadFileInputMeta() );

  FileInputList fileInputList = mock( FileInputList.class );
  List<FileObject> files = when( mock( List.class ).size() ).thenReturn( 1 ).getMock();
  doReturn( files ).when( fileInputList ).getFiles();
  doReturn( fileInputList ).when( spy ).getFiles( any( VariableSpace.class ) );

  @SuppressWarnings( "unchecked" )
  List<CheckResultInterface> validationResults = mock( List.class );

  // Check we do not get validation errors
  doAnswer( new Answer<Object>() {
    @Override
    public Object answer( InvocationOnMock invocation ) throws Throwable {
      if ( ( (CheckResultInterface) invocation.getArguments()[0] ).getType() != CheckResultInterface.TYPE_RESULT_OK ) {
        TestCase.fail( "We've got validation error" );
      }

      return null;
    }
  } ).when( validationResults ).add( any( CheckResultInterface.class ) );

  spy.check( validationResults, mock( TransMeta.class ), mock( StepMeta.class ), mock( RowMetaInterface.class ),
    new String[] {}, new String[] { "File content", "File size" }, mock( RowMetaInterface.class ),
    mock( VariableSpace.class ), mock( Repository.class ), mock( IMetaStore.class ) );
}
 
Example #28
Source File: FormattingFiler.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public FileObject createResource(
        JavaFileManager.Location location,
        CharSequence pkg,
        CharSequence relativeName,
        Element... originatingElements)
        throws IOException {
    return delegate.createResource(location, pkg, relativeName, originatingElements);
}
 
Example #29
Source File: SourcePositionImpl.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private SourcePositionImpl(FileObject file, int position,
                           Position.LineMap lineMap) {
    super();
    this.filename = file;
    this.position = position;
    this.lineMap = lineMap;
}
 
Example #30
Source File: PackageDocImpl.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * set doc path for an unzipped directory
 */
public void setDocPath(FileObject path) {
    setDocPath = true;
    if (path == null)
        return;
    if (!path.equals(docPath)) {
        docPath = path;
        checkDoc();
    }
}