use of org.springframework.roo.classpath.details.comments.CommentStructure in project spring-roo by spring-projects.
the class JpaDataOnDemandMetadata method getSpecificEntityMethod.
private MethodMetadata getSpecificEntityMethod() {
// Method definition to find or build
final JavaSymbolName methodName = new JavaSymbolName(JpaEntityFactoryMetadata.SPECIFIC_METHOD_PREFIX + this.entity.getSimpleTypeName());
final JavaType parameterType = JavaType.INT_PRIMITIVE;
final List<JavaSymbolName> parameterNames = Arrays.asList(INDEX_SYMBOL);
// Locate user-defined method
final MethodMetadata userMethod = getGovernorMethod(methodName, parameterType);
if (userMethod != null) {
Validate.isTrue(userMethod.getReturnType().equals(this.entity), "Method '%s on '%s' must return '%s'", methodName, this.destination, this.entity.getSimpleTypeName());
this.specificEntityMethod = userMethod;
return userMethod;
}
// Create method
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("init();");
bodyBuilder.appendFormalLine("if (" + INDEX_VAR + " < 0) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(INDEX_VAR + " = 0;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("if (" + INDEX_VAR + " > (" + getAccessorMethod(getDataField().build()).getMethodName() + "().size() - 1)) {");
bodyBuilder.indent();
bodyBuilder.appendFormalLine(INDEX_VAR + " = " + getAccessorMethod(getDataField().build()).getMethodName() + "().size() - 1;");
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
bodyBuilder.appendFormalLine("return %s().get(%s);", getAccessorMethod(getDataField().build()).getMethodName(), INDEX_VAR);
final MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, this.entity, AnnotatedJavaType.convertFromJavaTypes(parameterType), parameterNames, bodyBuilder);
CommentStructure comment = new CommentStructure();
List<String> paramsInfo = new ArrayList<String>();
paramsInfo.add(String.format("%s the position of the {@link %s} to return", INDEX_VAR, this.entity.getSimpleTypeName()));
JavadocComment javadocComment = new JavadocComment(String.format("Returns a generated and persisted {@link %s} in a given index.", this.entity.getSimpleTypeName()), paramsInfo, String.format("%1$s the specific {@link %1$s}", this.entity.getSimpleTypeName()), null);
comment.addComment(javadocComment, CommentLocation.BEGINNING);
methodBuilder.setCommentStructure(comment);
this.specificEntityMethod = methodBuilder.build();
return this.specificEntityMethod;
}
use of org.springframework.roo.classpath.details.comments.CommentStructure in project spring-roo by spring-projects.
the class EqualsMetadata method generateEqualsMethod.
/**
* Generate equals method
*
* @param metadataId
* @param target
* @param annotationValues
* @param identifierAccessor
* @param locatedFields
* @param builder
* @return
*/
protected static MethodMetadataBuilder generateEqualsMethod(String metadataId, JavaType target, EqualsAnnotationValues annotationValues, JavaSymbolName identifierAccessor, List<FieldMetadata> locatedFields, ItdTypeDetailsBuilder builder) {
final List<JavaSymbolName> parameterNames = Arrays.asList(new JavaSymbolName(OBJECT_NAME));
// Create the method body depending on destination class properties
InvocableMemberBodyBuilder bodyBuilder = null;
if (annotationValues.isJpaEntity()) {
bodyBuilder = getJpaEntityEqualsMethodBody(target, identifierAccessor, builder.getImportRegistrationResolver());
} else {
bodyBuilder = generateDefaultEqualsMethodBody(target, annotationValues.isAppendSuper(), locatedFields, builder.getImportRegistrationResolver());
}
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(metadataId, Modifier.PUBLIC, EQUALS_METHOD_NAME, BOOLEAN_PRIMITIVE, AnnotatedJavaType.convertFromJavaTypes(OBJECT), parameterNames, bodyBuilder);
if (annotationValues.isJpaEntity()) {
CommentStructure commentStructure = new CommentStructure();
commentStructure.addComment(new JavadocComment("This `equals` implementation is specific for JPA entities and uses ".concat(IOUtils.LINE_SEPARATOR).concat("the entity identifier for it, following the article in ").concat(IOUtils.LINE_SEPARATOR).concat("https://vladmihalcea.com/2016/06/06/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/")), CommentLocation.BEGINNING);
methodBuilder.setCommentStructure(commentStructure);
}
return methodBuilder;
}
use of org.springframework.roo.classpath.details.comments.CommentStructure in project spring-roo by spring-projects.
the class JavaParserFieldMetadataBuilder method addField.
public static void addField(final CompilationUnitServices compilationUnitServices, final List<BodyDeclaration> members, final FieldMetadata field) {
Validate.notNull(compilationUnitServices, "Flushable compilation unit services required");
Validate.notNull(members, "Members required");
Validate.notNull(field, "Field required");
JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), field.getFieldType());
final Type initType = JavaParserUtils.getResolvedName(compilationUnitServices.getEnclosingTypeName(), field.getFieldType(), compilationUnitServices);
final ClassOrInterfaceType finalType = JavaParserUtils.getClassOrInterfaceType(initType);
final FieldDeclaration newField = ASTHelper.createFieldDeclaration(JavaParserUtils.getJavaParserModifier(field.getModifier()), initType, field.getFieldName().getSymbolName());
// Add parameterized types for the field type (not initializer)
if (field.getFieldType().getParameters().size() > 0) {
final List<Type> fieldTypeArgs = new ArrayList<Type>();
finalType.setTypeArgs(fieldTypeArgs);
for (final JavaType parameter : field.getFieldType().getParameters()) {
fieldTypeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
}
final List<VariableDeclarator> vars = newField.getVariables();
Validate.notEmpty(vars, "Expected ASTHelper to have provided a single VariableDeclarator");
Validate.isTrue(vars.size() == 1, "Expected ASTHelper to have provided a single VariableDeclarator");
final VariableDeclarator vd = vars.iterator().next();
if (StringUtils.isNotBlank(field.getFieldInitializer())) {
// There is an initializer.
// We need to make a fake field that we can have JavaParser parse.
// Easiest way to do that is to build a simple source class
// containing the required field and re-parse it.
final StringBuilder sb = new StringBuilder();
sb.append("class TemporaryClass {\n");
sb.append(" private " + field.getFieldType() + " " + field.getFieldName() + " = " + field.getFieldInitializer() + ";\n");
sb.append("}\n");
final ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
CompilationUnit ci;
try {
ci = JavaParser.parse(bais);
} catch (final IOException e) {
throw new IllegalStateException("Illegal state: Unable to parse input stream", e);
} catch (final ParseException pe) {
throw new IllegalStateException("Illegal state: JavaParser did not parse correctly", pe);
}
final List<TypeDeclaration> types = ci.getTypes();
if (types == null || types.size() != 1) {
throw new IllegalArgumentException("Field member invalid");
}
final TypeDeclaration td = types.get(0);
final List<BodyDeclaration> bodyDeclarations = td.getMembers();
if (bodyDeclarations == null || bodyDeclarations.size() != 1) {
throw new IllegalStateException("Illegal state: JavaParser did not return body declarations correctly");
}
final BodyDeclaration bd = bodyDeclarations.get(0);
if (!(bd instanceof FieldDeclaration)) {
throw new IllegalStateException("Illegal state: JavaParser did not return a field declaration correctly");
}
final FieldDeclaration fd = (FieldDeclaration) bd;
if (fd.getVariables() == null || fd.getVariables().size() != 1) {
throw new IllegalStateException("Illegal state: JavaParser did not return a field declaration correctly");
}
final Expression init = fd.getVariables().get(0).getInit();
// Resolve imports (ROO-1505)
if (init instanceof ObjectCreationExpr) {
final ObjectCreationExpr ocr = (ObjectCreationExpr) init;
final JavaType typeToImport = JavaParserUtils.getJavaTypeNow(compilationUnitServices, ocr.getType(), null);
final NameExpr nameExpr = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), typeToImport);
final ClassOrInterfaceType classOrInterfaceType = JavaParserUtils.getClassOrInterfaceType(nameExpr);
ocr.setType(classOrInterfaceType);
if (typeToImport.getParameters().size() > 0) {
final List<Type> initTypeArgs = new ArrayList<Type>();
finalType.setTypeArgs(initTypeArgs);
for (final JavaType parameter : typeToImport.getParameters()) {
initTypeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
classOrInterfaceType.setTypeArgs(initTypeArgs);
}
}
vd.setInit(init);
}
// Add annotations
final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
newField.setAnnotations(annotations);
for (final AnnotationMetadata annotation : field.getAnnotations()) {
JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, annotations, annotation);
}
// ROO-3678: Add-on which include new field should be the responsible to check if field
// exists, not JavaParser.
/*// Locate where to add this field; also verify if this field already
// exists
int nextFieldIndex = 0;
int i = -1;
for (final BodyDeclaration bd : members) {
i++;
if (bd instanceof FieldDeclaration) {
// Next field should appear after this current field
nextFieldIndex = i + 1;
final FieldDeclaration bdf = (FieldDeclaration) bd;
for (final VariableDeclarator v : bdf.getVariables()) {
Validate.isTrue(!field.getFieldName().getSymbolName()
.equals(v.getId().getName()),
"A field with name '%s' already exists", field
.getFieldName().getSymbolName());
}
}
}*/
int nextFieldIndex = 0;
int i = -1;
for (final BodyDeclaration bd : members) {
i++;
if (bd instanceof FieldDeclaration) {
// Next field should appear after this current field
nextFieldIndex = i + 1;
}
}
if (field.getCommentStructure() != null) {
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, field.getCommentStructure());
// Otherwise, add comments to the field declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(newField, field.getCommentStructure());
}
} else {
// ROO-3834: Append default Javadoc if not exists a comment structure
CommentStructure defaultCommentStructure = new CommentStructure();
JavadocComment javadocComment = new JavadocComment("TODO Auto-generated attribute documentation");
defaultCommentStructure.addComment(javadocComment, CommentLocation.BEGINNING);
field.setCommentStructure(defaultCommentStructure);
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, defaultCommentStructure);
// Otherwise, add comments to the field declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(newField, defaultCommentStructure);
}
}
// Add the field to the compilation unit
members.add(nextFieldIndex, newField);
}
use of org.springframework.roo.classpath.details.comments.CommentStructure in project spring-roo by spring-projects.
the class JavaParserMethodMetadataBuilder method addMethod.
public static void addMethod(final CompilationUnitServices compilationUnitServices, final List<BodyDeclaration> members, final MethodMetadata method, Set<JavaSymbolName> typeParameters) {
Validate.notNull(compilationUnitServices, "Flushable compilation unit services required");
Validate.notNull(members, "Members required");
Validate.notNull(method, "Method required");
if (typeParameters == null) {
typeParameters = new HashSet<JavaSymbolName>();
}
// Create the return type we should use
Type returnType = null;
if (method.getReturnType().isPrimitive()) {
returnType = JavaParserUtils.getType(method.getReturnType());
} else {
final NameExpr importedType = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), method.getReturnType());
final ClassOrInterfaceType cit = JavaParserUtils.getClassOrInterfaceType(importedType);
// Add any type arguments presented for the return type
if (method.getReturnType().getParameters().size() > 0) {
final List<Type> typeArgs = new ArrayList<Type>();
cit.setTypeArgs(typeArgs);
for (final JavaType parameter : method.getReturnType().getParameters()) {
typeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
}
// Handle arrays
if (method.getReturnType().isArray()) {
final ReferenceType rt = new ReferenceType();
rt.setArrayCount(method.getReturnType().getArray());
rt.setType(cit);
returnType = rt;
} else {
returnType = cit;
}
}
// Start with the basic method
final MethodDeclaration d = new MethodDeclaration();
d.setModifiers(JavaParserUtils.getJavaParserModifier(method.getModifier()));
d.setName(method.getMethodName().getSymbolName());
d.setType(returnType);
// Add any method-level annotations (not parameter annotations)
final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
d.setAnnotations(annotations);
for (final AnnotationMetadata annotation : method.getAnnotations()) {
JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, annotations, annotation);
}
// Add any method parameters, including their individual annotations and
// type parameters
final List<Parameter> parameters = new ArrayList<Parameter>();
d.setParameters(parameters);
int index = -1;
for (final AnnotatedJavaType methodParameter : method.getParameterTypes()) {
index++;
// Add the parameter annotations applicable for this parameter type
final List<AnnotationExpr> parameterAnnotations = new ArrayList<AnnotationExpr>();
for (final AnnotationMetadata parameterAnnotation : methodParameter.getAnnotations()) {
JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, parameterAnnotations, parameterAnnotation);
}
// Compute the parameter name
final String parameterName = method.getParameterNames().get(index).getSymbolName();
// Compute the parameter type
Type parameterType = null;
if (methodParameter.getJavaType().isPrimitive()) {
parameterType = JavaParserUtils.getType(methodParameter.getJavaType());
} else {
final NameExpr type = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), methodParameter.getJavaType());
final ClassOrInterfaceType cit = JavaParserUtils.getClassOrInterfaceType(type);
// Add any type arguments presented for the return type
if (methodParameter.getJavaType().getParameters().size() > 0) {
final List<Type> typeArgs = new ArrayList<Type>();
cit.setTypeArgs(typeArgs);
for (final JavaType parameter : methodParameter.getJavaType().getParameters()) {
typeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
}
}
// Handle arrays
if (methodParameter.getJavaType().isArray()) {
final ReferenceType rt = new ReferenceType();
rt.setArrayCount(methodParameter.getJavaType().getArray());
rt.setType(cit);
parameterType = rt;
} else {
parameterType = cit;
}
}
// Create a Java Parser method parameter and add it to the list of
// parameters
final Parameter p = new Parameter(parameterType, new VariableDeclaratorId(parameterName));
p.setVarArgs(methodParameter.isVarArgs());
p.setAnnotations(parameterAnnotations);
parameters.add(p);
}
// Add exceptions which the method my throw
if (method.getThrowsTypes().size() > 0) {
final List<NameExpr> throwsTypes = new ArrayList<NameExpr>();
for (final JavaType javaType : method.getThrowsTypes()) {
final NameExpr importedType = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), javaType);
throwsTypes.add(importedType);
}
d.setThrows(throwsTypes);
}
// Set the body
if (StringUtils.isBlank(method.getBody())) {
// Never set the body if an abstract method
if (!Modifier.isAbstract(method.getModifier()) && !PhysicalTypeCategory.INTERFACE.equals(compilationUnitServices.getPhysicalTypeCategory())) {
d.setBody(new BlockStmt());
}
} else {
// There is a body.
// We need to make a fake method that we can have JavaParser parse.
// Easiest way to do that is to build a simple source class
// containing the required method and re-parse it.
final StringBuilder sb = new StringBuilder();
sb.append("class TemporaryClass {\n");
sb.append(" public void temporaryMethod() {\n");
sb.append(method.getBody());
sb.append("\n");
sb.append(" }\n");
sb.append("}\n");
final ByteArrayInputStream bais = new ByteArrayInputStream(sb.toString().getBytes());
CompilationUnit ci;
try {
ci = JavaParser.parse(bais);
} catch (final IOException e) {
throw new IllegalStateException("Illegal state: Unable to parse input stream", e);
} catch (final ParseException pe) {
throw new IllegalStateException("Illegal state: JavaParser did not parse correctly", pe);
}
final List<TypeDeclaration> types = ci.getTypes();
if (types == null || types.size() != 1) {
throw new IllegalArgumentException("Method body invalid");
}
final TypeDeclaration td = types.get(0);
final List<BodyDeclaration> bodyDeclarations = td.getMembers();
if (bodyDeclarations == null || bodyDeclarations.size() != 1) {
throw new IllegalStateException("Illegal state: JavaParser did not return body declarations correctly");
}
final BodyDeclaration bd = bodyDeclarations.get(0);
if (!(bd instanceof MethodDeclaration)) {
throw new IllegalStateException("Illegal state: JavaParser did not return a method declaration correctly");
}
final MethodDeclaration md = (MethodDeclaration) bd;
d.setBody(md.getBody());
}
// ROO-3678: Add-on which include new method should be the responsible to check if method
// exists, not JavaParser.
/*// Locate where to add this method; also verify if this method already
// exists
for (final BodyDeclaration bd : members) {
if (bd instanceof MethodDeclaration) {
// Next method should appear after this current method
final MethodDeclaration md = (MethodDeclaration) bd;
/*if (md.getName().equals(d.getName())) {
if ((md.getParameters() == null || md.getParameters()
.isEmpty())
&& (d.getParameters() == null || d.getParameters()
.isEmpty())) {
throw new IllegalStateException("Method '"
+ method.getMethodName().getSymbolName()
+ "' already exists");
}
else if (md.getParameters() != null
&& md.getParameters().size() == d.getParameters()
.size()) {
// Possible match, we need to consider parameter types
// as well now
final MethodMetadata methodMetadata = JavaParserMethodMetadataBuilder
.getInstance(method.getDeclaredByMetadataId(),
md, compilationUnitServices,
typeParameters).build();
boolean matchesFully = true;
index = -1;
for (final AnnotatedJavaType existingParameter : methodMetadata
.getParameterTypes()) {
index++;
final AnnotatedJavaType parameterType = method
.getParameterTypes().get(index);
if (!existingParameter.getJavaType().equals(
parameterType.getJavaType())) {
matchesFully = false;
break;
}
}
if (matchesFully) {
throw new IllegalStateException(
"Method '"
+ method.getMethodName()
.getSymbolName()
+ "' already exists with identical parameters");
}
}
}
}
}*/
// ROO-3834: Append Javadoc
CommentStructure commentStructure = method.getCommentStructure();
if (commentStructure != null) {
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, commentStructure);
// Otherwise, add comments to the method declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, commentStructure);
}
} else {
// ROO-3834: Include default documentation
CommentStructure defaultCommentStructure = new CommentStructure();
// ROO-3834: Append default Javadoc if not exists a comment structure,
// including method params, return and throws.
List<String> parameterNames = new ArrayList<String>();
for (JavaSymbolName name : method.getParameterNames()) {
parameterNames.add(name.getSymbolName());
}
List<String> throwsTypesNames = new ArrayList<String>();
for (JavaType type : method.getThrowsTypes()) {
throwsTypesNames.add(type.getSimpleTypeName());
}
String returnInfo = null;
JavaType returnJavaType = method.getReturnType();
if (!returnJavaType.equals(JavaType.VOID_OBJECT) && !returnJavaType.equals(JavaType.VOID_PRIMITIVE)) {
returnInfo = returnJavaType.getSimpleTypeName();
}
JavadocComment javadocComment = new JavadocComment("TODO Auto-generated method documentation", parameterNames, returnInfo, throwsTypesNames);
defaultCommentStructure.addComment(javadocComment, CommentLocation.BEGINNING);
method.setCommentStructure(defaultCommentStructure);
// annotation
if (annotations != null && annotations.size() > 0) {
AnnotationExpr firstAnnotation = annotations.get(0);
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, defaultCommentStructure);
// Otherwise, add comments to the method declaration line
} else {
JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, defaultCommentStructure);
}
}
// Add the method to the end of the compilation unit
members.add(d);
}
use of org.springframework.roo.classpath.details.comments.CommentStructure in project spring-roo by spring-projects.
the class JaxbEntityMetadata method getXmlIdentityInfoMethod.
/**
* This method returns the getXmlIdentityInfo() method.
*
* @return MethodMetadata that contains the getXmlIdentityInfoMethod
*/
public MethodMetadata getXmlIdentityInfoMethod() {
// Check if already exists
if (xmlIdentityInfoMethod != null) {
return xmlIdentityInfoMethod;
}
// If not, generate a new one
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
// return getClass().getName() + ":" + getId();
bodyBuilder.appendFormalLine(String.format("return getClass().getName() + \":\" + %s();", identifierAccessor.getMethodName()));
MethodMetadataBuilder method = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, new JavaSymbolName("getXmlIdentityInfo"), JavaType.STRING, bodyBuilder);
method.addAnnotation(new AnnotationMetadataBuilder(JavaType.XML_ID));
AnnotationMetadataBuilder xmlAttributeAnnotation = new AnnotationMetadataBuilder(JavaType.XML_ATTRIBUTE);
xmlAttributeAnnotation.addStringAttribute("name", "id");
method.addAnnotation(xmlAttributeAnnotation);
CommentStructure comment = new CommentStructure();
comment.addComment(new JavadocComment("Must return an unique ID across all entities"), CommentLocation.BEGINNING);
method.setCommentStructure(comment);
xmlIdentityInfoMethod = method.build();
return xmlIdentityInfoMethod;
}
Aggregations