use of com.github.antlrjavaparser.api.body.MethodDeclaration in project spring-roo by spring-projects.
the class UpdateCompilationUnitUtils method updateMethods.
/**
* Updates {@code originalType} methods from {@code newType} information
*
* @param originalType
* @param newType
*/
private static void updateMethods(final TypeDeclaration originalType, final TypeDeclaration newType) {
// Get a list of all methods
final List<MethodDeclaration> cidMethods = new ArrayList<MethodDeclaration>();
if (newType.getMembers() != null) {
for (final BodyDeclaration element : newType.getMembers()) {
if (element instanceof MethodDeclaration) {
cidMethods.add((MethodDeclaration) element);
}
}
}
MethodDeclaration originalMethod, newMethod;
boolean notFound;
// Iterate over every method definition
if (originalType.getMembers() != null) {
for (final Iterator<BodyDeclaration> originalMemberstIter = originalType.getMembers().iterator(); originalMemberstIter.hasNext(); ) {
final BodyDeclaration originalMember = originalMemberstIter.next();
if (!(originalMember instanceof MethodDeclaration)) {
// this is not a method definition
continue;
}
originalMethod = (MethodDeclaration) originalMember;
notFound = true;
// look at ciMethos for method
for (final Iterator<MethodDeclaration> newMethodsIter = cidMethods.iterator(); newMethodsIter.hasNext(); ) {
newMethod = newMethodsIter.next();
if (equals(originalMethod, newMethod)) {
notFound = false;
// Remove from cid methods to check
newMethodsIter.remove();
break;
}
}
if (notFound) {
originalMemberstIter.remove();
}
}
}
if (cidMethods.isEmpty()) {
// Done it
return;
}
// Add new methods
if (originalType.getMembers() == null) {
originalType.setMembers(new ArrayList<BodyDeclaration>());
}
originalType.getMembers().addAll(cidMethods);
}
use of com.github.antlrjavaparser.api.body.MethodDeclaration 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 com.github.antlrjavaparser.api.body.MethodDeclaration in project spring-roo by spring-projects.
the class JavaParserClassOrInterfaceTypeDetailsBuilder method build.
@Override
public ClassOrInterfaceTypeDetails build() {
Validate.notEmpty(compilationUnit.getTypes(), "No types in compilation unit, so unable to continue parsing");
ClassOrInterfaceDeclaration clazz = null;
EnumDeclaration enumClazz = null;
final StringBuilder sb = new StringBuilder(compilationUnit.getPackage().getName().toString());
if (name.getEnclosingType() != null) {
sb.append(".").append(name.getEnclosingType().getSimpleTypeName());
}
compilationUnitPackage = new JavaPackage(sb.toString());
// Determine the type name, adding type parameters if possible
final JavaType newName = JavaParserUtils.getJavaType(compilationUnitServices, typeDeclaration);
// Revert back to the original type name (thus avoiding unnecessary
// inferences about java.lang types; see ROO-244)
name = new JavaType(newName.getFullyQualifiedTypeName(), newName.getEnclosingType(), newName.getArray(), newName.getDataType(), newName.getArgName(), newName.getParameters(), name.getModule());
final ClassOrInterfaceTypeDetailsBuilder cidBuilder = new ClassOrInterfaceTypeDetailsBuilder(declaredByMetadataId);
physicalTypeCategory = PhysicalTypeCategory.CLASS;
if (typeDeclaration instanceof ClassOrInterfaceDeclaration) {
clazz = (ClassOrInterfaceDeclaration) typeDeclaration;
if (clazz.isInterface()) {
physicalTypeCategory = PhysicalTypeCategory.INTERFACE;
}
} else if (typeDeclaration instanceof EnumDeclaration) {
enumClazz = (EnumDeclaration) typeDeclaration;
physicalTypeCategory = PhysicalTypeCategory.ENUMERATION;
}
Validate.notNull(physicalTypeCategory, "%s (%s for %s)", UNSUPPORTED_MESSAGE_PREFIX, typeDeclaration.getClass().getSimpleName(), name);
cidBuilder.setName(name);
cidBuilder.setPhysicalTypeCategory(physicalTypeCategory);
imports = compilationUnit.getImports();
if (imports == null) {
imports = new ArrayList<ImportDeclaration>();
compilationUnit.setImports(imports);
}
// Verify the package declaration appears to be correct
if (compilationUnitPackage.equals(name.getPackage()) != true) {
String warningStr = "[Warning] Compilation unit package '" + compilationUnitPackage + "' unexpected for type '" + name.getPackage() + "', it may be a nested class.";
LOGGER.log(Level.WARNING, warningStr);
}
for (final ImportDeclaration importDeclaration : imports) {
if (importDeclaration.getName() instanceof QualifiedNameExpr) {
final String qualifier = ((QualifiedNameExpr) importDeclaration.getName()).getQualifier().toString();
final String simpleName = importDeclaration.getName().getName();
final String fullName = qualifier + "." + simpleName;
// We want to calculate these...
final JavaType type = new JavaType(fullName);
final JavaPackage typePackage = importDeclaration.isAsterisk() ? new JavaPackage(fullName) : type.getPackage();
// Process any comments for the import
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, importDeclaration);
final ImportMetadataBuilder newImport = new ImportMetadataBuilder(declaredByMetadataId, 0, typePackage, type, importDeclaration.isStatic(), importDeclaration.isAsterisk());
newImport.setCommentStructure(commentStructure);
cidBuilder.add(newImport.build());
}
}
// Convert Java Parser modifier into JDK modifier
cidBuilder.setModifier(JavaParserUtils.getJdkModifier(typeDeclaration.getModifiers()));
// Type parameters
final Set<JavaSymbolName> typeParameterNames = new HashSet<JavaSymbolName>();
for (final JavaType param : name.getParameters()) {
final JavaSymbolName arg = param.getArgName();
// Fortunately type names can only appear at the top-level
if (arg != null && !JavaType.WILDCARD_NEITHER_ARG.equals(arg) && !JavaType.WILDCARD_EXTENDS_ARG.equals(arg) && !JavaType.WILDCARD_SUPER_ARG.equals(arg)) {
typeParameterNames.add(arg);
}
}
List<ClassOrInterfaceType> implementsList;
List<AnnotationExpr> annotationsList = null;
List<BodyDeclaration> members = null;
if (clazz != null) {
final List<ClassOrInterfaceType> extendsList = clazz.getExtends();
if (extendsList != null) {
for (final ClassOrInterfaceType candidate : extendsList) {
final JavaType javaType = JavaParserUtils.getJavaTypeNow(compilationUnitServices, candidate, typeParameterNames);
cidBuilder.addExtendsTypes(javaType);
}
}
final List<JavaType> extendsTypes = cidBuilder.getExtendsTypes();
// Obtain the superclass, if this is a class and one is available
if (physicalTypeCategory == PhysicalTypeCategory.CLASS && extendsTypes.size() == 1) {
final JavaType superclass = extendsTypes.get(0);
final String superclassId = typeLocationService.getPhysicalTypeIdentifier(superclass);
PhysicalTypeMetadata superPtm = null;
if (superclassId != null) {
superPtm = (PhysicalTypeMetadata) metadataService.get(superclassId);
}
if (superPtm != null && superPtm.getMemberHoldingTypeDetails() != null) {
cidBuilder.setSuperclass(superPtm.getMemberHoldingTypeDetails());
}
}
implementsList = clazz.getImplements();
if (implementsList != null) {
for (final ClassOrInterfaceType candidate : implementsList) {
final JavaType javaType = JavaParserUtils.getJavaTypeNow(compilationUnitServices, candidate, typeParameterNames);
cidBuilder.addImplementsType(javaType);
}
}
annotationsList = typeDeclaration.getAnnotations();
members = clazz.getMembers();
}
if (enumClazz != null) {
final List<EnumConstantDeclaration> constants = enumClazz.getEntries();
if (constants != null) {
for (final EnumConstantDeclaration enumConstants : constants) {
cidBuilder.addEnumConstant(new JavaSymbolName(enumConstants.getName()));
}
}
implementsList = enumClazz.getImplements();
annotationsList = enumClazz.getAnnotations();
members = enumClazz.getMembers();
}
if (annotationsList != null) {
for (final AnnotationExpr candidate : annotationsList) {
final AnnotationMetadata md = JavaParserAnnotationMetadataBuilder.getInstance(candidate, compilationUnitServices).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, candidate);
md.setCommentStructure(commentStructure);
cidBuilder.addAnnotation(md);
}
}
if (members != null) {
// type in the signature of the enclosing type
for (final BodyDeclaration bodyDeclaration : members) {
if (bodyDeclaration instanceof TypeDeclaration) {
// Found a type
innerTypes.add((TypeDeclaration) bodyDeclaration);
}
}
for (final BodyDeclaration member : members) {
if (member instanceof FieldDeclaration) {
final FieldDeclaration castMember = (FieldDeclaration) member;
for (final VariableDeclarator var : castMember.getVariables()) {
final FieldMetadata field = JavaParserFieldMetadataBuilder.getInstance(declaredByMetadataId, castMember, var, compilationUnitServices, typeParameterNames).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
field.setCommentStructure(commentStructure);
cidBuilder.addField(field);
}
}
if (member instanceof MethodDeclaration) {
final MethodDeclaration castMember = (MethodDeclaration) member;
final MethodMetadata method = JavaParserMethodMetadataBuilder.getInstance(declaredByMetadataId, castMember, compilationUnitServices, typeParameterNames).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
method.setCommentStructure(commentStructure);
cidBuilder.addMethod(method);
}
if (member instanceof ConstructorDeclaration) {
final ConstructorDeclaration castMember = (ConstructorDeclaration) member;
final ConstructorMetadata constructor = JavaParserConstructorMetadataBuilder.getInstance(declaredByMetadataId, castMember, compilationUnitServices, typeParameterNames).build();
final CommentStructure commentStructure = new CommentStructure();
JavaParserCommentMetadataBuilder.updateCommentsToRoo(commentStructure, member);
constructor.setCommentStructure(commentStructure);
cidBuilder.addConstructor(constructor);
}
if (member instanceof TypeDeclaration) {
final TypeDeclaration castMember = (TypeDeclaration) member;
final JavaType innerType = new JavaType(castMember.getName(), name);
final String innerTypeMetadataId = PhysicalTypeIdentifier.createIdentifier(innerType, PhysicalTypeIdentifier.getPath(declaredByMetadataId));
final ClassOrInterfaceTypeDetails cid = new JavaParserClassOrInterfaceTypeDetailsBuilder(compilationUnit, compilationUnitServices, castMember, innerTypeMetadataId, innerType, metadataService, typeLocationService).build();
cidBuilder.addInnerType(cid);
}
}
}
return cidBuilder.build();
}
Aggregations