Example usage for javax.lang.model.element TypeElement getSimpleName

List of usage examples for javax.lang.model.element TypeElement getSimpleName

Introduction

In this page you can find the example usage for javax.lang.model.element TypeElement getSimpleName.

Prototype

@Override
Name getSimpleName();

Source Link

Document

Returns the simple name of this type element.

Usage

From source file:org.kie.workbench.common.stunner.core.processors.MainProcessor.java

private boolean processDefinitions(final Set<? extends TypeElement> set, final Element e,
        final RoundEnvironment roundEnv) throws Exception {
    final boolean isClass = e.getKind() == ElementKind.CLASS;
    if (isClass) {
        TypeElement classElement = (TypeElement) e;
        PackageElement packageElement = (PackageElement) classElement.getEnclosingElement();
        String defintionClassName = packageElement.getQualifiedName().toString() + "."
                + classElement.getSimpleName();
        Map<String, String> baseTypes = processingContext.getDefinitionAnnotations().getBaseTypes();
        TypeElement parentElement = getDefinitionInheritedType(classElement);
        if (null != parentElement && !baseTypes.containsKey(defintionClassName)) {
            PackageElement basePackageElement = (PackageElement) parentElement.getEnclosingElement();
            String baseClassName = basePackageElement.getQualifiedName().toString() + "."
                    + parentElement.getSimpleName();
            baseTypes.put(defintionClassName, baseClassName);
        }//from  w w w.j a  va  2 s .  c om
        // Category fields.
        processFieldName(classElement, defintionClassName, ANNOTATION_DEFINITION_CATEGORY,
                processingContext.getDefinitionAnnotations().getCategoryFieldNames(), true);
        // Title fields.
        processFieldName(classElement, defintionClassName, ANNOTATION_DEFINITION_TITLE,
                processingContext.getDefinitionAnnotations().getTitleFieldNames(), true);
        // Description fields.
        processFieldName(classElement, defintionClassName, ANNOTATION_DESCRIPTION,
                processingContext.getDefinitionAnnotations().getDescriptionFieldNames(), true);
        // Labels fields.
        processFieldName(classElement, defintionClassName, ANNOTATION_DEFINITION_LABELS,
                processingContext.getDefinitionAnnotations().getLabelsFieldNames(), true);
        // Builder class.
        processDefinitionModelBuilder(e, defintionClassName,
                processingContext.getDefinitionAnnotations().getBuilderFieldNames());
        // Graph element.
        Definition definitionAnn = e.getAnnotation(Definition.class);
        TypeMirror mirror = null;
        try {
            Class<?> graphClass = definitionAnn.graphFactory();
        } catch (MirroredTypeException mte) {
            mirror = mte.getTypeMirror();
        }
        if (null == mirror) {
            throw new RuntimeException("No graph factory class specified for the @Definition.");
        }
        String fqcn = mirror.toString();
        processingContext.getDefinitionAnnotations().getGraphFactoryFieldNames().put(defintionClassName, fqcn);
        // PropertySets fields.
        Map<String, Element> propertySetElements = getFieldNames(classElement, ANNOTATION_PROPERTY_SET);
        if (null != propertySetElements && !propertySetElements.isEmpty()) {
            processingContext.getPropertySetElements().addAll(propertySetElements.values());
            processingContext.getDefinitionAnnotations().getPropertySetFieldNames().put(defintionClassName,
                    new LinkedHashSet<>(propertySetElements.keySet()));
        } else {
            note("Definition for tye [" + defintionClassName + "] have no Property Set members.");
        }
        // Properties fields.
        Map<String, Element> propertyElements = getFieldNames(classElement, ANNOTATION_PROPERTY);
        if (null != propertyElements && !propertyElements.isEmpty()) {
            processingContext.getPropertyElements().addAll(propertyElements.values());
            processingContext.getDefinitionAnnotations().getPropertyFieldNames().put(defintionClassName,
                    new LinkedHashSet<>(propertyElements.keySet()));
        } else {
            note("Definition for tye [" + defintionClassName + "] have no Property members.");
        }
        // -- Morphing annotations --
        MorphBase morphBaseAnn = e.getAnnotation(MorphBase.class);
        Morph morphAnn = e.getAnnotation(Morph.class);
        if (null != morphBaseAnn && null != morphAnn) {
            TypeElement superElement = getAnnotationInTypeInheritance(classElement, MorphBase.class.getName());
            final String packageName = packageElement.getQualifiedName().toString();
            String morphBaseClassName = packageName + "." + superElement.getSimpleName().toString();
            Map<String, String> defaultTypesMap = processingContext.getMorphingAnnotations()
                    .getBaseDefaultTypes();
            if (null == defaultTypesMap.get(morphBaseClassName)) {
                TypeMirror morphDefaultTypeMirror = null;
                try {
                    Class<?> defaultTypeClass = morphBaseAnn.defaultType();
                } catch (MirroredTypeException mte) {
                    morphDefaultTypeMirror = mte.getTypeMirror();
                }
                if (null == morphDefaultTypeMirror) {
                    throw new RuntimeException("No default type class specifyed for the @MorphBase.");
                }
                String morphDefaultTypeClassName = morphDefaultTypeMirror.toString();
                processingContext.getMorphingAnnotations().getBaseDefaultTypes().put(morphBaseClassName,
                        morphDefaultTypeClassName);
                // MorphBase - targets
                List<? extends TypeMirror> morphTargetMirrors = null;
                try {
                    Class<?>[] defsClasses = morphBaseAnn.targets();
                } catch (MirroredTypesException mte) {
                    morphTargetMirrors = mte.getTypeMirrors();
                }
                if (null != morphTargetMirrors) {
                    Set<String> morphTargetMirrorClasses = new LinkedHashSet<>();
                    for (TypeMirror morphTargetMirror : morphTargetMirrors) {
                        String morphTargetMirrorClassName = morphTargetMirror.toString();
                        morphTargetMirrorClasses.add(morphTargetMirrorClassName);
                    }
                    processingContext.getMorphingAnnotations().getBaseTargets().put(morphBaseClassName,
                            morphTargetMirrorClasses);
                }
                // Morph Properties.
                processMorphProperties(superElement, morphBaseClassName);
            }
            TypeMirror morphBaseTypeMirror = null;
            try {
                Class<?> defaultTypeClass = morphAnn.base();
            } catch (MirroredTypeException mte) {
                morphBaseTypeMirror = mte.getTypeMirror();
            }
            if (null == morphBaseTypeMirror) {
                throw new RuntimeException("No base type class specifyed for the @MorphBase.");
            }
            String morphBaseTypeClassName = morphBaseTypeMirror.toString();
            Set<String> currentTargets = processingContext.getMorphingAnnotations().getBaseTargets()
                    .get(morphBaseTypeClassName);
            if (null == currentTargets) {
                currentTargets = new LinkedHashSet<>();
                processingContext.getMorphingAnnotations().getBaseTargets().put(morphBaseTypeClassName,
                        currentTargets);
            }
            currentTargets.add(defintionClassName);
        }
    }
    return false;
}

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;
    }/* w  w w.j a  v a2s .  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:com.googlecode.androidannotations.helper.ValidatorHelper.java

public void componentRegistered(Element element, AndroidManifest androidManifest, boolean printWarning,
        IsValid valid) {/*from  ww w.j  a  v a 2 s . c o m*/
    TypeElement typeElement = (TypeElement) element;

    if (typeElement.getModifiers().contains(Modifier.ABSTRACT)) {
        return;
    }

    if (androidManifest.isLibraryProject()) {
        return;
    }

    String componentQualifiedName = typeElement.getQualifiedName().toString();
    String generatedComponentQualifiedName = componentQualifiedName + ModelConstants.GENERATION_SUFFIX;

    List<String> componentQualifiedNames = androidManifest.getComponentQualifiedNames();
    if (!componentQualifiedNames.contains(generatedComponentQualifiedName)) {
        String simpleName = typeElement.getSimpleName().toString();
        String generatedSimpleName = simpleName + ModelConstants.GENERATION_SUFFIX;
        if (componentQualifiedNames.contains(componentQualifiedName)) {
            valid.invalidate();
            annotationHelper.printAnnotationError(element,
                    "The AndroidManifest.xml file contains the original component, and not the AndroidAnnotations generated component. Please register "
                            + generatedSimpleName + " instead of " + simpleName);
        } else {
            if (printWarning) {
                annotationHelper.printAnnotationWarning(element, "The component " + generatedSimpleName
                        + " is not registered in the AndroidManifest.xml file.");
            }
        }
    }

}

From source file:org.kie.workbench.common.stunner.core.processors.MainProcessor.java

private void processMorphProperties(final TypeElement classElement, final String definitionClassName) {
    final Messager messager = processingEnv.getMessager();
    final Elements elementUtils = processingEnv.getElementUtils();
    List<VariableElement> variableElements = ElementFilter.fieldsIn(classElement.getEnclosedElements());
    for (VariableElement variableElement : variableElements) {
        if (GeneratorUtils.getAnnotation(elementUtils, variableElement, ANNOTATION_MORPH_PROPERTY) != null) {
            final TypeMirror fieldReturnType = variableElement.asType();
            final String fieldReturnTypeName = GeneratorUtils.getTypeMirrorDeclaredName(fieldReturnType);
            final String fieldName = variableElement.getSimpleName().toString();
            messager.printMessage(Diagnostic.Kind.NOTE,
                    "Discovered Morph Property " + "for class [" + classElement.getSimpleName() + "] "
                            + "at field [" + fieldName + "] " + "of return type [" + fieldReturnTypeName + "]");
            // MorphBase - defaultType
            MorphProperty morphBaseAnn = variableElement.getAnnotation(MorphProperty.class);
            TypeMirror morphDefaultTypeMirror = null;
            try {
                Class<?> defaultTypeClass = morphBaseAnn.binder();
            } catch (MirroredTypeException mte) {
                morphDefaultTypeMirror = mte.getTypeMirror();
            }/*from  ww w. j av  a2 s  .  c om*/
            if (null == morphDefaultTypeMirror) {
                throw new RuntimeException("No binder class specifyed for the @MorphProperty.");
            }
            String binderClassName = morphDefaultTypeMirror.toString();
            ProcessingMorphProperty morphProperty = new ProcessingMorphProperty(fieldReturnTypeName,
                    StringUtils.capitalize(fieldName), binderClassName);
            List<ProcessingMorphProperty> morphProperties = processingContext.getMorphingAnnotations()
                    .getBaseMorphProperties().get(definitionClassName);
            if (null == morphProperties) {
                morphProperties = new LinkedList<>();
                processingContext.getMorphingAnnotations().getBaseMorphProperties().put(definitionClassName,
                        morphProperties);
            }
            morphProperties.add(morphProperty);
        }
    }
}

From source file:org.kie.workbench.common.stunner.core.processors.MainProcessor.java

private Map<String, Element> getFieldNames(TypeElement classElement, String annotation) {
    final Messager messager = processingEnv.getMessager();
    final Elements elementUtils = processingEnv.getElementUtils();
    Map<String, Element> result = new LinkedHashMap<>();
    while (!classElement.toString().equals(Object.class.getName())) {
        List<VariableElement> variableElements = ElementFilter.fieldsIn(classElement.getEnclosedElements());
        for (VariableElement variableElement : variableElements) {
            if (GeneratorUtils.getAnnotation(elementUtils, variableElement, annotation) != null) {
                final TypeMirror fieldReturnType = variableElement.asType();
                final TypeElement t = (TypeElement) ((DeclaredType) fieldReturnType).asElement();
                final String fieldReturnTypeName = GeneratorUtils.getTypeMirrorDeclaredName(fieldReturnType);
                final String fieldName = variableElement.getSimpleName().toString();
                result.put(fieldName, t);
                messager.printMessage(Diagnostic.Kind.NOTE,
                        "Discovered property value " + "for class [" + classElement.getSimpleName() + "] "
                                + "at field [" + fieldName + "] " + "of return type [" + fieldReturnTypeName
                                + "]");
            }/*w w  w  . j av a 2  s  .  com*/
        }
        classElement = getParent(classElement);
    }
    return result;
}

From source file:info.archinnov.achilles.internals.codegen.meta.EntityMetaCodeGen.java

public EntityMetaSignature buildEntityMeta(EntityType entityType, TypeElement elm,
        GlobalParsingContext globalParsingContext, List<FieldMetaSignature> fieldMetaSignatures) {
    final TypeName rawClassTypeName = getRawType(TypeName.get(elm.asType()));
    final Optional<Consistency> consistency = aptUtils.getAnnotationOnClass(elm, Consistency.class);
    final Optional<TTL> ttl = aptUtils.getAnnotationOnClass(elm, TTL.class);
    final Optional<Strategy> strategy = aptUtils.getAnnotationOnClass(elm, Strategy.class);
    final Optional<Table> entityAnnot = aptUtils.getAnnotationOnClass(elm, Table.class);

    final Optional<TypeName> viewBaseClass = AnnotationTree.findOptionalViewBaseClass(aptUtils, elm);

    aptUtils.validateFalse(entityAnnot.isPresent() && viewBaseClass.isPresent(),
            "Cannot have both @Table and @MaterializedView on the class '%s'", rawClassTypeName);

    if (entityType == EntityType.VIEW) {
        aptUtils.validateTrue(viewBaseClass.isPresent(),
                "Missing @MaterializedView annotation on entity class '%s'", rawClassTypeName);
    }// ww  w . j  ava 2 s  .  c om

    validateIsAConcreteNonFinalClass(aptUtils, elm);
    validateHasPublicConstructor(aptUtils, rawClassTypeName, elm);
    validateNoDuplicateNames(aptUtils, rawClassTypeName, fieldMetaSignatures);
    validateHasPartitionKey(aptUtils, rawClassTypeName, fieldMetaSignatures);

    final boolean isCounter = BeanValidator.isCounterTable(aptUtils, rawClassTypeName, fieldMetaSignatures);

    if (entityType == EntityType.TABLE) {
        validateStaticColumns(aptUtils, rawClassTypeName, fieldMetaSignatures);
    } else if (entityType == EntityType.VIEW) {
        validateNoStaticColumnsForView(aptUtils, rawClassTypeName, fieldMetaSignatures);
        aptUtils.validateFalse(isCounter,
                "The class '%s' cannot have counter columns because it is a materialized view",
                rawClassTypeName);
    }

    validateComputed(aptUtils, rawClassTypeName, fieldMetaSignatures);
    validateCqlColumnNotReservedWords(aptUtils, rawClassTypeName, fieldMetaSignatures);

    validateCorrectKeysOrder(aptUtils, rawClassTypeName,
            fieldMetaSignatures.stream().filter(x -> x.context.columnType == ColumnType.PARTITION)
                    .map(x -> Tuple2.of(x.context.fieldName, (KeyColumnInfo) x.context.columnInfo))
                    .collect(toList()),
            "@PartitionKey");

    validateCorrectKeysOrder(aptUtils, rawClassTypeName,
            fieldMetaSignatures.stream().filter(x -> x.context.columnType == CLUSTERING)
                    .map(x -> Tuple2.of(x.context.fieldName, (KeyColumnInfo) x.context.columnInfo))
                    .collect(toList()),
            "@ClusteringColumn");

    final TypeName rawBeanType = TypeName.get(aptUtils.erasure(elm));

    final String className = elm.getSimpleName() + META_SUFFIX;
    final TypeName typeName = ClassName.get(ENTITY_META_PACKAGE, className);

    final TypeSpec.Builder builder = TypeSpec.classBuilder(className)
            .addJavadoc("Meta class of all entities of type $T<br/>\n", rawBeanType)
            .addJavadoc("The meta class is responsible for<br/>\n").addJavadoc("<ul>\n")
            .addJavadoc("   <li>determining runtime consistency levels (read/write,serial)<li/>\n");

    if (entityType == EntityType.TABLE) {
        builder.addJavadoc("   <li>determining runtime insert strategy<li/>\n");
    }

    builder.addJavadoc("   <li>trigger event interceptors (if any)<li/>\n")
            .addJavadoc("   <li>map a $T back to an instance of $T<li/>\n", ClassName.get(Row.class),
                    rawBeanType)
            .addJavadoc(
                    "   <li>determine runtime keyspace name using static annotations and runtime SchemaNameProvider (if any)<li/>\n")
            .addJavadoc(
                    "   <li>determine runtime table name using static annotations and runtime SchemaNameProvider (if any)<li/>\n")
            .addJavadoc("   <li>generate schema during bootstrap<li/>\n")
            .addJavadoc("   <li>validate schema during bootstrap<li/>\n")
            .addJavadoc(
                    "   <li>expose all property meta classes for encoding/decoding purpose on unitary columns<li/>\n")
            .addJavadoc("<ul/>\n");

    builder.addAnnotation(ACHILLES_META_ANNOT).addModifiers(Modifier.PUBLIC, Modifier.FINAL)
            .addMethod(buildEntityClass(rawClassTypeName))
            .addMethod(buildDerivedTableName(elm, globalParsingContext.namingStrategy))
            .addMethod(buildFieldNameToCqlColumn(fieldMetaSignatures))
            .addMethod(buildGetStaticReadConsistency(consistency))
            .addMethod(buildGetStaticNamingStrategy(strategy))
            .addMethod(buildPartitionKeys(fieldMetaSignatures, rawBeanType))
            .addMethod(buildClusteringColumns(fieldMetaSignatures, rawBeanType))
            .addMethod(buildNormalColumns(fieldMetaSignatures, rawBeanType))
            .addMethod(buildComputedColumns(fieldMetaSignatures, rawBeanType));

    if (entityType == EntityType.TABLE) {
        builder.superclass(genericType(ABSTRACT_ENTITY_PROPERTY, rawBeanType))
                .addMethod(buildIsCounterTable(isCounter))
                .addMethod(
                        buildStaticKeyspace(aptUtils.getAnnotationOnClass(elm, Table.class).get().keyspace()))
                .addMethod(buildStaticTableOrViewName(
                        aptUtils.getAnnotationOnClass(elm, Table.class).get().table()))
                .addMethod(buildGetStaticWriteConsistency(consistency))
                .addMethod(buildGetStaticSerialConsistency(consistency)).addMethod(buildGetStaticTTL(ttl))
                .addMethod(buildGetStaticInsertStrategy(strategy))
                .addMethod(buildStaticColumns(fieldMetaSignatures, rawBeanType))
                .addMethod(buildCounterColumns(fieldMetaSignatures, rawBeanType));
    } else if (entityType == EntityType.VIEW) {
        builder.superclass(genericType(ABSTRACT_VIEW_PROPERTY, rawBeanType))
                .addMethod(buildStaticKeyspace(
                        aptUtils.getAnnotationOnClass(elm, MaterializedView.class).get().keyspace()))
                .addMethod(buildStaticTableOrViewName(
                        aptUtils.getAnnotationOnClass(elm, MaterializedView.class).get().view()))
                .addMethod(buildGetBaseEntityClass(viewBaseClass.get()));
    }

    for (FieldMetaSignature x : fieldMetaSignatures) {
        builder.addField(x.buildPropertyAsField());
    }

    // Build public static final xxx_AchillesMeta.ColumnsForFunctions COLUMNS = new xxx_AchillesMeta.ColumnsForFunctions();
    builder.addType(
            EntityMetaColumnsForFunctionsCodeGen.createColumnsClassForFunctionParam(fieldMetaSignatures))
            .addField(buildColumnsField(className));

    return new EntityMetaSignature(entityType, builder.build(), elm.getSimpleName().toString(), typeName,
            rawBeanType, viewBaseClass, fieldMetaSignatures);
}

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;
                }/*  w w  w.j a va  2 s  . co 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;
}