/** 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 }
/** * 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 ""; } }
@Override public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) 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 nameStr = FileObjects.convertPackage2Folder(className, File.separatorChar) + '.' + FileObjects.SIG; final File file = new File (root, nameStr); if (FileObjects.isValidFileName(className)) { return tx.createFileObject(location, file, root, null, null); } else { LOG.log( Level.WARNING, "Invalid class name: {0} sibling: {1}", //NOI18N new Object[]{ className, sibling }); return FileObjects.nullWriteFileObject(FileObjects.fileFileObject(file, root, null, null)); } }
@Override protected Enumeration<URL> findResources(final String name) throws IOException { try { return readAction(new Callable<Enumeration<URL>>(){ @Override public Enumeration<URL> call() throws Exception { @SuppressWarnings("UseOfObsoleteCollectionType") final Vector<URL> v = new Vector<URL>(); for (final Pair<URL,Archive> p : archives) { final Archive archive = p.second(); final FileObject file = archive.getFile(name); if (file != null) { v.add(file.toUri().toURL()); usedRoots .map((c) -> RES_PROCESSORS.equals(name) ? null : c) .ifPresent((c) -> c.accept(p.first())); } } return v.elements(); } }); } catch (Exception ex) { throw new IOException(ex); } }
private int readJavaFileObject(final FileObject jfo) throws IOException { assert LOCK.getReadLockCount() > 0; if (buffer == null) { buffer = new byte[INI_SIZE]; } int len = 0; final InputStream in = jfo.openInputStream(); try { while (true) { if (buffer.length == len) { byte[] nb = new byte[2*buffer.length]; System.arraycopy(buffer, 0, nb, 0, len); buffer = nb; } int l = in.read(buffer,len,buffer.length-len); if (l<=0) { break; } len+=l; } } finally { in.close(); } return len; }
@Override @CheckForNull public FileObject getFileForInput( @NonNull final Location l, @NonNull final String packageName, @NonNull final String relativeName) throws IOException { checkSingleOwnerThread(); try { JavaFileManager[] fms = cfg.getFileManagers(l, null); for (JavaFileManager fm : fms) { FileObject result = fm.getFileForInput(l, packageName, relativeName); if (result != null) { return result; } } return null; } finally { clearOwnerThread(); } }
void checkContains(StandardJavaFileManager fm, Location l, FileObject fo, boolean expect) throws IOException { boolean found = fm.contains(l, fo); if (found) { if (expect) { out.println("file found, as expected: " + l + " " + fo.getName()); } else { error("file not found: " + l + " " + fo.getName()); } } else { if (expect) { error("file found unexpectedly: " + l + " " + fo.getName()); } else { out.println("file not found, as expected: " + l + " " + fo.getName()); } } }
@Override @CheckForNull public JavaFileObject getJavaFileForOutput( @NonNull final Location l, @NonNull final String className, @NonNull final JavaFileObject.Kind kind, @NonNull final FileObject sibling) throws IOException, UnsupportedOperationException, IllegalArgumentException { checkSingleOwnerThread(); try { final JavaFileManager[] fms = cfg.getFileManagers (l, null); if (fms.length == 0) { throw new UnsupportedOperationException("No JavaFileManager for location: " + l); //NOI18N } else { return mark ( fms[0].getJavaFileForOutput (l, className, kind, sibling), l); } } finally { clearOwnerThread(); } }
private void writeFileObjects(JarOutputStream jos) throws IOException { for (FileObject fo : fileObjects) { String p = guessPath(fo); JarEntry e = new JarEntry(p); jos.putNextEntry(e); try { byte[] buf = new byte[1024]; try (BufferedInputStream in = new BufferedInputStream(fo.openInputStream())) { int n; while ((n = in.read(buf)) > 0) jos.write(buf, 0, n); } catch (IOException ex) { error("Exception while adding " + fo.getName() + " to jar file", ex); } } finally { jos.closeEntry(); } } }
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()); } } } }
private static void generateConverterDoc(ModelContext ctx, ConverterModel converter) throws TransformerFactoryConfigurationError, IOException { String bundleName = converter.getBundleName(); int dot = bundleName.lastIndexOf('.'); String packageName = bundleName.substring(0, dot); String fileName = bundleName.substring(dot + 1) + ".xml"; FileObject fo; try { fo = ctx.getFiler().getResource(StandardLocation.SOURCE_PATH, packageName, fileName); } catch (IOException ioe) { fo = ctx.getFiler().createResource(StandardLocation.SOURCE_OUTPUT, packageName, fileName); ctx.note("generating " + fo.getName()); PrintWriter out = new PrintWriter(fo.openOutputStream()); XMLUtils.writeDOMToFile(converter.generateDoc(), null, out); out.close(); } }
public FileObject createResource(Location location, CharSequence pkg, CharSequence relativeName, Element... originatingElements) throws IOException { locationCheck(location); String strPkg = pkg.toString(); if (strPkg.length() > 0) checkName(strPkg); FileObject fileObject = fileManager.getFileForOutput(location, strPkg, relativeName.toString(), null); checkFileReopening(fileObject, true); if (fileObject instanceof JavaFileObject) return new FilerOutputJavaFileObject(null, (JavaFileObject)fileObject); else return new FilerOutputFileObject(null, fileObject); }
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); }
@Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { if (kind != Kind.CLASS) { return _wrapped.getJavaFileForOutput(location, className, kind, sibling); } if (className.contains("/")) { className = className.replace('/', '.'); } ScriptingOutputFileObject fileObject; if (sibling != null) { fileObject = new ScriptingOutputFileObject(Paths.get(sibling.getName()), className, className.substring(className.lastIndexOf('.') + 1)); } else { fileObject = new ScriptingOutputFileObject(null, className, className.substring(className.lastIndexOf('.') + 1)); } _classOutputs.add(fileObject); return fileObject; }
private void listenForNewClassFile(OutputMemoryJavaFileObject jfo, JavaFileManager.Location location, String className, JavaFileObject.Kind kind, FileObject sibling) { //debug("listenForNewClassFile %s loc=%s kind=%s\n", className, location, kind); if (location == CLASS_OUTPUT) { state.debug(DBG_GEN, "Compiler generating class %s\n", className); OuterWrap w = ((sibling instanceof SourceMemoryJavaFileObject) && (((SourceMemoryJavaFileObject) sibling).getOrigin() instanceof OuterWrap)) ? (OuterWrap) ((SourceMemoryJavaFileObject) sibling).getOrigin() : null; classObjs.compute(w, (k, v) -> (v == null)? new ArrayList<>() : v) .add(jfo); } }
public void generateFile() throws IOException { FileObject fileObject = filer.createResource(StandardLocation.SOURCE_OUTPUT, "", "em.generated.bnd"); try (Writer writer = fileObject.openWriter()) { writer.write("Provide-Capability: " + String.join(",", capabilities)); writer.write("\n"); writer.write("Require-Capability: " + String.join(",", requrements)); } }
@Override public boolean isSameFile(FileObject a, FileObject b) { nullCheck(a); nullCheck(b); if (!(a instanceof PathFileObject)) throw new IllegalArgumentException("Not supported: " + a); if (!(b instanceof PathFileObject)) throw new IllegalArgumentException("Not supported: " + b); return ((PathFileObject) a).isSameFile((PathFileObject) b); }
@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); }
public static void doWithOriAndPrintWriter(Filer filer, JavaFileManager.Location location, String relativePath, String filename, BiConsumer<String, PrintWriter> consumer){ try { FileObject resource = filer.getResource(location, relativePath, filename); String data; try{ CharSequence cs = resource.getCharContent(false); data = cs.toString(); resource.delete(); }catch (FileNotFoundException ignored){ data = ""; } resource = filer.createResource(location, relativePath, filename); try(OutputStream outputStream = resource.openOutputStream()){ consumer.accept(data,new PrintWriter(outputStream)); } } catch (IOException e) { note("do with resource file failed"+relativePath+filename+" Exception: " + e.toString()); } }
@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; }
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); }
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); }
public FileObject getFileForInput(Location location, String packageName, String relativeName) throws IOException { if (location == StandardLocation.SOURCE_PATH) { final List<Integer> pkglst = packages.get(packageName); if (pkglst != null) { for (Integer id : pkglst) { final InferableJavaFileObject jfo = this.content.get (id); assert jfo != null; if (relativeName.equals(jfo.getName())) { //Todo: Rely on the file instanceof FileObjects.Base return jfo; } } } } return null; }
void assertFileContent(String relPath, String expectedContent) { try { FileObject fo = processingEnv.getFiler() .getResource(StandardLocation.CLASS_PATH, "", relPath); String actualContent = fo.getCharContent(false).toString(); if (!expectedContent.equals(actualContent)) { throw new AssertionError("Actual content not matching the expected content: " + actualContent); } } catch (IOException ex) { throw new AssertionError("Unexpected exception: ", ex); } }
private void writePackageJson() throws IOException { String packageJson = PackageJsonGenerator.packageJsonFor(model.getModuleInfo(), model); FileObject package_json_file_object = ModuleResourceHelper.createResource(env, model.getModuleInfo(), "package.json"); try (PrintWriter out = new PrintWriterWithLogging(package_json_file_object.openWriter(), "package.json")) { out.println(packageJson); } }
@Override @DefinedBy(Api.COMPILER_TREE) public DocCommentTree getDocCommentTree(Element e, String relativeFileName) throws IOException { PackageElement pkg = elements.getPackageOf(e); FileObject fileForInput = fileManager.getFileForInput(StandardLocation.SOURCE_PATH, pkg.getQualifiedName().toString(), relativeFileName); if (fileForInput == null) { throw new FileNotFoundException(relativeFileName); } return getDocCommentTree(fileForInput); }
private void writeProviderFile(TypeElement serviceProvider, String interfaceName) { String filename = "META-INF/providers/" + serviceProvider.getQualifiedName(); try { FileObject file = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", filename, serviceProvider); PrintWriter writer = new PrintWriter(new OutputStreamWriter(file.openOutputStream(), "UTF-8")); writer.println(interfaceName); writer.close(); } catch (IOException e) { processingEnv.getMessager().printMessage(isBug367599(e) ? Kind.NOTE : Kind.ERROR, e.getMessage(), serviceProvider); } }
/** * Convert the given Class to an HTML. * * @param te the class to convert. * @param outputdir the name of the directory to output to * @throws DocFileIOException if there is a problem generating the output file * @throws SimpleDocletException if there is a problem reading the source file */ public void convertClass(TypeElement te, DocPath outputdir) throws DocFileIOException, SimpleDocletException { if (te == null) { return; } FileObject fo = utils.getFileObject(te); if (fo == null) return; try { Reader r = fo.openReader(true); int lineno = 1; String line; relativePath = DocPaths.SOURCE_OUTPUT .resolve(DocPath.forPackage(utils, te)) .invert(); Content body = getHeader(); Content pre = new HtmlTree(HtmlTag.PRE); try (LineNumberReader reader = new LineNumberReader(r)) { while ((line = reader.readLine()) != null) { addLineNo(pre, lineno); addLine(pre, line, lineno); lineno++; } } addBlankLines(pre); Content div = HtmlTree.DIV(HtmlStyle.sourceContainer, pre); body.addContent((configuration.allowTag(HtmlTag.MAIN)) ? HtmlTree.MAIN(div) : div); writeToFile(body, outputdir.resolve(DocPath.forClass(utils, te))); } catch (IOException e) { String message = configuration.resources.getText("doclet.exception.read.file", fo.getName()); throw new SimpleDocletException(message, e); } }
@Override public JavaFileObject getJavaFileForOutput( Location location, String className, JavaFileObject.Kind kind, FileObject sibling ) throws IOException { if( !_fromJavaC || kind == JavaFileObject.Kind.CLASS && sibling instanceof GeneratedJavaStubFileObject ) { InMemoryClassJavaFileObject file = new InMemoryClassJavaFileObject( className, kind ); _classFiles.add( className, file ); className = className.replace( '$', '.' ); _classFiles.add( className, file ); return file; } return super.getJavaFileForOutput( location, className, kind, sibling ); }
@Override public FileObject getFileForInput( @NonNull final Location l, @NonNull final String pkgName, @NonNull final String relativeName ) { return findFile(ModuleLocation.cast(l), pkgName, relativeName); }
@Override public FileObject getFileForOutput( @NonNull final Location l, @NonNull final String pkgName, @NonNull final String relativeName, @NullAllowed final FileObject sibling ) throws IOException { throw new UnsupportedOperationException("Output is unsupported."); //NOI18N }
@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(); } }
@Override public Iterable<? extends File> getLocation(Location location) { org.openide.filesystems.FileObject[] roots; ClassPath cp = null; if (location == StandardLocation.SOURCE_PATH) { cp = cpInfo.getClassPath(ClasspathInfo.PathKind.SOURCE); } else if (location == StandardLocation.CLASS_PATH) { cp = cpInfo.getClassPath(ClasspathInfo.PathKind.COMPILE); } else if (location == StandardLocation.PLATFORM_CLASS_PATH) { cp = cpInfo.getClassPath(ClasspathInfo.PathKind.BOOT); } if (cp == null) { return null; } roots = cp.getRoots(); if (roots == null || roots.length == 0) { return null; } List<File> res = new ArrayList<>(roots.length); for (org.openide.filesystems.FileObject f : roots) { File x = FileUtil.toFile(f); if (x != null) { res.add(x); } } return res; }
@Override public JavaFileObject getJavaFileForOutput(Location location, String name, JavaFileObject.Kind kind, FileObject sibling) { return new MemoryFileObject(location, name, kind); }
@Override public Swagger generate(List<ParsedPath> parsedPaths, RoundDescriptor roundDescriptor) { Swagger swagger = delegate.generate(parsedPaths, roundDescriptor); if (roundDescriptor.isLast()) { FileObject yaml = fileManager.createResource("api.yaml"); SwaggerUtils.write(Yaml.pretty(), yaml, swagger); FileObject json = fileManager.createResource("api.json"); SwaggerUtils.write(Json.pretty(), json, swagger); } return swagger; }
private byte[] generateInstanceResolver(FileObject fo, Element e, File f, Registration r) throws LayerGenerationException { try { InputStream is = fo.openInputStream(); org.openide.filesystems.FileObject tmp = FileUtil.createMemoryFileSystem().getRoot().createData("resolver.xml"); OutputStream os = tmp.getOutputStream(); for (;;) { int ch = is.read(); if (ch == -1) { break; } os.write(ch); } os.close(); is.close(); MIMEResolver resolver = MIMEResolverImpl.forDescriptor(tmp, false); setFileChooserRelatedAttributes(r, resolver, f); final byte[] almostResult = MIMEResolverImpl.toStream(resolver); // XXX: it would be slightly shorter to return the array directly, // but the XMLFileSystem insist on deserializing the value, it does // not support returning plain byte[] ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(out); oos.writeObject(almostResult); oos.close(); return out.toByteArray(); } catch (IOException ex) { final LayerGenerationException le = new LayerGenerationException("Cannot process " + fo, e); le.initCause(ex); throw le; } }
/** * 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(); } }
@Override public JavaFileObject getJavaFileForOutput(Location location, String className, Kind kind, FileObject sibling) throws IOException { try { JavaFileObject jfo = new ByteArrayJFO(className, kind); store.put(className, jfo); return jfo; } catch(Exception e) { System.out.println(e); return null; } }