Example usage for javax.tools FileObject openWriter

List of usage examples for javax.tools FileObject openWriter

Introduction

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

Prototype

Writer openWriter() throws IOException;

Source Link

Document

Returns a Writer for this file object.

Usage

From source file:io.fabric8.kubernetes.generator.processor.AbstractKubernetesAnnotationProcessor.java

void generateJson(String fileName, KubernetesResource resource) {
    try {/*from ww w. ja v a  2  s  .  c o m*/
        FileObject fileObject = getFileObject(fileName);
        try (Writer writer = fileObject.openWriter()) {
            MAPPER.writeValue(writer, resource);
        }
    } catch (IOException e) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "Error generating json " + fileName);
    }
}

From source file:com.predic8.membrane.annot.generator.Parsers.java

public void writeParserDefinitior(Model m) throws IOException {

    for (MainInfo main : m.getMains()) {
        List<Element> sources = new ArrayList<Element>();
        sources.addAll(main.getInterceptorElements());
        sources.add(main.getElement());/*from  w ww.j  av a 2s.c o m*/

        try {
            FileObject o = processingEnv.getFiler().createSourceFile(
                    main.getAnnotation().outputPackage() + ".NamespaceHandlerAutoGenerated",
                    sources.toArray(new Element[0]));
            BufferedWriter bw = new BufferedWriter(o.openWriter());
            try {
                bw.write("/* Copyright 2012,2013 predic8 GmbH, www.predic8.com\r\n" + "\r\n"
                        + "   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n"
                        + "   you may not use this file except in compliance with the License.\r\n"
                        + "   You may obtain a copy of the License at\r\n" + "\r\n"
                        + "   http://www.apache.org/licenses/LICENSE-2.0\r\n" + "\r\n"
                        + "   Unless required by applicable law or agreed to in writing, software\r\n"
                        + "   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n"
                        + "   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n"
                        + "   See the License for the specific language governing permissions and\r\n"
                        + "   limitations under the License. */\r\n" + "\r\n" + "package "
                        + main.getAnnotation().outputPackage() + ";\r\n" + "\r\n" + "/**\r\n"
                        + "  * Automatically generated by " + Parsers.class.getName() + ".\r\n" + "  */\r\n"
                        + "public class NamespaceHandlerAutoGenerated {\r\n" + "\r\n"
                        + "   public static void registerBeanDefinitionParsers(NamespaceHandler nh) {\r\n");
                for (ElementInfo i : main.getIis()) {
                    if (i.getAnnotation().topLevel()) {
                        bw.write("      nh.registerGlobalBeanDefinitionParser(\"" + i.getAnnotation().name()
                                + "\", new " + i.getParserClassSimpleName() + "());\r\n");
                    } else {
                        for (ChildElementDeclarationInfo cedi : i.getUsedBy()) {
                            for (ChildElementInfo cei : cedi.getUsedBy()) {
                                TypeElement element = cei.getEi().getElement();
                                String clazz = AnnotUtils.getRuntimeClassName(element);
                                bw.write("      nh.registerLocalBeanDefinitionParser(\"" + clazz + "\", \""
                                        + i.getAnnotation().name() + "\", new " + i.getParserClassSimpleName()
                                        + "());\r\n");
                            }
                        }
                    }
                }
                bw.write("   }\r\n" + "}\r\n" + "");
            } finally {
                bw.close();
            }
        } catch (FilerException e) {
            if (e.getMessage().contains("Source file already created"))
                return;
            throw e;
        }
    }
}

From source file:com.predic8.membrane.annot.generator.Parsers.java

public void writeParsers(Model m) throws IOException {
    for (MainInfo main : m.getMains()) {
        for (ElementInfo ii : main.getIis()) {
            List<Element> sources = new ArrayList<Element>();
            sources.add(main.getElement());
            sources.add(ii.getElement());

            String interceptorClassName = ii.getElement().getQualifiedName().toString();

            try {
                FileObject o = processingEnv.getFiler().createSourceFile(
                        main.getAnnotation().outputPackage() + "." + ii.getParserClassSimpleName(),
                        sources.toArray(new Element[0]));
                BufferedWriter bw = new BufferedWriter(o.openWriter());
                try {
                    bw.write("/* Copyright 2012 predic8 GmbH, www.predic8.com\r\n" + "\r\n"
                            + "   Licensed under the Apache License, Version 2.0 (the \"License\");\r\n"
                            + "   you may not use this file except in compliance with the License.\r\n"
                            + "   You may obtain a copy of the License at\r\n" + "\r\n"
                            + "   http://www.apache.org/licenses/LICENSE-2.0\r\n" + "\r\n"
                            + "   Unless required by applicable law or agreed to in writing, software\r\n"
                            + "   distributed under the License is distributed on an \"AS IS\" BASIS,\r\n"
                            + "   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n"
                            + "   See the License for the specific language governing permissions and\r\n"
                            + "   limitations under the License. */\r\n" + "\r\n" + "package "
                            + main.getAnnotation().outputPackage() + ";\r\n" + "\r\n"
                            + "import org.w3c.dom.Element;\r\n"
                            + "import org.springframework.beans.factory.xml.ParserContext;\r\n"
                            + "import org.springframework.beans.factory.support.BeanDefinitionBuilder;\r\n");
                    if (!main.getAnnotation().outputPackage().equals("com.predic8.membrane.core.config.spring"))
                        bw.write("import com.predic8.membrane.core.config.spring.*;\r\n");
                    bw.write("\r\n" + "/**\r\n" + "  * Automatically generated by " + Parsers.class.getName()
                            + ".\r\n" + "  */\r\n" + "public class " + ii.getParserClassSimpleName()
                            + " extends AbstractParser {\r\n" + "\r\n"
                            + "   protected Class<?> getBeanClass(org.w3c.dom.Element element) {\r\n"
                            + "      return " + interceptorClassName + ".class;\r\n" + "   }\r\n");
                    bw.write("   @Override\r\n"
                            + "   protected void doParse(Element element, ParserContext parserContext, BeanDefinitionBuilder builder) {\r\n");
                    if (ii.isHasIdField())
                        bw.write("      setPropertyIfSet(\"id\", element, builder);\r\n");
                    bw.write("      setIdIfNeeded(element, parserContext, \"" + ii.getAnnotation().name()
                            + "\");\r\n");
                    for (AttributeInfo ai : ii.getAis()) {
                        if (ai.getXMLName().equals("id"))
                            continue;
                        if (ai.isBeanReference(processingEnv.getTypeUtils())) {
                            if (!ai.isRequired())
                                bw.write("      if (element.hasAttribute(\"" + ai.getXMLName() + "\"))\r\n");
                            bw.write("      builder.addPropertyReference(\"" + ai.getSpringName()
                                    + "\", element.getAttribute(\"" + ai.getXMLName() + "\"));\r\n");
                        } else {
                            bw.write("      setProperty" + (ai.isRequired() ? "" : "IfSet") + "(\""
                                    + ai.getXMLName() + "\", \"" + ai.getSpringName() + "\", element, builder"
                                    + (ai.isEnum(processingEnv.getTypeUtils()) ? ", true" : "") + ");\r\n");
                        }/*from   w  ww.j  a va 2 s. co  m*/
                        if (ai.getXMLName().equals("name"))
                            bw.write("      element.removeAttribute(\"name\");\r\n");
                    }
                    if (ii.getOai() != null) {
                        bw.write("      setProperties(\"" + ii.getOai().getSpringName()
                                + "\", element, builder);\r\n");
                    }
                    for (ChildElementInfo cei : ii.getCeis())
                        if (cei.isList())
                            bw.write("      builder.addPropertyValue(\"" + cei.getPropertyName()
                                    + "\", new java.util.ArrayList<Object>());\r\n");
                    if (ii.getTci() != null)
                        bw.write("      builder.addPropertyValue(\"" + ii.getTci().getPropertyName()
                                + "\", element.getTextContent());\r\n");
                    else
                        bw.write("      parseChildren(element, parserContext, builder);\r\n");
                    for (ChildElementInfo cei : ii.getCeis())
                        if (cei.isList() && cei.isRequired()) {
                            bw.write(
                                    "      if (builder.getBeanDefinition().getPropertyValues().getPropertyValue(\""
                                            + cei.getPropertyName() + "[0]\") == null)\r\n");
                            bw.write("         throw new RuntimeException(\"Property '" + cei.getPropertyName()
                                    + "' is required, but none was defined (empty list).\");\r\n");
                        }

                    bw.write("   }\r\n" + "");

                    bw.write("@Override\r\n"
                            + "protected void handleChildObject(Element ele, ParserContext parserContext, BeanDefinitionBuilder builder, Class<?> clazz, Object child) {\r\n");
                    for (ChildElementInfo cei : ii.getCeis()) {
                        bw.write("   if (" + cei.getTypeDeclaration().getQualifiedName()
                                + ".class.isAssignableFrom(clazz)) {\r\n" + "      setProperty(builder, \""
                                + cei.getPropertyName() + "\""
                                + (cei.isList()
                                        ? "+\"[\"+ incrementCounter(builder, \"" + cei.getPropertyName()
                                                + "\") + \"]\" "
                                        : "")
                                + ", child);\r\n" + "   } else \r\n");
                    }
                    bw.write("   {\r\n"
                            + "      throw new RuntimeException(\"Unknown child class \\\"\" + clazz + \"\\\".\");\r\n"
                            + "   }\r\n");
                    bw.write("}\r\n");

                    bw.write("}\r\n" + "");
                } finally {
                    bw.close();
                }
            } catch (FilerException e) {
                if (e.getMessage().contains("Source file already created"))
                    return;
                throw e;
            }

        }
    }

}

From source file:com.predic8.membrane.annot.SpringConfigurationXSDGeneratingAnnotationProcessor.java

private void write() {
    try {//from  www .  j a  v a2  s . c o m
        FileObject o = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "",
                "META-INF/membrane.cache");
        BufferedWriter bw = new BufferedWriter(o.openWriter());
        try {
            bw.write("1\n");

            for (Map.Entry<Class<? extends Annotation>, HashSet<Element>> e : cache.entrySet()) {
                bw.write(e.getKey().getName());
                bw.write("\n");
                for (Element f : e.getValue()) {
                    bw.write(" ");
                    bw.write(((TypeElement) f).getQualifiedName().toString());
                    bw.write("\n");
                }
            }
        } finally {
            bw.close();
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:net.minecrell.quartz.mappings.processor.MappingsGeneratorProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }/*www  . j  a  va  2s  . c  om*/

    List<TypeElement> mappingClasses = new ArrayList<>();

    for (Element element : roundEnv.getElementsAnnotatedWith(Mapping.class)) {
        if (element instanceof TypeElement) {
            mappingClasses.add((TypeElement) element);
        }
    }

    if (mappingClasses.isEmpty()) {
        return true;
    }

    try {
        FileObject file = this.processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
                "mappings.json");

        Map<String, MappedClass> mappings;
        try (Reader reader = file.openReader(false)) {
            mappings = Mappings.read(reader);
        } catch (IOException ignored) {
            mappings = new HashMap<>();
        }

        ClassMapper classMappings = createMapper(mappingClasses);

        // We need to remap the descriptors of the fields and methods, use ASM for convenience
        Remapper unmapper = classMappings.createUnmapper();

        for (TypeElement mappingClass : mappingClasses) {
            String internalName = getInternalName(mappingClass);

            Mapping annotation = mappingClass.getAnnotation(Mapping.class);
            String mappedName = annotation.value();
            if (mappedName.isEmpty()) {
                mappedName = internalName;
            }

            MappedClass mapping = new MappedClass(mappedName);

            Accessible accessible = mappingClass.getAnnotation(Accessible.class);
            if (accessible != null) {
                mapping.getAccess().put("", parseAccessible(accessible));
            }

            for (Element element : mappingClass.getEnclosedElements()) {
                accessible = element.getAnnotation(Accessible.class);

                Constructor constructor = element.getAnnotation(Constructor.class);
                if (constructor != null) {
                    if (accessible != null) {
                        String constructorDesc = getDescriptor((ExecutableElement) element);

                        mapping.getAccess().put("<init>" + constructorDesc, parseAccessible(accessible));
                    }
                    continue;
                }

                annotation = element.getAnnotation(Mapping.class);
                if (annotation == null) {
                    continue;
                }

                mappedName = annotation.value();
                checkArgument(!mappedName.isEmpty(), "Mapping detection is not supported yet");

                switch (element.getKind()) {
                case METHOD:
                    ExecutableElement method = (ExecutableElement) element;
                    String methodName = method.getSimpleName().toString();
                    String methodDesc = getDescriptor(method);
                    mapping.getMethods().put(mappedName + unmapper.mapMethodDesc(methodDesc), methodName);

                    if (accessible != null) {
                        mapping.getAccess().put(methodName + methodDesc, parseAccessible(accessible));
                    }

                    break;
                case FIELD:
                case ENUM_CONSTANT:
                    VariableElement field = (VariableElement) element;
                    String fieldName = field.getSimpleName().toString();
                    mapping.getFields().put(mappedName + ':' + unmapper.mapDesc(getDescriptor(field)),
                            fieldName);

                    if (accessible != null) {
                        mapping.getAccess().put(fieldName, parseAccessible(accessible));
                    }

                    break;
                default:
                }
            }

            mappings.put(internalName, mapping);
        }

        // Generate JSON output
        file = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "mappings.json");
        try (Writer writer = file.openWriter()) {
            Mappings.write(writer, mappings);
        }

        return true;
    } catch (IOException e) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getStackTrace(e));
        throw new RuntimeException("Failed to create mappings.json", e);
    }
}

From source file:org.ez18n.apt.processor.GwtXmlProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return true;
    }//www  . j  a  v  a 2  s .c  om

    final List<TypeElement> bundleTypes = new ArrayList<TypeElement>();
    for (Element element : roundEnv.getElementsAnnotatedWith(MessageBundle.class)) {
        if (element.getKind() != ElementKind.INTERFACE) {
            continue;
        }
        final TypeElement bundleType = (TypeElement) element;
        bundleTypes.add(bundleType);
    }

    if (bundleTypes.isEmpty()) {
        return true;
    }

    String packageName = null;
    for (TypeElement typeElement : bundleTypes) {
        String typeElementPackage = typeElement.getEnclosingElement().toString();
        if (packageName == null) {
            packageName = typeElementPackage;
        } else {
            packageName = intersectPackage(packageName, typeElementPackage);
        }
    }

    try {
        final FileObject file = processingEnv.getFiler().createResource(SOURCE_OUTPUT,
                packageName == null ? "net.courtanet.b2c" : packageName, "Generated.gwt.xml");
        final Writer writer = file.openWriter();
        writer.write(getCode(bundleTypes));
        writer.close();
    } catch (FilerException e) {
        return false;
    } catch (IOException e) {
        processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage());
    }
    return false;
}

From source file:org.ez18n.apt.processor.LabelBundleProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return true;
    }//from   w  w  w  .j  a v a 2  s  .c om
    final List<LabelTemplateMethod> methods = new ArrayList<LabelTemplateMethod>();
    for (Element element : roundEnv.getElementsAnnotatedWith(MessageBundle.class)) {
        if (element.getKind() != ElementKind.INTERFACE) {
            continue;
        }
        final TypeElement bundleType = (TypeElement) element;
        processLabels(bundleType, methods);
        try {

            FileObject file = null;
            switch (generationType) {
            case SOURCE:
                file = processingEnv.getFiler().createSourceFile(getTargetClassName(bundleType), bundleType);
                break;

            case RESSOURCE:
                file = processingEnv.getFiler().createResource(SOURCE_OUTPUT,
                        bundleType.getEnclosingElement().toString(),
                        getTargetSimpleName(bundleType) + ".properties");
                break;
            }

            final Writer writer = file.openWriter();
            writer.write(getCode(bundleType, methods));
            writer.close();
        } catch (IOException e) {
            processingEnv.getMessager().printMessage(Kind.ERROR, e.getMessage(), bundleType);
        } finally {
            methods.clear();
        }
    }
    return false;
}

From source file:org.jannocessor.processor.JannocessorProcessorBase.java

protected void writeToFile(Location location, String pkg, String filename, String text, CodeMerger merger)
        throws JannocessorException {
    boolean mergeFile = merger != null;

    String info = fileInfo(location, pkg, filename);
    String operation = mergeFile ? "Merging" : "Writing";
    logger.info("{} generated code ({} characters) to file: {}",
            new Object[] { operation, text.length(), info });

    try {//from  ww w  .  ja v  a2  s.  com
        if (mergeFile) {
            FileInformation oldCode = readFile(location, pkg, filename);
            if (oldCode != null) {
                FileInformation newCode = new DefaultFileInformation(text, oldCode.getFilename(), new Date());
                text = merger.mergeCode(oldCode, newCode);
            } else {
                logger.warn("Couldn't merge non-existing file: {}", info);
            }
        }
    } catch (Exception e) {
        throw new JannocessorException("Couldn't merge file: " + info, e);
    }

    Writer writer = null;
    try {
        FileObject fileRes = filer.createResource(location, pkg, filename);
        writer = fileRes.openWriter();
        writer.write(text);
    } catch (IOException e) {
        throw new JannocessorException("Couldn't write to file: " + info, e);
    } finally {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                throw new JannocessorException("Couldn't close file: " + info, e);
            }
        }
    }
}

From source file:org.squashtest.tm.tools.annotation.processor.DynamicComponentProcessor.java

private Writer openWriter() throws IOException {
    FileObject file;
    Writer writer;//from   ww  w.j  ava  2  s .  co  m
    file = filer.createResource(StandardLocation.SOURCE_OUTPUT, "spring", generatedFileName(),
            (Element[]) null);

    writer = file.openWriter();
    return writer;
}