use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class RepositoryJpaCustomImplMetadata method getCustomCountImpl.
/**
* Method that generates implementation methods for each count method, associated
* to each custom finder.
*
* @param methodInfo
* @param validFields
* @return
*/
private MethodMetadata getCustomCountImpl(Pair<MethodMetadata, PartTree> methodInfo) {
final 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 names to use in the code
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
bodyBuilder.newLine();
// QEntity qEntity = QEntity.entity;
bodyBuilder.appendFormalLine(String.format("%1$s %2$s = %1$s.%2$s;", getNameOfJavaType(entityQtype), entityVariable));
bodyBuilder.newLine();
// JPQLQuery query = from(qEntity);
bodyBuilder.appendFormalLine(String.format("%s query = from(%s);", getNameOfJavaType(getJPQLQueryFor(this.entity)), entityVariable));
bodyBuilder.newLine();
buildFormBeanFilterBody(bodyBuilder, finderParamType, finderParamName, entityVariable, methodInfo.getRight());
// return query.fetchCount();
bodyBuilder.appendFormalLine("return query.fetchCount();");
// Use provided finder method to generate its implementation
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, method.getReturnType(), parameterTypes, parameterNames, bodyBuilder);
return methodBuilder.build();
}
use of org.springframework.roo.classpath.details.MethodMetadata 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();
}
use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class RepositoryJpaCustomImplMetadata method getFindAllImpl.
/**
* Method that generates the findAll implementation method
* @param findAllGlobalSearchMethod
* @param ids the entity id fields
* @param fields the entity fields to search for
*
* @return
*/
private MethodMetadata getFindAllImpl(MethodMetadata findAllGlobalSearchMethod, FieldMetadata idField, List<FieldMetadata> fields) {
// Define method name
JavaSymbolName methodName = findAllGlobalSearchMethod.getMethodName();
// Define method parameter types
List<AnnotatedJavaType> parameterTypes = findAllGlobalSearchMethod.getParameterTypes();
// Define method parameter names
List<JavaSymbolName> parameterNames = findAllGlobalSearchMethod.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, findAllGlobalSearchMethod.getMethodName(), findAllGlobalSearchMethod.getReturnType(), findAllGlobalSearchMethod.getParameterTypes(), findAllGlobalSearchMethod.getParameterNames(), null);
// Generate body
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
// Getting variable name to use in the code
JavaSymbolName globalSearch = parameterNames.get(0);
JavaSymbolName pageable = parameterNames.get(1);
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();
// 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
}
use of org.springframework.roo.classpath.details.MethodMetadata 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);
}
use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class RepositoryJpaMetadata method getCountMethodByField.
/**
* Method that generates method "countByField" method.
*
* @param relationInfo
* @param identifierType
*
* @return field
*/
public MethodMetadata getCountMethodByField(FieldMetadata field, RelationInfo relationInfo) {
// Define method name
String countPattern = "countBy%s";
if (relationInfo.cardinality == Cardinality.MANY_TO_MANY) {
countPattern = "countBy%sContains";
}
final JavaSymbolName methodName = new JavaSymbolName(String.format(countPattern, field.getFieldName().getSymbolNameCapitalisedFirstLetter()));
// Define method parameter type and name
List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
final JavaType paramType = field.getFieldType().getBaseType();
parameterTypes.add(AnnotatedJavaType.convertFromJavaType(paramType));
parameterNames.add(new JavaSymbolName(StringUtils.uncapitalize(field.getFieldName().getSymbolName())));
MethodMetadata existingMethod = getGovernorMethod(methodName, AnnotatedJavaType.convertFromAnnotatedJavaTypes(parameterTypes));
if (existingMethod != null) {
return existingMethod;
}
// Use the MethodMetadataBuilder for easy creation of MethodMetadata
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC + Modifier.ABSTRACT, methodName, JavaType.LONG_PRIMITIVE, parameterTypes, parameterNames, null);
return methodBuilder.build();
}
Aggregations