Search in sources :

Example 1 with ServiceMetadata

use of org.springframework.roo.addon.layers.service.addon.ServiceMetadata in project spring-roo by spring-projects.

the class EntityDeserializerMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    final EntityDeserializerAnnotationValues values = new EntityDeserializerAnnotationValues(governorPhysicalTypeMetadata);
    final JavaType deserializerType = 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(), deserializerType, RooJavaType.ROO_DESERIALIZER.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(), deserializerType, RooJavaType.ROO_DESERIALIZER.getSimpleTypeName());
    // Register JpaEntityMetadata dependency
    final String entityId = JpaEntityMetadata.createIdentifier(entityDetails);
    final JpaEntityMetadata entityMetadata = getMetadataService().get(entityId);
    if (entityMetadata == null) {
        // not ready to this metadata yet
        return null;
    }
    registerDependency(entityId, metadataIdentificationString);
    // Register JavaBeanMetadata dependency
    final String javaBeanId = JavaBeanMetadata.createIdentifier(entityDetails);
    final JavaBeanMetadata javaBeanMetadata = getMetadataService().get(javaBeanId);
    if (javaBeanMetadata == null) {
        // not ready to this metadata yet
        return null;
    }
    registerDependency(javaBeanId, metadataIdentificationString);
    // Register ServiceMetadata dependency
    ClassOrInterfaceTypeDetails serviceDetails = getServiceLocator().getService(entity);
    String serviceMetadataId = ServiceMetadata.createIdentifier(serviceDetails);
    ServiceMetadata serviceMetadata = getMetadataService().get(serviceMetadataId);
    if (serviceMetadata == null) {
        // not ready to this metadata yet
        return null;
    }
    return new EntityDeserializerMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, values, entityMetadata, serviceMetadata);
}
Also used : RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) JavaBeanMetadata(org.springframework.roo.addon.javabean.addon.JavaBeanMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) ServiceMetadata(org.springframework.roo.addon.layers.service.addon.ServiceMetadata)

Example 2 with ServiceMetadata

use of org.springframework.roo.addon.layers.service.addon.ServiceMetadata 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 3 with ServiceMetadata

use of org.springframework.roo.addon.layers.service.addon.ServiceMetadata in project spring-roo by spring-projects.

the class ControllerMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    ControllerAnnotationValues controllerValues = new ControllerAnnotationValues(governorPhysicalTypeMetadata);
    // Getting entity
    final JavaType entity = controllerValues.getEntity();
    ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity);
    // Get entity metadata
    final String entityMetadataId = JpaEntityMetadata.createIdentifier(entityDetails);
    registerDependency(entityMetadataId, metadataIdentificationString);
    final JpaEntityMetadata entityMetadata = getMetadataService().get(entityMetadataId);
    // This metadata is not available yet.
    if (entityMetadata == null) {
        return null;
    }
    // Getting type
    ControllerType type = controllerValues.getType();
    // Getting related service
    ClassOrInterfaceTypeDetails serviceDetails = getServiceLocator().getService(entity);
    JavaType service = serviceDetails.getType();
    final String serviceMetadataId = ServiceMetadata.createIdentifier(serviceDetails);
    registerDependency(serviceMetadataId, metadataIdentificationString);
    final ServiceMetadata serviceMetadata = getMetadataService().get(serviceMetadataId);
    // This metadata is not available yet.
    if (serviceMetadata == null) {
        return null;
    }
    // Generate path
    final String path = getControllerOperations().getBasePathForController(governorPhysicalTypeMetadata.getMemberHoldingTypeDetails());
    final String baseUrl = getControllerOperations().getBaseUrlForController(governorPhysicalTypeMetadata.getMemberHoldingTypeDetails());
    List<RelationInfoExtended> detailsFieldInfo = null;
    String detailAnnotaionFieldValue = null;
    Map<JavaType, ServiceMetadata> detailsServiceMetadata = null;
    if (type == ControllerType.DETAIL || type == ControllerType.DETAIL_ITEM) {
        final JavaType controller = governorPhysicalTypeMetadata.getMemberHoldingTypeDetails().getName();
        // Getting the relationField from @RooDetail entity
        final AnnotationAttributeValue<Object> relationFieldAttr = governorPhysicalTypeMetadata.getMemberHoldingTypeDetails().getAnnotation(RooJavaType.ROO_DETAIL).getAttribute("relationField");
        Validate.notNull(relationFieldAttr, "ERROR: In %s controller, @RooDetail annotation must have relationField value", controller);
        detailAnnotaionFieldValue = (String) relationFieldAttr.getValue();
        Validate.isTrue(StringUtils.isNotBlank(detailAnnotaionFieldValue), "ERROR: In %s controller, @RooDetail annotation must have relationField value", controller);
        // generate detail info object
        detailsFieldInfo = getControllerOperations().getRelationInfoFor(entityMetadata, detailAnnotaionFieldValue);
        detailsServiceMetadata = new TreeMap<JavaType, ServiceMetadata>();
        for (RelationInfoExtended info : detailsFieldInfo) {
            if (detailsServiceMetadata.containsKey(info.childType)) {
                continue;
            }
            // Getting related service
            ClassOrInterfaceTypeDetails detailsServiceDetails = getServiceLocator().getService(info.childType);
            String detailServiceMetadataId = ServiceMetadata.createIdentifier(detailsServiceDetails);
            registerDependency(detailServiceMetadataId, metadataIdentificationString);
            ServiceMetadata curMetadata = getMetadataService().get(detailServiceMetadataId);
            if (curMetadata == null) {
                // Not ready for this metadata yet
                return null;
            }
            detailsServiceMetadata.put(info.childType, curMetadata);
            // Register dependency with related entity
            registerDependency(info.childEntityMetadata.getId(), metadataIdentificationString);
        }
    }
    Map<String, RelationInfoExtended> relationInfos = new HashMap<String, RelationInfoExtended>();
    for (String fieldName : entityMetadata.getRelationInfos().keySet()) {
        RelationInfoExtended info = getControllerOperations().getRelationInfoFor(entityMetadata, fieldName).get(0);
        if (info.childEntityMetadata == null) {
            // Not ready for this metadata yet
            return null;
        }
        relationInfos.put(fieldName, info);
    }
    return new ControllerMetadata(metadataIdentificationString, aspectName, controllerValues, governorPhysicalTypeMetadata, entity, entityMetadata, service, path, baseUrl, type, serviceMetadata, detailAnnotaionFieldValue, detailsServiceMetadata, detailsFieldInfo, relationInfos);
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ControllerType(org.springframework.roo.addon.web.mvc.controller.annotations.ControllerType) RooJavaType(org.springframework.roo.model.RooJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) ServiceMetadata(org.springframework.roo.addon.layers.service.addon.ServiceMetadata)

Example 4 with ServiceMetadata

use of org.springframework.roo.addon.layers.service.addon.ServiceMetadata in project spring-roo by spring-projects.

the class ThymeleafMetadata method getDeleteDetailMethod.

private MethodMetadata getDeleteDetailMethod() {
    RelationInfoExtended detailsInfo = controllerMetadata.getLastDetailsInfo();
    final ServiceMetadata detailsServiceMetadata = controllerMetadata.getServiceMetadataForEntity(detailsInfo.entityType);
    final MethodMetadata removeFromMethod = detailsServiceMetadata.getRemoveFromRelationMethods().get(detailsInfo);
    final FieldMetadata detailsServiceField = controllerMetadata.getDetailsServiceFields(detailsInfo.entityType);
    JavaSymbolName methodName = DELETE_METHOD_NAME;
    JavaSymbolName itemsName = detailsInfo.fieldMetadata.getFieldName();
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    parameterTypes.add(new AnnotatedJavaType(removeFromMethod.getParameterTypes().get(0).getJavaType(), ANN_METADATA_MODEL_ATTRIBUTE));
    parameterTypes.add(new AnnotatedJavaType(detailsInfo.childType, ANN_METADATA_MODEL_ATTRIBUTE));
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    // Adding annotations
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    // Adding @DeleteMapping annotation
    AnnotationMetadataBuilder postMappingAnnotation = new AnnotationMetadataBuilder(SpringJavaType.DELETE_MAPPING);
    postMappingAnnotation.addStringAttribute("name", methodName.getSymbolName());
    annotations.add(postMappingAnnotation);
    this.mvcMethodNames.put(methodName.getSymbolName(), methodName.getSymbolName());
    annotations.add(new AnnotationMetadataBuilder(SpringJavaType.RESPONSE_BODY));
    final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.add(removeFromMethod.getParameterNames().get(0));
    parameterNames.add(itemsName);
    // Generate body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // customerService.addToOrders(customer, order.getId());
    bodyBuilder.appendFormalLine("%s().%s(%s,%s.singleton(%s.%s()));", getAccessorMethod(detailsServiceField).getMethodName(), removeFromMethod.getMethodName(), removeFromMethod.getParameterNames().get(0), getNameOfJavaType(JavaType.COLLECTIONS), itemsName, detailsInfo.childEntityMetadata.getCurrentIdentifierAccessor().getMethodName());
    // return ResponseEntity.ok().build();
    bodyBuilder.appendFormalLine("return %s.ok().build();", getNameOfJavaType(RESPONSE_ENTITY));
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.wrapperWilcard(RESPONSE_ENTITY), parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    return methodBuilder.build();
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) ArrayList(java.util.ArrayList) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) MethodMetadataBuilder(org.springframework.roo.classpath.details.MethodMetadataBuilder) RelationInfoExtended(org.springframework.roo.addon.web.mvc.controller.addon.RelationInfoExtended) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder) ServiceMetadata(org.springframework.roo.addon.layers.service.addon.ServiceMetadata) AnnotationMetadataBuilder(org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)

Example 5 with ServiceMetadata

use of org.springframework.roo.addon.layers.service.addon.ServiceMetadata in project spring-roo by spring-projects.

the class ThymeleafMetadata method getListDatatablesByIdsInDetailMethod.

/**
 * This method provides detail datatablesByIdsIn list method using Thymeleaf
 * response type
 *
 * @return MethodMetadata
 */
private MethodMetadata getListDatatablesByIdsInDetailMethod() {
    RelationInfo detailsInfo = controllerMetadata.getLastDetailsInfo();
    final ServiceMetadata detailsServiceMetadata = controllerMetadata.getServiceMetadataForEntity(detailsInfo.childType);
    final MethodMetadata findAllByIdsInMethod = detailsServiceMetadata.getCurrentFindAllByIdsInWithGlobalSearchMethod();
    if (findAllByIdsInMethod == null) {
        return null;
    }
    final FieldMetadata detailsServiceField = controllerMetadata.getDetailsServiceFields(detailsInfo.childType);
    // Define methodName
    final JavaSymbolName methodName = LIST_DATATABLES_BY_IDS_IN_DETAILS_METHOD_NAME;
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    AnnotationMetadataBuilder requestParamIdsAnnotation = new AnnotationMetadataBuilder(REQUEST_PARAM);
    requestParamIdsAnnotation.addStringAttribute("value", "ids");
    parameterTypes.add(new AnnotatedJavaType(JavaType.wrapperOf(JavaType.LIST, findAllByIdsInMethod.getParameterTypes().get(0).getJavaType().getBaseType()), requestParamIdsAnnotation.build()));
    parameterTypes.add(DATATABLES_COLUMNS_PARAM);
    parameterTypes.add(GLOBAL_SEARCH_PARAM);
    parameterTypes.add(DATATABLES_PAGEABLE_PARAM);
    AnnotationMetadataBuilder requestParamAnnotation = new AnnotationMetadataBuilder(REQUEST_PARAM);
    requestParamAnnotation.addStringAttribute("value", "draw");
    parameterTypes.add(new AnnotatedJavaType(JavaType.INT_OBJECT, requestParamAnnotation.build()));
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.add(new JavaSymbolName("ids"));
    parameterNames.add(DATATABLES_COLUMNS_PARAM_NAME);
    parameterNames.add(new JavaSymbolName("search"));
    parameterNames.add(new JavaSymbolName("pageable"));
    parameterNames.add(new JavaSymbolName("draw"));
    // Adding annotations
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    // Adding @GetMapping annotation
    AnnotationMetadataBuilder getMappingAnnotation = new AnnotationMetadataBuilder(GET_MAPPING);
    getMappingAnnotation.addStringAttribute("name", methodName.getSymbolName());
    getMappingAnnotation.addEnumAttribute("produces", SPRINGLETS_DATATABLES, "MEDIA_TYPE");
    getMappingAnnotation.addStringAttribute("value", "/dtByIdsIn");
    annotations.add(getMappingAnnotation);
    this.mvcMethodNames.put(methodName.getSymbolName(), methodName.getSymbolName());
    // Adding @ResponseBody annotation
    annotations.add(RESPONSE_BODY_ANNOTATION);
    // Generating returnType
    final JavaType serviceReturnType = findAllByIdsInMethod.getReturnType();
    final JavaType dataReturnType = JavaType.wrapperOf(SpringletsJavaType.SPRINGLETS_CONVERTED_DATATABLES_DATA, serviceReturnType.getParameters().get(0));
    final JavaType returnType = JavaType.wrapperOf(RESPONSE_ENTITY, dataReturnType);
    // TODO
    // Add module dependency
    // getTypeLocationService().addModuleDependency(this.controller.getType().getModule(),
    // returnParameterTypes.get(i));
    // Generate body
    final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    final String itemsName = StringUtils.uncapitalize(detailsInfo.fieldName);
    // Page<CustomerOrder> orders =
    // customerOrderService.findByCustomer(customer, globalSearch,
    // pageable);
    bodyBuilder.newLine();
    bodyBuilder.appendFormalLine("%s %s = %s().%s(ids, search, pageable);", getNameOfJavaType(serviceReturnType), itemsName, getAccessorMethod(detailsServiceField).getMethodName(), findAllByIdsInMethod.getMethodName());
    final String totalVarName = "total" + StringUtils.capitalize(itemsName) + "Count";
    // long totalOrdersCount =
    // customerOrderService.countByCustomer(customer);
    bodyBuilder.appendFormalLine("long %s = %s.getTotalElements();", totalVarName, itemsName);
    // ConvertedDatatablesData<CustomerOrder> data = new
    // ConvertedDatatablesData<CustomerOrder>(orders,
    // totalOrdersCount, draw, conversionService, columns);
    bodyBuilder.appendFormalLine("%1$s data =  new %1$s(%2$s, %3$s, draw, %4$s(), %5$s);", getNameOfJavaType(dataReturnType), itemsName, totalVarName, getAccessorMethod(this.conversionServiceField).getMethodName(), DATATABLES_COLUMNS_PARAM_NAME);
    // return ResponseEntity.ok(data);
    bodyBuilder.appendFormalLine("return %s.ok(data);", getNameOfJavaType(SpringJavaType.RESPONSE_ENTITY));
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    return methodBuilder.build();
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) ArrayList(java.util.ArrayList) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) Jsr303JavaType(org.springframework.roo.model.Jsr303JavaType) JdkJavaType(org.springframework.roo.model.JdkJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) SpringletsJavaType(org.springframework.roo.model.SpringletsJavaType) JavaType(org.springframework.roo.model.JavaType) MethodMetadataBuilder(org.springframework.roo.classpath.details.MethodMetadataBuilder) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder) ServiceMetadata(org.springframework.roo.addon.layers.service.addon.ServiceMetadata) AnnotationMetadataBuilder(org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)

Aggregations

ServiceMetadata (org.springframework.roo.addon.layers.service.addon.ServiceMetadata)20 ArrayList (java.util.ArrayList)18 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)18 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)18 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)15 MethodMetadataBuilder (org.springframework.roo.classpath.details.MethodMetadataBuilder)15 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)15 InvocableMemberBodyBuilder (org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)15 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)15 JavaType (org.springframework.roo.model.JavaType)12 RelationInfo (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo)11 RelationInfoExtended (org.springframework.roo.addon.web.mvc.controller.addon.RelationInfoExtended)8 SpringJavaType (org.springframework.roo.model.SpringJavaType)8 Jsr303JavaType (org.springframework.roo.model.Jsr303JavaType)7 SpringletsJavaType (org.springframework.roo.model.SpringletsJavaType)7 JdkJavaType (org.springframework.roo.model.JdkJavaType)6 JpaEntityMetadata (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata)5 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)5 RooJavaType (org.springframework.roo.model.RooJavaType)4 HashMap (java.util.HashMap)3