use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata 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 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();
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata in project spring-roo by spring-projects.
the class JSONMetadata method getUpdateDetailMethod.
private MethodMetadata getUpdateDetailMethod() {
// Define methodName
final JavaSymbolName methodName = new JavaSymbolName("update");
final RelationInfoExtended info = controllerMetadata.getLastDetailsInfo();
final JavaType parentEntity = info.entityType;
final JavaType entity = info.childType;
final JpaEntityMetadata entityMetadata = info.childEntityMetadata;
final FieldMetadata entityIdentifier = entityMetadata.getCurrentIndentifierField();
final String entityItemName = StringUtils.uncapitalize(entity.getSimpleTypeName());
final ServiceMetadata serviceMetadata = controllerMetadata.getServiceMetadataForEntity(entity);
// Define parameters
final List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
parameterTypes.add(new AnnotatedJavaType(parentEntity, ANN_MODEL_ATTRIBUTE));
parameterTypes.add(new AnnotatedJavaType(entity, ANN_MODEL_ATTRIBUTE));
parameterTypes.add(new AnnotatedJavaType(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(entity.getSimpleTypeName());
parameterNames.add(new JavaSymbolName(StringUtils.uncapitalize(parentEntity.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("}");
// orderDetail.setId(storedOrderDetails.getId());
bodyBuilder.appendFormalLine("%s.set%s(%s.get%s());", entityItemName, entityIdentifier.getFieldName().getSymbolNameCapitalisedFirstLetter(), storedName, entityIdentifier.getFieldName().getSymbolNameCapitalisedFirstLetter());
// customerService.save(customer);
bodyBuilder.appendFormalLine("%s().%s(%s);", getAccessorMethod(controllerMetadata.getLastDetailServiceField()).getMethodName(), serviceMetadata.getCurrentSaveMethod().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();
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata in project spring-roo by spring-projects.
the class JSONMetadataProviderImpl method getMetadata.
@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
final JSONAnnotationValues annotationValues = new JSONAnnotationValues(governorPhysicalTypeMetadata);
ClassOrInterfaceTypeDetails controllerDetail = governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
// Getting controller metadata
final String controllerMetadataKey = ControllerMetadata.createIdentifier(controllerDetail);
final ControllerMetadata controllerMetadata = getMetadataService().get(controllerMetadataKey);
// This metadata is not available yet.
if (controllerMetadata == null) {
return null;
}
// Getting entity and check if is a readOnly entity or not
final JavaType entity = controllerMetadata.getEntity();
JavaType itemController = null;
if (controllerMetadata.getType() != ControllerType.ITEM) {
// Locate ItemController
Collection<ClassOrInterfaceTypeDetails> itemControllers = getControllerLocator().getControllers(entity, ControllerType.ITEM, RooJavaType.ROO_JSON);
if (itemControllers.isEmpty()) {
// We can't create metadata "Jet"
return null;
} else {
// Get controller with the same package
JavaPackage controllerPackage = controllerDetail.getType().getPackage();
for (ClassOrInterfaceTypeDetails controller : itemControllers) {
if (controllerPackage.equals(controller.getType().getPackage())) {
itemController = controller.getType();
break;
}
}
Validate.notNull(itemController, "ERROR: Can't find ITEM-type controller related to controller '%s'", controllerDetail.getType().getFullyQualifiedTypeName());
}
}
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());
// 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 && info.type == JpaRelationType.COMPOSITION) {
childEntityDetails = getTypeLocationService().getTypeDetails(info.childType);
childEntityMetadata = getMetadataService().get(JpaEntityMetadata.createIdentifier(childEntityDetails));
compositionRelationOneToOne.add(Pair.of(info, childEntityMetadata));
}
}
Map<String, MethodMetadata> findersToAdd = new HashMap<String, MethodMetadata>();
// Getting annotated finders
final SearchAnnotationValues searchAnnotationValues = new SearchAnnotationValues(governorPhysicalTypeMetadata);
// Add finders only if controller is of search type
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);
// 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, ", ")));
}
}
return new JSONMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, annotationValues, controllerMetadata, serviceMetadata, entityMetadata, entityPlural, entityIdentifierPlural, compositionRelationOneToOne, itemController, findersToAdd);
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata in project spring-roo by spring-projects.
the class AbstractViewGenerationService method createDetailEntityItem.
/**
* Create a new instance of {@link DetailEntityItem}. Implementation can
* override this method to include it own information or extend defaults.
*
* @param detailController
* @param detailSuffix
* @param ctx
* @param string
* @param entityMetadata
* @param entity
* @return
*/
protected DetailEntityItem createDetailEntityItem(T detailController, MemberDetails entityMembers, JpaEntityMetadata entityMetadata, String entityName, ViewContext<T> ctx, String detailSuffix, EntityItem rootEntity) {
ControllerMetadata controllerMetadata = detailController.getControllerMetadata();
RelationInfoExtended last = controllerMetadata.getLastDetailsInfo();
ClassOrInterfaceTypeDetails childEntityDetails = getTypeLocationService().getTypeDetails(last.childType);
JpaEntityMetadata childEntityMetadata = last.childEntityMetadata;
String controllerPath = getControllerOperations().getBasePathForController(controllerMetadata.getDestination());
DetailEntityItem detailItem = new DetailEntityItem(childEntityMetadata, controllerMetadata, controllerPath, detailSuffix, rootEntity);
// Saving necessary configuration
detailItem.addConfigurationElement("referencedFieldType", last.childType.getSimpleTypeName());
// Getting identifier field
detailItem.addConfigurationElement("identifierField", childEntityMetadata.getCurrentIndentifierField().getFieldName().getSymbolName());
// Getting referencedfield label plural
detailItem.addConfigurationElement("referencedFieldLabel", FieldItem.buildLabel(entityName, last.fieldName));
// Getting all referenced fields
List<FieldMetadata> referencedFields = null;
// Get the repository related with the child entity to check the default return type
RepositoryJpaMetadata repository = getRepositoryJpaLocator().getFirstRepositoryMetadata(childEntityMetadata.getAnnotatedEntity());
// All views should have a repository
Validate.notNull(repository, "ERROR: The provided child entity should have an associated repository to be able " + "to generate the list view.");
// Obtain the defaultReturnType
JavaType defaultReturnType = repository.getDefaultReturnType();
// The defaultReturnType must not be null. If it's not an entity projection,
// it must be an entity
Validate.notNull(defaultReturnType, "ERROR: The repository associated to the provided entity should define a defaultReturnType");
// Obtain details of the provided defaultReturnType. If not exists as type, show an error
ClassOrInterfaceTypeDetails defaultReturnTypeCid = getTypeLocationService().getTypeDetails(defaultReturnType);
Validate.notNull(defaultReturnTypeCid, "ERROR: The provided defaultReturnType is not a valid type");
MemberDetails defaultReturnTypeDetails = getMemberDetailsScanner().getMemberDetails(getClass().toString(), defaultReturnTypeCid);
Validate.notNull(defaultReturnTypeDetails, "ERROR: Is not possible to obtain any detail from the " + "provided defaultReturnType.");
List<FieldMetadata> defaultReturnTypeFields = defaultReturnTypeDetails.getFields();
if (defaultReturnTypeFields.isEmpty()) {
referencedFields = getEditableFields(getMemberDetailsScanner().getMemberDetails(getClass().toString(), childEntityDetails).getFields());
} else {
referencedFields = getEditableFields(defaultReturnTypeFields);
}
detailItem.addConfigurationElement("referenceFieldFields", getFieldViewItems(childEntityMetadata, referencedFields, entityName + "." + last.fieldName, true, ctx, StringUtils.EMPTY));
detailItem.addConfigurationElement("fields", getFieldViewItems(childEntityMetadata, referencedFields, detailItem.getEntityName(), true, ctx, StringUtils.EMPTY));
return detailItem;
}
Aggregations