Search in sources :

Example 1 with TypeDeclaration

use of com.github.antlrjavaparser.api.body.TypeDeclaration in project spring-roo by spring-projects.

the class JavaParserUtils method getJavaType.

/**
 * Resolves the effective {@link JavaType} a {@link NameExpr} represents.
 * <p>
 * You should use {@link #getJavaType(CompilationUnitServices, Type, Set)}
 * where possible so that type arguments are preserved (a {@link NameExpr}
 * does not contain type arguments).
 * <p>
 * A name expression can be either qualified or unqualified.
 * <p>
 * If a name expression is qualified and the qualification starts with a
 * lowercase letter, that represents the fully-qualified name. If the
 * qualification starts with an uppercase letter, the package name is
 * prepended to the qualifier.
 * <p>
 * If a name expression is unqualified, the imports are scanned. If the
 * unqualified name expression is found in the imports, that import
 * declaration represents the fully-qualified name. If the unqualified name
 * expression is not found in the imports, it indicates the name to find is
 * either in the same package as the qualified name expression, or the type
 * relates to a member of java.lang. If part of java.lang, the fully
 * qualified name is treated as part of java.lang. Otherwise the compilation
 * unit package plus unqualified name expression represents the fully
 * qualified name expression.
 *
 * @param compilationUnitServices for package management (required)
 * @param nameToFind to locate (required)
 * @param typeParameters names to consider type parameters (can be null if
 *            there are none)
 * @return the effective Java type (never null)
 */
public static JavaType getJavaType(final CompilationUnitServices compilationUnitServices, final NameExpr nameToFind, final Set<JavaSymbolName> typeParameters) {
    Validate.notNull(compilationUnitServices, "Compilation unit services required");
    Validate.notNull(nameToFind, "Name to find is required");
    final JavaPackage compilationUnitPackage = compilationUnitServices.getCompilationUnitPackage();
    if (nameToFind instanceof QualifiedNameExpr) {
        final QualifiedNameExpr qne = (QualifiedNameExpr) nameToFind;
        // Handle qualified name expressions that are related to inner types
        // (eg Foo.Bar)
        final NameExpr qneQualifier = qne.getQualifier();
        final NameExpr enclosedBy = getNameExpr(compilationUnitServices.getEnclosingTypeName().getSimpleTypeName());
        if (isEqual(qneQualifier, enclosedBy)) {
            // This qualified name expression is simply an inner type
            // reference
            final String name = compilationUnitServices.getEnclosingTypeName().getFullyQualifiedTypeName() + "." + nameToFind.getName();
            return new JavaType(name, compilationUnitServices.getEnclosingTypeName());
        }
        // package (ROO-1210)
        if (qne.toString().length() > 1 && Character.isUpperCase(qne.toString().charAt(0))) {
            // First letter is uppercase, so this likely requires prepending
            // of some package name
            final ImportDeclaration importDeclaration = getImportDeclarationFor(compilationUnitServices, qne.getQualifier());
            if (importDeclaration == null) {
                if (!compilationUnitPackage.getFullyQualifiedPackageName().equals("")) {
                    // package
                    return new JavaType(compilationUnitServices.getCompilationUnitPackage().getFullyQualifiedPackageName() + "." + qne.toString());
                }
            } else {
                return new JavaType(importDeclaration.getName() + "." + qne.getName());
            }
        // This name expression (which contains a dot) had its qualifier
        // imported, so let's use the import
        } else {
            // a package
            return new JavaType(qne.toString());
        }
    }
    if ("?".equals(nameToFind.getName())) {
        return new JavaType(OBJECT.getFullyQualifiedTypeName(), 0, DataType.TYPE, JavaType.WILDCARD_NEITHER_ARG, null);
    }
    // list
    if (typeParameters != null && typeParameters.contains(new JavaSymbolName(nameToFind.getName()))) {
        return new JavaType(nameToFind.getName(), 0, DataType.VARIABLE, null, null);
    }
    // Check if we are looking for the enclosingType itself
    final NameExpr enclosingTypeName = getNameExpr(compilationUnitServices.getEnclosingTypeName().getSimpleTypeName());
    if (isEqual(enclosingTypeName, nameToFind)) {
        return compilationUnitServices.getEnclosingTypeName();
    }
    // check if the compilation unit itself declares that type
    for (final TypeDeclaration internalType : compilationUnitServices.getInnerTypes()) {
        final NameExpr nameExpr = getNameExpr(internalType.getName());
        if (isEqual(nameExpr, nameToFind)) {
            // Found, so now we need to convert the internalType to a proper
            // JavaType
            final String name = compilationUnitServices.getEnclosingTypeName().getFullyQualifiedTypeName() + "." + nameToFind.getName();
            return new JavaType(name);
        }
    }
    final ImportDeclaration importDeclaration = getImportDeclarationFor(compilationUnitServices, nameToFind);
    if (importDeclaration == null) {
        if (JdkJavaType.isPartOfJavaLang(nameToFind.getName())) {
            return new JavaType("java.lang." + nameToFind.getName());
        }
        final String name = compilationUnitPackage.getFullyQualifiedPackageName().equals("") ? nameToFind.getName() : compilationUnitPackage.getFullyQualifiedPackageName() + "." + nameToFind.getName();
        return new JavaType(name);
    }
    return new JavaType(importDeclaration.getName().toString());
}
Also used : QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) JdkJavaType(org.springframework.roo.model.JdkJavaType) JavaType(org.springframework.roo.model.JavaType) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) ImportDeclaration(com.github.antlrjavaparser.api.ImportDeclaration) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration) JavaPackage(org.springframework.roo.model.JavaPackage)

Example 2 with TypeDeclaration

use of com.github.antlrjavaparser.api.body.TypeDeclaration in project spring-roo by spring-projects.

the class UpdateCompilationUnitUtils method updateCompilationUnitTypes.

/**
 * Updates {@code compilationUnit} types from {@code cidCompilationUnit}
 * information
 *
 * @param compilationUnit
 * @param cidCompilationUnit
 */
public static void updateCompilationUnitTypes(final CompilationUnit compilationUnit, final CompilationUnit cidCompilationUnit) {
    boolean notFound;
    final List<TypeDeclaration> cidTypes = new ArrayList<TypeDeclaration>(cidCompilationUnit.getTypes());
    for (final Iterator<TypeDeclaration> originalTypestIter = compilationUnit.getTypes().iterator(); originalTypestIter.hasNext(); ) {
        final TypeDeclaration originalType = originalTypestIter.next();
        notFound = true;
        for (final Iterator<TypeDeclaration> newTypeIter = cidTypes.iterator(); newTypeIter.hasNext(); ) {
            final TypeDeclaration newType = newTypeIter.next();
            if (originalType.getName().equals(newType.getName()) && originalType.getClass() == newType.getClass()) {
                // new Type found in original imports
                if (originalType instanceof EnumDeclaration) {
                    updateCompilationUnitEnumeration((EnumDeclaration) originalType, (EnumDeclaration) newType);
                } else {
                    updateCompilationUnitType(originalType, newType);
                }
                // remove from newImports to check
                newTypeIter.remove();
                // Mark as found
                notFound = false;
            }
        }
        if (notFound) {
            // If not found in newTypes so remove from compilation unit
            originalTypestIter.remove();
        }
    }
    if (cidTypes.isEmpty()) {
        // Done it
        return;
    }
    // Add missing new imports
    compilationUnit.getTypes().addAll(cidTypes);
}
Also used : ArrayList(java.util.ArrayList) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration) EnumDeclaration(com.github.antlrjavaparser.api.body.EnumDeclaration)

Example 3 with TypeDeclaration

use of com.github.antlrjavaparser.api.body.TypeDeclaration 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);
}
Also used : ObjectCreationExpr(com.github.antlrjavaparser.api.expr.ObjectCreationExpr) AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) ArrayList(java.util.ArrayList) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) FieldDeclaration(com.github.antlrjavaparser.api.body.FieldDeclaration) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) CommentStructure(org.springframework.roo.classpath.details.comments.CommentStructure) VariableDeclarator(com.github.antlrjavaparser.api.body.VariableDeclarator) JavadocComment(org.springframework.roo.classpath.details.comments.JavadocComment) CompilationUnit(com.github.antlrjavaparser.api.CompilationUnit) IOException(java.io.IOException) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) JavaType(org.springframework.roo.model.JavaType) Type(com.github.antlrjavaparser.api.type.Type) JavaType(org.springframework.roo.model.JavaType) ByteArrayInputStream(java.io.ByteArrayInputStream) Expression(com.github.antlrjavaparser.api.expr.Expression) BodyDeclaration(com.github.antlrjavaparser.api.body.BodyDeclaration) ParseException(com.github.antlrjavaparser.ParseException) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration)

Example 4 with TypeDeclaration

use of com.github.antlrjavaparser.api.body.TypeDeclaration 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);
}
Also used : AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) ArrayList(java.util.ArrayList) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) CommentStructure(org.springframework.roo.classpath.details.comments.CommentStructure) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) VariableDeclaratorId(com.github.antlrjavaparser.api.body.VariableDeclaratorId) JavadocComment(org.springframework.roo.classpath.details.comments.JavadocComment) CompilationUnit(com.github.antlrjavaparser.api.CompilationUnit) MethodDeclaration(com.github.antlrjavaparser.api.body.MethodDeclaration) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) BlockStmt(com.github.antlrjavaparser.api.stmt.BlockStmt) IOException(java.io.IOException) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JavaType(org.springframework.roo.model.JavaType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) Type(com.github.antlrjavaparser.api.type.Type) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JavaType(org.springframework.roo.model.JavaType) ByteArrayInputStream(java.io.ByteArrayInputStream) TypeParameter(com.github.antlrjavaparser.api.TypeParameter) Parameter(com.github.antlrjavaparser.api.body.Parameter) BodyDeclaration(com.github.antlrjavaparser.api.body.BodyDeclaration) ParseException(com.github.antlrjavaparser.ParseException) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration)

Example 5 with TypeDeclaration

use of com.github.antlrjavaparser.api.body.TypeDeclaration in project spring-roo by spring-projects.

the class JavaParserTypeParsingService method getCompilationUnitContents.

@Override
public final String getCompilationUnitContents(final ClassOrInterfaceTypeDetails cid) {
    Validate.notNull(cid, "Class or interface type details are required");
    // Create a compilation unit to store the type to be created
    final CompilationUnit compilationUnit = new CompilationUnit();
    // NB: this import list is replaced at the end of this method by a
    // sorted version
    compilationUnit.setImports(new ArrayList<ImportDeclaration>());
    if (!cid.getName().isDefaultPackage()) {
        compilationUnit.setPackage(new PackageDeclaration(ASTHelper.createNameExpr(cid.getName().getPackage().getFullyQualifiedPackageName())));
    }
    // Add the class of interface declaration to the compilation unit
    final List<TypeDeclaration> types = new ArrayList<TypeDeclaration>();
    compilationUnit.setTypes(types);
    updateOutput(compilationUnit, null, cid, null);
    return compilationUnit.toString();
}
Also used : CompilationUnit(com.github.antlrjavaparser.api.CompilationUnit) ImportDeclaration(com.github.antlrjavaparser.api.ImportDeclaration) ArrayList(java.util.ArrayList) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration) PackageDeclaration(com.github.antlrjavaparser.api.PackageDeclaration)

Aggregations

TypeDeclaration (com.github.antlrjavaparser.api.body.TypeDeclaration)12 ArrayList (java.util.ArrayList)7 JavaType (org.springframework.roo.model.JavaType)7 CompilationUnit (com.github.antlrjavaparser.api.CompilationUnit)6 BodyDeclaration (com.github.antlrjavaparser.api.body.BodyDeclaration)6 ParseException (com.github.antlrjavaparser.ParseException)5 AnnotationExpr (com.github.antlrjavaparser.api.expr.AnnotationExpr)5 ClassOrInterfaceType (com.github.antlrjavaparser.api.type.ClassOrInterfaceType)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 IOException (java.io.IOException)5 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)5 CommentStructure (org.springframework.roo.classpath.details.comments.CommentStructure)5 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)5 ImportDeclaration (com.github.antlrjavaparser.api.ImportDeclaration)4 EnumDeclaration (com.github.antlrjavaparser.api.body.EnumDeclaration)4 NameExpr (com.github.antlrjavaparser.api.expr.NameExpr)4 JavadocComment (org.springframework.roo.classpath.details.comments.JavadocComment)4 TypeParameter (com.github.antlrjavaparser.api.TypeParameter)3 QualifiedNameExpr (com.github.antlrjavaparser.api.expr.QualifiedNameExpr)3 Type (com.github.antlrjavaparser.api.type.Type)3