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

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

Introduction

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

Prototype

Name getQualifiedName();

Source Link

Document

Returns the fully qualified name of this type element.

Usage

From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionsProcessor.java

protected void processFormDefinition(TypeElement formElement) throws Exception {
    final Messager messager = processingEnv.getMessager();

    messager.printMessage(Diagnostic.Kind.NOTE,
            "Discovered FormDefintion class [" + formElement.getSimpleName() + "]");

    boolean checkInheritance = false;

    FormDefinition defintion = formElement.getAnnotation(FormDefinition.class);

    checkInheritance = defintion.allowInheritance();

    List<Map<String, String>> formElements = new ArrayList<>();

    if (checkInheritance) {
        TypeElement parent = getParent(formElement);
        formElements.addAll(extractParentFormFields(parent, defintion.policy(), defintion.i18n()));
    }// w w  w  .ja va 2s . co m

    formElements.addAll(extracFormFields(formElement, defintion.policy(), defintion.i18n()));

    FormGenerationUtils.sort(defintion.startElement(), formElements);

    messager.printMessage(Diagnostic.Kind.NOTE, "Discovered " + formElements.size() + " elements for form ["
            + formElement.getQualifiedName().toString() + "]");

    String modelClassName = formElement.getQualifiedName().toString();
    String builderClassName = fixClassName(formElement.getQualifiedName().toString()) + "FormBuilder";

    Map<String, Object> templateContext = new HashMap<>();
    templateContext.put("modelClass", modelClassName);
    templateContext.put("builderClassName", builderClassName);
    templateContext.put("startElement", defintion.startElement());

    templateContext.put("i18n_bundle",
            StringUtils.isEmpty(defintion.i18n().bundle()) ? formElement.asType().toString()
                    : defintion.i18n().bundle());

    Column[] columns = defintion.layout().value();

    List<String> layoutColumns = new ArrayList<>();
    if (columns.length == 0) {
        layoutColumns.add(ColSpan.SPAN_12.getName());
    } else {
        for (Column column : columns) {
            layoutColumns.add(column.value().getName());
        }
    }

    templateContext.put("layout_columns", layoutColumns);

    templateContext.put("elements", formElements);

    StringBuffer builder = writeTemplate("templates/FormDefinitionSettingsBuilder.ftl", templateContext);

    Map<String, String> form = new HashMap<>();

    form.put("package", ((PackageElement) formElement.getEnclosingElement()).getQualifiedName().toString());
    form.put("modelClass", modelClassName);
    form.put("builderClass", builderClassName);
    form.put("builderCode", builder.toString());

    context.getForms().add(form);
}

From source file:org.androidannotations.helper.ValidatorHelper.java

public void applicationRegistered(Element element, AndroidManifest manifest, IsValid valid) {

    if (manifest.isLibraryProject()) {
        return;/*from  w  ww .  ja  v  a 2  s  .  c  o m*/
    }

    String applicationClassName = manifest.getApplicationClassName();
    if (applicationClassName != null) {

        TypeElement typeElement = (TypeElement) element;

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

        if (!typeElement.getModifiers().contains(Modifier.ABSTRACT)
                && !applicationClassName.equals(generatedComponentQualifiedName)) {
            if (applicationClassName.equals(componentQualifiedName)) {
                valid.invalidate();
                annotationHelper.printAnnotationError(element,
                        "The AndroidManifest.xml file contains the original component, and not the AndroidAnnotations generated component. Please register "
                                + generatedComponentQualifiedName + " instead of " + componentQualifiedName);
            } else {
                annotationHelper.printAnnotationWarning(element,
                        "The component " + generatedComponentQualifiedName
                                + " is not registered in the AndroidManifest.xml file.");
            }
        }
    } else {
        valid.invalidate();
        annotationHelper.printAnnotationError(element,
                "No application class registered in the AndroidManifest.xml");
    }

}

From source file:ca.sqlpower.object.annotation.SPAnnotationProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    for (TypeElement el : annotations) {
        if (!this.annotations.contains(el.getQualifiedName().toString())) {
            return false;
        }/*  w ww  .  ja  va2s  .  co m*/
    }
    Map<Class<? extends SPObject>, SPClassVisitor> visitors = new HashMap<Class<? extends SPObject>, SPClassVisitor>();
    for (Element typeDecl : roundEnv.getElementsAnnotatedWith(Persistable.class)) {
        SPClassVisitor visitor = new SPClassVisitor(typeDecl);
        typeDecl.accept(visitor, null);
        if (visitor.isValid() && visitor.getVisitedClass() != null) {
            visitors.put(visitor.getVisitedClass(), visitor);
        }
    }

    // This block checks if each of the classes has super classes that
    // contain persistable properties. If so, they should inherit those
    // persistable properties. Any additional packages should be
    // imported as well.
    for (Entry<Class<? extends SPObject>, SPClassVisitor> e : visitors.entrySet()) {
        Class<? extends SPObject> superClass = e.getKey();
        SPClassVisitor visitor = e.getValue();

        Multimap<String, String> mutatorImports = HashMultimap.create(visitor.getMutatorImports());
        Map<String, Class<?>> propertiesToAccess = new HashMap<String, Class<?>>(
                visitor.getPropertiesToAccess());
        Multimap<String, String> accessorAdditionalInfo = LinkedHashMultimap
                .create(visitor.getAccessorAdditionalInfo());
        Map<String, Class<?>> propertiesToMutate = new HashMap<String, Class<?>>(
                visitor.getPropertiesToMutate());
        Multimap<String, MutatorParameterObject> mutatorExtraParameters = LinkedHashMultimap
                .create(visitor.getMutatorExtraParameters());
        Multimap<String, Class<? extends Exception>> mutatorThrownTypes = HashMultimap
                .create(visitor.getMutatorThrownTypes());
        Set<String> propertiesToPersistOnlyIfNonNull = new HashSet<String>(
                visitor.getPropertiesToPersistOnlyIfNonNull());

        importedClassNames.clear();

        // Generate the persister helper file if the SPObject class is not abstract.
        if (!Modifier.isAbstract(visitor.getVisitedClass().getModifiers())) {
            generatePersisterHelperFile(superClass, visitor.getConstructorImports(),
                    visitor.getConstructorParameters(), propertiesToAccess, accessorAdditionalInfo,
                    mutatorImports, propertiesToMutate, mutatorExtraParameters, mutatorThrownTypes,
                    propertiesToPersistOnlyIfNonNull);
        } else {
            generateAbstractPersisterHelperFile(superClass, visitor.getConstructorImports(), propertiesToAccess,
                    accessorAdditionalInfo, mutatorImports, propertiesToMutate, mutatorExtraParameters,
                    mutatorThrownTypes, propertiesToPersistOnlyIfNonNull);
        }
    }
    return true;
}

From source file:org.androidannotations.helper.ValidatorHelper.java

public void isSharedPreference(Element element, AnnotationElements validatedElements, IsValid valid) {

    TypeMirror type = element.asType();

    /*//from   w w  w  . j  a  v a 2 s .  c  o m
     * The type is not available yet because it has just been generated
     */
    if (type instanceof ErrorType || type.getKind() == TypeKind.ERROR) {
        String elementTypeName = type.toString();

        boolean sharedPrefValidatedInRound = false;
        if (elementTypeName.endsWith(GENERATION_SUFFIX)) {
            String prefTypeName = elementTypeName.substring(0,
                    elementTypeName.length() - GENERATION_SUFFIX.length());
            prefTypeName = prefTypeName.replace("_.", ".");

            Set<? extends Element> sharedPrefElements = validatedElements
                    .getRootAnnotatedElements(SharedPref.class.getName());

            for (Element sharedPrefElement : sharedPrefElements) {
                TypeElement sharedPrefTypeElement = (TypeElement) sharedPrefElement;

                String sharedPrefQualifiedName = sharedPrefTypeElement.getQualifiedName().toString();

                if (sharedPrefQualifiedName.endsWith(prefTypeName)) {
                    sharedPrefValidatedInRound = true;
                    break;
                }
            }
        }

        if (!sharedPrefValidatedInRound) {
            valid.invalidate();
        }

    } else {
        extendsType(element, SharedPreferencesHelper.class.getName(), valid);
    }

}

From source file:info.archinnov.achilles.internals.parser.FunctionParser.java

public static List<FunctionSignature> parseFunctionRegistryAndValidateTypes(AptUtils aptUtils, TypeElement elm,
        GlobalParsingContext context) {/* ww  w.  java 2 s . co  m*/
    final List<ExecutableElement> methods = ElementFilter.methodsIn(elm.getEnclosedElements());
    final Optional<String> keyspace = AnnotationTree.findKeyspaceForFunctionRegistry(aptUtils, elm);
    final FunctionParamParser paramParser = new FunctionParamParser(aptUtils);

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

    //Not allow to declare function in system keyspaces
    if (keyspace.isPresent()) {
        final String keyspaceName = keyspace.get();
        aptUtils.validateFalse(
                FORBIDDEN_KEYSPACES.contains(keyspaceName)
                        || FORBIDDEN_KEYSPACES.contains(keyspaceName.toLowerCase()),
                "The provided keyspace '%s' on function registry class '%s' is forbidden because it is a system keyspace",
                keyspaceName, parentType);
    }

    aptUtils.validateFalse(keyspace.isPresent() && isBlank(keyspace.get()),
            "The declared keyspace for function registry '%s' should not be blank",
            elm.getSimpleName().toString());

    return methods.stream().map(method -> {
        final String methodName = method.getSimpleName().toString();
        final List<AnnotationTree> annotationTrees = AnnotationTree.buildFromMethodForParam(aptUtils, method);
        final List<? extends VariableElement> parameters = method.getParameters();
        final List<FunctionParamSignature> parameterSignatures = new ArrayList<>(parameters.size());
        for (int i = 0; i < parameters.size(); i++) {
            final VariableElement parameter = parameters.get(i);
            context.nestedTypesStrategy.validate(aptUtils, annotationTrees.get(i), method.toString(),
                    parentType);
            final FunctionParamSignature functionParamSignature = paramParser.parseParam(context,
                    annotationTrees.get(i), parentType, methodName, parameter.getSimpleName().toString());
            parameterSignatures.add(functionParamSignature);
        }

        //Validate return type
        final TypeMirror returnType = method.getReturnType();
        aptUtils.validateFalse(returnType.getKind() == TypeKind.VOID,
                "The return type for the method '%s' on class '%s' should not be VOID", method.toString(),
                elm.getSimpleName().toString());

        aptUtils.validateFalse(returnType.getKind().isPrimitive(),
                "Due to internal JDK API limitations, UDF/UDA return types cannot be primitive. "
                        + "Use their Object counterpart instead for method '%s' " + "in function registry '%s'",
                method.toString(), elm.getQualifiedName());

        final FunctionParamSignature returnTypeSignature = paramParser.parseParam(context,
                AnnotationTree.buildFromMethodForReturnType(aptUtils, method), parentType, methodName,
                "returnType");

        // Validate NOT system function comparing only name lowercase
        aptUtils.validateFalse(SYSTEM_FUNCTIONS_NAME.contains(methodName.toLowerCase()),
                "The name of the function '%s' in class '%s' is reserved for system functions", method,
                parentType);

        return new FunctionSignature(keyspace, parentType, methodName, returnTypeSignature,
                parameterSignatures);
    }).collect(toList());
}

From source file:me.oriley.shiv.ShivProcessor.java

private void collectBindings(@NonNull RoundEnvironment env, @NonNull Map<TypeElement, BindingManager> bindings,
        @NonNull Class<? extends Annotation> annotation) throws ShivException {
    for (Element e : env.getElementsAnnotatedWith(annotation)) {
        if (e.getKind() != ElementKind.FIELD) {
            throw new ShivException(
                    e.getSimpleName() + " is annotated with @" + annotation.getName() + " but is not a field");
        }/*from   ww  w .  j  a  v  a  2  s  .com*/

        TypeMirror fieldType = e.asType();
        if (isPrivate(e)) {
            throw new ShivException("Field must not be private: " + e.getSimpleName());
        } else if (isStatic(e)) {
            throw new ShivException("Field must not be static: " + e.getSimpleName());
        }

        final TypeElement type = findEnclosingElement(e);
        // class should exist
        if (type == null) {
            throw new ShivException("Could not find a class for " + e.getSimpleName());
        }
        // and it should be public
        if (isPrivate(type)) {
            throw new ShivException("Class is private: " + type);
        }
        // as well as all parent classes
        TypeElement parentType = findEnclosingElement(type);
        while (parentType != null) {
            if (isPrivate(parentType)) {
                throw new ShivException("Parent class is private: " + parentType);
            }
            parentType = findEnclosingElement(parentType);
        }

        if (annotation == BindView.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)
                    && !isSubtypeOfType(type, ViewGroup.class)) {
                throw new ShivException("Invalid view binding class: " + type.getSimpleName());
            } else if (!isSubtypeOfType(fieldType, View.class)) {
                throw new ShivException("Field must inherit from View type: " + e.getSimpleName());
            }
        } else if (annotation == BindExtra.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)) {
                throw new ShivException("Invalid extra binding class: " + type.getSimpleName());
            } else if (!isValidBundleEntry(fieldType)) {
                throw new ShivException("Extra field not suitable for bundle: " + e.getSimpleName());
            }
        } else if (annotation == BindPreference.class) {
            if (isSubtypeOfType(type, PreferenceFragment.class)
                    || isSubtypeOfType(type, PreferenceActivity.class)) {
                if (!isSubtypeOfType(fieldType, Preference.class)) {
                    throw new ShivException("Preferences in " + type.getQualifiedName() + " must inherit from "
                            + Preference.class + ": " + e.getSimpleName());
                }
            } else if (isSubtypeOfType(type, PreferenceFragmentCompat.class)) {
                if (!isSubtypeOfType(fieldType, android.support.v7.preference.Preference.class)) {
                    throw new ShivException("Preferences in " + PreferenceFragmentCompat.class
                            + " must inherit from " + android.support.v7.preference.Preference.class + ": "
                            + e.getSimpleName());
                }
            } else {
                throw new ShivException("Invalid preference binding class: " + type.getSimpleName());
            }
        } else if (annotation == BindInstance.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)) {
                throw new ShivException("Invalid instance binding class: " + type.getSimpleName());
            } else if (!isValidBundleEntry(fieldType)) {
                throw new ShivException("Instance field not suitable for bundle: " + e.getSimpleName());
            }
        } else if (annotation == BindNonConfigurationInstance.class) {
            if (!isSubtypeOfType(type, Activity.class)) {
                throw new ShivException(
                        "Invalid non-configuration instance binding class: " + type.getSimpleName());
            }
        } else if (annotation == BindService.class) {
            if (!isSubtypeOfType(type, Activity.class) && !isSubtypeOfType(type, Fragment.class)
                    && !isSubtypeOfType(type, android.support.v4.app.Fragment.class)
                    && !isSubtypeOfType(type, View.class)) {
                throw new ShivException("Invalid service binding class: " + type.getSimpleName());
            }
        } else {
            throw new ShivException("Unrecognised annotation: " + annotation);
        }

        BindingManager manager = bindings.get(type);
        if (manager == null) {
            manager = new BindingManager(this, type);
            bindings.put(type, manager);
        }

        manager.addBinding(annotation, e);
    }
}

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  w ww  .  j  a v  a 2  s . c om

                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: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  w w  w .j  av a  2  s.c  om*/

        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.kie.workbench.common.forms.adf.processors.FormDefinitionsProcessor.java

private List<Map<String, String>> extracFormFields(TypeElement type, FieldPolicy policy,
        I18nSettings i18nSettings) throws Exception {

    final Elements elementUtils = processingEnv.getElementUtils();

    Collection<FieldInfo> fieldInfos = extractFieldInfos(type, fieldElement -> {
        if (policy.equals(FieldPolicy.ALL)) {
            AnnotationMirror annotation = GeneratorUtils.getAnnotation(elementUtils, fieldElement,
                    SkipFormField.class.getName());
            if (annotation != null) {
                return false;
            }// w  w  w .  jav  a2 s.c  om
        } else {
            AnnotationMirror annotation = GeneratorUtils.getAnnotation(elementUtils, fieldElement,
                    FormField.class.getName());
            if (annotation == null) {
                return false;
            }
        }
        return true;
    });

    List<Map<String, String>> elementsSettings = new ArrayList<>();

    for (FieldInfo fieldInfo : fieldInfos) {

        if (fieldInfo.getter != null && fieldInfo.setter != null) {

            String fieldName = fieldInfo.fieldElement.getSimpleName().toString();

            String fieldLabel = fieldName;
            String binding = fieldName;

            String methodName = "getFormElement_" + fieldName;

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

            boolean isList = false;

            org.kie.workbench.common.forms.model.TypeKind typeKind = org.kie.workbench.common.forms.model.TypeKind.BASE;

            boolean overrideI18nLabel = false;

            TypeMirror finalType = fieldInfo.fieldElement.asType();

            String fieldModifier = "";

            if (finalType instanceof DeclaredType) {
                Element finalTypeElement = processingEnv.getTypeUtils().asElement(finalType);

                if (finalTypeElement.getKind().equals(ElementKind.CLASS)) {
                    FieldDefinition fieldDefinitionAnnotation = finalTypeElement
                            .getAnnotation(FieldDefinition.class);
                    if (fieldDefinitionAnnotation != null) {

                        // Override the using the i18n mechanism
                        if (fieldDefinitionAnnotation.labelMode().equals(LabelMode.OVERRIDE_I18N_KEY)) {
                            Collection<FieldInfo> labelInfos = extractFieldInfos((TypeElement) finalTypeElement,
                                    fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null);

                            if (labelInfos == null || labelInfos.size() != 1) {
                                throw new Exception("Problem processing FieldDefinition [" + finalType
                                        + "]: it should have one field marked as @FieldLabel");
                            }

                            FieldInfo labelInfo = labelInfos.iterator().next();

                            fieldLabel = finalType.toString() + i18nSettings.separator()
                                    + labelInfo.fieldElement.getSimpleName();
                        }

                        Collection<FieldInfo> fieldValue = extractFieldInfos((TypeElement) finalTypeElement,
                                fieldElement -> fieldElement.getAnnotation(FieldValue.class) != null);

                        if (fieldValue == null || fieldValue.size() != 1) {
                            throw new Exception("Problem processing FieldDefinition [" + finalType
                                    + "]: it should have one field marked as @FieldValue");
                        }
                        FieldInfo valueInfo = fieldValue.iterator().next();

                        binding += "." + valueInfo.getFieldElement().getSimpleName();

                        fieldModifier = fixClassName(finalType.toString()) + "_FieldStatusModifier";

                        finalType = valueInfo.getFieldElement().asType();

                        overrideI18nLabel = !fieldDefinitionAnnotation.labelMode()
                                .equals(LabelMode.DONT_OVERRIDE);
                    } else {
                        FormDefinition formDefinitionAnnotation = finalTypeElement
                                .getAnnotation(FormDefinition.class);

                        if (formDefinitionAnnotation != null) {
                            Collection<FieldInfo> labelInfos = extractFieldInfos((TypeElement) finalTypeElement,
                                    fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null);

                            if (labelInfos != null & labelInfos.size() == 1) {
                                FieldInfo labelInfo = labelInfos.iterator().next();
                                fieldLabel = finalType.toString() + i18nSettings.separator()
                                        + labelInfo.fieldElement.getSimpleName();
                                overrideI18nLabel = true;
                            }
                            typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT;
                        }
                    }
                }

                DeclaredType fieldType = (DeclaredType) finalType;

                if (processingEnv.getTypeUtils().isAssignable(fieldType.asElement().asType(), listType)) {
                    if (fieldType.getTypeArguments().size() != 1) {
                        throw new IllegalArgumentException("Impossible to generate a field for type "
                                + fieldType.toString() + ". Type should have one and only one Type arguments.");
                    }
                    isList = true;
                    finalType = fieldType.getTypeArguments().get(0);
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT;
                } else if (elementUtils.getTypeElement(finalType.toString()).getSuperclass().toString()
                        .startsWith("java.lang.Enum")) {
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.ENUM;
                }
            }

            elementContext.put("formModel", type.getQualifiedName().toString());
            elementContext.put("methodName", methodName);
            elementContext.put("fieldName", fieldName);
            elementContext.put("binding", binding);
            elementContext.put("type", typeKind.toString());
            elementContext.put("className", finalType.toString());
            elementContext.put("isList", String.valueOf(isList));
            elementContext.put("fieldModifier", fieldModifier);

            Map<String, String> params = new HashMap<>();
            elementContext.put("params", params);

            String afterElement = "";
            FormField settings = fieldInfo.fieldElement.getAnnotation(FormField.class);

            if (settings != null) {
                String typeName;
                try {
                    typeName = settings.type().getName();
                } catch (MirroredTypeException exception) {
                    typeName = exception.getTypeMirror().toString();
                }
                if (StringUtils.isEmpty(typeName)) {
                    typeName = FieldType.class.getName();
                }

                afterElement = settings.afterElement();

                elementContext.put("preferredType", typeName);
                if (!overrideI18nLabel) {
                    fieldLabel = settings.labelKey();
                }
                elementContext.put("required", Boolean.valueOf(settings.required()).toString());
                elementContext.put("readOnly", Boolean.valueOf(settings.readonly()).toString());

                for (FieldParam fieldParam : settings.settings()) {
                    params.put(fieldParam.name(), fieldParam.value());
                }

                elementContext.put("wrap", Boolean.valueOf(settings.layoutSettings().wrap()).toString());
                elementContext.put("horizontalSpan",
                        String.valueOf(settings.layoutSettings().horizontalSpan()));
                elementContext.put("verticalSpan", String.valueOf(settings.layoutSettings().verticalSpan()));
            } else {
                elementContext.put("preferredType", FieldType.class.getName());
                elementContext.put("required", Boolean.FALSE.toString());
                elementContext.put("readOnly", Boolean.FALSE.toString());
                elementContext.put("wrap", Boolean.FALSE.toString());
                elementContext.put("horizontalSpan", "1");
                elementContext.put("verticalSpan", "1");
            }

            if (!overrideI18nLabel) {
                if (!StringUtils.isEmpty(i18nSettings.keyPreffix())) {
                    fieldLabel = i18nSettings.keyPreffix() + i18nSettings.separator() + fieldLabel;
                }
            }

            elementContext.put("labelKey", fieldLabel);
            elementContext.put("afterElement", afterElement);

            extractFieldExtraSettings(elementContext, fieldInfo.fieldElement);

            StringBuffer methodCode = writeTemplate("templates/FieldElement.ftl", elementContext);

            Map<String, String> fieldSettings = new HashMap<>();
            fieldSettings.put("elementName", fieldName);
            fieldSettings.put("afterElement", afterElement);
            fieldSettings.put("methodName", methodName);
            fieldSettings.put("method", methodCode.toString());

            elementsSettings.add(fieldSettings);
        }
    }
    return elementsSettings;
}