Search in sources :

Example 1 with FieldMetadata

use of org.springframework.roo.classpath.details.FieldMetadata in project spring-roo by spring-projects.

the class JSONMixinMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    final JSONMixinAnnotationValues values = new JSONMixinAnnotationValues(governorPhysicalTypeMetadata);
    final JavaType mixinType = governorPhysicalTypeMetadata.getType();
    final JavaType entity = values.getEntity();
    final ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity);
    Validate.notNull(entityDetails, "Can't get details of '%s' defined on '%s.@%s.entity'", entity.getFullyQualifiedTypeName(), mixinType, RooJavaType.ROO_JSON_MIXIN.getSimpleTypeName());
    Validate.notNull(entityDetails.getAnnotation(RooJavaType.ROO_JPA_ENTITY), "Class '%s' defined on '%s.@%s.entity' has no @%s annotation. Only JPA entities can set as mixin", entity.getFullyQualifiedTypeName(), mixinType, RooJavaType.ROO_JSON_MIXIN.getSimpleTypeName());
    final String entityId = JpaEntityMetadata.createIdentifier(entityDetails);
    final JpaEntityMetadata entityMetadata = getMetadataService().get(entityId);
    if (entityMetadata == null) {
        // not ready for this metadata yet
        return null;
    }
    // register metadata dependency
    registerDependency(entityId, metadataIdentificationString);
    // Register dependency with DomainModelModule
    Set<ClassOrInterfaceTypeDetails> domainModelModuleDetails = getTypeLocationService().findClassesOrInterfaceDetailsWithAnnotation(RooJavaType.ROO_DOMAIN_MODEL_MODULE);
    if (!domainModelModuleDetails.isEmpty()) {
        String domainModelModuleMetadataId = DomainModelModuleMetadata.createIdentifier(domainModelModuleDetails.iterator().next());
        registerDependency(metadataIdentificationString, domainModelModuleMetadataId);
    }
    Map<FieldMetadata, JavaType> jsonDeserializerByEntity = new TreeMap<FieldMetadata, JavaType>(FieldMetadata.COMPARATOR_BY_NAME);
    for (FieldMetadata field : entityMetadata.getRelationsAsChild().values()) {
        if (isAnyToOneRelation(field)) {
            JavaType parentEntity = field.getFieldType().withoutParameters();
            JavaType entityDeserializer = getEntityDeserializerFor(parentEntity);
            Validate.notNull(entityDeserializer, "Can't locate class with @%s.entity=%s required for %s entity Json Mixin (%s)", RooJavaType.ROO_DESERIALIZER, parentEntity, entity.getFullyQualifiedTypeName(), mixinType.getFullyQualifiedTypeName());
            jsonDeserializerByEntity.put(field, entityDeserializer);
        }
    }
    return new JSONMixinMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, values, entityMetadata, jsonDeserializerByEntity);
}
Also used : RooJavaType(org.springframework.roo.model.RooJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) TreeMap(java.util.TreeMap)

Example 2 with FieldMetadata

use of org.springframework.roo.classpath.details.FieldMetadata in project spring-roo by spring-projects.

the class ControllerCommands method getEntityByDetailField.

/**
 * Get a entity by field recursively
 *
 * @param paternEntity
 *            Root entity
 * @param field
 *            Field to search the entity
 * @param level
 *            Current recursion level
 * @return
 */
private ClassOrInterfaceTypeDetails getEntityByDetailField(ClassOrInterfaceTypeDetails paternEntity, String[] field, int level) {
    ClassOrInterfaceTypeDetails entity = paternEntity;
    MemberDetails entityDetails = getMemberDetailsScanner().getMemberDetails(paternEntity.getType().getSimpleTypeName(), paternEntity);
    List<FieldMetadata> fields = entityDetails.getFields();
    for (FieldMetadata entityField : fields) {
        if (entityField.getFieldName().getSymbolName().equals(field[level])) {
            entity = getTypeLocationService().getTypeDetails(entityField.getFieldType().getParameters().get(0));
        }
    }
    level++;
    if (level < field.length) {
        entity = getEntityByDetailField(entity, field, level);
    }
    return entity;
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails)

Example 3 with FieldMetadata

use of org.springframework.roo.classpath.details.FieldMetadata in project spring-roo by spring-projects.

the class PushInOperationsImpl method pushInClass.

/**
 * Makes push-in of all items defined on a provided class
 *
 * @param klass
 *            class to make the push-in operation
 * @param weiteOnDisk
 *            indicates if pushed elements should be writed on .java file
 * @param force
 *            if some operation will produce several changes, this parameter
 *            should be true.
 *
 * @return list of objects with all the pushed elements.
 */
public List<Object> pushInClass(JavaType klass, boolean writeOnDisk, boolean force) {
    List<Object> pushedElements = new ArrayList<Object>();
    // Check if current klass exists
    Validate.notNull(klass, "ERROR: You must specify a valid class to continue with push-in action");
    // Getting class details
    ClassOrInterfaceTypeDetails classDetails = getTypeLocationService().getTypeDetails(klass);
    Validate.notNull(klass, "ERROR: You must specify a valid class to continue with push-in action");
    // String builder where changes will be registered
    StringBuilder changesToApply = new StringBuilder();
    // Getting member details
    MemberDetails memberDetails = getMemberDetailsScanner().getMemberDetails(getClass().getName(), classDetails);
    List<MemberHoldingTypeDetails> memberHoldingTypes = memberDetails.getDetails();
    // Return if the class has not associated ITD's
    if (memberHoldingTypes.size() == 1 && memberHoldingTypes.get(0).getPhysicalTypeCategory() != PhysicalTypeCategory.ITD) {
        return pushedElements;
    }
    // Check if the provided class is a test to be able to select valid
    // class path
    Path path = classDetails.getAnnotation(RooJavaType.ROO_JPA_UNIT_TEST) == null ? Path.SRC_MAIN_JAVA : Path.SRC_TEST_JAVA;
    // Getting current class .java file metadata ID
    final String declaredByMetadataId = PhysicalTypeIdentifier.createIdentifier(klass, getPathResolver().getPath(klass.getModule(), path));
    // Getting detailsBuilder
    ClassOrInterfaceTypeDetailsBuilder detailsBuilder = new ClassOrInterfaceTypeDetailsBuilder(classDetails);
    // Getting all details
    for (final MemberHoldingTypeDetails memberHoldingTypeDetails : memberDetails.getDetails()) {
        // this .java file
        if (!memberHoldingTypeDetails.getType().equals(classDetails.getType())) {
            continue;
        }
        // Getting all declared methods (including declared on ITDs
        // and .java files)
        List<MethodMetadata> allDeclaredMethods = memberHoldingTypeDetails.getMethods();
        // Checking if is necessary to make push-in for all declared methods
        for (MethodMetadata method : allDeclaredMethods) {
            // If method exists on .aj file, add it!
            if (method.getDeclaredByMetadataId().split("\\?").length > 1 && method.getDeclaredByMetadataId().split("\\?")[1].equals(klass.getFullyQualifiedTypeName()) && !method.getDeclaredByMetadataId().equals(declaredByMetadataId)) {
                // Add method to .java file
                MethodMetadata newMethod = getNewMethod(declaredByMetadataId, method);
                detailsBuilder.addMethod(newMethod);
                // Save changes on pushed elements list
                pushedElements.add(newMethod);
                changesToApply.append(String.format("Method '%s' will be pushed on '%s.java' class. \n", method.getMethodName(), klass.getSimpleTypeName()));
            }
        }
        // Getting all declared fields (including declared on ITDs
        // and .java files)
        List<? extends FieldMetadata> allDeclaredFields = memberHoldingTypeDetails.getDeclaredFields();
        // Checking if is necessary to make push-in for all declared fields
        for (FieldMetadata field : allDeclaredFields) {
            // If field exists on .aj file, add it!
            if (field.getDeclaredByMetadataId().split("\\?").length > 1 && field.getDeclaredByMetadataId().split("\\?")[1].equals(klass.getFullyQualifiedTypeName()) && !field.getDeclaredByMetadataId().equals(declaredByMetadataId)) {
                // Add field to .java file
                FieldMetadata newField = getNewField(declaredByMetadataId, field);
                detailsBuilder.addField(newField);
                // Save changes on pushed elements list
                pushedElements.add(newField);
                changesToApply.append(String.format("Field '%s' will be pushed on '%s.java' class. \n", field.getFieldName(), klass.getSimpleTypeName()));
            }
        }
        // Getting all declared constructors (including declared on ITDs and
        // .java files)
        List<? extends ConstructorMetadata> allDeclaredConstructors = memberHoldingTypeDetails.getDeclaredConstructors();
        // constructors
        for (ConstructorMetadata constructor : allDeclaredConstructors) {
            // Check if current constructor exists on .java file
            classDetails = getTypeLocationService().getTypeDetails(detailsBuilder.build().getType());
            List<JavaType> parameterTypes = new ArrayList<JavaType>();
            for (AnnotatedJavaType type : constructor.getParameterTypes()) {
                parameterTypes.add(type.getJavaType());
            }
            ConstructorMetadata javaDeclaredConstructor = classDetails.getDeclaredConstructor(parameterTypes);
            // If not exists, add it!
            if (javaDeclaredConstructor == null) {
                // Add constructor to .java file
                detailsBuilder.addConstructor(constructor);
                // Save changes on pushed elements list
                pushedElements.add(constructor);
                String constructorParametersNames = "";
                for (JavaSymbolName paramName : constructor.getParameterNames()) {
                    constructorParametersNames = constructorParametersNames.concat(paramName.getSymbolName()).concat(", ");
                    changesToApply.append(String.format("Constructor with parameters '%s' will be pushed on '%s.java' class. \n", constructorParametersNames.substring(0, constructorParametersNames.length() - 2), klass.getSimpleTypeName()));
                }
            }
        }
        // Getting all declared annotations (including declared on ITDs
        // and .java files)
        List<AnnotationMetadata> allDeclaredAnnotations = memberHoldingTypeDetails.getAnnotations();
        for (AnnotationMetadata annotation : allDeclaredAnnotations) {
            // Check if current annotation exists on .java file
            classDetails = getTypeLocationService().getTypeDetails(detailsBuilder.build().getType());
            List<AnnotationMetadata> javaDeclaredAnnotations = classDetails.getAnnotations();
            boolean annotationExists = false;
            for (AnnotationMetadata javaAnnotation : javaDeclaredAnnotations) {
                if (javaAnnotation.getAnnotationType().getFullyQualifiedTypeName().equals(annotation.getAnnotationType().getFullyQualifiedTypeName())) {
                    annotationExists = true;
                }
            }
            // If not exists, add it!
            if (!annotationExists) {
                // Add annotation to .java file
                detailsBuilder.addAnnotation(annotation);
                // Save changes on pushed elements list
                pushedElements.add(annotation);
                changesToApply.append(String.format("Annotation '%s' will be pushed on '%s.java' class. \n", annotation.getAnnotationType().getSimpleTypeName(), klass.getSimpleTypeName()));
            }
        }
        // Getting all extends registered on .aj file to move to .java file
        List<JavaType> allExtendsTypes = memberHoldingTypeDetails.getExtendsTypes();
        for (JavaType extendsType : allExtendsTypes) {
            // If extends exists on .aj file, add it!
            if (!detailsBuilder.getExtendsTypes().contains(extendsType)) {
                detailsBuilder.addExtendsTypes(extendsType);
                // Save changes on pushed elements list
                pushedElements.add(extendsType);
                changesToApply.append(String.format("Extends type '%s' will be pushed on '%s.java' class. \n", extendsType.getSimpleTypeName(), klass.getSimpleTypeName()));
            }
        }
        // Getting all implements registered on .aj file to move to .java
        // file
        List<JavaType> allImplementsTypes = memberHoldingTypeDetails.getImplementsTypes();
        for (JavaType implementsType : allImplementsTypes) {
            if (!detailsBuilder.getImplementsTypes().contains(implementsType)) {
                detailsBuilder.addImplementsType(implementsType);
                // Save changes on pushed elements list
                pushedElements.add(implementsType);
                changesToApply.append(String.format("Implements type '%s' will be pushed on '%s.java' class. \n", implementsType.getSimpleTypeName(), klass.getSimpleTypeName()));
            }
        }
        // Getting all imports registered on .aj file to move to .java file
        Set<ImportMetadata> allRegisteredImports = memberHoldingTypeDetails.getImports();
        detailsBuilder.addImports(allRegisteredImports);
        // Save changes on pushed elements list
        pushedElements.add(allRegisteredImports);
    }
    // Updating .java file
    if (!force) {
        // Show message to be able to know which changes will be applied
        if (changesToApply.length() > 0) {
            LOGGER.log(Level.INFO, changesToApply.toString());
        }
    } else if (writeOnDisk) {
        getTypeManagementService().createOrUpdateTypeOnDisk(detailsBuilder.build());
    }
    return pushedElements;
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) ArrayList(java.util.ArrayList) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) ClassOrInterfaceTypeDetailsBuilder(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetailsBuilder) Path(org.springframework.roo.project.Path) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) ConstructorMetadata(org.springframework.roo.classpath.details.ConstructorMetadata) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) MemberHoldingTypeDetails(org.springframework.roo.classpath.details.MemberHoldingTypeDetails) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) ImportMetadata(org.springframework.roo.classpath.details.ImportMetadata)

Example 4 with FieldMetadata

use of org.springframework.roo.classpath.details.FieldMetadata in project spring-roo by spring-projects.

the class JpaFieldCreatorProvider method checkFieldExists.

/**
 * Checks if entity has already a field with the same name and throws an exception
 * in that case.
 *
 * @param fieldName
 * @param isforce
 * @param javaTypeDetails
 * @param parameterName
 */
private void checkFieldExists(final JavaSymbolName fieldName, final boolean isForce, final ClassOrInterfaceTypeDetails javaTypeDetails, final String parameterName) {
    MemberDetails memberDetails = memberDetailsScanner.getMemberDetails(this.getClass().getName(), javaTypeDetails);
    List<FieldMetadata> fields = memberDetails.getFields();
    for (FieldMetadata field : fields) {
        if (field.getFieldName().equals(fieldName) && !isForce) {
            throw new IllegalArgumentException(String.format("Field '%s' already exists and cannot be created. Try to use a " + "different field name on --%s parameter or use --force parameter to overwrite it.", fieldName, parameterName));
        }
    }
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails)

Example 5 with FieldMetadata

use of org.springframework.roo.classpath.details.FieldMetadata in project spring-roo by spring-projects.

the class IdentifierMetadata method getFieldBuilders.

/**
 * Locates declared fields.
 * <p>
 * If no parent is defined, one will be located or created. All declared
 * fields will be returned.
 *
 * @return fields (never returns null)
 */
private List<FieldMetadataBuilder> getFieldBuilders() {
    // Locate all declared fields
    final List<? extends FieldMetadata> declaredFields = governorTypeDetails.getDeclaredFields();
    // Add fields to ITD from annotation
    final List<FieldMetadata> fields = new ArrayList<FieldMetadata>();
    if (identifierServiceResult != null) {
        for (final Identifier identifier : identifierServiceResult) {
            final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
            annotations.add(getColumnBuilder(identifier));
            if (identifier.getFieldType().equals(DATE)) {
                setDateAnnotations(identifier.getColumnDefinition(), annotations);
            }
            final FieldMetadata idField = new FieldMetadataBuilder(getId(), Modifier.PRIVATE, annotations, identifier.getFieldName(), identifier.getFieldType()).build();
            // Only add field to ITD if not declared on governor
            if (!hasField(declaredFields, idField)) {
                fields.add(idField);
            }
        }
    }
    fields.addAll(declaredFields);
    // Remove fields with static and transient modifiers
    for (final Iterator<FieldMetadata> iter = fields.iterator(); iter.hasNext(); ) {
        final FieldMetadata field = iter.next();
        if (Modifier.isStatic(field.getModifier()) || Modifier.isTransient(field.getModifier())) {
            iter.remove();
        }
    }
    // Remove fields with the @Transient annotation
    final List<FieldMetadata> transientAnnotatedFields = governorTypeDetails.getFieldsWithAnnotation(TRANSIENT);
    if (fields.containsAll(transientAnnotatedFields)) {
        fields.removeAll(transientAnnotatedFields);
    }
    final List<FieldMetadataBuilder> fieldBuilders = new ArrayList<FieldMetadataBuilder>();
    if (!fields.isEmpty()) {
        for (final FieldMetadata field : fields) {
            fieldBuilders.add(new FieldMetadataBuilder(field));
        }
        return fieldBuilders;
    }
    // We need to create a default identifier field
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    // Compute the column name, as required
    final AnnotationMetadataBuilder columnBuilder = new AnnotationMetadataBuilder(COLUMN);
    columnBuilder.addStringAttribute("name", "id");
    columnBuilder.addBooleanAttribute("nullable", false);
    annotations.add(columnBuilder);
    fieldBuilders.add(new FieldMetadataBuilder(getId(), Modifier.PRIVATE, annotations, new JavaSymbolName("id"), LONG_OBJECT));
    return fieldBuilders;
}
Also used : JavaSymbolName(org.springframework.roo.model.JavaSymbolName) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) RooIdentifier(org.springframework.roo.addon.jpa.annotations.identifier.RooIdentifier) ArrayList(java.util.ArrayList) AnnotationMetadataBuilder(org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder) FieldMetadataBuilder(org.springframework.roo.classpath.details.FieldMetadataBuilder)

Aggregations

FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)141 JavaType (org.springframework.roo.model.JavaType)76 ArrayList (java.util.ArrayList)69 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)59 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)40 InvocableMemberBodyBuilder (org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)40 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)39 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)38 RooJavaType (org.springframework.roo.model.RooJavaType)38 JdkJavaType (org.springframework.roo.model.JdkJavaType)33 JpaJavaType (org.springframework.roo.model.JpaJavaType)32 MethodMetadataBuilder (org.springframework.roo.classpath.details.MethodMetadataBuilder)30 SpringJavaType (org.springframework.roo.model.SpringJavaType)30 MemberDetails (org.springframework.roo.classpath.scanner.MemberDetails)29 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)26 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)21 SpringletsJavaType (org.springframework.roo.model.SpringletsJavaType)21 Jsr303JavaType (org.springframework.roo.model.Jsr303JavaType)18 RelationInfo (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo)17 ServiceMetadata (org.springframework.roo.addon.layers.service.addon.ServiceMetadata)15