use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class JpaEntityFactoryMetadata method getCreateMethod.
private MethodMetadata getCreateMethod() {
// Define methodName
final JavaSymbolName methodName = CREATE_FACTORY_METHOD_NAME;
List<JavaType> parameterTypes = new ArrayList<JavaType>();
parameterTypes.add(JavaType.INT_PRIMITIVE);
// Check if method exists
MethodMetadata existingMethod = getGovernorMethod(methodName, parameterTypes);
if (existingMethod != null) {
return existingMethod;
}
List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
parameterNames.add(INDEX_SYMBOL);
// Add body
InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
// Entity obj = new Entity();
bodyBuilder.appendFormalLine("%1$s %2$s = new %1$s();", getNameOfJavaType(this.entity), OBJ_SYMBOL);
// Set values for transient object
for (final Map.Entry<FieldMetadata, JpaEntityFactoryMetadata> entry : locatedFields.entrySet()) {
bodyBuilder.appendFormalLine("%s(%s, %s);", BeanInfoUtils.getMutatorMethodName(entry.getKey()), OBJ_SYMBOL, INDEX_SYMBOL);
}
// return obj;
bodyBuilder.appendFormalLine("return %s;", OBJ_SYMBOL);
// Create method
MethodMetadataBuilder method = new MethodMetadataBuilder(this.getId(), Modifier.PUBLIC, methodName, this.entity, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder);
CommentStructure commentStructure = new CommentStructure();
List<String> paramsInfo = new ArrayList<String>();
paramsInfo.add(String.format("%s position of the %s", INDEX_VAR, this.entity.getSimpleTypeName()));
JavadocComment comment = new JavadocComment(String.format("Creates a new {@link %s} with the given %s.", this.entity.getSimpleTypeName(), INDEX_VAR), paramsInfo, String.format("a new transient %s", this.entity.getSimpleTypeName()), null);
commentStructure.addComment(comment, CommentLocation.BEGINNING);
method.setCommentStructure(commentStructure);
return method.build();
}
use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class ItdSourceFileComposer method writeMethods.
private void writeMethods(final List<? extends MethodMetadata> methods, final boolean defineTarget, final boolean isInterfaceMethod) {
for (final MethodMetadata method : methods) {
Validate.isTrue(method.getParameterTypes().size() == method.getParameterNames().size(), "Method %s has mismatched parameter names against parameter types", method.getMethodName().getSymbolName());
// ROO-3447: Append comments if exists
CommentStructure commentStructure = method.getCommentStructure();
if (commentStructure != null && commentStructure.getBeginComments() != null) {
List<AbstractComment> comments = commentStructure.getBeginComments();
String commentString = "";
boolean missingComponentsAdded = false;
for (AbstractComment comment : comments) {
// Join all JavadocComment's
if (comment instanceof JavadocComment) {
// Add JavaDoc missing components
if (!missingComponentsAdded) {
// Check params info
if (!method.getParameterNames().isEmpty() && ((JavadocComment) comment).getParamsInfo() == null) {
List<String> paramsInfo = new ArrayList<String>();
for (JavaSymbolName name : method.getParameterNames()) {
paramsInfo.add(name.getSymbolName());
}
((JavadocComment) comment).setParamsInfo(paramsInfo);
}
// Check return info
if (!method.getReturnType().equals(JavaType.VOID_OBJECT) && !method.getReturnType().equals(JavaType.VOID_PRIMITIVE) && ((JavadocComment) comment).getReturnInfo() == null) {
((JavadocComment) comment).setReturnInfo(method.getReturnType().getSimpleTypeName());
}
// Check throws info
if (!method.getThrowsTypes().isEmpty() && ((JavadocComment) comment).getThrowsInfo() == null) {
List<String> throwsInfo = new ArrayList<String>();
for (JavaType throwsType : method.getThrowsTypes()) {
throwsInfo.add(throwsType.getSimpleTypeName());
}
((JavadocComment) comment).setThrowsInfo(throwsInfo);
}
missingComponentsAdded = true;
}
commentString = commentString.concat(comment.getComment()).concat(IOUtils.LINE_SEPARATOR);
} else {
// Not JavadocComment, write comment as it is, unchanged
appendFormalLine(comment.getComment());
}
}
// Write JavadocComment's to ITD, in a single JavadocComment instance
String[] commentLines = commentString.split(IOUtils.LINE_SEPARATOR);
for (String commentLine : commentLines) {
appendFormalLine(commentLine);
}
} else {
// ROO-3834: Append default Javadoc if not exists a comment structure,
// including params, return and throws
CommentStructure defaultCommentStructure = new CommentStructure();
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 returnType = method.getReturnType();
if (!returnType.equals(JavaType.VOID_OBJECT) && !returnType.equals(JavaType.VOID_PRIMITIVE)) {
returnInfo = returnType.getSimpleTypeName();
}
JavadocComment javadocComment = new JavadocComment("TODO Auto-generated method documentation", parameterNames, returnInfo, throwsTypesNames);
defaultCommentStructure.addComment(javadocComment, CommentLocation.BEGINNING);
method.setCommentStructure(defaultCommentStructure);
// Now lines should be formatted, so write them
String[] comment = javadocComment.getComment().split(IOUtils.LINE_SEPARATOR);
for (String line : comment) {
appendFormalLine(line);
}
}
// Append annotations
for (final AnnotationMetadata annotation : method.getAnnotations()) {
appendIndent();
outputAnnotation(annotation);
this.newLine(false);
}
// Append "<modifier> <genericDefinition> <returnType> <methodName>" portion
appendIndent();
// modifier
if (method.getModifier() != 0) {
append(Modifier.toString(method.getModifier()));
append(" ");
}
// ROO-3648: genericDefinition
if (method.getGenericDefinition() != null && !method.getGenericDefinition().trim().equals("")) {
append("<".concat(method.getGenericDefinition()).concat(">"));
append(" ");
}
// return type
append(method.getReturnType().getNameIncludingTypeParameters(false, resolver));
append(" ");
if (defineTarget) {
append(introductionTo.getSimpleTypeName());
append(".");
}
append(method.getMethodName().getSymbolName());
// Append parameter types and names
append("(");
final List<AnnotatedJavaType> parameterTypes = method.getParameterTypes();
final List<JavaSymbolName> parameterNames = method.getParameterNames();
for (int i = 0; i < parameterTypes.size(); i++) {
final AnnotatedJavaType paramType = parameterTypes.get(i);
final JavaSymbolName paramName = parameterNames.get(i);
for (final AnnotationMetadata methodParameterAnnotation : paramType.getAnnotations()) {
outputAnnotation(methodParameterAnnotation);
append(" ");
}
append(paramType.getJavaType().getNameIncludingTypeParameters(false, resolver));
append(" ");
append(paramName.getSymbolName());
if (i < parameterTypes.size() - 1) {
append(", ");
}
}
// Add exceptions to be thrown
final List<JavaType> throwsTypes = method.getThrowsTypes();
if (throwsTypes.size() > 0) {
append(") throws ");
for (int i = 0; i < throwsTypes.size(); i++) {
append(throwsTypes.get(i).getNameIncludingTypeParameters(false, resolver));
if (throwsTypes.size() > i + 1) {
append(", ");
}
}
} else {
append(")");
}
if (isInterfaceMethod) {
append(";");
this.newLine(false);
} else {
append(" {");
this.newLine(false);
// Add body
indent();
append(method.getBody());
indentRemove();
appendFormalLine("}");
}
this.newLine();
}
}
use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class MemberDetailsBuilder method doModification.
private void doModification(final MethodMetadata method, final CustomData customData) {
final MemberHoldingTypeDetails memberHoldingTypeDetails = memberHoldingTypeDetailsMap.get(method.getDeclaredByMetadataId());
if (memberHoldingTypeDetails != null) {
final MethodMetadata matchedMethod = memberHoldingTypeDetails.getMethod(method.getMethodName(), AnnotatedJavaType.convertFromAnnotatedJavaTypes(method.getParameterTypes()));
if (matchedMethod != null && !matchedMethod.getCustomData().keySet().containsAll(customData.keySet())) {
final TypeDetailsBuilder typeDetailsBuilder = getTypeDetailsBuilder(memberHoldingTypeDetails);
typeDetailsBuilder.addDataToMethod(method, customData);
changed = true;
}
}
}
use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class MemberDetailsBuilder method tag.
public <T> void tag(final T toModify, final CustomDataKey<T> key, final Object value) {
if (toModify instanceof FieldMetadata) {
final CustomDataBuilder customDataBuilder = new CustomDataBuilder();
customDataBuilder.put(key, value);
doModification((FieldMetadata) toModify, customDataBuilder.build());
} else if (toModify instanceof MethodMetadata) {
final CustomDataBuilder customDataBuilder = new CustomDataBuilder();
customDataBuilder.put(key, value);
doModification((MethodMetadata) toModify, customDataBuilder.build());
} else if (toModify instanceof ConstructorMetadata) {
final CustomDataBuilder customDataBuilder = new CustomDataBuilder();
customDataBuilder.put(key, value);
doModification((ConstructorMetadata) toModify, customDataBuilder.build());
} else if (toModify instanceof MemberHoldingTypeDetails) {
final CustomDataBuilder customDataBuilder = new CustomDataBuilder();
customDataBuilder.put(key, value);
doModification((MemberHoldingTypeDetails) toModify, customDataBuilder.build());
}
}
use of org.springframework.roo.classpath.details.MethodMetadata in project spring-roo by spring-projects.
the class JpaDataOnDemandMetadata method getInitMethod.
/**
* Returns the DoD type's "void init()" method (existing or generated)
*
* @param persistMethod
* (required)
* @return never `null`
*/
private MethodMetadataBuilder getInitMethod(final int quantity) {
// Method definition to find or build
final JavaSymbolName methodName = new JavaSymbolName("init");
final JavaType[] parameterTypes = {};
final List<JavaSymbolName> parameterNames = Collections.<JavaSymbolName>emptyList();
final JavaType returnType = JavaType.VOID_PRIMITIVE;
// Locate user-defined method
final MethodMetadata userMethod = getGovernorMethod(methodName, parameterTypes);
if (userMethod != null) {
Validate.isTrue(userMethod.getReturnType().equals(returnType), "Method '%s' on '%s' must return '%s'", methodName, destination, returnType.getNameIncludingTypeParameters());
return new MethodMetadataBuilder(userMethod);
}
// Create the method body
final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
bodyBuilder.appendFormalLine("int from = 0;");
bodyBuilder.appendFormalLine("int to = " + quantity + ";");
// CriteriaBuilder cb = entityManager.getCriteriaBuilder();
bodyBuilder.newLine();
bodyBuilder.appendFormalLine("%s cb = %s().getCriteriaBuilder();", getNameOfJavaType(JpaJavaType.CRITERIA_BUILDER), getAccessorMethod(getEntityManagerField().build()).getMethodName());
// CriteriaQuery<Entity> cq = cb.createQuery(Entity.class);
bodyBuilder.appendFormalLine("%1$s<%2$s> cq = cb.createQuery(%2$s.class);", getNameOfJavaType(JpaJavaType.CRITERIA_QUERY), getNameOfJavaType(this.entity));
// Root<Entity> rootEntry = cq.from(Entity.class);
bodyBuilder.appendFormalLine("%1$s<%2$s> rootEntry = cq.from(%2$s.class);", getNameOfJavaType(JpaJavaType.ROOT), getNameOfJavaType(this.entity));
// CriteriaQuery<Owner> all = cq.select(rootEntry);
bodyBuilder.appendFormalLine("%s<%s> all = cq.select(rootEntry);", getNameOfJavaType(JpaJavaType.CRITERIA_QUERY), getNameOfJavaType(this.entity));
// TypedQuery<Owner> allQuery =
bodyBuilder.appendFormalLine("%s<%s> allQuery = ", getNameOfJavaType(JpaJavaType.TYPED_QUERY), getNameOfJavaType(this.entity));
// entityManager.createQuery(all).setFirstResult(from).setMaxResults(to);
bodyBuilder.indent();
bodyBuilder.appendFormalLine("%s().createQuery(all).setFirstResult(from).setMaxResults(to);", getAccessorMethod(getEntityManagerField().build()).getMethodName());
// setData(allQuery.getResultList());
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("%s(allQuery.getResultList());", getMutatorMethod(getDataField().build()).getMethodName());
// if (getData() == null) {
bodyBuilder.appendFormalLine("if (%s() == null) {", getAccessorMethod(getDataField().build()).getMethodName());
// throw new IllegalStateException(
bodyBuilder.indent();
bodyBuilder.appendFormalLine("throw new IllegalStateException(");
// "Find entries implementation for 'Owner' illegally returned null");
bodyBuilder.indent();
bodyBuilder.appendFormalLine("\"Find entries implementation for '%s' illegally returned null\");", getNameOfJavaType(this.entity));
// }
bodyBuilder.indentRemove();
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
// if (!data.isEmpty()) {
bodyBuilder.appendFormalLine("if (!%s().isEmpty()) {", getAccessorMethod(getDataField().build()).getMethodName());
// return;
bodyBuilder.indent();
bodyBuilder.appendFormalLine("return;");
// }
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
// setData(new ArrayList<Entity>());
bodyBuilder.newLine();
bodyBuilder.appendFormalLine("%s(new %s<%s>());", getMutatorMethod(getDataField().build()).getMethodName(), getNameOfJavaType(JdkJavaType.ARRAY_LIST), getNameOfJavaType(this.entity));
// for (int i = from; i < to; i++) {
bodyBuilder.appendFormalLine("for (int i = from; i < to; i++) {");
bodyBuilder.indent();
// Entity obj = factory.create(i);
bodyBuilder.appendFormalLine("%s %s = %s().%s(i);", getNameOfJavaType(this.entity), OBJ_VAR, getAccessorMethod(getEntityFactoryField().build()).getMethodName(), this.entityFactoryMetadata.getCreateFactoryMethodName());
// try {
bodyBuilder.appendFormalLine("try {");
bodyBuilder.indent();
// entityManager.persist(obj);
bodyBuilder.appendFormalLine("%s().persist(%s);", getAccessorMethod(getEntityManagerField().build()).getMethodName(), OBJ_VAR);
// } catch (final ConstraintViolationException e) {
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("} catch (final %s e) {", getNameOfJavaType(Jsr303JavaType.CONSTRAINT_VIOLATION_EXCEPTION));
bodyBuilder.indent();
// final StringBuilder msg = new StringBuilder();
bodyBuilder.appendFormalLine("final StringBuilder msg = new StringBuilder();");
// for (Iterator<ConstraintViolation<?>> iter = e.getConstraintViolations().iterator(); iter
bodyBuilder.appendFormalLine("for (%s<%s<?>> iter = e.getConstraintViolations().iterator(); iter", getNameOfJavaType(JdkJavaType.ITERATOR), getNameOfJavaType(Jsr303JavaType.CONSTRAINT_VIOLATION));
// .hasNext();) {
bodyBuilder.indent();
bodyBuilder.appendFormalLine(" .hasNext();) {");
// final ConstraintViolation<?> cv = iter.next();
bodyBuilder.appendFormalLine("final %s<?> cv = iter.next();", getNameOfJavaType(Jsr303JavaType.CONSTRAINT_VIOLATION));
// msg.append("[").append(cv.getRootBean().getClass().getName()).append(".")
bodyBuilder.appendFormalLine("msg.append(\"[\").append(cv.getRootBean().getClass().getName()).append(\".\")");
// .append(cv.getPropertyPath()).append(": ").append(cv.getMessage())
bodyBuilder.appendFormalLine(".append(cv.getPropertyPath()).append(\": \").append(cv.getMessage())");
// .append(" (invalid value = ").append(cv.getInvalidValue()).append(")").append("]");
bodyBuilder.appendFormalLine(".append(\" (invalid value = \").append(cv.getInvalidValue()).append(\")\").append(\"]\");");
// }
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
// throw new IllegalStateException(msg.toString(), e);
bodyBuilder.appendFormalLine("throw new IllegalStateException(msg.toString(), e);");
// }
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
// entityManager.flush();
bodyBuilder.appendFormalLine("%s().%s();", getAccessorMethod(getEntityManagerField().build()).getMethodName(), FLUSH_METHOD_NAME);
// data.add(obj);
bodyBuilder.appendFormalLine("%s().add(%s);", getAccessorMethod(getDataField().build()).getMethodName(), OBJ_VAR);
// }
bodyBuilder.indentRemove();
bodyBuilder.appendFormalLine("}");
// Create the method
MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName, returnType, AnnotatedJavaType.convertFromJavaTypes(parameterTypes), parameterNames, bodyBuilder);
CommentStructure comment = new CommentStructure();
JavadocComment javadocComment = new JavadocComment("Creates the initial list of generated entities.");
comment.addComment(javadocComment, CommentLocation.BEGINNING);
methodBuilder.setCommentStructure(comment);
return methodBuilder;
}
Aggregations