Search in sources :

Example 71 with AnnotationMetadata

use of org.springframework.roo.classpath.details.annotations.AnnotationMetadata 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 72 with AnnotationMetadata

use of org.springframework.roo.classpath.details.annotations.AnnotationMetadata 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 73 with AnnotationMetadata

use of org.springframework.roo.classpath.details.annotations.AnnotationMetadata in project spring-roo by spring-projects.

the class SeleniumOperationsImpl method convertToInitializer.

private String convertToInitializer(final FieldMetadata field) {
    String initializer = " ";
    short index = 1;
    final AnnotationMetadata min = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), MIN);
    if (min != null) {
        final AnnotationAttributeValue<?> value = min.getAttribute(new JavaSymbolName("value"));
        if (value != null) {
            index = new Short(value.getValue().toString());
        }
    }
    final JavaType fieldType = field.getFieldType();
    if (field.getFieldName().getSymbolName().contains("email") || field.getFieldName().getSymbolName().contains("Email")) {
        initializer = "some@email.com";
    } else if (fieldType.equals(JavaType.STRING)) {
        initializer = "some" + field.getFieldName().getSymbolNameCapitalisedFirstLetter() + index;
    } else if (fieldType.equals(new JavaType(Date.class.getName())) || fieldType.equals(new JavaType(Calendar.class.getName()))) {
        final Calendar cal = Calendar.getInstance();
        AnnotationMetadata dateTimeFormat = null;
        String style = null;
        if ((dateTimeFormat = MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), DATE_TIME_FORMAT)) != null) {
            final AnnotationAttributeValue<?> value = dateTimeFormat.getAttribute(new JavaSymbolName("style"));
            if (value != null) {
                style = value.getValue().toString();
            }
        }
        if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), PAST) != null) {
            cal.add(Calendar.YEAR, -1);
            cal.add(Calendar.MONTH, -1);
            cal.add(Calendar.DAY_OF_MONTH, -1);
        } else if (MemberFindingUtils.getAnnotationOfType(field.getAnnotations(), FUTURE) != null) {
            cal.add(Calendar.YEAR, 1);
            cal.add(Calendar.MONTH, 1);
            cal.add(Calendar.DAY_OF_MONTH, 1);
        }
        if (style != null) {
            if (style.startsWith("-")) {
                initializer = ((SimpleDateFormat) DateFormat.getTimeInstance(DateTime.parseDateFormat(style.charAt(1)), Locale.getDefault())).format(cal.getTime());
            } else if (style.endsWith("-")) {
                initializer = ((SimpleDateFormat) DateFormat.getDateInstance(DateTime.parseDateFormat(style.charAt(0)), Locale.getDefault())).format(cal.getTime());
            } else {
                initializer = ((SimpleDateFormat) DateFormat.getDateTimeInstance(DateTime.parseDateFormat(style.charAt(0)), DateTime.parseDateFormat(style.charAt(1)), Locale.getDefault())).format(cal.getTime());
            }
        } else {
            initializer = ((SimpleDateFormat) DateFormat.getDateInstance(DateFormat.SHORT, Locale.getDefault())).format(cal.getTime());
        }
    } else if (fieldType.equals(JavaType.BOOLEAN_OBJECT) || fieldType.equals(JavaType.BOOLEAN_PRIMITIVE)) {
        initializer = Boolean.valueOf(false).toString();
    } else if (fieldType.equals(JavaType.INT_OBJECT) || fieldType.equals(JavaType.INT_PRIMITIVE)) {
        initializer = Integer.valueOf(index).toString();
    } else if (fieldType.equals(JavaType.DOUBLE_OBJECT) || fieldType.equals(JavaType.DOUBLE_PRIMITIVE)) {
        initializer = Double.toString(index);
    } else if (fieldType.equals(JavaType.FLOAT_OBJECT) || fieldType.equals(JavaType.FLOAT_PRIMITIVE)) {
        initializer = Float.toString(index);
    } else if (fieldType.equals(LONG_OBJECT) || fieldType.equals(JavaType.LONG_PRIMITIVE)) {
        initializer = Long.valueOf(index).toString();
    } else if (fieldType.equals(JavaType.SHORT_OBJECT) || fieldType.equals(JavaType.SHORT_PRIMITIVE)) {
        initializer = Short.valueOf(index).toString();
    } else if (fieldType.equals(BIG_DECIMAL)) {
        initializer = new BigDecimal(index).toString();
    }
    return initializer;
}
Also used : JavaSymbolName(org.springframework.roo.model.JavaSymbolName) SpringJavaType(org.springframework.roo.model.SpringJavaType) JavaType(org.springframework.roo.model.JavaType) Calendar(java.util.Calendar) SimpleDateFormat(java.text.SimpleDateFormat) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) Date(java.util.Date) BigDecimal(java.math.BigDecimal)

Example 74 with AnnotationMetadata

use of org.springframework.roo.classpath.details.annotations.AnnotationMetadata in project spring-roo by spring-projects.

the class SeiMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    // Getting annotated class details
    ClassOrInterfaceTypeDetails cid = governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
    AnnotationMetadata seiAnnotation = cid.getAnnotation(ROO_SEI);
    AnnotationAttributeValue<?> serviceAttr = seiAnnotation.getAttribute(new JavaSymbolName("service"));
    Validate.notNull(serviceAttr, "ERROR: You must provide a valid service to be able to generate a SEI.");
    // Getting service from annotation
    JavaType serviceType = (JavaType) serviceAttr.getValue();
    // Getting service details
    ClassOrInterfaceTypeDetails serviceTypeDetails = getTypeLocationService().getTypeDetails(serviceType);
    // Obtaining all defined methods in the service interface
    MemberDetails serviceDetails = getMemberDetailsScanner().getMemberDetails(getClass().getName(), serviceTypeDetails);
    // Registering dependency between ServiceMetadata and this one, to be able to
    // update Endpoint if service .aj file changes
    final String serviceMetadataKey = ServiceMetadata.createIdentifier(serviceTypeDetails);
    registerDependency(serviceMetadataKey, metadataIdentificationString);
    // Register dependency between Service PhysicalTypeMetadata and this one,
    // to be able to update Endpoint if service .java file changes
    final String servicePhysicalTypeKey = PhysicalTypeIdentifier.createIdentifier(serviceTypeDetails);
    registerDependency(servicePhysicalTypeKey, metadataIdentificationString);
    return new SeiMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, getProjectOperations().getTopLevelPackage(""), cid, serviceType, serviceDetails.getMethods());
}
Also used : JavaSymbolName(org.springframework.roo.model.JavaSymbolName) RooJavaType(org.springframework.roo.model.RooJavaType) JavaType(org.springframework.roo.model.JavaType) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) MemberDetails(org.springframework.roo.classpath.scanner.MemberDetails) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata)

Example 75 with AnnotationMetadata

use of org.springframework.roo.classpath.details.annotations.AnnotationMetadata in project spring-roo by spring-projects.

the class WsClientsMetadataProviderImpl method getMetadata.

@Override
protected ItdTypeDetailsProvidingMetadataItem getMetadata(final String metadataIdentificationString, final JavaType aspectName, final PhysicalTypeMetadata governorPhysicalTypeMetadata, final String itdFilename) {
    RooWsClientsAnnotationValues annotationValues = new RooWsClientsAnnotationValues(governorPhysicalTypeMetadata);
    // Getting @RooWsClients annotation
    ClassOrInterfaceTypeDetails cid = governorPhysicalTypeMetadata.getMemberHoldingTypeDetails();
    AnnotationMetadata wsClientsAnnotation = cid.getAnnotation(ROO_WS_CLIENTS);
    // Getting profile from annotation
    String profile = annotationValues.getProfile();
    // Getting endpoints from annotation
    List<WsClientEndpoint> endpoints = new ArrayList<WsClientEndpoint>();
    AnnotationAttributeValue<?> currentEndpoints = wsClientsAnnotation.getAttribute("endpoints");
    if (currentEndpoints != null) {
        List<?> values = (List<?>) currentEndpoints.getValue();
        Iterator<?> valuesIt = values.iterator();
        while (valuesIt.hasNext()) {
            NestedAnnotationAttributeValue wsClientAnnotation = (NestedAnnotationAttributeValue) valuesIt.next();
            if (wsClientAnnotation.getValue() != null && wsClientAnnotation.getValue().getAttribute("endpoint") != null) {
                // Get endpoint name
                String endpointName = null;
                if (wsClientAnnotation.getValue().getAttribute("endpoint").getValue() instanceof String) {
                    endpointName = (String) wsClientAnnotation.getValue().getAttribute("endpoint").getValue();
                }
                Validate.notNull(endpointName, "'endpoint' attribute in @RooWsClient must be a String");
                // Get endpoint nameSpace
                String endpointNameSpace = null;
                if (wsClientAnnotation.getValue().getAttribute("targetNamespace").getValue() instanceof String) {
                    endpointNameSpace = (String) wsClientAnnotation.getValue().getAttribute("targetNamespace").getValue();
                }
                Validate.notNull(endpointName, "'targetNamespace' attribute in @RooWsClient must be a String");
                // Get endpoint binding type
                EnumDetails endpointBindingType = null;
                if (wsClientAnnotation.getValue().getAttribute("binding").getValue() instanceof EnumDetails) {
                    endpointBindingType = (EnumDetails) wsClientAnnotation.getValue().getAttribute("binding").getValue();
                }
                Validate.notNull(endpointBindingType, "'binding' attribute in @RooWsClient must be a SoapBindingType");
                endpoints.add(new WsClientEndpoint(endpointName, endpointNameSpace, endpointBindingType));
            }
        }
    }
    return new WsClientsMetadata(metadataIdentificationString, aspectName, governorPhysicalTypeMetadata, endpoints, profile);
}
Also used : ArrayList(java.util.ArrayList) EnumDetails(org.springframework.roo.model.EnumDetails) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) ArrayList(java.util.ArrayList) List(java.util.List) ClassOrInterfaceTypeDetails(org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails) NestedAnnotationAttributeValue(org.springframework.roo.classpath.details.annotations.NestedAnnotationAttributeValue)

Aggregations

AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)109 JavaType (org.springframework.roo.model.JavaType)59 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)52 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)47 ArrayList (java.util.ArrayList)40 RooJavaType (org.springframework.roo.model.RooJavaType)34 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)30 AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)24 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)21 MemberDetails (org.springframework.roo.classpath.scanner.MemberDetails)20 List (java.util.List)19 ClassOrInterfaceTypeDetailsBuilder (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetailsBuilder)19 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)18 AnnotationAttributeValue (org.springframework.roo.classpath.details.annotations.AnnotationAttributeValue)17 NestedAnnotationAttributeValue (org.springframework.roo.classpath.details.annotations.NestedAnnotationAttributeValue)16 SpringJavaType (org.springframework.roo.model.SpringJavaType)15 JdkJavaType (org.springframework.roo.model.JdkJavaType)12 JpaJavaType (org.springframework.roo.model.JpaJavaType)12 ArrayAttributeValue (org.springframework.roo.classpath.details.annotations.ArrayAttributeValue)11 LinkedHashMap (java.util.LinkedHashMap)10