Search in sources :

Example 86 with FileObject

use of javax.tools.FileObject in project jvarkit by lindenb.

the class JVarkitAnnotationProcessor method process.

@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv) {
    final String mainClass = System.getProperty("jvarkit.main.class");
    final String thisDir = System.getProperty("jvarkit.this.dir");
    roundEnv.getElementsAnnotatedWith(IncludeSourceInJar.class).stream().filter(E -> E.getKind() == ElementKind.CLASS).filter(E -> E.getAnnotation(IncludeSourceInJar.class) != null).forEach(E -> {
        if (thisDir == null || thisDir.isEmpty())
            return;
        copySource(E);
    });
    /* find if roundEnv contains main class annotated with 'Program' annotation
		 * if true: generate a file that will tell Make to compile the markdown
		 * documentation
		 */
    roundEnv.getElementsAnnotatedWith(Program.class).stream().filter(E -> E.getKind() == ElementKind.CLASS).filter(E -> {
        final Program prog = E.getAnnotation(Program.class);
        return prog != null && prog.generate_doc();
    }).forEach(E -> {
        copySource(E);
        final String className = E.toString();
        if (mainClass == null)
            return;
        if (!mainClass.equals(className))
            return;
        final Program prog = E.getAnnotation(Program.class);
        if (prog == null || !prog.generate_doc())
            return;
        try {
            final Filer filer = super.processingEnv.getFiler();
            FileObject fo = filer.createResource(StandardLocation.CLASS_OUTPUT, "", "markdown.flag");
            fo.openWriter().append(String.valueOf(mainClass)).close();
        } catch (final Exception err) {
            LOG.warn(err);
        }
        if (thisDir != null) {
            final File index_html = new File(thisDir, "docs/index.html");
            if (index_html.exists()) {
                try {
                    final Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(index_html);
                    Element tr = dom.createElement("tr");
                    tr.setAttribute("id", prog.name());
                    // name
                    Element td = dom.createElement("th");
                    tr.appendChild(td);
                    Element a = dom.createElement("a");
                    a.setAttribute("href", E.getSimpleName() + ".html");
                    a.setAttribute("title", E.getSimpleName().toString());
                    td.appendChild(a);
                    a.appendChild(dom.createTextNode(prog.name()));
                    // desc
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    td.appendChild(dom.createTextNode(prog.description()));
                    // keywords
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    td.appendChild(dom.createTextNode(Arrays.asList(prog.keywords()).stream().collect(Collectors.joining(" "))));
                    // terms
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    td.appendChild(dom.createTextNode(Arrays.asList(prog.terms()).stream().map(T -> "[" + T.getAccession() + "]" + T.getLabel()).collect(Collectors.joining(" "))));
                    // misc
                    td = dom.createElement("td");
                    tr.appendChild(td);
                    final DocumentFragment misc = dom.createDocumentFragment();
                    if (prog.deprecatedMsg() != null && !prog.deprecatedMsg().isEmpty()) {
                        Element span = dom.createElement("span");
                        span.setAttribute("style", "color:orange;");
                        span.setAttribute("title", "deprecated");
                        span.appendChild(dom.createTextNode(prog.deprecatedMsg()));
                        misc.appendChild(span);
                        misc.appendChild(dom.createTextNode(". "));
                    }
                    td.appendChild(misc);
                    final XPath xpath = XPathFactory.newInstance().newXPath();
                    final NodeList nodeList = (NodeList) xpath.evaluate("//table[1]/tbody/tr[@id='" + prog.name() + "']", dom, XPathConstants.NODESET);
                    for (int i = 0; i < nodeList.getLength(); ++i) {
                        Node oldTr = nodeList.item(i);
                        if (tr != null) {
                            oldTr.getParentNode().replaceChild(tr, oldTr);
                            tr = null;
                        } else {
                            oldTr.getParentNode().removeChild(oldTr);
                        }
                    }
                    if (tr != null) {
                        Node tbody = (Node) xpath.evaluate("//table[1]/tbody", dom, XPathConstants.NODE);
                        if (tbody != null) {
                            tbody.appendChild(tr);
                            tbody.appendChild(dom.createTextNode("\n"));
                            tr = null;
                        }
                    }
                    if (tr != null) {
                        LOG.warn("Cannot insert new doc in " + index_html);
                    } else {
                        final Transformer transformer = TransformerFactory.newInstance().newTransformer();
                        transformer.setOutputProperty(OutputKeys.INDENT, "no");
                        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
                        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                        transformer.transform(new DOMSource(dom), new StreamResult(index_html));
                    }
                } catch (final Exception err) {
                    LOG.warn(err);
                }
            } else {
                LOG.warn("Cannot get " + index_html);
            }
        }
    });
    return true;
}
Also used : Transformer(javax.xml.transform.Transformer) DOMSource(javax.xml.transform.dom.DOMSource) Arrays(java.util.Arrays) XPath(javax.xml.xpath.XPath) Program(com.github.lindenb.jvarkit.util.jcommander.Program) AbstractProcessor(javax.annotation.processing.AbstractProcessor) XPathConstants(javax.xml.xpath.XPathConstants) StreamResult(javax.xml.transform.stream.StreamResult) TypeElement(javax.lang.model.element.TypeElement) FileObject(javax.tools.FileObject) SupportedSourceVersion(javax.annotation.processing.SupportedSourceVersion) Document(org.w3c.dom.Document) DeclaredType(javax.lang.model.type.DeclaredType) Node(org.w3c.dom.Node) StandardLocation(javax.tools.StandardLocation) NodeList(org.w3c.dom.NodeList) ElementKind(javax.lang.model.element.ElementKind) Logger(com.github.lindenb.jvarkit.util.log.Logger) Set(java.util.Set) Reader(java.io.Reader) OutputKeys(javax.xml.transform.OutputKeys) Collectors(java.util.stream.Collectors) File(java.io.File) TypeKind(javax.lang.model.type.TypeKind) DocumentFragment(org.w3c.dom.DocumentFragment) SourceVersion(javax.lang.model.SourceVersion) XPathFactory(javax.xml.xpath.XPathFactory) TypeMirror(javax.lang.model.type.TypeMirror) Element(org.w3c.dom.Element) RoundEnvironment(javax.annotation.processing.RoundEnvironment) Filer(javax.annotation.processing.Filer) Writer(java.io.Writer) ProcessingEnvironment(javax.annotation.processing.ProcessingEnvironment) FileReader(java.io.FileReader) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) TransformerFactory(javax.xml.transform.TransformerFactory) XPath(javax.xml.xpath.XPath) DOMSource(javax.xml.transform.dom.DOMSource) Program(com.github.lindenb.jvarkit.util.jcommander.Program) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) TypeElement(javax.lang.model.element.TypeElement) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) FileObject(javax.tools.FileObject) Filer(javax.annotation.processing.Filer) File(java.io.File) DocumentFragment(org.w3c.dom.DocumentFragment)

Example 87 with FileObject

use of javax.tools.FileObject in project druid by druid-io.

the class S3DataSegmentPuller method buildFileObject.

public FileObject buildFileObject(final URI uri) throws AmazonServiceException {
    final CloudObjectLocation coords = new CloudObjectLocation(S3Utils.checkURI(uri));
    final String path = uri.getPath();
    return new FileObject() {

        S3Object s3Object = null;

        S3ObjectSummary objectSummary = null;

        @Override
        public URI toUri() {
            return uri;
        }

        @Override
        public String getName() {
            final String ext = Files.getFileExtension(path);
            return Files.getNameWithoutExtension(path) + (Strings.isNullOrEmpty(ext) ? "" : ("." + ext));
        }

        /**
         * Returns an input stream for a s3 object. The returned input stream is not thread-safe.
         */
        @Override
        public InputStream openInputStream() throws IOException {
            try {
                if (s3Object == null) {
                    // lazily promote to full GET
                    s3Object = s3Client.getObject(coords.getBucket(), coords.getPath());
                }
                final InputStream in = s3Object.getObjectContent();
                final Closer closer = Closer.create();
                closer.register(in);
                closer.register(s3Object);
                return new FilterInputStream(in) {

                    @Override
                    public void close() throws IOException {
                        closer.close();
                    }
                };
            } catch (AmazonServiceException e) {
                throw new IOE(e, "Could not load S3 URI [%s]", uri);
            }
        }

        @Override
        public OutputStream openOutputStream() {
            throw new UOE("Cannot stream S3 output");
        }

        @Override
        public Reader openReader(boolean ignoreEncodingErrors) {
            throw new UOE("Cannot open reader");
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            throw new UOE("Cannot open character sequence");
        }

        @Override
        public Writer openWriter() {
            throw new UOE("Cannot open writer");
        }

        @Override
        public long getLastModified() {
            if (s3Object != null) {
                return s3Object.getObjectMetadata().getLastModified().getTime();
            }
            if (objectSummary == null) {
                objectSummary = S3Utils.getSingleObjectSummary(s3Client, coords.getBucket(), coords.getPath());
            }
            return objectSummary.getLastModified().getTime();
        }

        @Override
        public boolean delete() {
            throw new UOE("Cannot delete S3 items anonymously. jetS3t doesn't support authenticated deletes easily.");
        }
    };
}
Also used : Closer(org.apache.druid.java.util.common.io.Closer) FilterInputStream(java.io.FilterInputStream) CloudObjectLocation(org.apache.druid.data.input.impl.CloudObjectLocation) FilterInputStream(java.io.FilterInputStream) InputStream(java.io.InputStream) AmazonServiceException(com.amazonaws.AmazonServiceException) S3ObjectSummary(com.amazonaws.services.s3.model.S3ObjectSummary) UOE(org.apache.druid.java.util.common.UOE) FileObject(javax.tools.FileObject) S3Object(com.amazonaws.services.s3.model.S3Object) IOE(org.apache.druid.java.util.common.IOE)

Example 88 with FileObject

use of javax.tools.FileObject in project fabric8 by fabric8io.

the class AbstractKubernetesAnnotationProcessor method generateYaml.

void generateYaml(String fileName, KubernetesResource resource) {
    try {
        FileObject fileObject = getFileObject(fileName);
        KubernetesHelper.saveYaml(resource, fileObject);
    } catch (IOException e) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error generating json " + fileName);
    }
}
Also used : FileObject(javax.tools.FileObject) IOException(java.io.IOException)

Example 89 with FileObject

use of javax.tools.FileObject in project fabric8 by fabric8io.

the class AbstractAnnotationProcessor method writeFile.

/**
 * Helper method to produce class output text file using the given handler
 */
protected void writeFile(String packageName, String fileName, String text) {
    Writer writer = null;
    try {
        Writer out;
        Filer filer = processingEnv.getFiler();
        FileObject resource;
        try {
            resource = filer.getResource(StandardLocation.CLASS_OUTPUT, packageName, fileName);
        } catch (Throwable e) {
            resource = filer.createResource(StandardLocation.CLASS_OUTPUT, packageName, fileName);
        }
        URI uri = resource.toUri();
        File file = null;
        if (uri != null) {
            try {
                file = new File(uri.getPath());
            } catch (Exception e) {
                warning("Could not convert output directory resource URI to a file " + e);
            }
        }
        if (file == null) {
            warning("No class output directory could be found!");
        } else {
            file.getParentFile().mkdirs();
            log("Generating file " + file);
            writer = new FileWriter(file);
            writer.write(text);
        }
    } catch (IOException e) {
        log(e);
    } finally {
        IOHelper.close(writer);
    }
}
Also used : FileWriter(java.io.FileWriter) FileObject(javax.tools.FileObject) IOException(java.io.IOException) Filer(javax.annotation.processing.Filer) URI(java.net.URI) File(java.io.File) PrintWriter(java.io.PrintWriter) StringWriter(java.io.StringWriter) FileWriter(java.io.FileWriter) Writer(java.io.Writer) IOException(java.io.IOException)

Example 90 with FileObject

use of javax.tools.FileObject in project ceylon-compiler by ceylon.

the class SourceToHTMLConverter method convertClass.

/**
 * Convert the given Class to an HTML.
 *
 * @param configuration the configuration.
 * @param cd the class to convert.
 * @param outputdir the name of the directory to output to.
 */
public static void convertClass(ConfigurationImpl configuration, ClassDoc cd, String outputdir) {
    if (cd == null || outputdir == null) {
        return;
    }
    try {
        SourcePosition sp = cd.position();
        if (sp == null)
            return;
        Reader r;
        // temp hack until we can update SourcePosition API.
        if (sp instanceof com.sun.tools.javadoc.SourcePositionImpl) {
            FileObject fo = ((com.sun.tools.javadoc.SourcePositionImpl) sp).fileObject();
            if (fo == null)
                return;
            r = fo.openReader(true);
        } else {
            File file = sp.file();
            if (file == null)
                return;
            r = new FileReader(file);
        }
        LineNumberReader reader = new LineNumberReader(r);
        int lineno = 1;
        String line;
        relativePath = DirectoryManager.getRelativePath(DocletConstants.SOURCE_OUTPUT_DIR_NAME) + DirectoryManager.getRelativePath(cd.containingPackage());
        Content body = getHeader();
        Content pre = new HtmlTree(HtmlTag.PRE);
        try {
            while ((line = reader.readLine()) != null) {
                addLineNo(pre, lineno);
                addLine(pre, line, configuration.sourcetab, lineno);
                lineno++;
            }
        } finally {
            reader.close();
        }
        addBlankLines(pre);
        Content div = HtmlTree.DIV(HtmlStyle.sourceContainer, pre);
        body.addContent(div);
        writeToFile(body, outputdir, cd.name(), configuration);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : FileObject(javax.tools.FileObject)

Aggregations

FileObject (javax.tools.FileObject)98 IOException (java.io.IOException)61 File (java.io.File)21 TypeElement (javax.lang.model.element.TypeElement)19 PrintWriter (java.io.PrintWriter)17 Writer (java.io.Writer)16 Filer (javax.annotation.processing.Filer)14 Element (javax.lang.model.element.Element)14 BufferedWriter (java.io.BufferedWriter)12 ArrayList (java.util.ArrayList)12 OutputStream (java.io.OutputStream)11 JavaFileObject (javax.tools.JavaFileObject)11 OutputStreamWriter (java.io.OutputStreamWriter)10 URI (java.net.URI)10 Properties (java.util.Properties)10 InputStream (java.io.InputStream)8 FileWriter (java.io.FileWriter)7 FilerException (javax.annotation.processing.FilerException)7 MainInfo (com.predic8.membrane.annot.model.MainInfo)6 BufferedReader (java.io.BufferedReader)6