Example usage for javax.lang.model.type DeclaredType toString

List of usage examples for javax.lang.model.type DeclaredType toString

Introduction

In this page you can find the example usage for javax.lang.model.type DeclaredType toString.

Prototype

String toString();

Source Link

Document

Returns an informative string representation of this type.

Usage

From source file:com.dspot.declex.action.Actions.java

private void createInformationForAction(String actionHolder, boolean isExternal) {

    TypeElement typeElement = env.getProcessingEnvironment().getElementUtils().getTypeElement(actionHolder);
    TypeElement generatedHolder = env.getProcessingEnvironment().getElementUtils()
            .getTypeElement(TypeUtils.getGeneratedClassName(typeElement, env));

    ActionFor actionForAnnotation = null;
    try {//from  w w  w. jav a  2  s  .c  om
        actionForAnnotation = typeElement.getAnnotation(ActionFor.class);
    } catch (Exception e) {
        LOGGER.error("An error occurred processing the @ActionFor annotation", e);
    }

    if (actionForAnnotation != null) {

        for (String name : actionForAnnotation.value()) {

            ACTION_HOLDER_ELEMENT_FOR_ACTION.put("$" + name, typeElement);

            //Get model info
            final ActionInfo actionInfo = new ActionInfo(actionHolder);
            actionInfo.isGlobal = actionForAnnotation.global();
            actionInfo.isTimeConsuming = actionForAnnotation.timeConsuming();

            if (isExternal) {
                actionInfo.generated = false;
            }

            //This will work only for cached classes
            if (generatedHolder != null) {
                for (Element elem : generatedHolder.getEnclosedElements()) {
                    if (elem instanceof ExecutableElement) {
                        final String elemName = elem.getSimpleName().toString();
                        final List<? extends VariableElement> params = ((ExecutableElement) elem)
                                .getParameters();

                        if (elemName.equals("onViewChanged") && params.size() == 1 && params.get(0).asType()
                                .toString().equals(HasViews.class.getCanonicalName())) {
                            actionInfo.handleViewChanges = true;
                            break;
                        }
                    }
                }
            }

            addAction(name, actionHolder, actionInfo, false);

            String javaDoc = env.getProcessingEnvironment().getElementUtils().getDocComment(typeElement);
            actionInfo.setReferences(javaDoc);

            List<DeclaredType> processors = annotationHelper.extractAnnotationClassArrayParameter(typeElement,
                    ActionFor.class.getCanonicalName(), "processors");

            //Load processors
            if (processors != null) {
                for (DeclaredType processor : processors) {

                    Class<ActionProcessor> processorClass = null;

                    try {

                        ClassLoader loader = classLoaderForProcessor.get(processor.toString());
                        if (loader != null) {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(), true,
                                    loader);
                        } else {
                            processorClass = (Class<ActionProcessor>) Class.forName(processor.toString());
                        }

                    } catch (ClassNotFoundException e) {

                        Element element = env.getProcessingEnvironment().getElementUtils()
                                .getTypeElement(processor.toString());
                        if (element == null) {
                            LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded",
                                    typeElement);
                        } else {

                            try {
                                //Get the file from which the class was loaded
                                java.lang.reflect.Field field = element.getClass().getField("classfile");
                                field.setAccessible(true);
                                JavaFileObject classfile = (JavaFileObject) field.get(element);

                                String jarUrl = classfile.toUri().toURL().toString();
                                jarUrl = jarUrl.substring(0, jarUrl.lastIndexOf('!') + 2);

                                //Create or use a previous created class loader for the given file
                                ClassLoader loader;
                                if (classLoaderForProcessor.containsKey(jarUrl)) {
                                    loader = classLoaderForProcessor.get(jarUrl);
                                } else {
                                    loader = new URLClassLoader(new URL[] { new URL(jarUrl) },
                                            Actions.class.getClassLoader());
                                    classLoaderForProcessor.put(processor.toString(), loader);
                                    classLoaderForProcessor.put(jarUrl, loader);
                                }

                                processorClass = (Class<ActionProcessor>) Class.forName(processor.toString(),
                                        true, loader);

                            } catch (Throwable e1) {
                                LOGGER.error("Processor \"" + processor.toString() + "\" couldn't be loaded: "
                                        + e1.getMessage(), typeElement);
                            }

                        }

                    } catch (ClassCastException e) {
                        LOGGER.error("Processor \"" + processor.toString() + "\" is not an Action Processor",
                                typeElement);
                    }

                    if (processorClass != null) {
                        try {
                            actionInfo.processors.add(processorClass.newInstance());
                        } catch (Throwable e) {
                            LOGGER.info("Processor \"" + processor.toString() + "\" couldn't be instantiated",
                                    typeElement);
                        }
                    }

                }
            }

            createInformationForMethods(typeElement, actionInfo);
        }

    }

}

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

private void checkConstructor(TypeElement el, GeneratedParamsClass inf) {
    Elements elements = processingEnv.getElementUtils();
    TypeElement pageParamsType = elements
            .getTypeElement("org.apache.wicket.request.mapper.parameter.PageParameters");
    TypeElement customParamsType = elements.getTypeElement(inf.qualifiedName());
    boolean found = false;
    boolean foundArgument = false;
    ExecutableElement con = null;
    outer: for (Element sub : el.getEnclosedElements()) {
        switch (sub.getKind()) {
        case CONSTRUCTOR:
            for (AnnotationMirror mir : sub.getAnnotationMirrors()) {
                DeclaredType type = mir.getAnnotationType();
                switch (type.toString()) {
                case "javax.inject.Inject":
                case "com.google.inject.Inject":
                    ExecutableElement constructor = (ExecutableElement) sub;
                    con = constructor;/*from   ww  w  .  ja v a  2 s  .co  m*/
                    for (VariableElement va : constructor.getParameters()) {
                        TypeMirror varType = va.asType();
                        if (pageParamsType != null && varType.toString().equals(pageParamsType.toString())) {
                            foundArgument = true;
                            break;
                        }
                        if (customParamsType != null
                                && varType.toString().equals(customParamsType.toString())) {
                            foundArgument = true;
                            break;
                        } else if (customParamsType == null && inf.qualifiedName().equals(varType.toString())) { //first compilation - type not generated yet
                            foundArgument = true;
                            break;
                        }
                    }
                    found = true;
                    break outer;
                default:
                    //do nothing
                }
            }
        }
    }
    if (!found) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Usually a constructor "
                + "annotated with @Inject that takes a " + inf.className + " is desired", el);
    } else if (found && !foundArgument) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING,
                "Usually a constructor taking " + "an argument of " + inf.className + " is desired", con);
    }
}

From source file:com.googlecode.androidannotations.helper.ValidatorHelper.java

public void returnTypeNotGenericUnlessResponseEntity(ExecutableElement element, IsValid valid) {
    TypeMirror returnType = element.getReturnType();
    TypeKind returnKind = returnType.getKind();
    if (returnKind == TypeKind.DECLARED) {
        DeclaredType declaredReturnType = (DeclaredType) returnType;
        if (!declaredReturnType.toString().startsWith("org.springframework.http.ResponseEntity<")
                && declaredReturnType.getTypeArguments().size() > 0) {
            valid.invalidate();/*from   w  w w  .  j a  v  a  2  s .  com*/
            annotationHelper.printAnnotationError(element,
                    "%s annotated methods cannot return parameterized types, except for ResponseEntity");
        }
    }
}

From source file:io.github.jeddict.jpa.spec.extend.MultiRelationAttribute.java

@Override
@Deprecated//from  w w w .  jav a2  s.c  o  m
public void loadAttribute(EntityMappings entityMappings, Element element, VariableElement variableElement,
        ExecutableElement getterElement, AnnotationMirror relationAnnotationMirror) {
    super.loadAttribute(entityMappings, element, variableElement, getterElement, relationAnnotationMirror);

    this.mappedBy = (String) JavaSourceParserUtil.findAnnotationValue(relationAnnotationMirror, "mappedBy");
    this.orderBy = OrderBy.load(element, variableElement);
    this.orderColumn = OrderColumn.load(element, variableElement);
    this.collectionType = ((DeclaredType) variableElement.asType()).asElement().toString();
    Class collectionTypeClass = null;
    try {
        collectionTypeClass = Class.forName(this.collectionType);
    } catch (ClassNotFoundException ex) {
    }
    boolean mapKeyExist = collectionTypeClass != null && Map.class.isAssignableFrom(collectionTypeClass);

    DeclaredType declaredType = (DeclaredType) JavaSourceParserUtil
            .findAnnotationValue(relationAnnotationMirror, "targetEntity");
    if (declaredType == null) {
        if (variableElement.asType() instanceof ErrorType) { //variable => "<any>"
            throw new TypeNotPresentException(this.name + " type not found", null);
        }
        declaredType = (DeclaredType) ((DeclaredType) variableElement.asType()).getTypeArguments()
                .get(mapKeyExist ? 1 : 0);
    }
    String fqn = declaredType.asElement().asType().toString();
    this.targetEntityPackage = getPackageName(fqn);
    this.targetEntity = getSimpleClassName(fqn);

    if (mapKeyExist) {
        this.mapKeyConvert = Convert.load(element, mapKeyExist, true);
        this.mapKey = new MapKey().load(element, null);
        this.mapKeyType = this.mapKey != null ? MapKeyType.EXT : MapKeyType.NEW;

        DeclaredType keyDeclaredType = MapKeyClass.getDeclaredType(element);
        if (keyDeclaredType == null) {
            keyDeclaredType = (DeclaredType) ((DeclaredType) variableElement.asType()).getTypeArguments()
                    .get(0);
        }
        if (isEmbeddable(keyDeclaredType.asElement())) {
            loadEmbeddableClass(entityMappings, element, variableElement, keyDeclaredType);
            this.mapKeyAttributeType = getSimpleClassName(keyDeclaredType.toString());
        } else if (isEntity(keyDeclaredType.asElement())) {
            loadEntity(entityMappings, element, variableElement, keyDeclaredType);
            this.mapKeyAttributeType = getSimpleClassName(keyDeclaredType.toString());
        } else {
            this.mapKeyAttributeType = keyDeclaredType.toString();
        }

        this.mapKeyColumn = new Column().load(element,
                JavaSourceParserUtil.findAnnotation(element, MAP_KEY_COLUMN_FQN));
        this.mapKeyTemporal = TemporalType.load(element,
                JavaSourceParserUtil.findAnnotation(element, MAP_KEY_TEMPORAL_FQN));
        this.mapKeyEnumerated = EnumType.load(element,
                JavaSourceParserUtil.findAnnotation(element, MAP_KEY_ENUMERATED_FQN));

        AnnotationMirror joinColumnsAnnotationMirror = JavaSourceParserUtil.findAnnotation(element,
                MAP_KEY_JOIN_COLUMNS_FQN);
        if (joinColumnsAnnotationMirror != null) {
            List joinColumnsAnnot = (List) JavaSourceParserUtil.findAnnotationValue(joinColumnsAnnotationMirror,
                    "value");
            if (joinColumnsAnnot != null) {
                for (Object joinColumnObj : joinColumnsAnnot) {
                    this.getMapKeyJoinColumn()
                            .add(new JoinColumn().load(element, (AnnotationMirror) joinColumnObj));
                }
            }
        } else {
            AnnotationMirror joinColumnAnnotationMirror = JavaSourceParserUtil.findAnnotation(element,
                    MAP_KEY_JOIN_COLUMN_FQN);
            if (joinColumnAnnotationMirror != null) {
                this.getMapKeyJoinColumn().add(new JoinColumn().load(element, joinColumnAnnotationMirror));
            }
        }

        this.mapKeyForeignKey = ForeignKey.load(element, null);
        this.getMapKeyAttributeOverride().addAll(AttributeOverride.load(element));

    }
}

From source file:io.github.jeddict.jpa.spec.extend.Attribute.java

protected void loadAttribute(Element element, VariableElement variableElement,
        ExecutableElement getterElement) {
    this.setId(NBModelerUtil.getAutoGeneratedStringId());
    this.name = variableElement.getSimpleName().toString();
    this.setAnnotation(JavaSourceParserUtil.getNonEEAnnotation(element, AttributeAnnotation.class));
    this.setAttributeConstraints(JavaSourceParserUtil.getBeanValidation(element));

    if (getterElement != null) {
        this.setFunctionalType(
                getterElement.getReturnType().toString().startsWith(Optional.class.getCanonicalName()));
    }//from  ww  w  .j  av a  2  s  .  com

    AnnotationMirror prpertyAnnotationMirror = JavaSourceParserUtil.findAnnotation(element, JSONB_PROPERTY_FQN);
    if (prpertyAnnotationMirror != null) {
        this.jsonbNillable = (Boolean) JavaSourceParserUtil.findAnnotationValue(prpertyAnnotationMirror,
                "nillable");
        this.jsonbProperty = (String) JavaSourceParserUtil.findAnnotationValue(prpertyAnnotationMirror,
                "value");
    }

    this.jsonbDateFormat = JsonbDateFormat.load(element);
    this.jsonbNumberFormat = JsonbNumberFormat.load(element);

    AnnotationMirror typeAdapterAnnotationMirror = JavaSourceParserUtil.findAnnotation(element,
            JSONB_TYPE_ADAPTER_FQN);
    if (typeAdapterAnnotationMirror != null) {
        DeclaredType classType = (DeclaredType) JavaSourceParserUtil
                .findAnnotationValue(typeAdapterAnnotationMirror, "value");
        if (classType != null) {
            this.jsonbTypeAdapter = new ReferenceClass(classType.toString());
        }
    }

    AnnotationMirror typeDeserializerAnnotationMirror = JavaSourceParserUtil.findAnnotation(element,
            JSONB_TYPE_DESERIALIZER_FQN);
    if (typeDeserializerAnnotationMirror != null) {
        DeclaredType classType = (DeclaredType) JavaSourceParserUtil
                .findAnnotationValue(typeDeserializerAnnotationMirror, "value");
        if (classType != null) {
            this.jsonbTypeDeserializer = new ReferenceClass(classType.toString());
        }
    }

    AnnotationMirror typeSerializerAnnotationMirror = JavaSourceParserUtil.findAnnotation(element,
            JSONB_TYPE_SERIALIZER_FQN);
    if (typeSerializerAnnotationMirror != null) {
        DeclaredType classType = (DeclaredType) JavaSourceParserUtil
                .findAnnotationValue(typeSerializerAnnotationMirror, "value");
        if (classType != null) {
            this.jsonbTypeSerializer = new ReferenceClass(classType.toString());
        }
    }
}

From source file:com.googlecode.androidannotations.helper.ValidatorHelper.java

public void extendsOrmLiteDaoWithValidModelParameter(Element element, IsValid valid) {
    TypeMirror elementType = element.asType();

    TypeMirror modelTypeMirror = annotationHelper.extractAnnotationParameter(element, "model");

    TypeElement daoTypeElement = annotationHelper.typeElementFromQualifiedName(CanonicalNameConstants.DAO);
    if (daoTypeElement != null) {

        TypeMirror wildcardType = annotationHelper.getTypeUtils().getWildcardType(null, null);
        DeclaredType daoParameterizedType = annotationHelper.getTypeUtils().getDeclaredType(daoTypeElement,
                modelTypeMirror, wildcardType);

        // Checks that elementType extends Dao<ModelType, ?>
        if (!annotationHelper.isSubtype(elementType, daoParameterizedType)) {
            valid.invalidate();/*from w w w.j  a  v a 2s .  com*/
            annotationHelper.printAnnotationError(element,
                    "%s can only be used on an element that extends " + daoParameterizedType.toString());
        }
    }
}

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

public void extendsListOfView(Element element, IsValid valid) {
    DeclaredType elementType = (DeclaredType) element.asType();
    List<? extends TypeMirror> elementTypeArguments = elementType.getTypeArguments();

    TypeMirror viewType = annotationHelper.typeElementFromQualifiedName(CanonicalNameConstants.VIEW).asType();

    if (!elementType.toString().equals(CanonicalNameConstants.LIST) && elementTypeArguments.size() == 1
            && !annotationHelper.isSubtype(elementTypeArguments.get(0), viewType)) {
        valid.invalidate();//  w ww.j a va 2 s  .c  o  m
        annotationHelper.printAnnotationError(element, "%s can only be used on a " + CanonicalNameConstants.LIST
                + " of elements extending " + CanonicalNameConstants.VIEW);
    }
}

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

public void extendsOrmLiteDao(Element element, IsValid valid, OrmLiteHelper ormLiteHelper) {
    if (!valid.isValid()) {
        // we now that the element is invalid. early exit as the reason
        // could be missing ormlite classes
        return;/*from  w  w w. j  a v a  2 s  .  c  om*/
    }

    TypeMirror elementTypeMirror = element.asType();
    Types typeUtils = annotationHelper.getTypeUtils();

    DeclaredType daoParametrizedType = ormLiteHelper.getDaoParametrizedType();
    DeclaredType runtimeExceptionDaoParametrizedType = ormLiteHelper.getRuntimeExceptionDaoParametrizedType();

    // Checks that elementType extends Dao<?, ?> or
    // RuntimeExceptionDao<?, ?>
    if (!annotationHelper.isSubtype(elementTypeMirror, daoParametrizedType)
            && !annotationHelper.isSubtype(elementTypeMirror, runtimeExceptionDaoParametrizedType)) {
        valid.invalidate();
        annotationHelper.printAnnotationError(element,
                "%s can only be used on an element that extends " + daoParametrizedType.toString() //
                        + " or " + runtimeExceptionDaoParametrizedType.toString());
        return;
    }

    if (annotationHelper.isSubtype(elementTypeMirror, runtimeExceptionDaoParametrizedType) //
            && !typeUtils.isAssignable(ormLiteHelper.getTypedRuntimeExceptionDao(element), elementTypeMirror)) {

        boolean hasConstructor = false;
        Element elementType = typeUtils.asElement(elementTypeMirror);
        DeclaredType daoWithTypedParameters = ormLiteHelper.getTypedDao(element);
        for (ExecutableElement constructor : ElementFilter.constructorsIn(elementType.getEnclosedElements())) {
            List<? extends VariableElement> parameters = constructor.getParameters();
            if (parameters.size() == 1) {
                TypeMirror type = parameters.get(0).asType();
                if (annotationHelper.isSubtype(type, daoWithTypedParameters)) {
                    hasConstructor = true;
                }
            }
        }
        if (!hasConstructor) {
            valid.invalidate();
            annotationHelper.printAnnotationError(element, elementTypeMirror.toString()
                    + " requires a constructor that takes only a " + daoWithTypedParameters.toString());
        }
    }
}

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

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

    final Types typeUtils = context.getProcessingEnvironment().getTypeUtils();

    Collection<FieldInfo> fieldInfos = FormGenerationUtils.extractFieldInfos(type,
            fieldElement -> filter(fieldElement, policy));

    List<FormDefinitionFieldData> fieldSettings = new ArrayList<>();

    for (FieldInfo fieldInfo : fieldInfos) {

        if (fieldInfo.getSetter() != null && fieldInfo.getGetter() != null) {

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

            FormDefinitionFieldData fieldData = new FormDefinitionFieldData(type.getQualifiedName().toString(),
                    fieldName);/*  w  ww.  ja  v  a  2 s.co  m*/

            fieldData.setLabel(fieldName);
            fieldData.setBinding(fieldName);
            fieldData.setMethodName("getFormElement_" + fieldName);

            boolean isList = false;

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

            boolean overrideI18n = false;

            TypeMirror finalType = fieldInfo.getFieldElement().asType();
            TypeElement finalTypeElement = (TypeElement) typeUtils.asElement(finalType);

            String fieldModifier = "";

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

                    // Override the using the i18n mechanism
                    if (fieldDefinitionAnnotation.i18nMode().equals(I18nMode.OVERRIDE_I18N_KEY)) {
                        fieldData.setLabel(finalType.toString() + i18nSettings.separator()
                                + fieldDefinitionAnnotation.labelKeySuffix());
                        Collection<FieldInfo> labelInfos = FormGenerationUtils.extractFieldInfos(
                                finalTypeElement,
                                fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null);

                        if (labelInfos != null && labelInfos.size() == 1) {
                            FieldInfo labelInfo = labelInfos.iterator().next();
                            fieldData.setLabel(finalType.toString() + i18nSettings.separator()
                                    + labelInfo.getFieldElement().getSimpleName());
                        }

                        fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator()
                                + fieldDefinitionAnnotation.helpMessageKeySuffix());
                        Collection<FieldInfo> helpMessages = FormGenerationUtils.extractFieldInfos(
                                finalTypeElement,
                                fieldElement -> fieldElement.getAnnotation(FieldHelp.class) != null);

                        if (helpMessages != null && helpMessages.size() == 1) {
                            FieldInfo helpInfo = helpMessages.iterator().next();
                            fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator()
                                    + helpInfo.getFieldElement().getSimpleName());
                        }
                    }

                    Collection<FieldInfo> fieldValue = FormGenerationUtils.extractFieldInfos(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();

                    fieldData.setBinding(
                            fieldData.getBinding() + "." + valueInfo.getFieldElement().getSimpleName());

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

                    finalType = valueInfo.getFieldElement().asType();
                    finalTypeElement = (TypeElement) typeUtils.asElement(finalType);

                    overrideI18n = !fieldDefinitionAnnotation.i18nMode().equals(I18nMode.DONT_OVERRIDE);
                } else {
                    FormDefinition formDefinitionAnnotation = finalTypeElement
                            .getAnnotation(FormDefinition.class);

                    if (formDefinitionAnnotation != null) {
                        fieldData.setLabel(
                                finalType.toString() + i18nSettings.separator() + FieldDefinition.LABEL);
                        Collection<FieldInfo> labelInfos = FormGenerationUtils.extractFieldInfos(
                                finalTypeElement,
                                fieldElement -> fieldElement.getAnnotation(FieldLabel.class) != null);

                        if (labelInfos != null && labelInfos.size() == 1) {
                            FieldInfo labelInfo = labelInfos.iterator().next();
                            fieldData.setLabel(finalType.toString() + i18nSettings.separator()
                                    + labelInfo.getFieldElement().getSimpleName());
                            overrideI18n = true;
                        }

                        fieldData.setHelpMessage(
                                finalType.toString() + i18nSettings.separator() + FieldDefinition.HELP_MESSAGE);
                        Collection<FieldInfo> helpMessages = FormGenerationUtils.extractFieldInfos(
                                finalTypeElement,
                                fieldElement -> fieldElement.getAnnotation(FieldHelp.class) != null);

                        if (helpMessages != null && helpMessages.size() == 1) {
                            FieldInfo helpInfo = helpMessages.iterator().next();
                            fieldData.setHelpMessage(finalType.toString() + i18nSettings.separator()
                                    + helpInfo.getFieldElement().getSimpleName());
                            overrideI18n = true;
                        }

                        typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT;
                    }
                }
            }

            DeclaredType fieldType = (DeclaredType) finalType;

            if (typeUtils.isAssignable(finalTypeElement.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);
                finalTypeElement = (TypeElement) typeUtils.asElement(finalType);

                if (FormModelPropertiesUtil.isBaseType(finalTypeElement.getQualifiedName().toString())) {
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.BASE;
                } else if (typeUtils.isAssignable(finalTypeElement.asType(), enumType)) {
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.ENUM;
                } else {
                    typeKind = org.kie.workbench.common.forms.model.TypeKind.OBJECT;
                }
            } else if (typeUtils.isAssignable(finalTypeElement.asType(), enumType)) {
                typeKind = org.kie.workbench.common.forms.model.TypeKind.ENUM;
            }

            fieldData.setType(typeKind.toString());
            fieldData.setClassName(finalTypeElement.getQualifiedName().toString());
            fieldData.setList(String.valueOf(isList));
            fieldData.setFieldModifier(fieldModifier);
            fieldData.getParams().putAll(defaultParams);

            FormField settings = fieldInfo.getFieldElement().getAnnotation(FormField.class);

            if (settings != null) {
                try {
                    fieldData.setPreferredType(settings.type().getName());
                } catch (MirroredTypeException exception) {
                    fieldData.setPreferredType(exception.getTypeMirror().toString());
                }

                fieldData.setAfterElement(settings.afterElement());

                if (!overrideI18n && !isEmpty(settings.labelKey())) {
                    fieldData.setLabel(settings.labelKey());
                }

                if (!overrideI18n && !isEmpty(settings.helpMessageKey())) {
                    fieldData.setHelpMessage(settings.helpMessageKey());
                }

                fieldData.setRequired(Boolean.valueOf(settings.required()).toString());
                fieldData.setReadOnly(Boolean.valueOf(settings.readonly()).toString());

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

                fieldData.setWrap(Boolean.valueOf(settings.layoutSettings().wrap()).toString());
                fieldData.setHorizontalSpan(String.valueOf(settings.layoutSettings().horizontalSpan()));
                fieldData.setVerticalSpan(String.valueOf(settings.layoutSettings().verticalSpan()));
            }

            if (!overrideI18n) {
                if (!isEmpty(i18nSettings.keyPreffix())) {
                    fieldData.setLabel(
                            i18nSettings.keyPreffix() + i18nSettings.separator() + fieldData.getLabel());
                    if (!isEmpty(fieldData.getHelpMessage())) {
                        fieldData.setHelpMessage(i18nSettings.keyPreffix() + i18nSettings.separator()
                                + fieldData.getHelpMessage());
                    }
                }
            }

            extractFieldExtraSettings(fieldData, fieldInfo.getFieldElement());

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

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;
            }/*from  w  w w .  java 2s  . c  o  m*/
        } 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;
}