use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata in project spring-roo by spring-projects.
the class ControllerOperationsImpl method getRelationInfoFor.
@Override
public List<RelationInfoExtended> getRelationInfoFor(final JavaType entity, final String path) {
Validate.notNull(entity, "entity is required");
Validate.notBlank(path, "path is required");
ClassOrInterfaceTypeDetails cid = getTypeLocationService().getTypeDetails(entity);
Validate.notNull(cid, "%s not found", entity.getFullyQualifiedTypeName());
JpaEntityMetadata entityMetada = getMetadataService().get(JpaEntityMetadata.createIdentifier(cid));
Validate.notNull(entityMetada, "Can't get Entity metadata information for %s", entity.getFullyQualifiedTypeName());
return getRelationInfoFor(entityMetada, path);
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata 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();
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata 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();
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata 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);
}
use of org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata in project spring-roo by spring-projects.
the class RepositoryJpaCustomImplMetadataProviderImpl method getMetadata.
@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
final RepositoryJpaCustomImplAnnotationValues annotationValues = new RepositoryJpaCustomImplAnnotationValues(governorPhysicalTypeMetadata);
// Getting repository custom
JavaType repositoryCustom = annotationValues.getRepository();
// Validate that contains repository interface
Validate.notNull(repositoryCustom, "ERROR: You need to specify interface repository to be implemented.");
ClassOrInterfaceTypeDetails repositoryDetails = getTypeLocationService().getTypeDetails(repositoryCustom);
AnnotationMetadata repositoryCustomAnnotation = repositoryDetails.getAnnotation(ROO_REPOSITORY_JPA_CUSTOM);
Validate.notNull(repositoryCustomAnnotation, "ERROR: Repository interface should be annotated with @RooJpaRepositoryCustom");
AnnotationAttributeValue<JavaType> entityAttribute = repositoryCustomAnnotation.getAttribute("entity");
Validate.notNull(entityAttribute, "ERROR: Repository interface should be contain an entity on @RooJpaRepositoryCustom annotation");
JavaType entity = entityAttribute.getValue();
RepositoryJpaMetadata repositoryMetadata = getRepositoryJpaLocator().getRepositoryMetadata(entity);
if (repositoryMetadata == null) {
// Can't generate it jet
return null;
}
// Register downstream dependency for RepositoryJpaCustomImplMetadata to update projection
// finders implementations
String repositoryCustomMetadataKey = RepositoryJpaCustomMetadata.createIdentifier(repositoryDetails);
registerDependency(repositoryCustomMetadataKey, metadataIdentificationString);
ClassOrInterfaceTypeDetails entityDetails = getTypeLocationService().getTypeDetails(entity);
// Check if default return type is a Projection
JavaType returnType = repositoryMetadata.getDefaultReturnType();
ClassOrInterfaceTypeDetails returnTypeDetails = getTypeLocationService().getTypeDetails(returnType);
AnnotationMetadata entityProjectionAnnotation = returnTypeDetails.getAnnotation(RooJavaType.ROO_ENTITY_PROJECTION);
boolean returnTypeIsProjection = entityProjectionAnnotation != null;
// Get projection constructor fields from @RooEntityProjection and add it to a Map with
// domain type's variable names
Map<JavaType, List<Pair<String, String>>> typesFieldMaps = new LinkedHashMap<JavaType, List<Pair<String, String>>>();
Map<JavaType, Boolean> typesAreProjections = new HashMap<JavaType, Boolean>();
if (returnTypeIsProjection) {
buildFieldNamesMap(entity, returnType, entityProjectionAnnotation, typesFieldMaps);
typesAreProjections.put(returnType, true);
}
final RepositoryJpaCustomMetadata repositoryCustomMetadata = getMetadataService().get(repositoryCustomMetadataKey);
// Prevent empty metadata
if (repositoryCustomMetadata == null) {
return null;
}
// Getting java bean metadata
final String javaBeanMetadataKey = JavaBeanMetadata.createIdentifier(entityDetails);
// Getting jpa entity metadata
final String jpaEntityMetadataKey = JpaEntityMetadata.createIdentifier(entityDetails);
JpaEntityMetadata entityMetadata = getMetadataService().get(jpaEntityMetadataKey);
// Create dependency between repository and java bean annotation
registerDependency(javaBeanMetadataKey, metadataIdentificationString);
// Create dependency between repository and jpa entity annotation
registerDependency(jpaEntityMetadataKey, metadataIdentificationString);
// Getting entity properties
MemberDetails entityMemberDetails = getMemberDetailsScanner().getMemberDetails(getClass().getName(), entityDetails);
// Getting valid fields to construct the findAll query
List<FieldMetadata> validFields = new ArrayList<FieldMetadata>();
loadValidFields(entityMemberDetails, entityMetadata, validFields);
// Getting all necessary information about referencedFields
Map<FieldMetadata, MethodMetadata> referencedFieldsMethods = repositoryCustomMetadata.getReferencedFieldsFindAllMethods();
Map<FieldMetadata, String> referencedFieldsIdentifierNames = new HashMap<FieldMetadata, String>();
List<Pair<MethodMetadata, PartTree>> customFinderMethods = repositoryCustomMetadata.getCustomFinderMethods();
List<Pair<MethodMetadata, PartTree>> customCountMethods = repositoryCustomMetadata.getCustomCountMethods();
if (customCountMethods == null) {
customCountMethods = new ArrayList<Pair<MethodMetadata, PartTree>>();
}
for (Entry<FieldMetadata, MethodMetadata> referencedFields : referencedFieldsMethods.entrySet()) {
// Get identifier field name in path format
String fieldPathName = String.format("%s.%s", StringUtils.uncapitalize(entity.getSimpleTypeName()), referencedFields.getKey().getFieldName().getSymbolNameUnCapitalisedFirstLetter());
// Put keys and values in map
referencedFieldsIdentifierNames.put(referencedFields.getKey(), fieldPathName);
}
// Add valid entity fields to mappings
Map<JavaType, Map<String, FieldMetadata>> typesFieldsMetadataMap = new HashMap<JavaType, Map<String, FieldMetadata>>();
Map<String, FieldMetadata> entityFieldMetadata = new LinkedHashMap<String, FieldMetadata>();
List<Pair<String, String>> entityFieldMappings = new ArrayList<Pair<String, String>>();
typesAreProjections.put(entity, false);
for (FieldMetadata field : validFields) {
entityFieldMetadata.put(field.getFieldName().getSymbolName(), field);
entityFieldMappings.add(Pair.of(field.getFieldName().getSymbolName(), StringUtils.uncapitalize(entity.getSimpleTypeName()).concat(".").concat(field.getFieldName().getSymbolName())));
}
typesFieldsMetadataMap.put(entity, entityFieldMetadata);
typesFieldMaps.put(entity, entityFieldMappings);
// Make a list with all domain types, excepting entities
List<JavaType> domainTypes = new ArrayList<JavaType>();
domainTypes.add(returnType);
for (Pair<MethodMetadata, PartTree> methodInfo : customFinderMethods) {
// Get finder return type from first parameter of method return type (Page)
JavaType finderReturnType = getDomainTypeOfFinderMethod(methodInfo.getKey());
domainTypes.add(finderReturnType);
// If type is a DTO, add finder fields to mappings
JavaType parameterType = methodInfo.getKey().getParameterTypes().get(0).getJavaType();
typesAreProjections.put(parameterType, false);
}
// Add typesFieldMaps for each projection finder and check for id fields
for (JavaType type : domainTypes) {
// Check if projection fields has been added already
if (typesFieldMaps.containsKey(type)) {
continue;
}
// Build Map with FieldMetadata of each projection
ClassOrInterfaceTypeDetails typeDetails = getTypeLocationService().getTypeDetails(type);
if (typeDetails == null) {
LOGGER.warning("Detail not found for type: " + type);
continue;
}
List<FieldMetadata> typeFieldList = getMemberDetailsScanner().getMemberDetails(this.getClass().getName(), typeDetails).getFields();
Map<String, FieldMetadata> fieldMetadataMap = new LinkedHashMap<String, FieldMetadata>();
for (FieldMetadata field : typeFieldList) {
fieldMetadataMap.put(field.getFieldName().getSymbolName(), field);
}
typesFieldsMetadataMap.put(type, fieldMetadataMap);
AnnotationMetadata projectionAnnotation = typeDetails.getAnnotation(RooJavaType.ROO_ENTITY_PROJECTION);
if (projectionAnnotation != null) {
typesAreProjections.put(type, true);
// Type is a Projection
JavaType associatedEntity = (JavaType) projectionAnnotation.getAttribute("entity").getValue();
// Add fields to typesFieldMaps
buildFieldNamesMap(associatedEntity, type, projectionAnnotation, typesFieldMaps);
}
}
return new RepositoryJpaCustomImplMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, annotationValues, entity, entityMetadata, entityMetadata.getCurrentIndentifierField(), validFields, repositoryCustomMetadata.getCurrentFindAllGlobalSearchMethod(), repositoryCustomMetadata.getCurrentFindAllByIdsInGlobalSearchMethod(), repositoryCustomMetadata.getDefaultReturnType(), referencedFieldsMethods, referencedFieldsIdentifierNames, typesFieldMaps, customFinderMethods, customCountMethods, typesFieldsMetadataMap, typesAreProjections);
}
Aggregations