Example usage for javax.tools FileObject openOutputStream

List of usage examples for javax.tools FileObject openOutputStream

Introduction

In this page you can find the example usage for javax.tools FileObject openOutputStream.

Prototype

OutputStream openOutputStream() throws IOException;

Source Link

Document

Returns an OutputStream for this file object.

Usage

From source file:android.databinding.tool.util.GenerationalClassUtil.java

public static void writeIntermediateFile(ProcessingEnvironment processingEnv, String packageName,
        String fileName, Serializable object) {
    ObjectOutputStream oos = null;
    try {//ww  w  . j  a va  2s  .c o  m
        FileObject intermediate = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT,
                packageName, fileName);
        OutputStream ios = intermediate.openOutputStream();
        oos = new ObjectOutputStream(ios);
        oos.writeObject(object);
        oos.close();
        L.d("wrote intermediate bindable file %s %s", packageName, fileName);
    } catch (IOException e) {
        L.e(e, "Could not write to intermediate file: %s", fileName);
    } finally {
        IOUtils.closeQuietly(oos);
    }
}

From source file:cop.raml.processor.RestProcessor.java

private static void saveRamlToFile(@NotNull RestApi api, @NotNull String fileName) throws Exception {
    FileObject file = ThreadLocalContext.getProcessingEnv().getFiler()
            .createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
    String template = Config.get().ramlVersion().getTemplate();

    try (OutputStreamWriter out = new OutputStreamWriter(file.openOutputStream(), StandardCharsets.UTF_8)) {
        assemble(out, api, template);// w  ww . j a v a2 s. c  om
    }
}

From source file:com.spotify.docgenerator.JacksonJerseyAnnotationProcessor.java

private void writeJsonToFile(Filer filer, String resourceFile, Object obj) {
    try {/* w w w.jav a2s . co m*/
        final FileObject outputFile = filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceFile);
        try (final OutputStream out = outputFile.openOutputStream()) {
            out.write(NORMALIZING_OBJECT_WRITER.writeValueAsBytes(obj));
        }
    } catch (IOException e) {
        fatalError("Failed writing to " + resourceFile + "\n");
        e.printStackTrace();
    }
}

From source file:ch.rasc.extclassgenerator.ModelAnnotationProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
            "Running " + getClass().getSimpleName());

    if (roundEnv.processingOver() || annotations.size() == 0) {
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }/*  ww w. j  a  v a  2s.c o m*/

    if (roundEnv.getRootElements() == null || roundEnv.getRootElements().isEmpty()) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, "No sources to process");
        return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
    }

    OutputConfig outputConfig = new OutputConfig();

    outputConfig.setDebug(!"false".equals(this.processingEnv.getOptions().get(OPTION_DEBUG)));
    boolean createBaseAndSubclass = "true"
            .equals(this.processingEnv.getOptions().get(OPTION_CREATEBASEANDSUBCLASS));

    String outputFormatString = this.processingEnv.getOptions().get(OPTION_OUTPUTFORMAT);
    outputConfig.setOutputFormat(OutputFormat.EXTJS4);
    if (StringUtils.hasText(outputFormatString)) {
        if (OutputFormat.TOUCH2.name().equalsIgnoreCase(outputFormatString)) {
            outputConfig.setOutputFormat(OutputFormat.TOUCH2);
        } else if (OutputFormat.EXTJS5.name().equalsIgnoreCase(outputFormatString)) {
            outputConfig.setOutputFormat(OutputFormat.EXTJS5);
        }
    }

    String includeValidationString = this.processingEnv.getOptions().get(OPTION_INCLUDEVALIDATION);
    outputConfig.setIncludeValidation(IncludeValidation.NONE);
    if (StringUtils.hasText(includeValidationString)) {
        if (IncludeValidation.ALL.name().equalsIgnoreCase(includeValidationString)) {
            outputConfig.setIncludeValidation(IncludeValidation.ALL);
        } else if (IncludeValidation.BUILTIN.name().equalsIgnoreCase(includeValidationString)) {
            outputConfig.setIncludeValidation(IncludeValidation.BUILTIN);
        }
    }

    outputConfig.setUseSingleQuotes("true".equals(this.processingEnv.getOptions().get(OPTION_USESINGLEQUOTES)));
    outputConfig.setSurroundApiWithQuotes(
            "true".equals(this.processingEnv.getOptions().get(OPTION_SURROUNDAPIWITHQUOTES)));

    for (TypeElement annotation : annotations) {
        Set<? extends Element> elements = roundEnv.getElementsAnnotatedWith(annotation);
        for (Element element : elements) {

            try {
                TypeElement typeElement = (TypeElement) element;

                String qualifiedName = typeElement.getQualifiedName().toString();
                Class<?> modelClass = Class.forName(qualifiedName);

                String code = ModelGenerator.generateJavascript(modelClass, outputConfig);

                Model modelAnnotation = element.getAnnotation(Model.class);
                String modelName = modelAnnotation.value();
                String fileName;
                String packageName = "";
                if (StringUtils.hasText(modelName)) {
                    int lastDot = modelName.lastIndexOf('.');
                    if (lastDot != -1) {
                        fileName = modelName.substring(lastDot + 1);
                        int firstDot = modelName.indexOf('.');
                        if (firstDot < lastDot) {
                            packageName = modelName.substring(firstDot + 1, lastDot);
                        }
                    } else {
                        fileName = modelName;
                    }
                } else {
                    fileName = typeElement.getSimpleName().toString();
                }

                if (createBaseAndSubclass) {
                    code = code.replaceFirst("(Ext.define\\([\"'].+?)([\"'],)", "$1Base$2");
                    FileObject fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                            packageName, fileName + "Base.js");
                    OutputStream os = fo.openOutputStream();
                    os.write(code.getBytes(ModelGenerator.UTF8_CHARSET));
                    os.close();

                    try {
                        fo = this.processingEnv.getFiler().getResource(StandardLocation.SOURCE_OUTPUT,
                                packageName, fileName + ".js");
                        InputStream is = fo.openInputStream();
                        is.close();
                    } catch (FileNotFoundException e) {
                        String subClassCode = generateSubclassCode(modelClass, outputConfig);
                        fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                                packageName, fileName + ".js");
                        os = fo.openOutputStream();
                        os.write(subClassCode.getBytes(ModelGenerator.UTF8_CHARSET));
                        os.close();
                    }

                } else {
                    FileObject fo = this.processingEnv.getFiler().createResource(StandardLocation.SOURCE_OUTPUT,
                            packageName, fileName + ".js");
                    OutputStream os = fo.openOutputStream();
                    os.write(code.getBytes(ModelGenerator.UTF8_CHARSET));
                    os.close();
                }

            } catch (ClassNotFoundException e) {
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
            } catch (IOException e) {
                this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage());
            }

        }
    }

    return ALLOW_OTHER_PROCESSORS_TO_CLAIM_ANNOTATIONS;
}

From source file:org.shredzone.commons.taglib.processor.TaglibProcessor.java

/**
 * Generates a TLD file for the tag library.
 *
 * @param tldfile//  w  w w .j a  va  2  s .  com
 *            name of the TLD file to be generated
 * @throws IOException
 *             when the generated TLD file could not be saved.
 */
private void generateTaglibTld(String tldfile) throws IOException {
    FileObject file = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", tldfile);
    try (PrintWriter out = new PrintWriter(new OutputStreamWriter(file.openOutputStream(), "UTF-8"))) {
        out.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        out.println(
                "<!DOCTYPE taglib PUBLIC \"-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN\" \"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd\">");
        out.println("<!-- Generated file, do not edit! -->");
        out.println("<taglib>");
        out.printf("  <tlibversion>%s</tlibversion>", taglib.getTlibversion()).println();
        out.printf("  <jspversion>%s</jspversion>", taglib.getJspversion()).println();
        out.printf("  <shortname>%s</shortname>", taglib.getShortname()).println();
        out.printf("  <uri>%s</uri>", escapeXml(taglib.getUri())).println();
        out.printf("  <info>%s</info>", escapeXml(taglib.getInfo())).println();

        for (TagBean tag : new TreeSet<TagBean>(taglib.getTags())) {
            out.println("  <tag>");
            out.printf("    <name>%s</name>", tag.getName()).println();
            out.printf("    <tagclass>%s</tagclass>", tag.getProxyClassName()).println();
            out.printf("    <bodycontent>%s</bodycontent>", tag.getBodycontent()).println();
            if (tag.getInfo() != null) {
                out.printf("    <info>%s</info>", escapeXml(tag.getInfo())).println();
            }

            for (AttributeBean attr : new TreeSet<AttributeBean>(tag.getAttributes())) {
                out.println("    <attribute>");
                out.printf("      <name>%s</name>", attr.getName()).println();
                out.printf("      <required>%s</required>", String.valueOf(attr.isRequired())).println();
                out.printf("      <rtexprvalue>%s</rtexprvalue>", String.valueOf(attr.isRtexprvalue()))
                        .println();
                out.println("    </attribute>");
            }

            out.println("  </tag>");
        }

        out.println("</taglib>");
    }
}

From source file:com.mastfrog.parameters.processor.Processor.java

@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment re) {

    SourceVersion sv = processingEnv.getSourceVersion();
    if (sv.ordinal() > SourceVersion.RELEASE_7.ordinal()) {
        optionalType = "java.util.Optional";
    } else {//w  w  w  . j av a 2  s  .c om
        TypeElement el = processingEnv.getElementUtils().getTypeElement(optionalType);
        if (el == null) {
            optionalType = "com.mastfrog.util.Optional";
        } else {
            optionalType = "com.google.common.base.Optional";
            fromNullable = "fromNullable";
        }
    }

    Set<? extends Element> all = re.getElementsAnnotatedWith(Params.class);
    List<GeneratedParamsClass> interfaces = new LinkedList<>();
    outer: for (Element e : all) {
        TypeElement te = (TypeElement) e;
        if (te.getSimpleName().toString().endsWith("__GenPage")) {
            continue;
        }
        PackageElement pkg = findPackage(e);
        if (pkg == null) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "@Params may not be used in the default package", e);
            continue;
        }
        if (!isPageSubtype(te)) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "@Params must be used on a subclass of org.apache.wicket.Page", e);
            continue;
        }
        String className = te.getQualifiedName().toString();
        Params params = te.getAnnotation(Params.class);

        Map<String, List<String>> validators = validatorsForParam(e);
        GeneratedParamsClass inf = new GeneratedParamsClass(className, te, pkg, params, validators);

        if (!params.useRequestBody()) {
            checkConstructor(te, inf);
        }
        interfaces.add(inf);
        Set<String> names = new HashSet<>();
        for (Param param : params.value()) {
            //                if (param.required() && !param.defaultValue().isEmpty()) {
            //                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Don't set required to "
            //                            + "true if you are providing a default value - required makes it an error not "
            //                            + "to have a value, and if there is a default value, that error is an impossibility "
            //                            + "because it will always have a value.", e);
            //                    continue outer;
            //                }
            if (param.value().trim().isEmpty()) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Empty parameter name", e);
                continue outer;
            }
            if (!isJavaIdentifier(param.value())) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "Not a valid Java identifier: " + param.value(), e);
                continue outer;
            }
            if (!names.add(param.value())) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "Duplicate parameter name '" + param.value() + "'", e);
                continue outer;
            }
            for (char c : ";,./*!@&^/\\<>?'\"[]{}-=+)(".toCharArray()) {
                if (param.value().contains("" + c)) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            "Param name may not contain the character '" + c + "'", e);
                }
            }
            inf.add(param);
        }
    }
    Filer filer = processingEnv.getFiler();
    StringBuilder listBuilder = new StringBuilder();
    for (GeneratedParamsClass inf : interfaces) {
        try {
            String pth = inf.packageAsPath() + '/' + inf.className;
            pth = pth.replace('/', '.');
            JavaFileObject obj = filer.createSourceFile(pth, inf.el);
            try (OutputStream out = obj.openOutputStream()) {
                out.write(inf.toString().getBytes("UTF-8"));
            }
            listBuilder.append(inf.className).append('\n');
        } catch (Exception ex) {
            ex.printStackTrace();
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    "Error processing annotation: " + ex.getMessage(), inf.el);
            Logger.getLogger(Processor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    if (re.processingOver()) {
        try {
            FileObject list = filer.createResource(StandardLocation.CLASS_OUTPUT, "",
                    "META-INF/paramanos/bind.list", all.toArray(new Element[0]));
            try (OutputStream out = list.openOutputStream()) {
                out.write(listBuilder.toString().getBytes("UTF-8"));
            }
        } catch (FilerException ex) {
            Logger.getLogger(Processor.class.getName()).log(Level.INFO, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Processor.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return true;
}

From source file:org.mule.module.extension.internal.resources.AnnotationProcessorResourceGenerator.java

@Override
protected void write(GeneratedResource resource) {
    FileObject file;
    try {/*  ww w. j a v a 2  s  . c o m*/
        file = processingEnv.getFiler().createResource(SOURCE_OUTPUT, EMPTY, resource.getFilePath());
    } catch (IOException e) {
        throw wrapException(e, resource);
    }

    try (OutputStream out = file.openOutputStream()) {
        out.write(resource.getContentBuilder().toString().getBytes());
        out.flush();
    } catch (IOException e) {
        throw wrapException(e, resource);
    }
}

From source file:org.mule.module.extension.internal.resources.AnnotationProcessorResourceGeneratorTestCase.java

@Test
public void dumpAll() throws Exception {
    final String filepath = "path";
    final String content = "hello world!";

    GeneratedResource resource = generator.get(filepath);
    resource.getContentBuilder().append(content);

    FileObject file = mock(FileObject.class);
    when(processingEnvironment.getFiler().createResource(SOURCE_OUTPUT, EMPTY, filepath)).thenReturn(file);

    OutputStream out = mock(OutputStream.class, RETURNS_DEEP_STUBS);
    when(file.openOutputStream()).thenReturn(out);

    generator.dumpAll();/*from   w w w.ja  v a  2 s  .  co m*/

    verify(out).write(content.getBytes());
    verify(out).flush();
}

From source file:org.versly.rest.wsdoc.AnnotationProcessor.java

@Override
public boolean process(Set<? extends TypeElement> supportedAnnotations, RoundEnvironment roundEnvironment) {

    // short-circuit if there are multiple rounds
    if (_isComplete)
        return true;

    Collection<String> processedPackageNames = new LinkedHashSet<String>();
    processElements(roundEnvironment, processedPackageNames, new SpringMVCRestImplementationSupport());
    processElements(roundEnvironment, processedPackageNames, new JaxRSRestImplementationSupport());
    processElements(roundEnvironment, processedPackageNames, new JavaEEWebsocketImplementationSupport());

    _docs.postProcess();/*w  w w.  ja  va 2 s. co  m*/

    if (_docs.getApis().size() > 0) {

        OutputStream fileOutput = null;
        try {
            FileObject file = getOutputFile();
            boolean exists = new File(file.getName()).exists();
            fileOutput = file.openOutputStream();
            _docs.toStream(fileOutput);
            processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE,
                    String.format("Wrote REST docs for %s apis to %s file at %s", _docs.getApis().size(),
                            exists ? "existing" : "new", file.getName()));
        } catch (Exception e) {
            throw new RuntimeException(e); // TODO wrap in something nicer
        } finally {
            if (fileOutput != null) {
                try {
                    fileOutput.close();
                } catch (IOException ignored) {
                    // ignored
                }
            }
        }
    }
    _isComplete = true;
    return true;
}