Search in sources :

Example 6 with Type

use of com.github.antlrjavaparser.api.type.Type in project spring-roo by spring-projects.

the class JavaParserUtils method getResolvedName.

public static Type getResolvedName(final JavaType target, final JavaType current, final CompilationUnitServices compilationUnit) {
    final NameExpr nameExpr = JavaParserUtils.importTypeIfRequired(target, compilationUnit.getImports(), current);
    final ClassOrInterfaceType resolvedName = JavaParserUtils.getClassOrInterfaceType(nameExpr);
    if (current.getParameters() != null && current.getParameters().size() > 0) {
        resolvedName.setTypeArgs(new ArrayList<Type>());
        for (final JavaType param : current.getParameters()) {
            resolvedName.getTypeArgs().add(getResolvedName(target, param, compilationUnit));
        }
    }
    if (current.getArray() > 0) {
        // Primitives includes array declaration in resolvedName
        if (!current.isPrimitive()) {
            return new ReferenceType(resolvedName, current.getArray());
        }
    }
    return resolvedName;
}
Also used : WildcardType(com.github.antlrjavaparser.api.type.WildcardType) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) DataType(org.springframework.roo.model.DataType) JdkJavaType(org.springframework.roo.model.JdkJavaType) VoidType(com.github.antlrjavaparser.api.type.VoidType) JavaType(org.springframework.roo.model.JavaType) PrimitiveType(com.github.antlrjavaparser.api.type.PrimitiveType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) Type(com.github.antlrjavaparser.api.type.Type) JdkJavaType(org.springframework.roo.model.JdkJavaType) JavaType(org.springframework.roo.model.JavaType) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType)

Example 7 with Type

use of com.github.antlrjavaparser.api.type.Type in project spring-roo by spring-projects.

the class JavaParserConstructorMetadataBuilder method addConstructor.

// TODO: Should parse the throws types from JavaParser source
public static void addConstructor(final CompilationUnitServices compilationUnitServices, final List<BodyDeclaration> members, final ConstructorMetadata constructor, final Set<JavaSymbolName> typeParameters) {
    Validate.notNull(compilationUnitServices, "Compilation unit services required");
    Validate.notNull(members, "Members required");
    Validate.notNull(constructor, "Method required");
    // Start with the basic constructor
    final ConstructorDeclaration d = new ConstructorDeclaration();
    d.setModifiers(JavaParserUtils.getJavaParserModifier(constructor.getModifier()));
    d.setName(PhysicalTypeIdentifier.getJavaType(constructor.getDeclaredByMetadataId()).getSimpleTypeName());
    // Add any constructor-level annotations (not parameter annotations)
    final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
    d.setAnnotations(annotations);
    for (final AnnotationMetadata annotation : constructor.getAnnotations()) {
        JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, annotations, annotation);
    }
    // Add any constructor parameters, including their individual
    // annotations and type parameters
    final List<Parameter> parameters = new ArrayList<Parameter>();
    d.setParameters(parameters);
    int index = -1;
    for (final AnnotatedJavaType constructorParameter : constructor.getParameterTypes()) {
        index++;
        // Add the parameter annotations applicable for this parameter type
        final List<AnnotationExpr> parameterAnnotations = new ArrayList<AnnotationExpr>();
        for (final AnnotationMetadata parameterAnnotation : constructorParameter.getAnnotations()) {
            JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, parameterAnnotations, parameterAnnotation);
        }
        // Compute the parameter name
        final String parameterName = constructor.getParameterNames().get(index).getSymbolName();
        // Compute the parameter type
        Type parameterType = null;
        if (constructorParameter.getJavaType().isPrimitive()) {
            parameterType = JavaParserUtils.getType(constructorParameter.getJavaType());
        } else {
            final Type finalType = JavaParserUtils.getResolvedName(constructorParameter.getJavaType(), constructorParameter.getJavaType(), compilationUnitServices);
            final ClassOrInterfaceType cit = JavaParserUtils.getClassOrInterfaceType(finalType);
            // Add any type arguments presented for the return type
            if (constructorParameter.getJavaType().getParameters().size() > 0) {
                final List<Type> typeArgs = new ArrayList<Type>();
                cit.setTypeArgs(typeArgs);
                for (final JavaType parameter : constructorParameter.getJavaType().getParameters()) {
                    // NameExpr importedParameterType =
                    // JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(),
                    // compilationUnitServices.getImports(), parameter);
                    // typeArgs.add(JavaParserUtils.getReferenceType(importedParameterType));
                    typeArgs.add(JavaParserUtils.importParametersForType(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), parameter));
                }
            }
            parameterType = finalType;
        }
        // Create a Java Parser constructor parameter and add it to the list
        // of parameters
        final Parameter p = new Parameter(parameterType, new VariableDeclaratorId(parameterName));
        p.setAnnotations(parameterAnnotations);
        parameters.add(p);
    }
    // Set the body
    if (constructor.getBody() == null || constructor.getBody().length() == 0) {
        d.setBlock(new BlockStmt());
    } else {
        // There is a body.
        // We need to make a fake constructor 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("  TemporaryClass() {\n");
        sb.append(constructor.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 ConstructorDeclaration)) {
            throw new IllegalStateException("Illegal state: JavaParser did not return a method declaration correctly");
        }
        final ConstructorDeclaration cd = (ConstructorDeclaration) bd;
        d.setBlock(cd.getBlock());
    }
    // already exists
    for (final BodyDeclaration bd : members) {
        if (bd instanceof ConstructorDeclaration) {
            // Next constructor should appear after this current constructor
            final ConstructorDeclaration cd = (ConstructorDeclaration) bd;
            if (cd.getParameters().size() == d.getParameters().size()) {
                // Possible match, we need to consider parameter types as
                // well now
                final ConstructorMetadata constructorMetadata = new JavaParserConstructorMetadataBuilder(constructor.getDeclaredByMetadataId(), cd, compilationUnitServices, typeParameters).build();
                boolean matchesFully = true;
                for (final AnnotatedJavaType existingParameter : constructorMetadata.getParameterTypes()) {
                    if (!existingParameter.getJavaType().equals(constructor.getParameterTypes().get(index))) {
                        matchesFully = false;
                        break;
                    }
                }
                if (matchesFully) {
                    throw new IllegalStateException("Constructor '" + constructor.getParameterNames() + "' already exists with identical parameters");
                }
            }
        }
    }
    // ROO-3834: Append Javadoc
    CommentStructure commentStructure = constructor.getCommentStructure();
    if (constructor.getCommentStructure() != null) {
        // annotation
        if (annotations != null && annotations.size() > 0) {
            AnnotationExpr firstAnnotation = annotations.get(0);
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, commentStructure);
        // Otherwise, add comments to the field declaration line
        } else {
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, commentStructure);
        }
    } else {
        // ROO-3834: Append default Javadoc if not exists a comment structure,
        // including constructor params
        CommentStructure defaultCommentStructure = new CommentStructure();
        List<String> parameterNames = new ArrayList<String>();
        for (JavaSymbolName name : constructor.getParameterNames()) {
            parameterNames.add(name.getSymbolName());
        }
        JavadocComment javadocComment = new JavadocComment("TODO Auto-generated constructor documentation", parameterNames, null, null);
        defaultCommentStructure.addComment(javadocComment, CommentLocation.BEGINNING);
        constructor.setCommentStructure(defaultCommentStructure);
        // annotation
        if (annotations != null && annotations.size() > 0) {
            AnnotationExpr firstAnnotation = annotations.get(0);
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, defaultCommentStructure);
        // Otherwise, add comments to the constructor declaration line
        } else {
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(d, defaultCommentStructure);
        }
    }
    // Add the constructor to the end of the compilation unit
    members.add(d);
}
Also used : AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) ArrayList(java.util.ArrayList) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) 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) ConstructorDeclaration(com.github.antlrjavaparser.api.body.ConstructorDeclaration) CompilationUnit(com.github.antlrjavaparser.api.CompilationUnit) 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) Type(com.github.antlrjavaparser.api.type.Type) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JavaType(org.springframework.roo.model.JavaType) ConstructorMetadata(org.springframework.roo.classpath.details.ConstructorMetadata) 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 8 with Type

use of com.github.antlrjavaparser.api.type.Type in project spring-roo by spring-projects.

the class JavaParserUtils method importExpressionIfRequired.

/**
 * Recognises {@link Expression}s of type {@link FieldAccessExpr} and
 * {@link ClassExpr} and automatically imports them if required, returning
 * the correct {@link Expression} that should subsequently be used.
 * <p>
 * Even if an {@link Expression} is not resolved by this method into a type
 * and/or imported, the method guarantees to always return an
 * {@link Expression} that the caller can subsequently use in place of the
 * passed {@link Expression}. In practical terms, the {@link Expression}
 * passed to this method will be returned unless the type was already
 * imported, just imported, or represented a java.lang type.
 *
 * @param targetType the compilation unit target type (required)
 * @param imports the existing imports (required)
 * @param value that expression, which need not necessarily be resolvable to
 *            a type (required)
 * @return the expression to now use, as appropriately resolved (never
 *         returns null)
 */
public static Expression importExpressionIfRequired(final JavaType targetType, final List<ImportDeclaration> imports, final Expression value) {
    Validate.notNull(targetType, "Target type required");
    Validate.notNull(imports, "Imports required");
    Validate.notNull(value, "Expression value required");
    if (value instanceof FieldAccessExpr) {
        final Expression scope = ((FieldAccessExpr) value).getScope();
        final String field = ((FieldAccessExpr) value).getField();
        if (scope instanceof QualifiedNameExpr) {
            final String packageName = ((QualifiedNameExpr) scope).getQualifier().getName();
            final String simpleName = ((QualifiedNameExpr) scope).getName();
            final String fullyQualifiedName = packageName + "." + simpleName;
            final JavaType javaType = new JavaType(fullyQualifiedName);
            final NameExpr nameToUse = importTypeIfRequired(targetType, imports, javaType);
            if (!(nameToUse instanceof QualifiedNameExpr)) {
                return new FieldAccessExpr(nameToUse, field);
            }
        }
    } else if (value instanceof ClassExpr) {
        final Type type = ((ClassExpr) value).getType();
        if (type instanceof ClassOrInterfaceType) {
            final JavaType javaType = new JavaType(((ClassOrInterfaceType) type).getName());
            final NameExpr nameToUse = importTypeIfRequired(targetType, imports, javaType);
            if (!(nameToUse instanceof QualifiedNameExpr)) {
                return new ClassExpr(new ClassOrInterfaceType(javaType.getSimpleTypeName()));
            }
        } else if (type instanceof ReferenceType && ((ReferenceType) type).getType() instanceof ClassOrInterfaceType) {
            final ClassOrInterfaceType cit = (ClassOrInterfaceType) ((ReferenceType) type).getType();
            final JavaType javaType = new JavaType(cit.getName());
            final NameExpr nameToUse = importTypeIfRequired(targetType, imports, javaType);
            if (!(nameToUse instanceof QualifiedNameExpr)) {
                return new ClassExpr(new ClassOrInterfaceType(javaType.getSimpleTypeName()));
            }
        }
    } else if (value instanceof ArrayInitializerExpr) {
        List<Expression> values = ((ArrayInitializerExpr) value).getValues();
        for (Expression expressionValue : values) {
            // Check annotation expression
            if (expressionValue instanceof NormalAnnotationExpr) {
                Validate.isInstanceOf(NormalAnnotationExpr.class, expressionValue, "Attempting to add >1 annotation member-value pair requires an existing normal annotation expression");
                final List<MemberValuePair> annotationPairs = ((NormalAnnotationExpr) expressionValue).getPairs();
                for (final MemberValuePair pair : annotationPairs) {
                    final Expression toUse = JavaParserUtils.importExpressionIfRequired(targetType, imports, pair.getValue());
                    pair.setValue(toUse);
                }
            }
        }
    }
    // Make no changes
    return value;
}
Also used : NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) JdkJavaType(org.springframework.roo.model.JdkJavaType) JavaType(org.springframework.roo.model.JavaType) WildcardType(com.github.antlrjavaparser.api.type.WildcardType) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) DataType(org.springframework.roo.model.DataType) JdkJavaType(org.springframework.roo.model.JdkJavaType) VoidType(com.github.antlrjavaparser.api.type.VoidType) JavaType(org.springframework.roo.model.JavaType) PrimitiveType(com.github.antlrjavaparser.api.type.PrimitiveType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) Type(com.github.antlrjavaparser.api.type.Type) MemberValuePair(com.github.antlrjavaparser.api.expr.MemberValuePair) Expression(com.github.antlrjavaparser.api.expr.Expression) ArrayInitializerExpr(com.github.antlrjavaparser.api.expr.ArrayInitializerExpr) FieldAccessExpr(com.github.antlrjavaparser.api.expr.FieldAccessExpr) ClassExpr(com.github.antlrjavaparser.api.expr.ClassExpr) NormalAnnotationExpr(com.github.antlrjavaparser.api.expr.NormalAnnotationExpr)

Example 9 with Type

use of com.github.antlrjavaparser.api.type.Type in project spring-roo by spring-projects.

the class JavaParserUtils method importParametersForType.

public static ReferenceType importParametersForType(final JavaType targetType, final List<ImportDeclaration> imports, final JavaType typeToImport) {
    Validate.notNull(targetType, "Target type is required");
    Validate.notNull(imports, "Compilation unit imports required");
    Validate.notNull(typeToImport, "Java type to import is required");
    final ClassOrInterfaceType cit = getClassOrInterfaceType(importTypeIfRequired(targetType, imports, typeToImport));
    // Add any type arguments presented for the return type
    if (typeToImport.getParameters().size() > 0) {
        final List<Type> typeArgs = new ArrayList<Type>();
        cit.setTypeArgs(typeArgs);
        for (final JavaType parameter : typeToImport.getParameters()) {
            typeArgs.add(JavaParserUtils.importParametersForType(targetType, imports, parameter));
        }
    }
    final ReferenceType refType = new ReferenceType(cit);
    // Handle arrays
    if (typeToImport.isArray()) {
        refType.setArrayCount(typeToImport.getArray());
    }
    return refType;
}
Also used : WildcardType(com.github.antlrjavaparser.api.type.WildcardType) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) DataType(org.springframework.roo.model.DataType) JdkJavaType(org.springframework.roo.model.JdkJavaType) VoidType(com.github.antlrjavaparser.api.type.VoidType) JavaType(org.springframework.roo.model.JavaType) PrimitiveType(com.github.antlrjavaparser.api.type.PrimitiveType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) Type(com.github.antlrjavaparser.api.type.Type) JdkJavaType(org.springframework.roo.model.JdkJavaType) JavaType(org.springframework.roo.model.JavaType) ArrayList(java.util.ArrayList) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType)

Example 10 with Type

use of com.github.antlrjavaparser.api.type.Type in project spring-roo by spring-projects.

the class JavaParserUtils method getJavaTypeNow.

/**
 * Resolves the effective {@link JavaType} a {@link ClassOrInterfaceType}
 * represents, including any type arguments.
 *
 * @param compilationUnitServices for package management (required)
 * @param cit the class or interface type to resolve (required)
 * @return the effective Java type (never null)
 */
public static JavaType getJavaTypeNow(final CompilationUnitServices compilationUnitServices, final ClassOrInterfaceType cit, final Set<JavaSymbolName> typeParameters) {
    Validate.notNull(compilationUnitServices, "Compilation unit services required");
    Validate.notNull(cit, "ClassOrInterfaceType required");
    final JavaPackage compilationUnitPackage = compilationUnitServices.getCompilationUnitPackage();
    Validate.notNull(compilationUnitPackage, "Compilation unit package required");
    String typeName = cit.getName();
    ClassOrInterfaceType scope = cit.getScope();
    while (scope != null) {
        typeName = scope.getName() + "." + typeName;
        scope = scope.getScope();
    }
    final NameExpr nameExpr = getNameExpr(typeName);
    final JavaType effectiveType = getJavaType(compilationUnitServices, nameExpr, typeParameters);
    // Handle any type arguments
    final List<JavaType> parameterTypes = new ArrayList<JavaType>();
    if (cit.getTypeArgs() != null) {
        for (final Type ta : cit.getTypeArgs()) {
            parameterTypes.add(getJavaType(compilationUnitServices, ta, typeParameters));
        }
    }
    return new JavaType(effectiveType.getFullyQualifiedTypeName(), effectiveType.getArray(), effectiveType.getDataType(), null, parameterTypes);
}
Also used : JdkJavaType(org.springframework.roo.model.JdkJavaType) JavaType(org.springframework.roo.model.JavaType) WildcardType(com.github.antlrjavaparser.api.type.WildcardType) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) DataType(org.springframework.roo.model.DataType) JdkJavaType(org.springframework.roo.model.JdkJavaType) VoidType(com.github.antlrjavaparser.api.type.VoidType) JavaType(org.springframework.roo.model.JavaType) PrimitiveType(com.github.antlrjavaparser.api.type.PrimitiveType) ReferenceType(com.github.antlrjavaparser.api.type.ReferenceType) Type(com.github.antlrjavaparser.api.type.Type) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) ArrayList(java.util.ArrayList) ClassOrInterfaceType(com.github.antlrjavaparser.api.type.ClassOrInterfaceType) JavaPackage(org.springframework.roo.model.JavaPackage)

Aggregations

Type (com.github.antlrjavaparser.api.type.Type)10 JavaType (org.springframework.roo.model.JavaType)10 ClassOrInterfaceType (com.github.antlrjavaparser.api.type.ClassOrInterfaceType)9 NameExpr (com.github.antlrjavaparser.api.expr.NameExpr)7 ReferenceType (com.github.antlrjavaparser.api.type.ReferenceType)7 PrimitiveType (com.github.antlrjavaparser.api.type.PrimitiveType)6 VoidType (com.github.antlrjavaparser.api.type.VoidType)6 WildcardType (com.github.antlrjavaparser.api.type.WildcardType)6 ArrayList (java.util.ArrayList)6 DataType (org.springframework.roo.model.DataType)6 JdkJavaType (org.springframework.roo.model.JdkJavaType)6 AnnotationExpr (com.github.antlrjavaparser.api.expr.AnnotationExpr)4 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)4 ParseException (com.github.antlrjavaparser.ParseException)3 CompilationUnit (com.github.antlrjavaparser.api.CompilationUnit)3 BodyDeclaration (com.github.antlrjavaparser.api.body.BodyDeclaration)3 TypeDeclaration (com.github.antlrjavaparser.api.body.TypeDeclaration)3 Expression (com.github.antlrjavaparser.api.expr.Expression)3 QualifiedNameExpr (com.github.antlrjavaparser.api.expr.QualifiedNameExpr)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3