use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.
the class ControllerOperationsImpl method createOrUpdateDetailControllerForEntity.
@Override
public void createOrUpdateDetailControllerForEntity(JavaType entity, String relationField, ControllerMVCResponseService responseType, JavaPackage controllerPackage, String viewsList) {
// Getting entity details to obtain information about it
ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity);
AnnotationMetadata entityAnnotation = entityDetails.getAnnotation(RooJavaType.ROO_JPA_ENTITY);
if (entityAnnotation == null) {
LOGGER.log(Level.INFO, String.format("ERROR: The provided class %s is not a valid entity. It should be annotated with @RooJpaEntity", entity.getSimpleTypeName()));
return;
}
// Check controllersPackage value
if (controllerPackage == null) {
controllerPackage = getDefaultControllerPackage();
if (controllerPackage == null) {
return;
}
}
boolean existsBasicControllers = false;
String pathPrefixController = "";
Collection<ClassOrInterfaceTypeDetails> itemControllers = getControllerLocator().getControllers(entity, ControllerType.ITEM);
for (ClassOrInterfaceTypeDetails existingController : itemControllers) {
if (existingController.getType().getPackage().equals(controllerPackage)) {
ControllerAnnotationValues values = new ControllerAnnotationValues(existingController);
AnnotationMetadata responseTypeAnnotation = existingController.getAnnotation(responseType.getAnnotation());
if (responseTypeAnnotation != null) {
pathPrefixController = values.getPathPrefix();
existsBasicControllers = true;
break;
}
}
}
if (!existsBasicControllers) {
LOGGER.log(Level.INFO, String.format("INFO: Doesn't exist parent controller in the package %s with the response type %s for the entity %s. Please, use 'web mvc controller' command to create them.", controllerPackage, responseType.getName(), entity.getSimpleTypeName()));
return;
}
JpaEntityMetadata entityMetadata = getMetadataService().get(JpaEntityMetadata.createIdentifier(entityDetails));
List<Pair<String, List<RelationInfoExtended>>> relationsToAdd = new ArrayList<Pair<String, List<RelationInfoExtended>>>();
if (StringUtils.isNotBlank(relationField)) {
// Check field received as parameter
List<RelationInfoExtended> infos = getRelationInfoFor(entityMetadata, relationField);
// TODO support multilevel detail (TO BE ANALIZED)
if (infos.size() > 1) {
LOGGER.log(Level.INFO, "ERROR: multi-level details not supported.");
return;
}
StringBuilder sbuilder = new StringBuilder();
for (int i = 0; i < infos.size(); i++) {
RelationInfoExtended info = infos.get(i);
sbuilder.append(info.fieldName);
if (!(info.cardinality == Cardinality.ONE_TO_MANY || info.cardinality == Cardinality.MANY_TO_MANY)) {
LOGGER.log(Level.INFO, String.format("ERROR: %s.%s is not a one-to-many or many-to-many relationships.", info.entityType.getFullyQualifiedTypeName(), info.fieldName));
return;
}
// Check than previous level details has been created before
if (i < infos.size() - 2) {
if (!checkDetailControllerExists(entity, responseType, controllerPackage, pathPrefixController, sbuilder.toString())) {
LOGGER.log(Level.INFO, String.format("ERROR: Detail controller for entity %s and detail field %s must be created before generate %s controller.", entity, sbuilder.toString(), relationField));
return;
}
}
}
relationsToAdd.add(Pair.of(relationField, infos));
} else {
for (RelationInfo info : entityMetadata.getRelationInfos().values()) {
if (info.cardinality == Cardinality.ONE_TO_MANY || info.cardinality == Cardinality.MANY_TO_MANY) {
// Check that is not already generated controller
if (!checkDetailControllerExists(entity, responseType, controllerPackage, pathPrefixController, info.fieldName)) {
relationsToAdd.add(Pair.of(info.fieldName, getRelationInfoFor(entityMetadata, info.fieldName)));
}
}
}
}
if (relationsToAdd.isEmpty()) {
LOGGER.log(Level.INFO, String.format("INFO: none relation found to generate detail controllers for entity '%s'.", entity.getSimpleTypeName()));
return;
}
for (Pair<String, List<RelationInfoExtended>> relation : relationsToAdd) {
boolean generated = createDetailClass(relation.getLeft(), entity, responseType, controllerPackage, pathPrefixController, viewsList);
RelationInfo lastRelation = relation.getRight().get(relation.getRight().size() - 1);
if (generated && lastRelation.type == JpaRelationType.COMPOSITION) {
createDetailsItemClass(relation.getLeft(), entity, responseType, controllerPackage, pathPrefixController, viewsList);
}
}
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.
the class ControllerOperationsImpl method getBaseUrlForController.
@Override
public String getBaseUrlForController(ClassOrInterfaceTypeDetails controller) {
Validate.notNull(controller, "controller is required");
Validate.notNull(controller.getAnnotation(RooJavaType.ROO_CONTROLLER), "%s must be annotated with @%s", controller.getType(), RooJavaType.ROO_CONTROLLER.getSimpleTypeName());
ControllerAnnotationValues values = new ControllerAnnotationValues(controller);
StringBuilder sbuilder = getBasePathStringBuilder(controller, values);
final JavaType entity = values.getEntity();
if (values.getType() == ControllerType.COLLECTION) {
return sbuilder.toString();
} else if (values.getType() == ControllerType.ITEM) {
return sbuilder.append("/{").append(StringUtils.uncapitalize(entity.getSimpleTypeName())).append("}").toString();
} else if (values.getType() == ControllerType.SEARCH) {
return sbuilder.append("/search").toString();
}
Validate.isTrue(values.getType() == ControllerType.DETAIL || values.getType() == ControllerType.DETAIL_ITEM, "Unsupported @%s.type '%s' on %s", RooJavaType.ROO_CONTROLLER, values.getType(), controller.getType());
// Getting the relationField from @RooDetail entity
final AnnotationAttributeValue<Object> relationFieldAttr = controller.getAnnotation(RooJavaType.ROO_DETAIL).getAttribute("relationField");
final String detailAnnotaionFieldValue = (String) relationFieldAttr.getValue();
Validate.notNull(relationFieldAttr, "ERROR: In %s controller, @RooDetail annotation must have relationField value", controller.getType());
List<RelationInfoExtended> detailsFieldInfo = getRelationInfoFor(entity, detailAnnotaionFieldValue);
Validate.isTrue(detailsFieldInfo != null & detailsFieldInfo.size() > 0, "Missing details information for %s", controller.getType());
for (RelationInfo info : detailsFieldInfo) {
sbuilder.append("/{").append(StringUtils.uncapitalize(info.entityType.getSimpleTypeName())).append("}/").append(info.fieldName);
}
if (values.getType() == ControllerType.DETAIL_ITEM) {
sbuilder.append("/{").append(detailsFieldInfo.get(detailsFieldInfo.size() - 1).fieldName).append("}");
}
return sbuilder.toString();
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.
the class ControllerOperationsImpl method getParentAndChildrenRelatedEntities.
private List<JavaType> getParentAndChildrenRelatedEntities(JavaType currentEntity) {
// Get related entities
ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(currentEntity);
JpaEntityMetadata entityMetadata = getMetadataService().get(JpaEntityMetadata.createIdentifier(entityDetails));
List<JavaType> entitiesToCreateSerializers = new ArrayList<JavaType>();
entitiesToCreateSerializers.add(currentEntity);
// Get related child entities
for (RelationInfo info : entityMetadata.getRelationInfos().values()) {
// One-To-One composition child entities doesn't need deserializers
if (info.type == JpaRelationType.COMPOSITION && info.cardinality == Cardinality.ONE_TO_ONE) {
continue;
}
// Need serializer
if (!entitiesToCreateSerializers.contains(info.childType)) {
entitiesToCreateSerializers.add(info.childType);
}
}
// We need as well to get related parent entities
for (FieldMetadata parentEntityField : entityMetadata.getRelationsAsChild().values()) {
JavaType parentEntity = null;
if (parentEntityField.getFieldType().isCommonCollectionType()) {
// Get wrappedType
parentEntity = parentEntityField.getFieldType().getBaseType();
} else {
parentEntity = parentEntityField.getFieldType();
}
// Add parent entity to list
if (!entitiesToCreateSerializers.contains(parentEntity)) {
entitiesToCreateSerializers.add(parentEntity);
}
}
return entitiesToCreateSerializers;
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.
the class JSONMetadata method getListDetailsMethod.
private MethodMetadata getListDetailsMethod() {
RelationInfo detailsInfo = controllerMetadata.getLastDetailsInfo();
final ServiceMetadata detailsServiceMetadata = controllerMetadata.getServiceMetadataForEntity(detailsInfo.childType);
final MethodMetadata findAllMethod = detailsServiceMetadata.getRefencedFieldFindAllDefinedMethod(detailsInfo.mappedBy);
final FieldMetadata detailsServiceField = controllerMetadata.getDetailsServiceFields(detailsInfo.childType);
// Define methodName
final JavaSymbolName methodName = new JavaSymbolName("list" + StringUtils.capitalize(detailsInfo.fieldName));
List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
parameterTypes.add(new AnnotatedJavaType(findAllMethod.getParameterTypes().get(0).getJavaType(), ANN_MODEL_ATTRIBUTE));
parameterTypes.add(new AnnotatedJavaType(SpringletsJavaType.SPRINGLETS_GLOBAL_SEARCH));
parameterTypes.add(new AnnotatedJavaType(SpringJavaType.PAGEABLE));
MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
if (existingMethod != null) {
return existingMethod;
}
final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
final JavaSymbolName parentParamName = findAllMethod.getParameterNames().get(0);
parameterNames.add(parentParamName);
parameterNames.add(GLOBAL_SEARCH_NAME);
parameterNames.add(PAGEABLE_PARAM_NAME);
// Adding annotations
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
// Adding @GetMapping annotation
AnnotationMetadataBuilder getMappingAnnotation = new AnnotationMetadataBuilder(GET_MAPPING);
getMappingAnnotation.addStringAttribute("name", methodName.getSymbolName());
annotations.add(getMappingAnnotation);
// Generating returnType
JavaType serviceReturnType = findAllMethod.getReturnType();
JavaType returnType = JavaType.wrapperOf(RESPONSE_ENTITY, serviceReturnType);
// TODO
// Add module dependency
// getTypeLocationService().addModuleDependency(this.controller.getType().getModule(),
// returnParameterTypes.get(i));
// Generate body
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
final String itemNames = StringUtils.uncapitalize(detailsInfo.fieldName);
// Page<Customer> customers = customerService.findAll(globalSearch, pageable);
bodyBuilder.newLine();
bodyBuilder.appendFormalLine("%s %s = %s().%s(%s, %s, %s);", getNameOfJavaType(serviceReturnType), itemNames, getAccessorMethod(detailsServiceField).getMethodName(), findAllMethod.getMethodName(), parentParamName, GLOBAL_SEARCH_NAME, PAGEABLE_PARAM_NAME);
// return ResponseEntity.ok(customers);
bodyBuilder.appendFormalLine(String.format("return %s.ok(%s);", getNameOfJavaType(RESPONSE_ENTITY), itemNames));
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, parameterTypes, parameterNames, bodyBuilder);
methodBuilder.setAnnotations(annotations);
return methodBuilder.build();
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo in project spring-roo by spring-projects.
the class JSONMetadata method getUpdateMethod.
/**
* This method provides the "update" method using JSON response type
*
* @return MethodMetadata
*/
private MethodMetadata getUpdateMethod() {
// Define methodName
final JavaSymbolName methodName = new JavaSymbolName("update");
// Define parameters
List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
parameterTypes.add(new AnnotatedJavaType(this.entity, ANN_MODEL_ATTRIBUTE));
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;
}
final List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
final String storedName = "stored".concat(this.entity.getSimpleTypeName());
parameterNames.add(new JavaSymbolName(storedName));
parameterNames.add(new JavaSymbolName(entityItemName));
parameterNames.add(new JavaSymbolName("result"));
// Adding annotations
final List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();
// Adding @PutMapping annotation
AnnotationMetadataBuilder putMappingAnnotation = new AnnotationMetadataBuilder(PUT_MAPPING);
putMappingAnnotation.addStringAttribute("name", methodName.getSymbolName());
annotations.add(putMappingAnnotation);
// Generate body
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
// if (result.hasErrors()) {
// return new 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("}");
// customer.setId(storedCustomer.getId());
bodyBuilder.appendFormalLine("%s.set%s(%s.get%s());", entityItemName, StringUtils.capitalize(entityIdentifier), storedName, StringUtils.capitalize(entityIdentifier));
for (Pair<RelationInfo, JpaEntityMetadata> item : compositionRelationOneToOne) {
// customer.getAddress().setId(storedCustomer.getAddress().getId());
JavaSymbolName relationField = item.getLeft().fieldMetadata.getFieldName();
JavaSymbolName relatedEntityIdentifier = item.getRight().getCurrentIndentifierField().getFieldName();
bodyBuilder.appendFormalLine("%1$s.get%2$s().set%3$s(%4$s.get%2$s().get%3$s());", entityItemName, relationField.getSymbolNameCapitalisedFirstLetter(), relatedEntityIdentifier.getSymbolNameCapitalisedFirstLetter(), storedName);
}
// customerService.save(customer);
bodyBuilder.appendFormalLine("%s().save(%s);", getAccessorMethod(controllerMetadata.getServiceField()).getMethodName(), entityItemName);
// 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();
}
Aggregations