Search in sources :

Example 81 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project spring-roo by spring-projects.

the class JpaOperationsImpl method getFieldChildPartOfCompositionRelation.

@Override
public Pair<FieldMetadata, RelationInfo> getFieldChildPartOfCompositionRelation(ClassOrInterfaceTypeDetails entityCdi) {
    JavaType domainType = entityCdi.getType();
    List<Pair<FieldMetadata, RelationInfo>> relations = getFieldChildPartOfRelation(entityCdi);
    if (relations.isEmpty()) {
        return null;
    }
    JpaEntityMetadata parent;
    JavaType parentType;
    RelationInfo info;
    List<Pair<FieldMetadata, RelationInfo>> compositionRelation = new ArrayList<Pair<FieldMetadata, RelationInfo>>();
    for (Pair<FieldMetadata, RelationInfo> field : relations) {
        if (field.getRight().type == JpaRelationType.COMPOSITION) {
            compositionRelation.add(field);
        }
    }
    Validate.isTrue(compositionRelation.size() <= 1, "Entity %s has more than one relations of composition as child part: ", domainType, StringUtils.join(getFieldNamesOfRelationList(compositionRelation), ","));
    if (compositionRelation.isEmpty()) {
        return null;
    }
    return compositionRelation.get(0);
}
Also used : JdkJavaType(org.springframework.roo.model.JdkJavaType) RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) ArrayList(java.util.ArrayList) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) Pair(org.apache.commons.lang3.tuple.Pair)

Example 82 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair 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 83 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project spring-roo by spring-projects.

the class RepositoryJpaCustomImplMetadata method buildQuery.

/**
 * Builds the search query
 *
 * @param bodyBuilder method body builder
 * @param entityVariable name of the variable that contains the Q entity
 * @param globalSearch global search variable name
 * @param referencedFieldParamName
 * @param referencedField
 * @param referencedFieldIdentifierPathName
 * @param formBeanType the JavaType which contains the fields to use for filtering.
 *            Can be null in findAll queries.
 * @param formBeanParameterName the name of the search param
 * @param returnType
 * @param finderName the name of the finder. Only available when method is a
 *            projection/DTO finder.
 * @param partTree
 */
private void buildQuery(InvocableMemberBodyBuilder bodyBuilder, String entityVariable, JavaSymbolName globalSearch, JavaSymbolName referencedFieldParamName, FieldMetadata referencedField, String referencedFieldIdentifierPathName, JavaType formBeanType, String formBeanParameterName, JavaType returnType, JavaSymbolName finderName, PartTree partTree) {
    // Prepare leftJoin for compositions oneToOne
    StringBuilder fetchJoins = new StringBuilder();
    for (RelationInfo relationInfo : entityMetadata.getRelationInfos().values()) {
        if (relationInfo.type == JpaRelationType.COMPOSITION && relationInfo.cardinality == Cardinality.ONE_TO_ONE) {
            fetchJoins.append(".leftJoin(");
            fetchJoins.append(entityVariable);
            fetchJoins.append(".");
            fetchJoins.append(relationInfo.fieldName);
            fetchJoins.append(")");
        }
    }
    // JPQLQuery query = from(qEntity);
    bodyBuilder.appendFormalLine(String.format("%s query = from(%s)%s;", getNameOfJavaType(getJPQLQueryFor(entity)), entityVariable, fetchJoins));
    bodyBuilder.newLine();
    if (formBeanType != null) {
        // Query for finder
        // if (formSearch != null) {
        bodyBuilder.appendFormalLine(String.format("if (%s != null) {", formBeanParameterName));
        if (partTree != null) {
            buildFormBeanFilterBody(bodyBuilder, formBeanType, formBeanParameterName, entityVariable, partTree);
        } else {
            // formBean is an entity, filter by all its fields
            for (Entry<String, FieldMetadata> field : this.typesFieldsMetadata.get(formBeanType).entrySet()) {
                // if (formSearch.getField() != null) {
                String accessorMethodName = BeanInfoUtils.getAccessorMethodName(field.getValue()).getSymbolName();
                bodyBuilder.appendIndent();
                bodyBuilder.appendFormalLine(String.format("if (%s.%s() != null) {", formBeanParameterName, accessorMethodName));
                // Get path field name from field mappings
                String pathFieldName = getValueOfPairFor(this.typesFieldMaps.get(formBeanType), field.getKey());
                // query.where(myEntity.field.eq(formBean.getField()));
                bodyBuilder.appendIndent();
                bodyBuilder.appendIndent();
                bodyBuilder.appendFormalLine(String.format("query.where(%s.eq(%s.%s()));", pathFieldName, formBeanParameterName, accessorMethodName));
                // }
                bodyBuilder.appendIndent();
                bodyBuilder.appendFormalLine("}");
            }
        }
        // }
        bodyBuilder.appendFormalLine("}");
        bodyBuilder.newLine();
    } else if (referencedFieldParamName != null && referencedFieldIdentifierPathName != null) {
        // Query for reference
        // Assert.notNull(referenced, "referenced is required");
        bodyBuilder.appendFormalLine(String.format("%s.notNull(%s, \"%s is required\");", SpringJavaType.ASSERT.getNameIncludingTypeParameters(false, importResolver), referencedFieldParamName, referencedFieldParamName));
        bodyBuilder.newLine();
        // Query should include a where clause
        if (referencedField.getAnnotation(JpaJavaType.MANY_TO_MANY) != null) {
            // query.where(referencedFieldPath.contains(referencedFieldName));
            bodyBuilder.appendFormalLine(String.format("query.where(%s.contains(%s));", referencedFieldIdentifierPathName, referencedFieldParamName));
        } else {
            // query.where(referencedFieldPath.eq(referencedFieldName));
            bodyBuilder.appendFormalLine(String.format("query.where(%s.eq(%s));", referencedFieldIdentifierPathName, referencedFieldParamName));
        }
    }
    // Path<?>[] paths = new Path[] { .... };
    bodyBuilder.appendIndent();
    final String pathType = getNameOfJavaType(QUERYDSL_PATH);
    bodyBuilder.append(String.format("%s<?>[] paths = new %s<?>[] {", pathType, pathType));
    List<String> toAppend = new ArrayList<String>();
    // ... returnType.field1, returnType.field2);
    if (!this.typesAreProjections.get(returnType)) {
        // Return type is the same entity
        Map<String, FieldMetadata> projectionFields = this.typesFieldsMetadata.get(returnType);
        Iterator<Entry<String, FieldMetadata>> iterator = projectionFields.entrySet().iterator();
        while (iterator.hasNext()) {
            Entry<String, FieldMetadata> field = iterator.next();
            String fieldName = field.getValue().getFieldName().getSymbolName();
            toAppend.add(entityVariable + "." + fieldName);
        }
    } else {
        // Return type is a projection
        List<Pair<String, String>> projectionFields = this.typesFieldMaps.get(returnType);
        Validate.notNull(projectionFields, "Couldn't get projection fields for %s", this.defaultReturnType);
        Iterator<Pair<String, String>> iterator = projectionFields.iterator();
        while (iterator.hasNext()) {
            Entry<String, String> entry = iterator.next();
            toAppend.add(entry.getValue());
        }
    }
    bodyBuilder.append(StringUtils.join(toAppend, ','));
    bodyBuilder.append("};");
    bodyBuilder.newLine();
    // applyGlobalSearch(search, query, paths);
    bodyBuilder.appendFormalLine("applyGlobalSearch(globalSearch, query, paths);");
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) ToStringBuilder(org.apache.commons.lang3.builder.ToStringBuilder) ArrayList(java.util.ArrayList) Entry(java.util.Map.Entry) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) Pair(org.apache.commons.lang3.tuple.Pair)

Example 84 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project spring-roo by spring-projects.

the class RepositoryJpaCustomImplMetadata method getFindAllByIdsInImpl.

/**
 * Method that generates the findAllByIdsIn implementation method
 * @param findAllByIdsInGlobalSearchMethod
 * @param ids the entity id fields
 * @param fields the entity fields to search for
 *
 * @return
 */
private MethodMetadata getFindAllByIdsInImpl(MethodMetadata findAllByIdsInGlobalSearchMethod, FieldMetadata idField, List<FieldMetadata> fields) {
    // Define method name
    JavaSymbolName methodName = findAllByIdsInGlobalSearchMethod.getMethodName();
    // Define method parameter types
    List<AnnotatedJavaType> parameterTypes = findAllByIdsInGlobalSearchMethod.getParameterTypes();
    // Define method parameter names
    List<JavaSymbolName> parameterNames = findAllByIdsInGlobalSearchMethod.getParameterNames();
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    // Use provided findAll method to generate its implementation
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, findAllByIdsInGlobalSearchMethod.getMethodName(), findAllByIdsInGlobalSearchMethod.getReturnType(), findAllByIdsInGlobalSearchMethod.getParameterTypes(), findAllByIdsInGlobalSearchMethod.getParameterNames(), null);
    // Generate body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // Getting variable name to use in the code
    JavaSymbolName globalSearch = parameterNames.get(1);
    JavaSymbolName pageable = parameterNames.get(2);
    String entity = this.entity.getSimpleTypeName();
    String entityVariable = StringUtils.uncapitalize(entity);
    // Types to import
    JavaType projection = QUERYDSL_PROJECTIONS;
    bodyBuilder.newLine();
    // QEntity qEntity = QEntity.entity;
    bodyBuilder.appendFormalLine(String.format("%1$s %2$s = %1$s.%2$s;", entityQtype.getNameIncludingTypeParameters(false, importResolver), entityVariable));
    bodyBuilder.newLine();
    // Construct query
    buildQuery(bodyBuilder, entityVariable, globalSearch, null, null, null, null, null, this.defaultReturnType, null, null);
    bodyBuilder.newLine();
    bodyBuilder.appendFormalLine("// Also, filter by the provided ids");
    bodyBuilder.appendFormalLine("query.where(%s.%s.in(ids));", entityVariable, idField.getFieldName());
    bodyBuilder.newLine();
    // AttributeMappingBuilder mapping = buildMapper()
    StringBuffer mappingBuilderLine = new StringBuffer();
    mappingBuilderLine.append(String.format("%s mapping = buildMapper()", getNameOfJavaType(SpringletsJavaType.SPRINGLETS_QUERYDSL_REPOSITORY_SUPPORT_ATTRIBUTE_BUILDER)));
    if (!this.typesAreProjections.get(this.defaultReturnType)) {
        // Return type is the same entity
        Iterator<FieldMetadata> iterator = fields.iterator();
        while (iterator.hasNext()) {
            FieldMetadata field = iterator.next();
            String fieldName = field.getFieldName().getSymbolName();
            mappingBuilderLine.append(String.format("\n\t\t\t.map(%s, %s.%s)", getConstantForField(fieldName).getFieldName(), entityVariable, fieldName));
        }
    } else {
        // Return type is a projection
        List<Pair<String, String>> projectionFields = this.typesFieldMaps.get(this.defaultReturnType);
        Iterator<Pair<String, String>> iterator = projectionFields.iterator();
        while (iterator.hasNext()) {
            Entry<String, String> entry = iterator.next();
            mappingBuilderLine.append(String.format("\n\t\t\t.map(%s, %s)", getConstantForField(entry.getKey()).getFieldName(), entry.getValue()));
        }
    }
    mappingBuilderLine.append(";");
    bodyBuilder.appendFormalLine(mappingBuilderLine.toString());
    bodyBuilder.newLine();
    // applyPagination(pageable, query, mapping);
    bodyBuilder.appendFormalLine(String.format("applyPagination(%s, query, mapping);", pageable));
    // applyOrderById(query);
    bodyBuilder.appendFormalLine("applyOrderById(query);");
    bodyBuilder.newLine();
    buildQueryResult(bodyBuilder, pageable, entityVariable, projection, this.defaultReturnType);
    // Sets body to generated method
    methodBuilder.setBodyBuilder(bodyBuilder);
    // Build and return a MethodMetadata
    return methodBuilder.build();
// instance
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) SpringletsJavaType(org.springframework.roo.model.SpringletsJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) MethodMetadataBuilder(org.springframework.roo.classpath.details.MethodMetadataBuilder) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder) Pair(org.apache.commons.lang3.tuple.Pair)

Example 85 with Pair

use of org.apache.beam.repackaged.core.org.apache.commons.lang3.tuple.Pair in project spring-roo by spring-projects.

the class RepositoryJpaCustomImplMetadata method getCustomFindersImpl.

/**
 * Method that generates implementation methods for each finder which return type
 * is a projection or argument is a DTO.
 *
 * @param methodInfo
 * @return
 */
private MethodMetadata getCustomFindersImpl(Pair<MethodMetadata, PartTree> methodInfo, List<FieldMetadata> fields) {
    MethodMetadata method = methodInfo.getLeft();
    // Define method name
    JavaSymbolName methodName = method.getMethodName();
    // Define method parameter types
    List<AnnotatedJavaType> parameterTypes = method.getParameterTypes();
    // Define method parameter names
    List<JavaSymbolName> parameterNames = method.getParameterNames();
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    // Generate body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // Getting variable name to use in the code
    JavaSymbolName globalSearch = getParameterNameFor(method, SpringletsJavaType.SPRINGLETS_GLOBAL_SEARCH);
    JavaSymbolName pageable = getParameterNameFor(method, SpringJavaType.PAGEABLE);
    String entity = this.entity.getSimpleTypeName();
    String entityVariable = StringUtils.uncapitalize(entity);
    JavaType finderParamType = parameterTypes.get(0).getJavaType();
    String finderParamName = parameterNames.get(0).getSymbolName();
    // Types to import
    JavaType returnType = getDomainTypeOfFinderMethod(method);
    bodyBuilder.newLine();
    // QEntity qEntity = QEntity.entity;
    bodyBuilder.appendFormalLine(String.format("%1$s %2$s = %1$s.%2$s;", getNameOfJavaType(entityQtype), entityVariable));
    bodyBuilder.newLine();
    // Construct query
    buildQuery(bodyBuilder, entityVariable, globalSearch, null, null, null, finderParamType, finderParamName, returnType, method.getMethodName(), methodInfo.getRight());
    bodyBuilder.newLine();
    // AttributeMappingBuilder mapping = buildMapper()
    StringBuffer mappingBuilderLine = new StringBuffer();
    mappingBuilderLine.append(String.format("%s mapping = buildMapper()", getNameOfJavaType(SpringletsJavaType.SPRINGLETS_QUERYDSL_REPOSITORY_SUPPORT_ATTRIBUTE_BUILDER)));
    // .map(entiyVarName, varName) ...
    if (!this.typesAreProjections.get(returnType)) {
        // Return type is the same entity
        Iterator<FieldMetadata> iterator = fields.iterator();
        while (iterator.hasNext()) {
            FieldMetadata field = iterator.next();
            String fieldName = field.getFieldName().getSymbolName();
            mappingBuilderLine.append(String.format("\n\t\t\t.map(%s, %s.%s)", getConstantForField(fieldName).getFieldName(), entityVariable, fieldName));
        }
    } else {
        // Return type is a projection
        List<Pair<String, String>> projectionFields = this.typesFieldMaps.get(returnType);
        Iterator<Pair<String, String>> iterator = projectionFields.iterator();
        while (iterator.hasNext()) {
            Entry<String, String> entry = iterator.next();
            mappingBuilderLine.append(String.format("\n\t\t\t.map(%s, %s)", getConstantForField(entry.getKey()).getFieldName(), entry.getValue()));
        }
    }
    mappingBuilderLine.append(";");
    bodyBuilder.appendFormalLine(mappingBuilderLine.toString());
    bodyBuilder.newLine();
    // applyPagination(pageable, query, mapping);
    bodyBuilder.appendFormalLine(String.format("applyPagination(%s, query, mapping);", pageable));
    // applyOrderById(query);
    bodyBuilder.appendFormalLine("applyOrderById(query);");
    bodyBuilder.newLine();
    buildQueryResult(bodyBuilder, pageable, entityVariable, QUERYDSL_PROJECTIONS, returnType);
    // Use provided finder method to generate its implementation
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, methodInfo.getLeft().getReturnType(), parameterTypes, parameterNames, bodyBuilder);
    return methodBuilder.build();
}
Also used : FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) SpringletsJavaType(org.springframework.roo.model.SpringletsJavaType) JpaJavaType(org.springframework.roo.model.JpaJavaType) JavaType(org.springframework.roo.model.JavaType) MethodMetadataBuilder(org.springframework.roo.classpath.details.MethodMetadataBuilder) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

Pair (org.apache.commons.lang3.tuple.Pair)685 ArrayList (java.util.ArrayList)209 List (java.util.List)154 Test (org.junit.Test)150 ImmutablePair (org.apache.commons.lang3.tuple.ImmutablePair)142 HashMap (java.util.HashMap)123 Collectors (java.util.stream.Collectors)123 Map (java.util.Map)112 Message (com.microsoft.azure.sdk.iot.device.Message)71 IOException (java.io.IOException)70 MutablePair (org.apache.commons.lang3.tuple.MutablePair)64 java.util (java.util)55 IotHubTransportMessage (com.microsoft.azure.sdk.iot.device.transport.IotHubTransportMessage)52 Set (java.util.Set)49 StringUtils (org.apache.commons.lang3.StringUtils)48 File (java.io.File)46 Optional (java.util.Optional)45 Arrays (java.util.Arrays)44 HashSet (java.util.HashSet)40 Test (org.junit.jupiter.api.Test)39