Search in sources :

Example 6 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class ThymeleafMetadata method getCreateDetailsMethod.

/**
 * This method provides the "create" method for details association
 * relationship using Thymeleaf view response type
 *
 * @return MethodMetadata
 */
private MethodMetadata getCreateDetailsMethod() {
    RelationInfo detailsInfo = controllerMetadata.getLastDetailsInfo();
    final ServiceMetadata detailsServiceMetadata = controllerMetadata.getServiceMetadataForEntity(detailsInfo.entityType);
    final MethodMetadata setMethod = detailsServiceMetadata.getSetRelationMethods().get(detailsInfo);
    final FieldMetadata detailsServiceField = controllerMetadata.getDetailsServiceFields(detailsInfo.entityType);
    // Define methodName
    final JavaSymbolName methodName = CREATE_METHOD_NAME;
    JavaSymbolName itemsName = setMethod.getParameterNames().get(1);
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    parameterTypes.add(new AnnotatedJavaType(setMethod.getParameterTypes().get(0).getJavaType(), ANN_METADATA_MODEL_ATTRIBUTE));
    AnnotationMetadataBuilder requestParamAnnotation = new AnnotationMetadataBuilder(REQUEST_PARAM);
    requestParamAnnotation.addStringAttribute("value", itemsName.getSymbolName().concat("Ids"));
    requestParamAnnotation.addBooleanAttribute("required", false);
    JavaType identifierType = setMethod.getParameterTypes().get(1).getJavaType().getParameters().get(0);
    parameterTypes.add(new AnnotatedJavaType(JavaType.wrapperOf(JavaType.LIST, identifierType), requestParamAnnotation.build()));
    // Version parameter
    if (this.entityMetadata.getCurrentVersionField() != null) {
        AnnotationMetadataBuilder versionRequestParamAnnotation = new AnnotationMetadataBuilder(REQUEST_PARAM);
        versionRequestParamAnnotation.addStringAttribute("value", "parentVersion");
        parameterTypes.add(new AnnotatedJavaType(this.entityMetadata.getCurrentVersionField().getFieldType(), versionRequestParamAnnotation.build()));
        // Concurrency control parameter
        AnnotationMetadataBuilder concurrencyControlRequestParam = new AnnotationMetadataBuilder(REQUEST_PARAM);
        concurrencyControlRequestParam.addStringAttribute("value", "concurrency");
        concurrencyControlRequestParam.addBooleanAttribute("required", false);
        concurrencyControlRequestParam.addStringAttribute("defaultValue", "");
        parameterTypes.add(new AnnotatedJavaType(JavaType.STRING, concurrencyControlRequestParam.build()));
    }
    parameterTypes.add(AnnotatedJavaType.convertFromJavaType(SpringJavaType.MODEL));
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    // Adding annotations
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    // Adding @PostMapping annotation
    AnnotationMetadataBuilder postMappingAnnotation = new AnnotationMetadataBuilder(SpringJavaType.POST_MAPPING);
    postMappingAnnotation.addStringAttribute("name", methodName.getSymbolName());
    annotations.add(postMappingAnnotation);
    this.mvcMethodNames.put(methodName.getSymbolName(), methodName.getSymbolName());
    final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.addAll(setMethod.getParameterNames());
    parameterNames.add(VERSION_PARAM_NAME);
    parameterNames.add(new JavaSymbolName("concurrencyControl"));
    parameterNames.add(MODEL_PARAM_NAME);
    // Generate body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    /*
     * // Remove empty values for (Iterator<Long> iterator =
     * products.iterator(); iterator.hasNext();) { if (iterator.next() ==
     * null) { iterator.remove(); } }
     */
    bodyBuilder.appendFormalLine("// Remove empty values");
    // if(books != null){
    bodyBuilder.appendFormalLine("if (%s != null) {", itemsName);
    bodyBuilder.indent();
    bodyBuilder.appendFormalLine("for (%s<%s> iterator = %s.iterator(); iterator.hasNext();) {", getNameOfJavaType(JavaType.ITERATOR), getNameOfJavaType(identifierType), itemsName);
    bodyBuilder.indent();
    bodyBuilder.appendFormalLine("if (iterator.next() == null) {");
    bodyBuilder.indent();
    bodyBuilder.appendFormalLine("iterator.remove();");
    bodyBuilder.indentRemove();
    bodyBuilder.appendFormalLine("}");
    bodyBuilder.indentRemove();
    bodyBuilder.appendFormalLine("}");
    bodyBuilder.indentRemove();
    bodyBuilder.appendFormalLine("}");
    if (this.entityMetadata.getCurrentVersionField() != null) {
        // // Concurrency control
        bodyBuilder.appendFormalLine("// Concurrency control");
        JavaSymbolName parentName = setMethod.getParameterNames().get(0);
        // if(version != pet.getVersion() && StringUtils.isEmpty(concurrencyControl)){
        bodyBuilder.appendFormalLine("if(!%s.equals(%s, %s.%s()) && %s.isEmpty(concurrencyControl)){", getNameOfJavaType(JavaType.OBJECTS), VERSION_PARAM_NAME, parentName, getAccessorMethod(this.entityMetadata.getCurrentVersionField()).getMethodName(), getNameOfJavaType(new JavaType("org.apache.commons.lang3.StringUtils")));
        bodyBuilder.indent();
        // populateForm(model);
        bodyBuilder.appendFormalLine("populateForm(model);");
        // // Obtain the selected books and include them in the author that will be
        bodyBuilder.appendFormalLine("// Obtain the selected books and include them in the author that will be ");
        // // included in the view
        bodyBuilder.appendFormalLine("// included in the view");
        // if(books != null){
        bodyBuilder.appendFormalLine("if (%s != null) {", itemsName);
        bodyBuilder.indent();
        // author.setBooks(new HashSet<Book>(getBookService().findAll(books)));
        bodyBuilder.appendFormalLine("%s.%s(new %s<%s>(%s().findAll(%s)));", parentName, setMethod.getMethodName(), getNameOfJavaType(JavaType.HASH_SET), getNameOfJavaType(detailsInfo.childType), getAccessorMethod(controllerMetadata.getDetailsServiceFields(detailsInfo.childType)).getMethodName(), itemsName);
        bodyBuilder.indentRemove();
        bodyBuilder.appendFormalLine("}else{");
        bodyBuilder.indent();
        // author.setBooks(new HashSet<Book>());
        bodyBuilder.appendFormalLine("%s.%s(new %s<%s>());", parentName, setMethod.getMethodName(), getNameOfJavaType(JavaType.HASH_SET), getNameOfJavaType(detailsInfo.childType));
        bodyBuilder.indentRemove();
        bodyBuilder.appendFormalLine("}");
        // // Reset the version to prevent update
        bodyBuilder.appendFormalLine("// Reset the version to prevent update");
        // author.setVersion(version);
        bodyBuilder.appendFormalLine(" %s.setVersion(%s);", parentName, VERSION_PARAM_NAME);
        // // Include the updated author in the model
        bodyBuilder.appendFormalLine("// Include the updated element in the model");
        // model.addAttribute("author", author);
        bodyBuilder.appendFormalLine("model.addAttribute(\"%s\", %s);", parentName, parentName);
        // model.addAttribute("concurrency", true);
        bodyBuilder.appendFormalLine("model.addAttribute(\"concurrency\", true);");
        // return new ModelAndView("owners/pets/create");
        bodyBuilder.appendFormalLine("return new %s(\"%s/%s/create\");", getNameOfJavaType(SpringJavaType.MODEL_AND_VIEW), viewsPath, itemsName);
        bodyBuilder.indentRemove();
        // }else if(version != pet.getVersion() && "discard".equals(concurrencyControl)){
        bodyBuilder.appendFormalLine("}else if(!%s.equals(%s, %s.%s()) && \"discard\".equals(concurrencyControl)){", getNameOfJavaType(JavaType.OBJECTS), VERSION_PARAM_NAME, parentName, getAccessorMethod(this.entityMetadata.getCurrentVersionField()).getMethodName());
        bodyBuilder.indent();
        // populateForm(model);
        bodyBuilder.appendFormalLine("populateForm(model);");
        // // Provide the original author from the Database
        bodyBuilder.appendFormalLine("// Provide the original element from the Database");
        // model.addAttribute("author", author);
        bodyBuilder.appendFormalLine("model.addAttribute(\"%s\", %s);", parentName, parentName);
        // model.addAttribute("concurrency", false);
        bodyBuilder.appendFormalLine("model.addAttribute(\"concurrency\", false);");
        // return new ModelAndView("owners/pets/create");
        bodyBuilder.appendFormalLine("return new %s(\"%s/%s/create\");", getNameOfJavaType(SpringJavaType.MODEL_AND_VIEW), viewsPath, itemsName);
        bodyBuilder.indentRemove();
        bodyBuilder.appendFormalLine("}");
    }
    // categoryService.setProducts(category, products);
    bodyBuilder.appendFormalLine("%s().%s(%s,%s);", getAccessorMethod(detailsServiceField).getMethodName(), setMethod.getMethodName(), setMethod.getParameterNames().get(0), itemsName);
    // return new ModelAndView("redirect:" +
    // collectionLink.to("list").toUriString());
    bodyBuilder.appendFormalLine("return new %s(\"redirect:\" + %s().to(%s.LIST).toUriString());", getNameOfJavaType(SpringJavaType.MODEL_AND_VIEW), getAccessorMethod(this.collectionMethodLinkBuilderFactoryField).getMethodName(), getNameOfJavaType(relatedCollectionLinkFactory));
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, SpringJavaType.MODEL_AND_VIEW, 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)

Example 7 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class ThymeleafMetadata method getInitBinderMethod.

/**
 * Creates getInitBinderMethod method
 *
 * @return
 */
private MethodMetadata getInitBinderMethod(JavaType entity) {
    // Define methodName
    final JavaSymbolName methodName = new JavaSymbolName("init" + entity.getSimpleTypeName() + "Binder");
    // Define method parameter types and parameter names
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    parameterTypes.add(AnnotatedJavaType.convertFromJavaType(SpringJavaType.WEB_DATA_BINDER));
    List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.add(new JavaSymbolName("dataBinder"));
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    InvocableMemberBodyBuilder body = new InvocableMemberBodyBuilder();
    // dataBinder.setDisallowedFields("id");
    body.appendFormalLine("dataBinder.setDisallowedFields(\"%s\");", entityIdentifier);
    for (Pair<RelationInfo, JpaEntityMetadata> item : compositionRelationOneToOne) {
        body.appendFormalLine("dataBinder.setDisallowedFields(\"%s.%s\");", item.getKey().fieldName, item.getValue().getCurrentIndentifierField().getFieldName());
    }
    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, JavaType.VOID_PRIMITIVE, parameterTypes, parameterNames, body);
    // Adding annotation
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    // Adding @InitBinder annotation
    AnnotationMetadataBuilder getInitBinderAnnotation = new AnnotationMetadataBuilder(INIT_BINDER);
    getInitBinderAnnotation.addStringAttribute("value", StringUtils.uncapitalize(entity.getSimpleTypeName()));
    annotations.add(getInitBinderAnnotation);
    methodBuilder.setAnnotations(annotations);
    return methodBuilder.build();
}
Also used : 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) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) AnnotationMetadataBuilder(org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)

Example 8 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class JSONMetadata method getCreateMethod.

/**
 * This method provides the "create" method using JSON response type
 *
 * @param serviceSaveMethod
 *
 * @return MethodMetadata
 */
private MethodMetadata getCreateMethod() {
    // Define methodName
    final JavaSymbolName methodName = new JavaSymbolName("create");
    // Adding parameter types
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    parameterTypes.add(new AnnotatedJavaType(this.entity, ANN_METADATA_VALID, ANN_METADATA_REQUEST_BODY));
    parameterTypes.add(new AnnotatedJavaType(SpringJavaType.BINDING_RESULT));
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    // Adding parameter names
    final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.add(new JavaSymbolName(entityItemName));
    parameterNames.add(new JavaSymbolName("result"));
    // Adding annotations
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    // Adding @PostMapping annotation
    AnnotationMetadataBuilder postMappingAnnotation = new AnnotationMetadataBuilder(POST_MAPPING);
    postMappingAnnotation.addStringAttribute("name", methodName.getSymbolName());
    annotations.add(postMappingAnnotation);
    // Generate body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // Concurrency control
    if (entityMetadata.getCurrentVersionField() != null) {
        // if (customer.getId() != null || customer.getVersion() != null
        bodyBuilder.newLine();
        bodyBuilder.appendIndent();
        bodyBuilder.append("if (%s || %s", createNullExpression(entityMetadata.getCurrentIndentifierField()), createNullExpression(entityMetadata.getCurrentVersionField()));
        if (compositionRelationOneToOne.isEmpty()) {
            bodyBuilder.append(") {");
            bodyBuilder.newLine();
        } else {
            bodyBuilder.indent();
            bodyBuilder.indent();
            for (Pair<RelationInfo, JpaEntityMetadata> item : compositionRelationOneToOne) {
                JavaSymbolName versionFieldName = item.getRight().getCurrentVersionField().getFieldName();
                JavaSymbolName idFieldName = item.getRight().getCurrentIndentifierField().getFieldName();
                JavaSymbolName relationFieldName = item.getKey().fieldMetadata.getFieldName();
                // || (customer.getAddress() != null && (customer.getAddress().getId() != null || customer.getAddress().getVersion() != null))
                bodyBuilder.newLine();
                bodyBuilder.appendIndent();
                bodyBuilder.append("|| ( ");
                bodyBuilder.append("%1$s.get%2$s() != null && (%1$s.get%2$s().get%3$s() != null || %1$s.get%2$s().get%4$s() != null)", entityItemName, relationFieldName.getSymbolNameCapitalisedFirstLetter(), idFieldName.getSymbolNameCapitalisedFirstLetter(), versionFieldName.getSymbolNameCapitalisedFirstLetter());
                bodyBuilder.append(")");
            }
            bodyBuilder.append(") {");
            bodyBuilder.newLine();
            bodyBuilder.indentRemove();
            bodyBuilder.indentRemove();
        }
        bodyBuilder.indent();
        // return ResponseEntity.status(HttpStatus.CONFLICT).build();
        bodyBuilder.appendFormalLine("return %s.status(%s.CONFLICT).build();", getNameOfJavaType(RESPONSE_ENTITY), getNameOfJavaType(SpringJavaType.HTTP_STATUS));
        bodyBuilder.indentRemove();
        bodyBuilder.appendFormalLine("}");
    } else {
        // if (customer.getId() != null)
        bodyBuilder.newLine();
        bodyBuilder.appendIndent();
        bodyBuilder.append("if (%s", createNullExpression(entityMetadata.getCurrentIndentifierField()));
        if (compositionRelationOneToOne.isEmpty()) {
            bodyBuilder.append(") {");
            bodyBuilder.newLine();
        } else {
            bodyBuilder.indent();
            bodyBuilder.indent();
            for (Pair<RelationInfo, JpaEntityMetadata> item : compositionRelationOneToOne) {
                JavaSymbolName idFieldName = item.getRight().getCurrentIndentifierField().getFieldName();
                JavaSymbolName relationFieldName = item.getKey().fieldMetadata.getFieldName();
                // || (customer.getAddress() != null && (customer.getAddress().getId() != null || customer.getAddress().getVersion() != null))
                bodyBuilder.newLine();
                bodyBuilder.appendIndent();
                bodyBuilder.append("|| ( ");
                bodyBuilder.append("%1$s.get%2$s() != null && %1$s.get%2$s().get%3$s() != null", entityItemName, relationFieldName.getSymbolNameCapitalisedFirstLetter(), idFieldName.getSymbolNameCapitalisedFirstLetter());
                bodyBuilder.append(")");
            }
            bodyBuilder.append(") {");
            bodyBuilder.newLine();
            bodyBuilder.indentRemove();
            bodyBuilder.indentRemove();
        }
        bodyBuilder.indent();
        // return ResponseEntity.status(HttpStatus.CONFLICT).build();
        bodyBuilder.appendFormalLine("return %s.status(%s.CONFLICT).build();", getNameOfJavaType(RESPONSE_ENTITY), getNameOfJavaType(SpringJavaType.HTTP_STATUS));
        bodyBuilder.indentRemove();
        bodyBuilder.appendFormalLine("}");
    }
    // if (result.hasErrors()) {
    // return ResponseEntity.status(HttpStatus.CONFLICT).body(result);
    // }
    bodyBuilder.newLine();
    bodyBuilder.appendFormalLine("if (result.hasErrors()) {");
    bodyBuilder.indent();
    bodyBuilder.appendFormalLine("return %s.status(%s.CONFLICT).body(result);", getNameOfJavaType(RESPONSE_ENTITY), getNameOfJavaType(SpringJavaType.HTTP_STATUS));
    bodyBuilder.indentRemove();
    bodyBuilder.appendFormalLine("}");
    // Entity newEntity = entityService.saveMethodName(entity);
    bodyBuilder.newLine();
    bodyBuilder.appendFormalLine("%s new%s = %s().%s(%s);", getNameOfJavaType(entity), StringUtils.capitalize(entityItemName), getAccessorMethod(controllerMetadata.getServiceField()).getMethodName(), serviceMetadata.getCurrentSaveMethod().getMethodName(), entityItemName);
    // UriComponents showURI = CustomersItemJsonController.showURI(newCustomer);
    bodyBuilder.appendFormalLine("%s showURI = %s.%s(new%s);", getNameOfJavaType(SpringJavaType.URI_COMPONENTS), getNameOfJavaType(itemController), SHOW_URI_METHOD_NAME, StringUtils.capitalize(entityItemName));
    // return ResponseEntity.created(showURI.toUri()).build();
    bodyBuilder.newLine();
    bodyBuilder.appendFormalLine("return %s.created(showURI.toUri()).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 : 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) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata) AnnotationMetadataBuilder(org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)

Example 9 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class JSONMetadata method getAddToDetailsMethod.

private MethodMetadata getAddToDetailsMethod() {
    RelationInfo detailsInfo = controllerMetadata.getLastDetailsInfo();
    final ServiceMetadata detailsServiceMetadata = controllerMetadata.getServiceMetadataForEntity(detailsInfo.entityType);
    final MethodMetadata addToMethod = detailsServiceMetadata.getAddToRelationMethods().get(detailsInfo);
    final FieldMetadata detailsServiceField = controllerMetadata.getDetailsServiceFields(detailsInfo.entityType);
    // Define methodName
    final JavaSymbolName methodName = addToMethod.getMethodName();
    JavaSymbolName itemsName = addToMethod.getParameterNames().get(1);
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    parameterTypes.add(new AnnotatedJavaType(addToMethod.getParameterTypes().get(0).getJavaType(), ANN_MODEL_ATTRIBUTE));
    AnnotationMetadataBuilder pathVariableAnnotation = new AnnotationMetadataBuilder(SpringJavaType.PATH_VARIABLE);
    pathVariableAnnotation.addStringAttribute("value", itemsName.getSymbolName());
    parameterTypes.add(new AnnotatedJavaType(addToMethod.getParameterTypes().get(1).getJavaType().getParameters().get(0), pathVariableAnnotation.build()));
    MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
    if (existingMethod != null) {
        return existingMethod;
    }
    // Adding annotations
    final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
    // Adding @PostMapping annotation
    AnnotationMetadataBuilder postMappingAnnotation = new AnnotationMetadataBuilder(POST_MAPPING);
    postMappingAnnotation.addStringAttribute("name", methodName.getSymbolName());
    annotations.add(postMappingAnnotation);
    final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    parameterNames.addAll(addToMethod.getParameterNames());
    // Generate body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // customerService.addToOrders(customer, Collections.singleton(order));
    bodyBuilder.appendFormalLine("%s().%s(%s,%s.singleton(%s));", getAccessorMethod(detailsServiceField).getMethodName(), addToMethod.getMethodName(), addToMethod.getParameterNames().get(0), getNameOfJavaType(JavaType.COLLECTIONS), itemsName);
    // 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) 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)

Example 10 with RelationInfo

use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.

the class ThymeleafControllerIntegrationTestMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    final ThymeleafControllerIntegrationTestAnnotationValues annotationValues = new ThymeleafControllerIntegrationTestAnnotationValues(governorPhysicalTypeMetadata);
    // Get JSON controller target class
    final JavaType jsonController = annotationValues.getTargetClass();
    // Get the controller managed entity
    ClassOrInterfaceTypeDetails controllerCid = getTypeLocationService().getTypeDetails(jsonController);
    AnnotationMetadata rooControllerAnnotation = controllerCid.getAnnotation(RooJavaType.ROO_CONTROLLER);
    if (rooControllerAnnotation == null) {
        LOGGER.warning(String.format("Ignoring %s of %s as missing %s annotation in %s", ROO_THYMELEAF_CONTROLLER_INTEGRATION_TEST.getSimpleTypeName(), governorPhysicalTypeMetadata.getType().getFullyQualifiedTypeName(), RooJavaType.ROO_CONTROLLER.getSimpleTypeName(), jsonController.getSimpleTypeName()));
        return null;
    }
    Validate.notNull(rooControllerAnnotation.getAttribute("entity"), "The @RooController must have an 'entity' attribute, targeting managed entity.");
    final JavaType managedEntity = (JavaType) rooControllerAnnotation.getAttribute("entity").getValue();
    // Get the entity metadata
    String jpaEntityIdentifier = JpaEntityMetadata.createIdentifier(getTypeLocationService().getTypeDetails(managedEntity));
    JpaEntityMetadata entityMetadata = getMetadataService().get(jpaEntityIdentifier);
    if (entityMetadata == null) {
        return null;
    }
    // Get child related entities
    Collection<RelationInfo> relatioInfos = entityMetadata.getRelationInfos().values();
    Set<JavaType> relatedEntities = new TreeSet<JavaType>();
    // First, add managed entity
    relatedEntities.add(managedEntity);
    for (RelationInfo relationInfo : relatioInfos) {
        if (relationInfo.cardinality == Cardinality.ONE_TO_ONE && relationInfo.type == JpaRelationType.COMPOSITION) {
            // OneToOne composition is managed by owner's service
            continue;
        }
        relatedEntities.add(relationInfo.childType);
    }
    // Get the entity factory of managed entity
    final JavaType entityFactory = getJpaEntityFactoryLocator().getFirstJpaEntityFactoryForEntity(managedEntity);
    // Get the services related to managed entity
    List<JavaType> relatedServices = new ArrayList<JavaType>();
    for (JavaType entity : relatedEntities) {
        final ClassOrInterfaceTypeDetails serviceDetails = getServiceLocator().getFirstService(entity);
        if (serviceDetails == null) {
            LOGGER.warning(String.format("Couldn't find service of related entity %s in %s", entity.getSimpleTypeName(), this.getClass().getName()));
        } else {
            if (!relatedServices.contains(serviceDetails.getType())) {
                relatedServices.add(serviceDetails.getType());
            }
        }
    }
    return new ThymeleafControllerIntegrationTestMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, annotationValues, jsonController, managedEntity, entityFactory, relatedServices);
}
Also used : ArrayList(java.util.ArrayList) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) RelationInfo(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo) TreeSet(java.util.TreeSet) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) JpaEntityMetadata(org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata)

Aggregations

RelationInfo (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo)31 ArrayList (java.util.ArrayList)27 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)19 JpaEntityMetadata (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata)18 JavaType (org.springframework.roo.model.JavaType)18 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)17 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)16 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)15 InvocableMemberBodyBuilder (org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)14 MethodMetadataBuilder (org.springframework.roo.classpath.details.MethodMetadataBuilder)12 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)12 ServiceMetadata (org.springframework.roo.addon.layers.service.addon.ServiceMetadata)11 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)11 RooJavaType (org.springframework.roo.model.RooJavaType)11 Pair (org.apache.commons.lang3.tuple.Pair)8 JdkJavaType (org.springframework.roo.model.JdkJavaType)8 SpringJavaType (org.springframework.roo.model.SpringJavaType)8 Jsr303JavaType (org.springframework.roo.model.Jsr303JavaType)5 SpringletsJavaType (org.springframework.roo.model.SpringletsJavaType)5 HashMap (java.util.HashMap)4