Search in sources :

Example 71 with AnnotatedJavaType

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

the class EntityDeserializerMetadata method getConstructor.

public static ConstructorMetadata getConstructor(String declaredByMetadataId, FieldMetadata serviceField, FieldMetadata conversionServiceField) {
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // Generating constructor
    ConstructorMetadataBuilder constructor = new ConstructorMetadataBuilder(declaredByMetadataId);
    constructor.setModifier(Modifier.PUBLIC);
    constructor.addAnnotation(new AnnotationMetadataBuilder(SpringJavaType.AUTOWIRED));
    // add Service to constructor
    String serviceFieldName = serviceField.getFieldName().getSymbolName();
    AnnotatedJavaType serviceParameter = new AnnotatedJavaType(serviceField.getFieldType(), new AnnotationMetadataBuilder(SpringJavaType.LAZY).build());
    constructor.addParameterName(serviceField.getFieldName());
    constructor.addParameterType(serviceParameter);
    // Generating body
    bodyBuilder.appendFormalLine("this.%1$s = %1$s;", serviceFieldName);
    // add Conversion service to constructor
    String conversionServiceFieldName = conversionServiceField.getFieldName().getSymbolName();
    constructor.addParameter(conversionServiceFieldName, conversionServiceField.getFieldType());
    // Generating body
    bodyBuilder.appendFormalLine("this.%1$s = %1$s;", conversionServiceFieldName);
    // Adding body
    constructor.setBodyBuilder(bodyBuilder);
    return constructor.build();
}
Also used : ConstructorMetadataBuilder(org.springframework.roo.classpath.details.ConstructorMetadataBuilder) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder) AnnotationMetadataBuilder(org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)

Example 72 with AnnotatedJavaType

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

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

the class SeiImplMetadata method getEndpointMethodFromSEIMethod.

/**
 * This method obtains an Endpoint method from a provided SEI method.
 *
 * This method caches the generated methods
 *
 * @param seiMethod defined in a SEI interface
 * @param serviceMethod where this enpoint should delegate
 *
 * @return MethodMetadataBuilder that contains all the information about the new Endpoint method.
 */
private MethodMetadataBuilder getEndpointMethodFromSEIMethod(MethodMetadata seiMethod, MethodMetadata serviceMethod) {
    // Check if already exists the method
    if (endpointMethodsFromSeiMethods.get(seiMethod) != null) {
        return endpointMethodsFromSeiMethods.get(seiMethod);
    }
    // If not exists, generate it and cache it.
    // First of all, obtain the SEI method parameters and remove the @WebParam annotation from them.
    // Is not necessary in the endpoint because is already defined in the SEI
    List<JavaType> parameters = new ArrayList<JavaType>();
    for (AnnotatedJavaType type : seiMethod.getParameterTypes()) {
        parameters.add(type.getJavaType());
    }
    // Create the new endpoint method wind the updated information
    MethodMetadataBuilder endpointMethod = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, seiMethod.getMethodName(), seiMethod.getReturnType(), AnnotatedJavaType.convertFromJavaTypes(parameters), seiMethod.getParameterNames(), null);
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    // Getting parameters
    String parametersList = "";
    for (JavaSymbolName param : seiMethod.getParameterNames()) {
        parametersList = parametersList.concat(param.getSymbolName()).concat(", ");
    }
    if (StringUtils.isNotBlank(parametersList)) {
        parametersList = parametersList.substring(0, parametersList.length() - 2);
    }
    bodyBuilder.appendFormalLine("%s%s().%s(%s);", seiMethod.getReturnType() != JavaType.VOID_PRIMITIVE ? "return " : "", getAccessorMethod(getServiceField()).getMethodName(), serviceMethod.getMethodName().getSymbolName(), parametersList);
    endpointMethod.setBodyBuilder(bodyBuilder);
    endpointMethodsFromSeiMethods.put(seiMethod, endpointMethod);
    endpointMethods.add(endpointMethod.build());
    return endpointMethod;
}
Also used : AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) JavaType(org.springframework.roo.model.JavaType) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) MethodMetadataBuilder(org.springframework.roo.classpath.details.MethodMetadataBuilder) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) ArrayList(java.util.ArrayList) InvocableMemberBodyBuilder(org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)

Example 74 with AnnotatedJavaType

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

the class ItdSourceFileComposer method appendConstructors.

private void appendConstructors() {
    final List<? extends ConstructorMetadata> constructors = itdTypeDetails.getDeclaredConstructors();
    if (constructors == null || constructors.isEmpty()) {
        return;
    }
    content = true;
    for (final ConstructorMetadata constructor : constructors) {
        Validate.isTrue(constructor.getParameterTypes().size() == constructor.getParameterNames().size(), "Mismatched parameter names against parameter types");
        // ROO-3447: Append comments if exists
        CommentStructure commentStructure = constructor.getCommentStructure();
        if (commentStructure != null && commentStructure.getBeginComments() != null) {
            List<AbstractComment> constructorComments = commentStructure.getBeginComments();
            String comment = "";
            boolean missingComponentsAdded = false;
            for (AbstractComment constructorComment : constructorComments) {
                // Join all JavadocComment's
                if (constructorComment instanceof JavadocComment) {
                    // Add JavaDoc missing components
                    if (!missingComponentsAdded) {
                        if (!constructor.getParameterNames().isEmpty() && ((JavadocComment) constructorComment).getParamsInfo() == null) {
                            List<String> paramsInfo = new ArrayList<String>();
                            for (JavaSymbolName name : constructor.getParameterNames()) {
                                paramsInfo.add(name.getSymbolName());
                            }
                            ((JavadocComment) constructorComment).setParamsInfo(paramsInfo);
                        }
                    }
                    missingComponentsAdded = true;
                    comment = comment.concat(constructorComment.getComment()).concat(IOUtils.LINE_SEPARATOR);
                } else {
                    // Not JavadocComment, write comment as it is, unchanged
                    appendFormalLine(constructorComment.getComment());
                }
            }
            // Write JavadocComment's to ITD, in a single JavadocComment instance
            String[] commentLines = comment.split(IOUtils.LINE_SEPARATOR);
            for (String commentLine : commentLines) {
                appendFormalLine(commentLine);
            }
        } 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);
            // Now lines should be formatted, so write them
            String[] comment = javadocComment.getComment().split(IOUtils.LINE_SEPARATOR);
            for (String line : comment) {
                appendFormalLine(line);
            }
        }
        // Append annotations
        for (final AnnotationMetadata annotation : constructor.getAnnotations()) {
            appendIndent();
            outputAnnotation(annotation);
            this.newLine(false);
        }
        // Append "<modifier> <TargetOfIntroduction>.new" portion
        appendIndent();
        if (constructor.getModifier() != 0) {
            append(Modifier.toString(constructor.getModifier()));
            append(" ");
        }
        append(introductionTo.getSimpleTypeName());
        append(".");
        append("new");
        // Append parameter types and names
        append("(");
        final List<AnnotatedJavaType> parameterTypes = constructor.getParameterTypes();
        final List<JavaSymbolName> parameterNames = constructor.getParameterNames();
        for (int i = 0; i < parameterTypes.size(); i++) {
            final AnnotatedJavaType paramType = parameterTypes.get(i);
            final JavaSymbolName paramName = parameterNames.get(i);
            for (final AnnotationMetadata methodParameterAnnotation : paramType.getAnnotations()) {
                append(AnnotationMetadataUtils.toSourceForm(methodParameterAnnotation, resolver));
                append(" ");
            }
            append(paramType.getJavaType().getNameIncludingTypeParameters(false, resolver));
            append(" ");
            append(paramName.getSymbolName());
            if (i < parameterTypes.size() - 1) {
                append(", ");
            }
        }
        append(") {");
        this.newLine(false);
        indent();
        // Add body
        append(constructor.getBody());
        indentRemove();
        appendFormalLine("}");
        this.newLine(false);
    }
}
Also used : AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) ArrayList(java.util.ArrayList) CommentStructure(org.springframework.roo.classpath.details.comments.CommentStructure) AnnotationMetadata(org.springframework.roo.classpath.details.annotations.AnnotationMetadata) ConstructorMetadata(org.springframework.roo.classpath.details.ConstructorMetadata) JavaSymbolName(org.springframework.roo.model.JavaSymbolName) JavadocComment(org.springframework.roo.classpath.details.comments.JavadocComment) AbstractComment(org.springframework.roo.classpath.details.comments.AbstractComment)

Example 75 with AnnotatedJavaType

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

the class RepositoryJpaCustomMetadata method getFindAllGlobalSearchMethod.

/**
 * Method that generates the findAll method on current interface.
 *
 * @return
 */
private MethodMetadata getFindAllGlobalSearchMethod() {
    // Define method parameter types and parameter names
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();
    List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();
    // Global search parameter
    parameterTypes.add(GLOBAL_SEARCH_PARAMETER);
    parameterNames.add(GOBAL_SEARCH_PARAMETER_NAME);
    // Pageable parameter
    parameterTypes.add(PAGEABLE_PARAMETER);
    parameterNames.add(PAGEABLE_PARAMETER_NAME);
    // Method name
    JavaSymbolName methodName = new JavaSymbolName("findAll");
    // Return type
    JavaType returnType = new JavaType("org.springframework.data.domain.Page", 0, DataType.TYPE, null, Arrays.asList(defaultReturnType));
    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC + Modifier.ABSTRACT, methodName, returnType, parameterTypes, parameterNames, null);
    // Build and return a MethodMetadata
    return methodBuilder.build();
}
Also used : JavaSymbolName(org.springframework.roo.model.JavaSymbolName) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) SpringJavaType(org.springframework.roo.model.SpringJavaType) SpringletsJavaType(org.springframework.roo.model.SpringletsJavaType) JavaType(org.springframework.roo.model.JavaType) MethodMetadataBuilder(org.springframework.roo.classpath.details.MethodMetadataBuilder) AnnotatedJavaType(org.springframework.roo.classpath.details.annotations.AnnotatedJavaType) ArrayList(java.util.ArrayList)

Aggregations

AnnotatedJavaType (org.springframework.roo.classpath.details.annotations.AnnotatedJavaType)130 JavaSymbolName (org.springframework.roo.model.JavaSymbolName)117 ArrayList (java.util.ArrayList)116 MethodMetadataBuilder (org.springframework.roo.classpath.details.MethodMetadataBuilder)108 MethodMetadata (org.springframework.roo.classpath.details.MethodMetadata)99 InvocableMemberBodyBuilder (org.springframework.roo.classpath.itd.InvocableMemberBodyBuilder)81 AnnotationMetadataBuilder (org.springframework.roo.classpath.details.annotations.AnnotationMetadataBuilder)71 JavaType (org.springframework.roo.model.JavaType)63 SpringJavaType (org.springframework.roo.model.SpringJavaType)46 SpringletsJavaType (org.springframework.roo.model.SpringletsJavaType)41 JdkJavaType (org.springframework.roo.model.JdkJavaType)28 Jsr303JavaType (org.springframework.roo.model.Jsr303JavaType)25 FieldMetadata (org.springframework.roo.classpath.details.FieldMetadata)23 ServiceMetadata (org.springframework.roo.addon.layers.service.addon.ServiceMetadata)18 AnnotationMetadata (org.springframework.roo.classpath.details.annotations.AnnotationMetadata)16 RelationInfo (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata.RelationInfo)15 RelationInfoExtended (org.springframework.roo.addon.web.mvc.controller.addon.RelationInfoExtended)12 JpaEntityMetadata (org.springframework.roo.addon.jpa.addon.entity.JpaEntityMetadata)10 Pair (org.apache.commons.lang3.tuple.Pair)7 ClassOrInterfaceTypeDetails (org.springframework.roo.classpath.details.ClassOrInterfaceTypeDetails)7