Example usage for javax.tools JavaFileObject openWriter

List of usage examples for javax.tools JavaFileObject openWriter

Introduction

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

Prototype

Writer openWriter() throws IOException;

Source Link

Document

Returns a Writer for this file object.

Usage

From source file:org.boundbox.processor.BoundBoxProcessor.java

@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnvironment) {
    // Get all classes that has the annotation
    Set<? extends Element> classElements = roundEnvironment.getElementsAnnotatedWith(BoundBox.class);
    // For each class that has the annotation
    for (final Element classElement : classElements) {

        // Get the annotation information
        TypeElement boundClass = null;
        String maxSuperClass = null;
        String[] prefixes = null;
        String boundBoxPackageName = null;

        List<? extends AnnotationValue> extraBoundFields = null;
        List<? extends AnnotationMirror> listAnnotationMirrors = classElement.getAnnotationMirrors();
        if (listAnnotationMirrors == null) {
            messager.printMessage(Kind.WARNING, "listAnnotationMirrors is null", classElement);
            return true;
        }/*from   ww w  .  j ava 2  s  . c  o  m*/

        StringBuilder message = new StringBuilder();
        for (AnnotationMirror annotationMirror : listAnnotationMirrors) {
            log.info("mirror " + annotationMirror.getAnnotationType());
            Map<? extends ExecutableElement, ? extends AnnotationValue> map = annotationMirror
                    .getElementValues();
            for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : map.entrySet()) {
                message.append(entry.getKey().getSimpleName().toString());
                message.append("\n");
                message.append(entry.getValue().toString());
                if (BOUNDBOX_ANNOTATION_PARAMETER_BOUND_CLASS
                        .equals(entry.getKey().getSimpleName().toString())) {
                    boundClass = getAnnotationValueAsTypeElement(entry.getValue());
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_MAX_SUPER_CLASS
                        .equals(entry.getKey().getSimpleName().toString())) {
                    maxSuperClass = getAnnotationValueAsTypeElement(entry.getValue()).asType().toString();
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_EXTRA_BOUND_FIELDS
                        .equals(entry.getKey().getSimpleName().toString())) {
                    extraBoundFields = getAnnotationValueAsAnnotationValueList(entry.getValue());
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_PREFIXES.equals(entry.getKey().getSimpleName().toString())) {
                    List<? extends AnnotationValue> listPrefixes = getAnnotationValueAsAnnotationValueList(
                            entry.getValue());
                    prefixes = new String[listPrefixes.size()];
                    for (int indexAnnotation = 0; indexAnnotation < listPrefixes.size(); indexAnnotation++) {
                        prefixes[indexAnnotation] = getAnnotationValueAsString(
                                listPrefixes.get(indexAnnotation));
                    }
                }
                if (BOUNDBOX_ANNOTATION_PARAMETER_PACKAGE.equals(entry.getKey().getSimpleName().toString())) {
                    boundBoxPackageName = getAnnotationValueAsString(entry.getValue());
                }
            }
        }

        if (boundClass == null) {
            messager.printMessage(Kind.WARNING, "BoundClass is null : " + message, classElement);
            return true;
        }

        if (maxSuperClass != null) {
            boundClassVisitor.setMaxSuperClassName(maxSuperClass);
        }

        if (prefixes != null && prefixes.length != 2 && prefixes.length != 1) {
            error(classElement,
                    "You must provide 1 or 2 prefixes. The first one for class names, the second one for methods.");
            return true;
        }
        if (prefixes != null && prefixes.length == 1) {
            String[] newPrefixes = new String[] { prefixes[0], prefixes[0].toLowerCase(Locale.US) };
            prefixes = newPrefixes;
        }
        boundboxWriter.setPrefixes(prefixes);

        if (boundBoxPackageName == null) {
            String boundClassFQN = boundClass.getQualifiedName().toString();
            if (boundClassFQN.contains(PACKAGE_SEPARATOR)) {
                boundBoxPackageName = StringUtils.substringBeforeLast(boundClassFQN, PACKAGE_SEPARATOR);
            } else {
                boundBoxPackageName = StringUtils.EMPTY;
            }
        }
        boundClassVisitor.setBoundBoxPackageName(boundBoxPackageName);
        boundboxWriter.setBoundBoxPackageName(boundBoxPackageName);

        ClassInfo classInfo = boundClassVisitor.scan(boundClass);

        injectExtraBoundFields(extraBoundFields, classInfo);

        listClassInfo.add(classInfo);

        // perform some computations on meta model
        inheritanceComputer.computeInheritanceAndHidingFields(classInfo.getListFieldInfos());
        inheritanceComputer.computeInheritanceAndOverridingMethods(classInfo.getListMethodInfos(), boundClass,
                elements);
        inheritanceComputer.computeInheritanceAndHidingInnerClasses(classInfo.getListInnerClassInfo());
        inheritanceComputer.computeInheritanceInInnerClasses(classInfo, elements);

        // write meta model to java class file
        Writer sourceWriter = null;
        try {
            String boundBoxClassName = boundboxWriter.getNamingGenerator().createBoundBoxName(classInfo);
            String boundBoxClassFQN = boundBoxPackageName.isEmpty() ? boundBoxClassName
                    : boundBoxPackageName + PACKAGE_SEPARATOR + boundBoxClassName;
            JavaFileObject sourceFile = filer.createSourceFile(boundBoxClassFQN, (Element[]) null);
            sourceWriter = sourceFile.openWriter();

            boundboxWriter.writeBoundBox(classInfo, sourceWriter);
        } catch (IOException e) {
            e.printStackTrace();
            error(classElement, e.getMessage());
        } finally {
            if (sourceWriter != null) {
                IOUtils.closeQuietly(sourceWriter);
            }
        }
    }

    return true;
}

From source file:org.jraf.android.prefs.compiler.PrefsProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (TypeElement te : annotations) {
        for (Element element : roundEnv.getElementsAnnotatedWith(te)) {
            TypeElement classElement = (TypeElement) element;
            PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();

            String classComment = processingEnv.getElementUtils().getDocComment(classElement);

            List<Pref> prefList = new ArrayList<Pref>();
            // Iterate over the fields of the class
            for (VariableElement variableElement : ElementFilter.fieldsIn(classElement.getEnclosedElements())) {
                if (variableElement.getModifiers().contains(Modifier.STATIC)) {
                    // Ignore constants
                    continue;
                }//from www.  j a v a  2 s . c o m

                TypeMirror fieldType = variableElement.asType();
                boolean isAllowedType = PrefType.isAllowedType(fieldType);
                if (!isAllowedType) {
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            fieldType + " is not allowed here, only these types are allowed: "
                                    + PrefType.getAllowedTypes(),
                            variableElement);
                    // Problem detected: halt
                    return true;
                }

                String fieldName = variableElement.getSimpleName().toString();
                org.jraf.android.prefs.Name fieldNameAnnot = variableElement
                        .getAnnotation(org.jraf.android.prefs.Name.class);
                String prefName = getPrefName(fieldName, fieldNameAnnot);

                String prefDefaultValue = getDefaultValue(variableElement, fieldType);
                if (prefDefaultValue == null) {
                    // Problem detected: halt
                    return true;
                }

                String fieldComment = processingEnv.getElementUtils().getDocComment(variableElement);
                Pref pref = new Pref(fieldName, prefName, PrefType.from(fieldType), prefDefaultValue,
                        fieldComment);
                prefList.add(pref);
            }

            Map<String, Object> args = new HashMap<String, Object>();

            // File name (optional - also use 'value' for this)
            org.jraf.android.prefs.Prefs prefsAnnot = classElement
                    .getAnnotation(org.jraf.android.prefs.Prefs.class);
            String fileName = prefsAnnot.value();
            if (fileName.isEmpty()) {
                fileName = prefsAnnot.fileName();
            }
            if (!fileName.isEmpty())
                args.put("fileName", fileName);

            // File mode (must only appear if fileName is defined)
            int fileMode = prefsAnnot.fileMode();
            if (fileMode != -1) {
                if (fileName.isEmpty()) {
                    // File mode set, but not file name (which makes no sense)
                    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                            "fileMode must only be set if fileName (or value) is also set", classElement);
                    // Problem detected: halt
                    return true;
                }
                args.put("fileMode", fileMode);
            }

            // Disable @Nullable generation
            args.put("disableNullable", prefsAnnot.disableNullable());

            JavaFileObject javaFileObject = null;
            try {
                // SharedPreferencesWrapper
                javaFileObject = processingEnv.getFiler()
                        .createSourceFile(classElement.getQualifiedName() + SUFFIX_PREF_WRAPPER);
                Template template = getFreemarkerConfiguration().getTemplate("prefwrapper.ftl");
                args.put("package", packageElement.getQualifiedName());
                args.put("comment", classComment);
                args.put("prefWrapperClassName", classElement.getSimpleName() + SUFFIX_PREF_WRAPPER);
                args.put("editorWrapperClassName", classElement.getSimpleName() + SUFFIX_EDITOR_WRAPPER);
                args.put("prefList", prefList);
                Writer writer = javaFileObject.openWriter();
                template.process(args, writer);
                IOUtils.closeQuietly(writer);

                // EditorWrapper
                javaFileObject = processingEnv.getFiler()
                        .createSourceFile(classElement.getQualifiedName() + "EditorWrapper");
                template = getFreemarkerConfiguration().getTemplate("editorwrapper.ftl");
                writer = javaFileObject.openWriter();
                template.process(args, writer);
                IOUtils.closeQuietly(writer);

            } catch (Exception e) {
                processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                        "En error occurred while generating Prefs code " + e.getClass() + e.getMessage(),
                        element);
                e.printStackTrace();
                // Problem detected: halt
                return true;
            }
        }
    }
    return true;
}

From source file:therian.buildweaver.StandardOperatorsProcessor.java

private void write() {
    InputStream templateStream = null;
    Writer targetWriter = null;/*from   w w  w .  j  a va 2s .c om*/
    try {
        templateStream = getClass().getResourceAsStream(TEMPLATE_RESOURCE);
        final String template = IOUtils.toString(templateStream, CharEncoding.UTF_8);
        final String output = StrSubstitutor.replace(template,
                Collections.singletonMap("operators", StringUtils.join(operators, ",\n")));
        final JavaFileObject target = processingEnv.getFiler().createSourceFile(TARGET_CLASSNAME,
                originatingElements.toArray(new Element[originatingElements.size()]));
        targetWriter = target.openWriter();
        IOUtils.write(output, targetWriter);
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        IOUtils.closeQuietly(templateStream);
        IOUtils.closeQuietly(targetWriter);
    }

}