Java Code Examples for javax.tools.FileObject

The following examples show how to use javax.tools.FileObject. 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: DataLoader   Source File: DataLoaderProcessor.java    License: 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 2
Source Project: openjdk-8   Source File: DocImpl.java    License: 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 3
Source Project: armeria   Source File: DocumentationProcessor.java    License: 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 4
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 5
Source Project: streamline   Source File: CompilingClassLoader.java    License: 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 6
Source Project: netbeans   Source File: AbstractServiceProviderProcessor.java    License: 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 7
Source Project: TencentKona-8   Source File: DocImpl.java    License: 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 8
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 9
Source Project: hottub   Source File: JavacFileManager.java    License: 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 10
Source Project: konduit-serving   Source File: AnnotationUtils.java    License: 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 11
Source Project: doma   Source File: TestingJavaFileManager.java    License: 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 12
Source Project: netbeans   Source File: TreeLoaderOutputFileManager.java    License: 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 13
Source Project: jdk8u60   Source File: DocImpl.java    License: 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 14
Source Project: javaide   Source File: JavacFileManager.java    License: 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 15
Source Project: netbeans   Source File: ProxyFileManager.java    License: 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 16
Source Project: jdk8u_jdk   Source File: MemoryClassLoader.java    License: 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 17
Source Project: openjdk-jdk9   Source File: DPrinter.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void printFileObject(String label, FileObject fo) {
    if (fo == null) {
        printNull(label);
    } else {
        printString(label, fo.getName());
    }
}
 
Example 18
Source Project: hop   Source File: PDI_6976_Test.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testVerifyNoPreviousTransform() {
  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( IVariables.class ) );

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

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

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

  spy.check( validationResults, mock( PipelineMeta.class ), mock( TransformMeta.class ), mock( IRowMeta.class ),
    new String[] {}, new String[] { "File content", "File size" }, mock( IRowMeta.class ),
    mock( IVariables.class ), mock( IHopMetadataProvider.class ) );
}
 
Example 19
Source Project: javaide   Source File: JavacFileManager.java    License: 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 20
Source Project: openjdk-jdk8u   Source File: BaseFileObject.java    License: GNU General Public License v2.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 21
Source Project: jdk8u-jdk   Source File: MemoryClassLoader.java    License: 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 22
Source Project: TencentKona-8   Source File: PackageDocImpl.java    License: 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 23
@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 24
Source Project: doma   Source File: DaoMetaFactory.java    License: 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 25
Source Project: jdk8u60   Source File: MemoryClassLoader.java    License: 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 26
Source Project: netbeans   Source File: Schema2BeansProcessor.java    License: 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 27
/**
 * 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 28
Source Project: java-n-IDE-for-Android   Source File: FormattingFiler.java    License: 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 Project: pentaho-kettle   Source File: PDI_6976_Test.java    License: 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 30
Source Project: javaide   Source File: BaseFileObject.java    License: 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

}