Search in sources :

Example 21 with MemberDetails

use of org.springframework.roo.classpath.scanner.MemberDetails in project spring-roo by spring-projects.

the class AbstractViewGenerationService method addI18nLabelsFromEntityFormatExpressions.

/**
 * Locates `@EntityFormat` annotations at type-level and relation fields and
 * adds a new message to provided map if the annotation has the `message`
 * attribute.
 *
 * @param properties the Map<String, String> to be added to message bundles.
 * @param details the ClassOrInterfaceTypeDetails to check.
 */
private void addI18nLabelsFromEntityFormatExpressions(final Map<String, String> properties, ClassOrInterfaceTypeDetails details) {
    // Get all projection member details
    if (details != null) {
        MemberDetails memberDetails = getMemberDetailsScanner().getMemberDetails(this.getClass().getName(), details);
        // Search for @EntityFormat at type-level
        AnnotationMetadata entityFormatTypeLevelAnnotation = memberDetails.getAnnotation(SpringletsJavaType.SPRINGLETS_ENTITY_FORMAT);
        if (entityFormatTypeLevelAnnotation != null) {
            AnnotationAttributeValue<Object> messageAttribute = entityFormatTypeLevelAnnotation.getAttribute("message");
            if (messageAttribute != null) {
                properties.put((String) messageAttribute.getValue(), "TO BE MODIFIED BY DEVELOPER");
            }
        }
        // Search for @EntityFormat at relation fields
        for (FieldMetadata field : memberDetails.getFields()) {
            AnnotationMetadata entityFormatAnnotation = field.getAnnotation(SpringletsJavaType.SPRINGLETS_ENTITY_FORMAT);
            if (entityFormatAnnotation != null) {
                AnnotationAttributeValue<Object> messageAttribute = entityFormatAnnotation.getAttribute("message");
                if (messageAttribute != null) {
                    properties.put((String) messageAttribute.getValue(), "TO BE MODIFIED BY DEVELOPER");
                }
            }
        }
    }
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata)

Example 22 with MemberDetails

use of org.springframework.roo.classpath.scanner.MemberDetails in project spring-roo by spring-projects.

the class AbstractViewGeneratorMetadataProvider method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    // Use provided MVCViewGenerationService to generate views
    MVCViewGenerationService<T> viewGenerationService = getViewGenerationService();
    ClassOrInterfaceTypeDetails controllerDetail = governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
    // Getting controller metadata
    final String controllerMetadataKey = ControllerMetadata.createIdentifier(controllerDetail);
    final ControllerMetadata controllerMetadata = getMetadataService().get(controllerMetadataKey);
    if (controllerMetadata == null) {
        return null;
    }
    // Getting entity and check if is a readOnly entity or not
    final JavaType entity = controllerMetadata.getEntity();
    JavaType viewType = viewGenerationService.getType();
    JavaType itemController = null;
    JavaType collectionController = null;
    final JavaPackage controllerPackage = controllerDetail.getType().getPackage();
    final String pathPrefix = controllerMetadata.getAnnotationValues().getPathPrefix();
    if (controllerMetadata.getType() != ControllerType.ITEM) {
        // Locate ItemController
        Collection<ClassOrInterfaceTypeDetails> itemControllers = getControllerLocator().getControllers(entity, ControllerType.ITEM, viewType);
        if (itemControllers.isEmpty()) {
            // We can't create metadata "Jet"
            return null;
        } else {
            // Get controller with the same package
            itemController = filterControllerByPackageAndPrefix(itemControllers, controllerPackage, pathPrefix);
            Validate.notNull(itemControllers, "ERROR: Can't find ITEM-type controller related to controller '%s'", controllerDetail.getType().getFullyQualifiedTypeName());
        }
    }
    if (controllerMetadata.getType() != ControllerType.COLLECTION) {
        // Locate ItemController
        Collection<ClassOrInterfaceTypeDetails> collectionControllers = getControllerLocator().getControllers(entity, ControllerType.COLLECTION, viewType);
        // Get controller with the same package
        collectionController = filterControllerByPackageAndPrefix(collectionControllers, controllerPackage, pathPrefix);
        Validate.notNull(collectionController, "ERROR: Can't find Collection-type controller related to controller '%s'", controllerDetail.getType().getFullyQualifiedTypeName());
    }
    JavaType detailItemController = null;
    JavaType detailCollectionController = null;
    if (controllerMetadata.getType() == ControllerType.DETAIL) {
        if (controllerMetadata.getLastDetailsInfo().type == JpaRelationType.AGGREGATION) {
            // Locate controller item which handles details elements
            JavaType detailEntity = controllerMetadata.getLastDetailEntity();
            Collection<ClassOrInterfaceTypeDetails> detailsControllersToCheck = getControllerLocator().getControllers(detailEntity, ControllerType.ITEM, viewType);
            for (ClassOrInterfaceTypeDetails controller : detailsControllersToCheck) {
                if (controllerPackage.equals(controller.getType().getPackage())) {
                    detailItemController = controller.getType();
                    break;
                }
            }
            Validate.notNull(detailItemController, "ERROR: Can't find Item-type controller for details entity '%s' related to controller '%s'", detailEntity.getFullyQualifiedTypeName(), controllerDetail.getType().getFullyQualifiedTypeName());
            // Locate controller collection which handles details elements
            detailsControllersToCheck = getControllerLocator().getControllers(detailEntity, ControllerType.COLLECTION, viewType);
            for (ClassOrInterfaceTypeDetails controller : detailsControllersToCheck) {
                if (controllerPackage.equals(controller.getType().getPackage())) {
                    detailCollectionController = controller.getType();
                    break;
                }
            }
            Validate.notNull(detailItemController, "ERROR: Can't find Collection-type controller for details entity '%s' related to controller '%s'", detailEntity.getFullyQualifiedTypeName(), controllerDetail.getType().getFullyQualifiedTypeName());
        } else {
            // ** COMPOSITION **
            // Locate controller item which handles details elements
            Collection<ClassOrInterfaceTypeDetails> detailsControllersToCheck = getControllerLocator().getControllers(entity, ControllerType.DETAIL_ITEM, viewType);
            for (ClassOrInterfaceTypeDetails controller : detailsControllersToCheck) {
                if (controllerPackage.equals(controller.getType().getPackage())) {
                    DetailAnnotationValues annotationValues = new DetailAnnotationValues(controller);
                    if (controllerMetadata.getDetailAnnotaionFieldValue().equals(annotationValues.getRelationField())) {
                        detailItemController = controller.getType();
                    }
                    break;
                }
            }
            Validate.notNull(detailItemController, "ERROR: Can't find Detail-Item-type controller for details entity '%s' related to controller '%s' (relation '%s')", entity.getFullyQualifiedTypeName(), controllerDetail.getType().getFullyQualifiedTypeName(), controllerMetadata.getDetailAnnotaionFieldValue());
        }
    }
    if (controllerMetadata.getType() == ControllerType.DETAIL_ITEM) {
        // Locate controller item which handles details elements
        Collection<ClassOrInterfaceTypeDetails> detailsControllersToCheck = getControllerLocator().getControllers(entity, ControllerType.DETAIL, viewType);
        for (ClassOrInterfaceTypeDetails controller : detailsControllersToCheck) {
            if (controllerPackage.equals(controller.getType().getPackage())) {
                DetailAnnotationValues annotationValues = new DetailAnnotationValues(controller);
                if (controllerMetadata.getDetailAnnotaionFieldValue().equals(annotationValues.getRelationField())) {
                    detailCollectionController = controller.getType();
                }
                break;
            }
        }
        Validate.notNull(detailCollectionController, "ERROR: Can't find Detail-type controller for details entity '%s' related to controller '%s' (relation '%s')", entity.getFullyQualifiedTypeName(), controllerDetail.getType().getFullyQualifiedTypeName(), controllerMetadata.getDetailAnnotaionFieldValue());
    }
    Validate.notNull(entity, "ERROR: You should provide a valid entity for controller '%s'", controllerDetail.getType().getFullyQualifiedTypeName());
    final ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity);
    Validate.notNull(entityDetails, "ERROR: Can't load details of %s", entity.getFullyQualifiedTypeName());
    final JpaEntityMetadata entityMetadata = getMetadataService().get(JpaEntityMetadata.createIdentifier(entityDetails));
    Validate.notNull(entityMetadata, "ERROR: Can't get Jpa Entity metada of %s", entity.getFullyQualifiedTypeName());
    MemberDetails entityMemberDetails = getMemberDetails(entityDetails);
    // Get entity plural
    final String entityPlural = getPluralService().getPlural(entity);
    final String entityIdentifierPlural = getPluralService().getPlural(entityMetadata.getCurrentIndentifierField().getFieldName());
    // Getting service and its metadata
    final JavaType service = controllerMetadata.getService();
    ClassOrInterfaceTypeDetails serviceDetails = getTypeLocationService().getTypeDetails(service);
    final String serviceMetadataKey = ServiceMetadata.createIdentifier(serviceDetails);
    registerDependency(serviceMetadataKey, metadataIdentificationString);
    final ServiceMetadata serviceMetadata = getMetadataService().get(serviceMetadataKey);
    // Prepare information about ONE-TO-ONE relations
    final List<Pair<RelationInfo, JpaEntityMetadata>> compositionRelationOneToOne = new ArrayList<Pair<RelationInfo, JpaEntityMetadata>>();
    ClassOrInterfaceTypeDetails childEntityDetails;
    JpaEntityMetadata childEntityMetadata;
    for (RelationInfo info : entityMetadata.getRelationInfos().values()) {
        if (info.cardinality == Cardinality.ONE_TO_ONE) {
            childEntityDetails = getTypeLocationService().getTypeDetails(info.childType);
            childEntityMetadata = getMetadataService().get(JpaEntityMetadata.createIdentifier(childEntityDetails));
            compositionRelationOneToOne.add(Pair.of(info, childEntityMetadata));
        }
    }
    List<FieldMetadata> dateTimeFields;
    List<FieldMetadata> enumFields;
    if (controllerMetadata.getType() == ControllerType.DETAIL || controllerMetadata.getType() == ControllerType.DETAIL_ITEM) {
        ClassOrInterfaceTypeDetails childCid = getTypeLocationService().getTypeDetails(controllerMetadata.getLastDetailEntity());
        MemberDetails childMemberDetails = getMemberDetails(childCid);
        dateTimeFields = getDateTimeFields(childMemberDetails);
        enumFields = getEnumFields(childMemberDetails);
    } else {
        dateTimeFields = getDateTimeFields(entityMemberDetails);
        enumFields = getEnumFields(entityMemberDetails);
    }
    Map<String, MethodMetadata> findersToAdd = new HashMap<String, MethodMetadata>();
    Map<JavaType, List<FieldMetadata>> formBeansDateTimeFields = new HashMap<JavaType, List<FieldMetadata>>();
    Map<JavaType, List<FieldMetadata>> formBeansEnumFields = new HashMap<JavaType, List<FieldMetadata>>();
    // Getting annotated finders
    final SearchAnnotationValues searchAnnotationValues = new SearchAnnotationValues(governorPhysicalTypeMetadata);
    // Add finders only if controller is of search type
    Map<String, JavaType> finderReturnTypes = new HashMap<String, JavaType>();
    Map<String, JavaType> finderFormBeans = new HashMap<String, JavaType>();
    if (controllerMetadata.getType() == ControllerType.SEARCH && searchAnnotationValues != null && searchAnnotationValues.getFinders() != null) {
        List<String> finders = new ArrayList<String>(Arrays.asList(searchAnnotationValues.getFinders()));
        // Search indicated finders in its related service
        for (MethodMetadata serviceFinder : serviceMetadata.getFinders()) {
            String finderName = serviceFinder.getMethodName().getSymbolName();
            if (finders.contains(finderName)) {
                findersToAdd.put(finderName, serviceFinder);
                // FormBean parameters is always the first finder parameter
                JavaType formBean = serviceFinder.getParameterTypes().get(0).getJavaType();
                // Save the associated formBean to the current finder
                finderFormBeans.put(finderName, formBean);
                // Getting the returnType for this finder
                JavaType returnType = serviceFinder.getReturnType();
                // Save the associated returnType to the current finder
                finderReturnTypes.put(finderName, returnType);
                // Get dateTime and Enum of formBean
                MemberDetails formBeanDetails = getMemberDetails(formBean);
                List<FieldMetadata> formBeanDateTimeFields = getDateTimeFields(formBeanDetails);
                List<FieldMetadata> formBeanEnumFields = getEnumFields(formBeanDetails);
                if (!formBeanDateTimeFields.isEmpty()) {
                    formBeansDateTimeFields.put(formBean, formBeanDateTimeFields);
                }
                if (!formBeanEnumFields.isEmpty()) {
                    formBeansEnumFields.put(formBean, formBeanEnumFields);
                }
                // Add dependencies between modules
                List<JavaType> types = new ArrayList<JavaType>();
                types.add(serviceFinder.getReturnType());
                types.addAll(serviceFinder.getReturnType().getParameters());
                for (AnnotatedJavaType parameter : serviceFinder.getParameterTypes()) {
                    types.add(parameter.getJavaType());
                    types.addAll(parameter.getJavaType().getParameters());
                }
                for (JavaType parameter : types) {
                    getTypeLocationService().addModuleDependency(governorPhysicalTypeMetadata.getType().getModule(), parameter);
                }
                finders.remove(finderName);
            }
        }
        // Check all finders have its service method
        if (!finders.isEmpty()) {
            throw new IllegalArgumentException(String.format("ERROR: Service %s does not have these finder methods: %s ", service.getFullyQualifiedTypeName(), StringUtils.join(finders, ", ")));
        }
    }
    T viewMetadata = createMetadataInstance(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, controllerMetadata, serviceMetadata, entityMetadata, entityPlural, entityIdentifierPlural, compositionRelationOneToOne, itemController, collectionController, dateTimeFields, enumFields, findersToAdd, formBeansDateTimeFields, formBeansEnumFields, detailItemController, detailCollectionController);
    // Fill view context
    ViewContext ctx = viewGenerationService.createViewContext(controllerMetadata, entity, entityMetadata, viewMetadata);
    // Checking if Spring Security has been installed
    if (getProjectOperations().isFeatureInstalled(FeatureNames.SECURITY)) {
        ctx.setSecurityEnabled(true);
    }
    final String module = controllerDetail.getType().getModule();
    switch(controllerMetadata.getType()) {
        case COLLECTION:
            // Obtain the details controllers to use only them that includes "list" value in the
            // views parameter of @RooDetail annotation. If @RooDetail doesn't include views
            // parameter, include it.
            List<T> detailsControllersForListView = getDetailsControllers(controllerMetadata, controllerPackage, entity, viewType, "list");
            // Add list view
            if (viewMetadata.shouldGenerateView("list")) {
                viewGenerationService.addListView(module, entityMetadata, entityMemberDetails, detailsControllersForListView, ctx);
            }
            if (!entityMetadata.isReadOnly()) {
                // If not readOnly, add create view
                if (viewMetadata.shouldGenerateView("create")) {
                    viewGenerationService.addCreateView(module, entityMetadata, entityMemberDetails, ctx);
                }
                if (viewMetadata.shouldGenerateView("listDeleteModal")) {
                    // If not readOnly, add the modal dialogs for delete and delete batch
                    viewGenerationService.addListDeleteModalView(module, entityMetadata, entityMemberDetails, ctx);
                    if (viewMetadata.shouldGenerateView("listDeleteModalBatch")) {
                        viewGenerationService.addListDeleteModalBatchView(module, entityMetadata, entityMemberDetails, ctx);
                    }
                }
            }
            break;
        case ITEM:
            // Obtain the details controllers to use only them that includes "show" value in the
            // views parameter of @RooDetail annotation.
            List<T> detailsControllersForShowView = getDetailsControllers(controllerMetadata, controllerPackage, entity, viewType, "show");
            // Add show view
            if (viewMetadata.shouldGenerateView("show")) {
                viewGenerationService.addShowView(module, entityMetadata, entityMemberDetails, detailsControllersForShowView, ctx);
            }
            if (viewMetadata.shouldGenerateView("showInLine")) {
                // Add showInline view
                viewGenerationService.addShowInlineView(module, entityMetadata, entityMemberDetails, ctx);
            }
            if (!entityMetadata.isReadOnly() && viewMetadata.shouldGenerateView("edit")) {
                // If not readOnly, add update view
                viewGenerationService.addUpdateView(module, entityMetadata, entityMemberDetails, ctx);
            }
            break;
        case DETAIL:
            viewGenerationService.addDetailsViews(module, entityMetadata, entityMemberDetails, controllerMetadata, viewMetadata, ctx);
            // Add this metadata as upstream dependency for parent controllers
            // for updating views of parent controllers
            JavaType parentEntity = entityMetadata.getAnnotatedEntity();
            List<ClassOrInterfaceTypeDetails> parentControllers = new ArrayList<ClassOrInterfaceTypeDetails>();
            parentControllers.addAll(getControllerLocator().getControllers(parentEntity, ControllerType.COLLECTION, viewType));
            parentControllers.addAll(getControllerLocator().getControllers(parentEntity, ControllerType.ITEM, viewType));
            parentControllers.addAll(getControllerLocator().getControllers(parentEntity, ControllerType.SEARCH, viewType));
            for (ClassOrInterfaceTypeDetails parentController : parentControllers) {
                String viewMetadatIdentifier = createLocalIdentifier(parentController);
                registerDependency(metadataIdentificationString, viewMetadatIdentifier);
            }
            break;
        case DETAIL_ITEM:
            viewGenerationService.addDetailsItemViews(module, entityMetadata, entityMemberDetails, controllerMetadata, viewMetadata, ctx);
            RelationInfoExtended last = controllerMetadata.getLastDetailsInfo();
            ClassOrInterfaceTypeDetails childCid = getTypeLocationService().getTypeDetails(last.childType);
            MemberDetails detailMemberDetails = getMemberDetails(childCid);
            // Update i18n labels of detail entity
            if (shouldGenerateI18nLabels()) {
                Map<String, String> labels = viewGenerationService.getI18nLabels(detailMemberDetails, last.childType, last.childEntityMetadata, controllerMetadata, module, ctx);
                getI18nOperations().addOrUpdateLabels(module, labels);
            }
            break;
        case SEARCH:
            // in @RooSearch annotation
            if (searchAnnotationValues != null && searchAnnotationValues.getFinders() != null) {
                List<String> finders = new ArrayList<String>(Arrays.asList(searchAnnotationValues.getFinders()));
                // Generating views for all finders
                for (String finderName : finders) {
                    // Getting the formBean for this finder
                    JavaType formBean = finderFormBeans.get(finderName);
                    viewGenerationService.addFinderFormView(module, entityMetadata, viewMetadata, formBean, finderName, ctx);
                    // Getting the returnType for this finder
                    JavaType returnType = finderReturnTypes.get(finderName);
                    if (!returnType.getParameters().isEmpty()) {
                        returnType = returnType.getParameters().get(0);
                    }
                    // Obtain the details controllers to use only them that includes this finder value in the
                    // views parameter of @RooDetail annotation.
                    List<T> detailsControllersForFinderListView = getDetailsControllers(controllerMetadata, controllerPackage, entity, viewType, finderName);
                    viewGenerationService.addFinderListView(module, entityMetadata, entityMemberDetails, viewMetadata, formBean, returnType, finderName, detailsControllersForFinderListView, ctx);
                }
            }
            break;
        default:
            throw new IllegalArgumentException();
    }
    // be included on it. Must be fixed on future versions.
    if (shouldUpdateMenu()) {
        viewGenerationService.updateMenuView(module, ctx);
    }
    if (shouldGenerateI18nLabels()) {
        // Update i18n labels
        Map<String, String> labels = viewGenerationService.getI18nLabels(entityMemberDetails, entity, entityMetadata, controllerMetadata, module, ctx);
        getI18nOperations().addOrUpdateLabels(module, labels);
        // Add labels for child composite entity as well
        for (Pair<RelationInfo, JpaEntityMetadata> compositionRelation : compositionRelationOneToOne) {
            MemberDetails childMemberDetails = getMemberDetailsScanner().getMemberDetails(this.getClass().getName(), getTypeLocationService().getTypeDetails(compositionRelation.getKey().childType));
            Map<String, String> i18nLabels = viewGenerationService.getI18nLabels(childMemberDetails, compositionRelation.getKey().childType, compositionRelation.getValue(), null, module, ctx);
            getI18nOperations().addOrUpdateLabels(module, i18nLabels);
        }
    }
    // Register dependency between JavaBeanMetadata and this one
    final String javaBeanMetadataKey = JavaBeanMetadata.createIdentifier(entityDetails);
    registerDependency(javaBeanMetadataKey, metadataIdentificationString);
    // Register dependency between JpaEntityMetadata and this one
    final String jpaEntityMetadataKey = JpaEntityMetadata.createIdentifier(entityDetails);
    registerDependency(jpaEntityMetadataKey, metadataIdentificationString);
    return viewMetadata;
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) SearchAnnotationValues(org.springframework.roo.addon.web.mvc.controller.addon.finder.SearchAnnotationValues) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) DetailAnnotationValues(org.springframework.roo.addon.web.mvc.controller.addon.DetailAnnotationValues) JavaPackage(org.springframework.roo.model.JavaPackage) ArrayList(java.util.ArrayList) List(java.util.List) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) Pair(org.apache.commons.lang3.tuple.Pair) ControllerMetadata(org.springframework.roo.addon.web.mvc.controller.addon.ControllerMetadata) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JdkJavaType(org.springframework.roo.model.JdkJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) RelationInfoExtended(org.springframework.roo.addon.web.mvc.controller.addon.RelationInfoExtended) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) ServiceMetadata(org.springframework.roo.addon.layers.service.addon.ServiceMetadata)

Example 23 with MemberDetails

use of org.springframework.roo.classpath.scanner.MemberDetails in project spring-roo by spring-projects.

the class ControllerMetadataProviderImpl method getEntityFromRelationField.

/**
 * Get the entity that represents a relation field
 *
 * @param relationField Array that represents the relation field.
 * @param entity Current entity to search the corresponding field
 * @param level Current array level to search
 * @return
 */
private JavaType getEntityFromRelationField(String[] relationField, JavaType entity, int level) {
    JavaType entityTypeToCalculate = null;
    MemberDetails memberDetails = getMemberDetails(entity);
    List<FieldMetadata> fields = memberDetails.getFields();
    for (FieldMetadata entityField : fields) {
        if (entityField.getFieldName().getSymbolName().equals(relationField[level])) {
            AnnotationMetadata oneToManyAnnotation = entityField.getAnnotation(JpaJavaType.ONE_TO_MANY);
            if (oneToManyAnnotation != null && (entityField.getFieldType().getFullyQualifiedTypeName().equals(JavaType.LIST.getFullyQualifiedTypeName()) || entityField.getFieldType().getFullyQualifiedTypeName().equals(JavaType.SET.getFullyQualifiedTypeName()))) {
                level++;
                if (relationField.length > level) {
                    entityTypeToCalculate = getEntityFromRelationField(relationField, entityField.getFieldType().getParameters().get(0), level);
                } else {
                    entityTypeToCalculate = entityField.getFieldType().getParameters().get(0);
                }
                break;
            }
        }
    }
    return entityTypeToCalculate;
}
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) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata)

Example 24 with MemberDetails

use of org.springframework.roo.classpath.scanner.MemberDetails in project spring-roo by spring-projects.

the class RepositoryJpaCustomImplMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    final RepositoryJpaCustomImplAnnotationValues annotationValues = new RepositoryJpaCustomImplAnnotationValues(governorPhysicalTypeMetadata);
    // Getting repository custom
    JavaType repositoryCustom = annotationValues.getRepository();
    // Validate that contains repository interface
    Validate.notNull(repositoryCustom, "ERROR: You need to specify interface repository to be implemented.");
    ClassOrInterfaceTypeDetails repositoryDetails = getTypeLocationService().getTypeDetails(repositoryCustom);
    AnnotationMetadata repositoryCustomAnnotation = repositoryDetails.getAnnotation(ROO_REPOSITORY_JPA_CUSTOM);
    Validate.notNull(repositoryCustomAnnotation, "ERROR: Repository interface should be annotated with @RooJpaRepositoryCustom");
    AnnotationAttributeValue<JavaType> entityAttribute = repositoryCustomAnnotation.getAttribute("entity");
    Validate.notNull(entityAttribute, "ERROR: Repository interface should be contain an entity on @RooJpaRepositoryCustom annotation");
    JavaType entity = entityAttribute.getValue();
    RepositoryJpaMetadata repositoryMetadata = getRepositoryJpaLocator().getRepositoryMetadata(entity);
    if (repositoryMetadata == null) {
        // Can't generate it jet
        return null;
    }
    // Register downstream dependency for RepositoryJpaCustomImplMetadata to update projection
    // finders implementations
    String repositoryCustomMetadataKey = RepositoryJpaCustomMetadata.createIdentifier(repositoryDetails);
    registerDependency(repositoryCustomMetadataKey, metadataIdentificationString);
    ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity);
    // Check if default return type is a Projection
    JavaType returnType = repositoryMetadata.getDefaultReturnType();
    ClassOrInterfaceTypeDetails returnTypeDetails = getTypeLocationService().getTypeDetails(returnType);
    AnnotationMetadata entityProjectionAnnotation = returnTypeDetails.getAnnotation(RooJavaType.ROO_ENTITY_PROJECTION);
    boolean returnTypeIsProjection = entityProjectionAnnotation != null;
    // Get projection constructor fields from @RooEntityProjection and add it to a Map with
    // domain type's variable names
    Map<JavaType, List<Pair<String, String>>> typesFieldMaps = new LinkedHashMap<JavaType, List<Pair<String, String>>>();
    Map<JavaType, Boolean> typesAreProjections = new HashMap<JavaType, Boolean>();
    if (returnTypeIsProjection) {
        buildFieldNamesMap(entity, returnType, entityProjectionAnnotation, typesFieldMaps);
        typesAreProjections.put(returnType, true);
    }
    final RepositoryJpaCustomMetadata repositoryCustomMetadata = getMetadataService().get(repositoryCustomMetadataKey);
    // Prevent empty metadata
    if (repositoryCustomMetadata == null) {
        return null;
    }
    // Getting java bean metadata
    final String javaBeanMetadataKey = JavaBeanMetadata.createIdentifier(entityDetails);
    // Getting jpa entity metadata
    final String jpaEntityMetadataKey = JpaEntityMetadata.createIdentifier(entityDetails);
    JpaEntityMetadata entityMetadata = getMetadataService().get(jpaEntityMetadataKey);
    // Create dependency between repository and java bean annotation
    registerDependency(javaBeanMetadataKey, metadataIdentificationString);
    // Create dependency between repository and jpa entity annotation
    registerDependency(jpaEntityMetadataKey, metadataIdentificationString);
    // Getting entity properties
    MemberDetails entityMemberDetails = getMemberDetailsScanner().getMemberDetails(getClass().getName(), entityDetails);
    // Getting valid fields to construct the findAll query
    List<FieldMetadata> validFields = new ArrayList<FieldMetadata>();
    loadValidFields(entityMemberDetails, entityMetadata, validFields);
    // Getting all necessary information about referencedFields
    Map<FieldMetadata, MethodMetadata> referencedFieldsMethods = repositoryCustomMetadata.getReferencedFieldsFindAllMethods();
    Map<FieldMetadata, String> referencedFieldsIdentifierNames = new HashMap<FieldMetadata, String>();
    List<Pair<MethodMetadata, PartTree>> customFinderMethods = repositoryCustomMetadata.getCustomFinderMethods();
    List<Pair<MethodMetadata, PartTree>> customCountMethods = repositoryCustomMetadata.getCustomCountMethods();
    if (customCountMethods == null) {
        customCountMethods = new ArrayList<Pair<MethodMetadata, PartTree>>();
    }
    for (Entry<FieldMetadata, MethodMetadata> referencedFields : referencedFieldsMethods.entrySet()) {
        // Get identifier field name in path format
        String fieldPathName = String.format("%s.%s", StringUtils.uncapitalize(entity.getSimpleTypeName()), referencedFields.getKey().getFieldName().getSymbolNameUnCapitalisedFirstLetter());
        // Put keys and values in map
        referencedFieldsIdentifierNames.put(referencedFields.getKey(), fieldPathName);
    }
    // Add valid entity fields to mappings
    Map<JavaType, Map<String, FieldMetadata>> typesFieldsMetadataMap = new HashMap<JavaType, Map<String, FieldMetadata>>();
    Map<String, FieldMetadata> entityFieldMetadata = new LinkedHashMap<String, FieldMetadata>();
    List<Pair<String, String>> entityFieldMappings = new ArrayList<Pair<String, String>>();
    typesAreProjections.put(entity, false);
    for (FieldMetadata field : validFields) {
        entityFieldMetadata.put(field.getFieldName().getSymbolName(), field);
        entityFieldMappings.add(Pair.of(field.getFieldName().getSymbolName(), StringUtils.uncapitalize(entity.getSimpleTypeName()).concat(".").concat(field.getFieldName().getSymbolName())));
    }
    typesFieldsMetadataMap.put(entity, entityFieldMetadata);
    typesFieldMaps.put(entity, entityFieldMappings);
    // Make a list with all domain types, excepting entities
    List<JavaType> domainTypes = new ArrayList<JavaType>();
    domainTypes.add(returnType);
    for (Pair<MethodMetadata, PartTree> methodInfo : customFinderMethods) {
        // Get finder return type from first parameter of method return type (Page)
        JavaType finderReturnType = getDomainTypeOfFinderMethod(methodInfo.getKey());
        domainTypes.add(finderReturnType);
        // If type is a DTO, add finder fields to mappings
        JavaType parameterType = methodInfo.getKey().getParameterTypes().get(0).getJavaType();
        typesAreProjections.put(parameterType, false);
    }
    // Add typesFieldMaps for each projection finder and check for id fields
    for (JavaType type : domainTypes) {
        // Check if projection fields has been added already
        if (typesFieldMaps.containsKey(type)) {
            continue;
        }
        // Build Map with FieldMetadata of each projection
        ClassOrInterfaceTypeDetails typeDetails = getTypeLocationService().getTypeDetails(type);
        if (typeDetails == null) {
            LOGGER.warning("Detail not found for type: " + type);
            continue;
        }
        List<FieldMetadata> typeFieldList = getMemberDetailsScanner().getMemberDetails(this.getClass().getName(), typeDetails).getFields();
        Map<String, FieldMetadata> fieldMetadataMap = new LinkedHashMap<String, FieldMetadata>();
        for (FieldMetadata field : typeFieldList) {
            fieldMetadataMap.put(field.getFieldName().getSymbolName(), field);
        }
        typesFieldsMetadataMap.put(type, fieldMetadataMap);
        AnnotationMetadata projectionAnnotation = typeDetails.getAnnotation(RooJavaType.ROO_ENTITY_PROJECTION);
        if (projectionAnnotation != null) {
            typesAreProjections.put(type, true);
            // Type is a Projection
            JavaType associatedEntity = (JavaType) projectionAnnotation.getAttribute("entity").getValue();
            // Add fields to typesFieldMaps
            buildFieldNamesMap(associatedEntity, type, projectionAnnotation, typesFieldMaps);
        }
    }
    return new RepositoryJpaCustomImplMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, annotationValues, entity, entityMetadata, entityMetadata.getCurrentIndentifierField(), validFields, repositoryCustomMetadata.getCurrentFindAllGlobalSearchMethod(), repositoryCustomMetadata.getCurrentFindAllByIdsInGlobalSearchMethod(), repositoryCustomMetadata.getDefaultReturnType(), referencedFieldsMethods, referencedFieldsIdentifierNames, typesFieldMaps, customFinderMethods, customCountMethods, typesFieldsMetadataMap, typesAreProjections);
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) LinkedHashMap(java.util.LinkedHashMap) ArrayList(java.util.ArrayList) List(java.util.List) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) Pair(org.apache.commons.lang3.tuple.Pair) RooJavaType(org.springframework.roo.model.RooJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) PartTree(org.springframework.roo.addon.layers.repository.jpa.addon.finder.parser.PartTree) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map)

Example 25 with MemberDetails

use of org.springframework.roo.classpath.scanner.MemberDetails in project spring-roo by spring-projects.

the class JpaEntityFactoryMetadataProviderImpl method getEmbeddedIdHolder.

private EmbeddedIdHolder getEmbeddedIdHolder(final MemberDetails memberDetails, final String metadataIdentificationString) {
    final List<FieldMetadata> idFields = new ArrayList<FieldMetadata>();
    final List<FieldMetadata> fields = MemberFindingUtils.getFieldsWithTag(memberDetails, EMBEDDED_ID_FIELD);
    if (fields.isEmpty()) {
        return null;
    }
    final FieldMetadata embeddedIdField = fields.get(0);
    final MemberDetails identifierMemberDetails = getMemberDetails(embeddedIdField.getFieldType());
    if (identifierMemberDetails == null) {
        return null;
    }
    for (final FieldMetadata field : identifierMemberDetails.getFields()) {
        if (!(Modifier.isStatic(field.getModifier()) || Modifier.isFinal(field.getModifier()) || Modifier.isTransient(field.getModifier()))) {
            getMetadataDependencyRegistry().registerDependency(field.getDeclaredByMetadataId(), metadataIdentificationString);
            idFields.add(field);
        }
    }
    return new EmbeddedIdHolder(embeddedIdField, idFields);
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) EmbeddedIdHolder(org.springframework.roo.addon.jpa.addon.dod.EmbeddedIdHolder) ArrayList(java.util.ArrayList) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails)

Aggregations

MemberDetails (org.springframework.roo.classpath.scanner.MemberDetails)56 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)36 JavaType (org.springframework.roo.model.JavaType)35 RooJavaType (org.springframework.roo.model.RooJavaType)31 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)29 ArrayList (java.util.ArrayList)25 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)20 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)16 JpaJavaType (org.springframework.roo.model.JpaJavaType)15 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)14 SpringJavaType (org.springframework.roo.model.SpringJavaType)12 List (java.util.List)10 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)9 DetailEntityItem (org.springframework.roo.addon.web.mvc.views.components.DetailEntityItem)8 EntityItem (org.springframework.roo.addon.web.mvc.views.components.EntityItem)7 FieldItem (org.springframework.roo.addon.web.mvc.views.components.FieldItem)7 ClassOrInterfaceTypeDetailsBuilder (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetailsBuilder)7 JdkJavaType (org.springframework.roo.model.JdkJavaType)7 RepositoryJpaMetadata (org.springframework.roo.addon.layers.repository.jpa.addon.RepositoryJpaMetadata)6 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)6