Search in sources :

Example 11 with NameExpr

use of com.github.antlrjavaparser.api.expr.NameExpr in project spring-roo by spring-projects.

the class JavaParserAnnotationMetadataBuilder method convert.

@SuppressWarnings("unchecked")
private static MemberValuePair convert(final AnnotationAttributeValue<?> value, CompilationUnitServices compilationUnitServices) {
    if (value instanceof NestedAnnotationAttributeValue) {
        final NestedAnnotationAttributeValue castValue = (NestedAnnotationAttributeValue) value;
        AnnotationExpr annotationExpr;
        final AnnotationMetadata nestedAnnotation = castValue.getValue();
        if (castValue.getValue().getAttributeNames().size() == 0) {
            annotationExpr = new MarkerAnnotationExpr(JavaParserUtils.getNameExpr(nestedAnnotation.getAnnotationType().getSimpleTypeName()));
        } else if (castValue.getValue().getAttributeNames().size() == 1 && (castValue.getValue().getAttributeNames().get(0) == null || "value".equals(castValue.getValue().getAttributeNames().get(0).getSymbolName()))) {
            annotationExpr = new SingleMemberAnnotationExpr(JavaParserUtils.getNameExpr(nestedAnnotation.getAnnotationType().getSimpleTypeName()), convert(nestedAnnotation.getAttribute(nestedAnnotation.getAttributeNames().get(0)), compilationUnitServices).getValue());
        } else {
            final List<MemberValuePair> memberValuePairs = new ArrayList<MemberValuePair>();
            for (final JavaSymbolName attributeName : nestedAnnotation.getAttributeNames()) {
                memberValuePairs.add(convert(nestedAnnotation.getAttribute(attributeName), compilationUnitServices));
            }
            annotationExpr = new NormalAnnotationExpr(JavaParserUtils.getNameExpr(nestedAnnotation.getAnnotationType().getSimpleTypeName()), memberValuePairs);
        }
        // Add imports for nested annotation types
        JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), nestedAnnotation.getAnnotationType());
        // Rely on the nested instance to know its member value pairs
        return new MemberValuePair(value.getName().getSymbolName(), annotationExpr);
    }
    if (value instanceof BooleanAttributeValue) {
        final boolean castValue = ((BooleanAttributeValue) value).getValue();
        final BooleanLiteralExpr convertedValue = new BooleanLiteralExpr(castValue);
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof CharAttributeValue) {
        final char castValue = ((CharAttributeValue) value).getValue();
        final CharLiteralExpr convertedValue = new CharLiteralExpr(new String(new char[] { castValue }));
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof LongAttributeValue) {
        final Long castValue = ((LongAttributeValue) value).getValue();
        final LongLiteralExpr convertedValue = new LongLiteralExpr(castValue.toString() + "L");
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof IntegerAttributeValue) {
        final Integer castValue = ((IntegerAttributeValue) value).getValue();
        final IntegerLiteralExpr convertedValue = new IntegerLiteralExpr(castValue.toString());
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof DoubleAttributeValue) {
        final DoubleAttributeValue doubleAttributeValue = (DoubleAttributeValue) value;
        final Double castValue = doubleAttributeValue.getValue();
        DoubleLiteralExpr convertedValue;
        if (doubleAttributeValue.isFloatingPrecisionOnly()) {
            convertedValue = new DoubleLiteralExpr(castValue.toString() + "F");
        } else {
            convertedValue = new DoubleLiteralExpr(castValue.toString() + "D");
        }
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof StringAttributeValue) {
        final String castValue = ((StringAttributeValue) value).getValue();
        final StringLiteralExpr convertedValue = new StringLiteralExpr(castValue.toString());
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof EnumAttributeValue) {
        final EnumDetails castValue = ((EnumAttributeValue) value).getValue();
        // This isn't as elegant as it could be (ie loss of type
        // parameters), but it will do for now
        final FieldAccessExpr convertedValue = new FieldAccessExpr(JavaParserUtils.getNameExpr(castValue.getType().getFullyQualifiedTypeName()), castValue.getField().getSymbolName());
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof ClassAttributeValue) {
        final JavaType castValue = ((ClassAttributeValue) value).getValue();
        // This doesn't preserve type parameters
        final NameExpr nameExpr = JavaParserUtils.importTypeIfRequired(compilationUnitServices.getEnclosingTypeName(), compilationUnitServices.getImports(), castValue);
        final ClassExpr convertedValue = new ClassExpr(JavaParserUtils.getReferenceType(nameExpr));
        return new MemberValuePair(value.getName().getSymbolName(), convertedValue);
    }
    if (value instanceof ArrayAttributeValue) {
        final ArrayAttributeValue<AnnotationAttributeValue<?>> castValue = (ArrayAttributeValue<AnnotationAttributeValue<?>>) value;
        final List<Expression> arrayElements = new ArrayList<Expression>();
        for (final AnnotationAttributeValue<?> v : castValue.getValue()) {
            final MemberValuePair converted = convert(v, compilationUnitServices);
            if (converted != null) {
                arrayElements.add(converted.getValue());
            }
        }
        return new MemberValuePair(value.getName().getSymbolName(), new ArrayInitializerExpr(arrayElements));
    }
    throw new UnsupportedOperationException("Unsupported attribute value '" + value.getName() + "' of type '" + value.getClass().getName() + "'");
}
Also used : IntegerLiteralExpr(com.github.antlrjavaparser.api.expr.IntegerLiteralExpr) ClassAttributeValue(org.springframework.roo.classpath.details.annotations.ClassAttributeValue) AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) MarkerAnnotationExpr(com.github.antlrjavaparser.api.expr.MarkerAnnotationExpr) SingleMemberAnnotationExpr(com.github.antlrjavaparser.api.expr.SingleMemberAnnotationExpr) NormalAnnotationExpr(com.github.antlrjavaparser.api.expr.NormalAnnotationExpr) DoubleAttributeValue(org.springframework.roo.classpath.details.annotations.DoubleAttributeValue) StringLiteralExpr(com.github.antlrjavaparser.api.expr.StringLiteralExpr) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) ArrayList(java.util.ArrayList) CharAttributeValue(org.springframework.roo.classpath.details.annotations.CharAttributeValue) EnumAttributeValue(org.springframework.roo.classpath.details.annotations.EnumAttributeValue) EnumDetails(org.springframework.roo.model.EnumDetails) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) SingleMemberAnnotationExpr(com.github.antlrjavaparser.api.expr.SingleMemberAnnotationExpr) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) MemberValuePair(com.github.antlrjavaparser.api.expr.MemberValuePair) ArrayInitializerExpr(com.github.antlrjavaparser.api.expr.ArrayInitializerExpr) BooleanLiteralExpr(com.github.antlrjavaparser.api.expr.BooleanLiteralExpr) LongLiteralExpr(com.github.antlrjavaparser.api.expr.LongLiteralExpr) ArrayList(java.util.ArrayList) List(java.util.List) FieldAccessExpr(com.github.antlrjavaparser.api.expr.FieldAccessExpr) NormalAnnotationExpr(com.github.antlrjavaparser.api.expr.NormalAnnotationExpr) StringAttributeValue(org.springframework.roo.classpath.details.annotations.StringAttributeValue) NestedAnnotationAttributeValue(org.springframework.roo.classpath.details.annotations.NestedAnnotationAttributeValue) ArrayAttributeValue(org.springframework.roo.classpath.details.annotations.ArrayAttributeValue) AnnotationAttributeValue(org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue) NestedAnnotationAttributeValue(org.springframework.roo.classpath.details.annotations.NestedAnnotationAttributeValue) IntegerAttributeValue(org.springframework.roo.classpath.details.annotations.IntegerAttributeValue) CharLiteralExpr(com.github.antlrjavaparser.api.expr.CharLiteralExpr) MarkerAnnotationExpr(com.github.antlrjavaparser.api.expr.MarkerAnnotationExpr) BooleanAttributeValue(org.springframework.roo.classpath.details.annotations.BooleanAttributeValue) JavaType(org.springframework.roo.model.JavaType) LongAttributeValue(org.springframework.roo.classpath.details.annotations.LongAttributeValue) DoubleLiteralExpr(com.github.antlrjavaparser.api.expr.DoubleLiteralExpr) Expression(com.github.antlrjavaparser.api.expr.Expression) ClassExpr(com.github.antlrjavaparser.api.expr.ClassExpr)

Example 12 with NameExpr

use of com.github.antlrjavaparser.api.expr.NameExpr in project spring-roo by spring-projects.

the class JavaParserTypeParsingService method updateOutput.

/**
 * Appends the presented class to the end of the presented body
 * declarations. The body declarations appear within the presented
 * compilation unit. This is used to progressively build inner types.
 *
 * @param compilationUnit the work-in-progress compilation unit (required)
 * @param enclosingCompilationUnitServices
 * @param cid the new class to add (required)
 * @param parent the class body declarations a subclass should be added to
 *            (may be null, which denotes a top-level type within the
 *            compilation unit)
 */
private void updateOutput(final CompilationUnit compilationUnit, CompilationUnitServices enclosingCompilationUnitServices, final ClassOrInterfaceTypeDetails cid, final List<BodyDeclaration> parent) {
    // Append the new imports this class declares
    Validate.notNull(compilationUnit.getImports(), "Compilation unit imports should be non-null when producing type '%s'", cid.getName());
    for (final ImportMetadata importType : cid.getRegisteredImports()) {
        ImportDeclaration importDeclaration;
        if (!importType.isAsterisk()) {
            NameExpr typeToImportExpr;
            if (importType.getImportType().getEnclosingType() == null) {
                typeToImportExpr = new QualifiedNameExpr(new NameExpr(importType.getImportType().getPackage().getFullyQualifiedPackageName()), importType.getImportType().getSimpleTypeName());
            } else {
                typeToImportExpr = new QualifiedNameExpr(new NameExpr(importType.getImportType().getEnclosingType().getFullyQualifiedTypeName()), importType.getImportType().getSimpleTypeName());
            }
            importDeclaration = new ImportDeclaration(typeToImportExpr, importType.isStatic(), false);
        } else {
            importDeclaration = new ImportDeclaration(new NameExpr(importType.getImportPackage().getFullyQualifiedPackageName()), importType.isStatic(), importType.isAsterisk());
        }
        JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(importDeclaration, importType.getCommentStructure());
        compilationUnit.getImports().add(importDeclaration);
    }
    // Create a class or interface declaration to represent this actual type
    final int javaParserModifier = JavaParserUtils.getJavaParserModifier(cid.getModifier());
    TypeDeclaration typeDeclaration;
    ClassOrInterfaceDeclaration classOrInterfaceDeclaration;
    // Implements handling
    final List<ClassOrInterfaceType> implementsList = new ArrayList<ClassOrInterfaceType>();
    for (final JavaType current : cid.getImplementsTypes()) {
        implementsList.add(JavaParserUtils.getResolvedName(cid.getName(), current, compilationUnit));
    }
    if (cid.getPhysicalTypeCategory() == PhysicalTypeCategory.INTERFACE || cid.getPhysicalTypeCategory() == PhysicalTypeCategory.CLASS) {
        final boolean isInterface = cid.getPhysicalTypeCategory() == PhysicalTypeCategory.INTERFACE;
        if (parent == null) {
            // Top level type
            typeDeclaration = new ClassOrInterfaceDeclaration(javaParserModifier, isInterface, cid.getName().getNameIncludingTypeParameters().replace(cid.getName().getPackage().getFullyQualifiedPackageName() + ".", ""));
            classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration) typeDeclaration;
        } else {
            // Inner type
            typeDeclaration = new ClassOrInterfaceDeclaration(javaParserModifier, isInterface, cid.getName().getSimpleTypeName());
            classOrInterfaceDeclaration = (ClassOrInterfaceDeclaration) typeDeclaration;
            if (cid.getName().getParameters().size() > 0) {
                classOrInterfaceDeclaration.setTypeParameters(new ArrayList<TypeParameter>());
                for (final JavaType param : cid.getName().getParameters()) {
                    NameExpr pNameExpr = JavaParserUtils.importTypeIfRequired(cid.getName(), compilationUnit.getImports(), param);
                    final String tempName = StringUtils.replace(pNameExpr.toString(), param.getArgName() + " extends ", "", 1);
                    pNameExpr = new NameExpr(tempName);
                    final ClassOrInterfaceType pResolvedName = JavaParserUtils.getClassOrInterfaceType(pNameExpr);
                    classOrInterfaceDeclaration.getTypeParameters().add(new TypeParameter(param.getArgName().getSymbolName(), Collections.singletonList(pResolvedName)));
                }
            }
        }
        // Superclass handling
        final List<ClassOrInterfaceType> extendsList = new ArrayList<ClassOrInterfaceType>();
        for (final JavaType current : cid.getExtendsTypes()) {
            if (!OBJECT.equals(current)) {
                extendsList.add(JavaParserUtils.getResolvedName(cid.getName(), current, compilationUnit));
            }
        }
        if (extendsList.size() > 0) {
            classOrInterfaceDeclaration.setExtends(extendsList);
        }
        // Implements handling
        if (implementsList.size() > 0) {
            classOrInterfaceDeclaration.setImplements(implementsList);
        }
    } else {
        typeDeclaration = new EnumDeclaration(javaParserModifier, cid.getName().getSimpleTypeName());
    }
    typeDeclaration.setMembers(new ArrayList<BodyDeclaration>());
    Validate.notNull(typeDeclaration.getName(), "Missing type declaration name for '%s'", cid.getName());
    // If adding a new top-level type, must add it to the compilation unit
    // types
    Validate.notNull(compilationUnit.getTypes(), "Compilation unit types must not be null when attempting to add '%s'", cid.getName());
    if (parent == null) {
        // Top-level class
        compilationUnit.getTypes().add(typeDeclaration);
    } else {
        // Inner class
        parent.add(typeDeclaration);
    }
    // CompilationUnitServices needs to be created
    if (enclosingCompilationUnitServices == null) {
        // Create a compilation unit so that we can use JavaType*Metadata
        // static methods directly
        enclosingCompilationUnitServices = new CompilationUnitServices() {

            @Override
            public JavaPackage getCompilationUnitPackage() {
                return cid.getName().getPackage();
            }

            @Override
            public JavaType getEnclosingTypeName() {
                return cid.getName();
            }

            @Override
            public List<ImportDeclaration> getImports() {
                return compilationUnit.getImports();
            }

            @Override
            public List<TypeDeclaration> getInnerTypes() {
                return compilationUnit.getTypes();
            }

            @Override
            public PhysicalTypeCategory getPhysicalTypeCategory() {
                return cid.getPhysicalTypeCategory();
            }
        };
    }
    final CompilationUnitServices finalCompilationUnitServices = enclosingCompilationUnitServices;
    // A hybrid CompilationUnitServices must be provided that references the
    // enclosing types imports and package
    final CompilationUnitServices compilationUnitServices = new CompilationUnitServices() {

        @Override
        public JavaPackage getCompilationUnitPackage() {
            return finalCompilationUnitServices.getCompilationUnitPackage();
        }

        @Override
        public JavaType getEnclosingTypeName() {
            return cid.getName();
        }

        @Override
        public List<ImportDeclaration> getImports() {
            return finalCompilationUnitServices.getImports();
        }

        @Override
        public List<TypeDeclaration> getInnerTypes() {
            return compilationUnit.getTypes();
        }

        @Override
        public PhysicalTypeCategory getPhysicalTypeCategory() {
            return cid.getPhysicalTypeCategory();
        }
    };
    // Add type annotations
    final List<AnnotationExpr> annotations = new ArrayList<AnnotationExpr>();
    typeDeclaration.setAnnotations(annotations);
    for (final AnnotationMetadata candidate : cid.getAnnotations()) {
        JavaParserAnnotationMetadataBuilder.addAnnotationToList(compilationUnitServices, annotations, candidate);
    }
    // ROO-3834: Generating default Javadoc inside class if class doesn't contains JavaDoc
    List<Comment> classComments = compilationUnit.getComments();
    if (classComments == null || classComments.isEmpty()) {
        CommentStructure defaultCommentStructure = new CommentStructure();
        String defaultComment = "= ".concat(cid.getType().getSimpleTypeName()).concat("\n \nTODO Auto-generated class documentation");
        defaultCommentStructure.addComment(new JavadocComment(defaultComment), CommentLocation.BEGINNING);
        if (annotations.isEmpty()) {
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(typeDeclaration, defaultCommentStructure);
        } else {
            // If exists some annotation, include comment before the existing annotations
            AnnotationExpr firstAnnotation = annotations.get(0);
            JavaParserCommentMetadataBuilder.updateCommentsToJavaParser(firstAnnotation, defaultCommentStructure);
        }
    }
    // Add enum constants and interfaces
    if (typeDeclaration instanceof EnumDeclaration && cid.getEnumConstants().size() > 0) {
        final EnumDeclaration enumDeclaration = (EnumDeclaration) typeDeclaration;
        final List<EnumConstantDeclaration> constants = new ArrayList<EnumConstantDeclaration>();
        enumDeclaration.setEntries(constants);
        for (final JavaSymbolName constant : cid.getEnumConstants()) {
            addEnumConstant(constants, constant);
        }
        // Implements handling
        if (implementsList.size() > 0) {
            enumDeclaration.setImplements(implementsList);
        }
    }
    // Add fields
    for (final FieldMetadata candidate : cid.getDeclaredFields()) {
        JavaParserFieldMetadataBuilder.addField(compilationUnitServices, typeDeclaration.getMembers(), candidate);
    }
    // Add constructors
    for (final ConstructorMetadata candidate : cid.getDeclaredConstructors()) {
        JavaParserConstructorMetadataBuilder.addConstructor(compilationUnitServices, typeDeclaration.getMembers(), candidate, null);
    }
    // Add methods
    for (final MethodMetadata candidate : cid.getDeclaredMethods()) {
        JavaParserMethodMetadataBuilder.addMethod(compilationUnitServices, typeDeclaration.getMembers(), candidate, null);
    }
    // Add inner types
    for (final ClassOrInterfaceTypeDetails candidate : cid.getDeclaredInnerTypes()) {
        updateOutput(compilationUnit, compilationUnitServices, candidate, typeDeclaration.getMembers());
    }
    final HashSet<String> imported = new HashSet<String>();
    final ArrayList<ImportDeclaration> imports = new ArrayList<ImportDeclaration>();
    for (final ImportDeclaration importDeclaration : compilationUnit.getImports()) {
        JavaPackage importPackage = null;
        JavaType importType = null;
        if (importDeclaration.isAsterisk()) {
            importPackage = new JavaPackage(importDeclaration.getName().toString());
        } else {
            importType = new JavaType(importDeclaration.getName().toString());
            importPackage = importType.getPackage();
        }
        if (importPackage.equals(cid.getName().getPackage()) && importDeclaration.isAsterisk()) {
            continue;
        }
        if (importPackage.equals(cid.getName().getPackage()) && importType != null && importType.getEnclosingType() == null) {
            continue;
        }
        if (importType != null && importType.equals(cid.getName())) {
            continue;
        }
        if (!imported.contains(importDeclaration.getName().toString())) {
            imports.add(importDeclaration);
            imported.add(importDeclaration.getName().toString());
        }
    }
    Collections.sort(imports, new Comparator<ImportDeclaration>() {

        @Override
        public int compare(final ImportDeclaration importDeclaration, final ImportDeclaration importDeclaration1) {
            return importDeclaration.getName().toString().compareTo(importDeclaration1.getName().toString());
        }
    });
    compilationUnit.setImports(imports);
}
Also used : TypeParameter(com.github.antlrjavaparser.api.TypeParameter) PhysicalTypeCategory(org.springframework.roo.classpath.PhysicalTypeCategory) FieldMetadata(org.springframework.roo.classpath.details.FieldMetadata) AnnotationExpr(com.github.antlrjavaparser.api.expr.AnnotationExpr) ClassOrInterfaceDeclaration(com.github.antlrjavaparser.api.body.ClassOrInterfaceDeclaration) 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) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) CommentStructure(org.springframework.roo.classpath.details.comments.CommentStructure) EnumConstantDeclaration(com.github.antlrjavaparser.api.body.EnumConstantDeclaration) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) JavadocComment(org.springframework.roo.classpath.details.comments.JavadocComment) List(java.util.List) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Comment(com.github.antlrjavaparser.api.Comment) JavadocComment(org.springframework.roo.classpath.details.comments.JavadocComment) EnumDeclaration(com.github.antlrjavaparser.api.body.EnumDeclaration) JavaType(org.springframework.roo.model.JavaType) ConstructorMetadata(org.springframework.roo.classpath.details.ConstructorMetadata) ImportDeclaration(com.github.antlrjavaparser.api.ImportDeclaration) BodyDeclaration(com.github.antlrjavaparser.api.body.BodyDeclaration) MethodMetadata(org.springframework.roo.classpath.details.MethodMetadata) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) ImportMetadata(org.springframework.roo.classpath.details.ImportMetadata) TypeDeclaration(com.github.antlrjavaparser.api.body.TypeDeclaration)

Example 13 with NameExpr

use of com.github.antlrjavaparser.api.expr.NameExpr 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 14 with NameExpr

use of com.github.antlrjavaparser.api.expr.NameExpr in project spring-roo by spring-projects.

the class JavaParserUtils method importTypeIfRequired.

/**
 * Attempts to import the presented {@link JavaType}.
 * <p>
 * Whether imported or not, the method returns a {@link NameExpr} suitable
 * for subsequent use when referring to that type.
 * <p>
 * If an attempt is made to import a java.lang type, it is ignored.
 * <p>
 * If an attempt is made to import a type without a package, it is ignored.
 * <p>
 * We import every type usage even if the type usage is within the same
 * package and would theoretically not require an import. This is undertaken
 * so that there is no requirement to separately parse every unqualified
 * type usage within the compilation unit so as to refrain from importing
 * subsequently conflicting types.
 *
 * @param targetType the compilation unit target type (required)
 * @param imports the compilation unit's imports (required)
 * @param typeToImport the type to be imported (required)
 * @return the name expression to be used when referring to that type (never
 *         null)
 */
public static NameExpr importTypeIfRequired(final JavaType targetType, final List<ImportDeclaration> imports, final JavaType typeToImport) {
    Validate.notNull(targetType, "Target type is required");
    final JavaPackage compilationUnitPackage = targetType.getPackage();
    Validate.notNull(imports, "Compilation unit imports required");
    Validate.notNull(typeToImport, "Java type to import is required");
    // If it's a primitive, it's really easy
    if (typeToImport.isPrimitive()) {
        return new NameExpr(typeToImport.getNameIncludingTypeParameters());
    }
    // Handle if the type doesn't have a package at all
    if (typeToImport.isDefaultPackage()) {
        return new NameExpr(typeToImport.getSimpleTypeName());
    }
    final JavaPackage typeToImportPackage = typeToImport.getPackage();
    if (typeToImportPackage.equals(compilationUnitPackage)) {
        return new NameExpr(typeToImport.getSimpleTypeName());
    }
    NameExpr typeToImportExpr;
    if (typeToImport.getEnclosingType() == null) {
        typeToImportExpr = new QualifiedNameExpr(new NameExpr(typeToImport.getPackage().getFullyQualifiedPackageName()), typeToImport.getSimpleTypeName());
    } else {
        typeToImportExpr = new QualifiedNameExpr(new NameExpr(typeToImport.getEnclosingType().getFullyQualifiedTypeName()), typeToImport.getSimpleTypeName());
    }
    final ImportDeclaration newImport = new ImportDeclaration(typeToImportExpr, false, false);
    boolean addImport = true;
    boolean useSimpleTypeName = false;
    for (final ImportDeclaration existingImport : imports) {
        if (existingImport.getName().getName().equals(newImport.getName().getName())) {
            // Do not import, as there is already an import with the simple
            // type name
            addImport = false;
            // simple type name
            if (isEqual(existingImport.getName(), newImport.getName())) {
                useSimpleTypeName = true;
                break;
            }
        }
    }
    if (addImport && JdkJavaType.isPartOfJavaLang(typeToImport.getSimpleTypeName())) {
        // This simple type name would be part of java.lang if left as the
        // simple name. We want a fully-qualified name.
        addImport = false;
        useSimpleTypeName = false;
    }
    if (JdkJavaType.isPartOfJavaLang(typeToImport)) {
        // So we would have imported, but we don't need to
        addImport = false;
        // The fact we could have imported means there was no other
        // conflicting simple type names
        useSimpleTypeName = true;
    }
    if (addImport && typeToImport.getPackage().equals(compilationUnitPackage)) {
    // It is not theoretically necessary to add an import for something
    // in the same package,
    // but we elect to explicitly perform an import so future
    // conflicting types are not imported
    // addImport = true;
    // useSimpleTypeName = false;
    }
    if (addImport && targetType.getSimpleTypeName().equals(typeToImport.getSimpleTypeName())) {
        // So we would have imported it, but then it would conflict with the
        // simple name of the type
        addImport = false;
        useSimpleTypeName = false;
    }
    if (addImport) {
        imports.add(newImport);
        useSimpleTypeName = true;
    }
    // (forget imports, though!)
    if (typeToImport.getArgName() != null) {
        return new NameExpr(typeToImport.toString());
    }
    if (useSimpleTypeName) {
        return new NameExpr(typeToImport.getSimpleTypeName());
    }
    return new QualifiedNameExpr(new NameExpr(typeToImport.getPackage().getFullyQualifiedPackageName()), typeToImport.getSimpleTypeName());
}
Also used : QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) ImportDeclaration(com.github.antlrjavaparser.api.ImportDeclaration) JavaPackage(org.springframework.roo.model.JavaPackage)

Example 15 with NameExpr

use of com.github.antlrjavaparser.api.expr.NameExpr in project spring-roo by spring-projects.

the class JavaParserUtils method getNameExpr.

/**
 * Converts the presented class name into a name expression (either a
 * {@link NameExpr} or {@link QualifiedNameExpr} depending on whether a
 * package was presented).
 *
 * @param className to convert (required; can be fully qualified or simple
 *            name only)
 * @return a compatible expression (never returns null)
 */
public static NameExpr getNameExpr(final String className) {
    Validate.notBlank(className, "Class name required");
    if (className.contains(".")) {
        final int offset = className.lastIndexOf(".");
        final String packageName = className.substring(0, offset);
        final String typeName = className.substring(offset + 1);
        return new QualifiedNameExpr(new NameExpr(packageName), typeName);
    }
    return new NameExpr(className);
}
Also used : QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr) NameExpr(com.github.antlrjavaparser.api.expr.NameExpr) QualifiedNameExpr(com.github.antlrjavaparser.api.expr.QualifiedNameExpr)

Aggregations

NameExpr (com.github.antlrjavaparser.api.expr.NameExpr)16 QualifiedNameExpr (com.github.antlrjavaparser.api.expr.QualifiedNameExpr)11 JavaType (org.springframework.roo.model.JavaType)11 ClassOrInterfaceType (com.github.antlrjavaparser.api.type.ClassOrInterfaceType)8 ArrayList (java.util.ArrayList)8 Type (com.github.antlrjavaparser.api.type.Type)7 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)7 AnnotationExpr (com.github.antlrjavaparser.api.expr.AnnotationExpr)6 JdkJavaType (org.springframework.roo.model.JdkJavaType)6 Expression (com.github.antlrjavaparser.api.expr.Expression)5 NormalAnnotationExpr (com.github.antlrjavaparser.api.expr.NormalAnnotationExpr)5 ReferenceType (com.github.antlrjavaparser.api.type.ReferenceType)5 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)5 ImportDeclaration (com.github.antlrjavaparser.api.ImportDeclaration)4 TypeDeclaration (com.github.antlrjavaparser.api.body.TypeDeclaration)4 MarkerAnnotationExpr (com.github.antlrjavaparser.api.expr.MarkerAnnotationExpr)4 SingleMemberAnnotationExpr (com.github.antlrjavaparser.api.expr.SingleMemberAnnotationExpr)4 TypeParameter (com.github.antlrjavaparser.api.TypeParameter)3 BodyDeclaration (com.github.antlrjavaparser.api.body.BodyDeclaration)3 ArrayInitializerExpr (com.github.antlrjavaparser.api.expr.ArrayInitializerExpr)3