Example usage for java.lang.reflect Modifier PUBLIC

List of usage examples for java.lang.reflect Modifier PUBLIC

Introduction

In this page you can find the example usage for java.lang.reflect Modifier PUBLIC.

Prototype

int PUBLIC

To view the source code for java.lang.reflect Modifier PUBLIC.

Click Source Link

Document

The int value representing the public modifier.

Usage

From source file:com.github.venkateshamurthy.designpatterns.builders.FluentBuilders.java

/**
 * Writes the Builder interface source file for each of the pojo class that
 * has setter methods.<br>/*w  w w. j  av  a  2 s .c  o  m*/
 * <b>Note:It is important to look at the method's return list of classes
 * that could not be built for {@link Builder} </b>
 * 
 * @param pojoClasses
 *            is a set of pojo classes for each of which a {@link Builder}
 *            interface would be fabricated to a source folder.
 * @return a list of class objects which could not be used for building
 *         {@link Builder} interface
 * @throws NotFoundException
 *             when CtClass / Class is not found
 * @throws CannotCompileException
 *             when non-compilable statements are added
 * @throws IOException
 *             when during io errors
 */
public List<Class<?>> writeInterface(final Class<?>... pojoClasses)
        throws NotFoundException, CannotCompileException, IOException {
    if (pojoClasses.length == 0) {
        throw new IllegalArgumentException(
                "The Parameters to this method must be an array of valid public class objects");
    }
    final List<Class<?>> failedList = new ArrayList<>();
    for (final Class<?> thisPojoClass : pojoClasses) {
        if (isNotAPublicClass(thisPojoClass)) {
            throw new IllegalArgumentException(
                    "The Builders can only be created for a valid public class objects:"
                            + thisPojoClass.getName());
        }
        final Set<CtMethod> writableMethods = getWritableMethods(thisPojoClass);
        final Set<Method> writableNormalMethods = getWritableNormalMethods(thisPojoClass);
        if (writableMethods.isEmpty()) {
            failedList.add(thisPojoClass);
        } else {
            final String interfaceName = String.format("%s.%sBuilder", thisPojoClass.getPackage().getName(),
                    thisPojoClass.getSimpleName());
            final CtClass pojoBuilderInterface = ctPool.makeInterface(interfaceName, fluentBuilderClass);
            addMethodsToBuilder(pojoBuilderInterface, writableMethods);
            JCodeModel cm = new JCodeModel();
            try {
                JClass bl = new JCodeModel()._class(Builder.class.getName(), ClassType.INTERFACE)
                        .narrow(thisPojoClass);
                JDefinedClass cl = cm._class(interfaceName, ClassType.INTERFACE)._extends(bl);
                Class<?> builderClass = ctPool.toClass(pojoBuilderInterface);
                for (Method m : writableNormalMethods) {
                    JMethod jm = cl.method(Modifier.PUBLIC, builderClass, m.getName());
                    for (int i = 0; i < m.getParameterTypes().length; i++) {
                        jm.param(m.getParameterTypes()[i], "arg" + i++);
                    }
                }
                sourceFolderRoot.mkdirs();
                cm.build(sourceFolderRoot);
            } catch (Exception e) {
                throw new IOException(e);
            }
        }
    }
    return failedList;
}

From source file:org.gvnix.addon.jpa.addon.audit.JpaAuditOperationsImpl.java

@Override
public void setup(JavaType serviceClass, JavaType userType) {
    // Check parameters: get defaults
    JavaType targetServiceClass;//from  w  ww . j ava  2  s.  c o  m
    if (serviceClass == null) {
        targetServiceClass = generateUserServiceJavaType();
    } else {
        targetServiceClass = serviceClass;
    }
    JavaType targetUserType;
    if (userType == null) {
        targetUserType = JavaType.STRING;
    } else {
        targetUserType = userType;
    }

    Validate.isTrue(!JdkJavaType.isPartOfJavaLang(targetServiceClass.getSimpleTypeName()),
            "Target service class '%s' must not be part of java.lang", targetServiceClass);

    int modifier = Modifier.PUBLIC;

    final String declaredByMetadataId = PhysicalTypeIdentifier.createIdentifier(targetServiceClass,
            pathResolver.getFocusedPath(Path.SRC_MAIN_JAVA));
    File targetUserServiceFile = new File(
            typeLocationService.getPhysicalTypeCanonicalPath(declaredByMetadataId));
    if (targetUserServiceFile.exists()) {
        Validate.isTrue(!targetUserServiceFile.exists(), "Type '%s' already exists", targetServiceClass);
    }

    // Prepare class builder
    final ClassOrInterfaceTypeDetailsBuilder cidBuilder = new ClassOrInterfaceTypeDetailsBuilder(
            declaredByMetadataId, modifier, targetServiceClass, PhysicalTypeCategory.CLASS);

    // Prepare annotations array
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>(2);

    // Add @GvNIXJpaAuditUserService annotation
    AnnotationMetadataBuilder jpaAuditUserServiceAnnotation = new AnnotationMetadataBuilder(
            new JavaType(GvNIXJpaAuditUserService.class));
    if (!JavaType.STRING.equals(targetUserType)) {
        jpaAuditUserServiceAnnotation.addClassAttribute("userType", targetUserType);
    }
    annotations.add(jpaAuditUserServiceAnnotation);

    // Set annotations
    cidBuilder.setAnnotations(annotations);

    // Create User Service class
    typeManagementService.createOrUpdateTypeOnDisk(cidBuilder.build());

    refreshAuditedEntities();

    PathResolver pathResolver = projectOperations.getPathResolver();
    LogicalPath path = pathResolver.getFocusedPath(Path.SRC_MAIN_JAVA);
    String metadataId = JpaAuditUserServiceMetadata.createIdentifier(targetServiceClass, path);

    JpaAuditUserServiceMetadata metadata = (JpaAuditUserServiceMetadata) metadataService.get(metadataId);

    // Show warning about UserType
    if (isSpringSecurityInstalled()) {
        if (JavaType.STRING.equals(targetUserType)) {
            LOGGER.warning(String.format(
                    "Generating implemention of %s.%s() method which use UserDetails.getName() as user info. Customize it if is needed.",
                    targetServiceClass, JpaAuditUserServiceMetadata.GET_USER_METHOD));
        } else if (!(metadata.isUserTypeSpringSecUserDetails() && metadata.isUserTypeEntity())) {
            LOGGER.warning(String.format(
                    "You MUST customize %s.%s() method to provider user information for aduit. Addon can't identify how get %s instance.",
                    targetServiceClass, JpaAuditUserServiceMetadata.GET_USER_METHOD, targetUserType));
        }
    } else {
        LOGGER.warning(
                String.format("You MUST implement %s.%s() method to provider user information for aduit.",
                        targetServiceClass, JpaAuditUserServiceMetadata.GET_USER_METHOD));
    }

}

From source file:org.gvnix.addon.jpa.addon.batch.JpaBatchMetadata.java

/**
 * Return method <code>getEntity</code>
 * //from ww w  . j a  v a 2s  .c o  m
 * @return
 */
private MethodMetadata getGetEntityMethod() {
    // method name
    JavaSymbolName methodName = new JavaSymbolName("getEntity");

    // Check if a method exist in type
    final MethodMetadata method = methodExists(methodName, new ArrayList<AnnotatedJavaType>());
    if (method != null) {
        // If it already exists, just return the method
        return method;
    }

    // Define method annotations (none in this case)
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();

    // Define method throws types (none in this case)
    List<JavaType> throwsTypes = new ArrayList<JavaType>();

    // Define method parameter types (none in this case)
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();

    // Define method parameter names (none in this case)
    List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();

    // Create the method body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    bodyBuilder.appendFormalLine(String.format("return %s.class;", getFinalTypeName(entity)));

    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName,
            JavaType.CLASS, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    methodBuilder.setThrowsTypes(throwsTypes);

    return methodBuilder.build(); // Build and return a MethodMetadata
                                  // instance
}

From source file:org.gvnix.addon.jpa.addon.audit.JpaAuditMetadata.java

/**
 * @return gets or creates/*from   w  ww. jav a2s .c  om*/
 *         findRevison(fromRevsion,toRevision,filter,order,start,limit)
 *         method
 */
private MethodMetadata getFindRevisionsMethod() {
    // method name
    JavaSymbolName methodName = findRevisionsMethodName;

    // Define method parameter types
    List<AnnotatedJavaType> parameterTypes = helper.toAnnotedJavaType(JavaType.LONG_OBJECT,
            JavaType.LONG_OBJECT, MAP_STRING_OBJECT, LIST_STRING, JavaType.INT_OBJECT, JavaType.INT_OBJECT);

    // Check if a method exist in type
    final MethodMetadata method = helper.methodExists(methodName, parameterTypes);
    if (method != null) {
        // If it already exists, just return the method
        return method;
    }

    // Define method annotations (none in this case)
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();

    // Define method throws types (none in this case)
    List<JavaType> throwsTypes = new ArrayList<JavaType>();

    // Define method parameter names (none in this case)
    List<JavaSymbolName> parameterNames = helper.toSymbolName("fromRevision", "toRevision", "filterMap",
            "order", "start", "limit");

    // Create the method body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    revisionLogBuilder.buildBodyFindRevision(bodyBuilder, parameterNames);

    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC + Modifier.STATIC,
            methodName, revisonItemListType, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    methodBuilder.setThrowsTypes(throwsTypes);

    return methodBuilder.build(); // Build and return a MethodMetadata
}

From source file:org.gvnix.web.screen.roo.addon.RelatedPatternMetadata.java

protected MethodMetadata getCreateMethod(String patternName) {

    // TODO Some code duplicated with same method in PatternMetadata

    // Specify the desired method name
    JavaSymbolName methodName = new JavaSymbolName("createPattern" + patternName);

    // @RequestParam(value = "gvnixpattern", required = true) String
    // gvnixpattern, @Valid Owner owner, BindingResult bindingResult,
    // HttpServletRequest req, Model uiModel)

    List<JavaSymbolName> methodParamNames = new ArrayList<JavaSymbolName>();
    List<AnnotatedJavaType> methodParamTypes = new ArrayList<AnnotatedJavaType>();

    getRequestParam(methodParamNames, methodParamTypes);

    Entry<JavaSymbolName, AnnotatedJavaType> referenceRequestParam = getReferenceRequestParam();
    methodParamNames.add(referenceRequestParam.getKey());
    methodParamTypes.add(referenceRequestParam.getValue());

    MethodMetadata method = methodExists(methodName, methodParamTypes);
    if (method != null) {
        // If it already exists, just return null and omit its
        // generation via the ITD
        return null;
    }//  w  w w .  j a v  a 2 s .c  o  m

    // Create method body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    String entityNamePlural = entityTypeDetails.getPlural();

    // TODO Set master pattern reference into this entity if master has
    // composite PK

    // TODO Unify with method appendMasterRelationToEntity

    /*
     * MasterEntityName masterentityname =
     * MasterEntityName.findMasterEntityName(gvnixreference); EntityName
     * entityname = new EntityName();
     * entityname.setMasterEntityName(masterentityname);
     * uiModel.addAttribute("entityName", entityname);
     * addDateTimeFormatPatterns(uiModel); // Only if date types exists
     * return "entitynames/create";
     */
    String masterEntityName = masterEntity.getSimpleTypeName();
    String entityName = entity.getSimpleTypeName();

    // Get field from entity related with some master entity defined into
    // the fields names list
    FieldMetadata relationField = getFieldRelationMasterEntity();

    // TODO Unify next 3 cases code
    if (relationField == null) {

        // TODO This case is already required ?

        /*
         * MasterEntityName masterentityname =
         * MasterEntityName.findMasterEntityName(gvnixreference);
         * entityname.setMasterEntityName(masterentityname);
         */

        bodyBuilder.appendFormalLine(
                masterEntity.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver())
                        + " " + masterEntityName.toLowerCase() + EQUAL_OPE + masterEntityName + "."
                        + masterEntityJavaDetails.getPersistenceDetails().getFindMethod().getMethodName()
                        + GVNIX_REF_TAG);
        bodyBuilder.appendFormalLine(entityName.toLowerCase() + DOT_SET + masterEntityName + "("
                + masterEntityName.toLowerCase() + ");");
    } else if (entityTypeDetails.getPersistenceDetails().getRooIdentifierFields().contains(relationField)) {

        /*
         * EntityPK entitypk = new EntityPK(entity.getId().getField1(), ...
         * gvnixreference, ... entity.getId().getFieldN());
         * entity.setId(entitypk);
         */

        // When field metadata in composite roo identifier: use PK
        // constructor
        StringBuilder tmpBody = new StringBuilder();
        tmpBody.append(entityTypeDetails.getPersistenceDetails().getIdentifierField().getFieldType()
                .getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver())
                + " "
                + entityTypeDetails.getPersistenceDetails().getIdentifierField().getFieldType()
                        .getSimpleTypeName().toLowerCase()
                + EQUAL_NEW + entityTypeDetails.getPersistenceDetails().getIdentifierField().getFieldType()
                        .getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver())
                + "(");
        Iterator<FieldMetadata> fields = entityTypeDetails.getPersistenceDetails().getRooIdentifierFields()
                .iterator();
        while (fields.hasNext()) {
            FieldMetadata field = fields.next();
            if (field.getFieldName().equals(relationField.getFieldName())) {
                tmpBody.append(GVNIX_REF);
            } else {
                tmpBody.append(entityTypeDetails.getJavaType().getSimpleTypeName().toLowerCase() + ".get"
                        + entityTypeDetails.getPersistenceDetails().getIdentifierField().getFieldName()
                                .getSymbolNameCapitalisedFirstLetter()
                        + "().get" + field.getFieldName().getSymbolNameCapitalisedFirstLetter() + "()");
            }
            if (fields.hasNext()) {
                tmpBody.append(", ");
            }
        }
        tmpBody.append(");");
        bodyBuilder.appendFormalLine(tmpBody.toString());

        bodyBuilder.appendFormalLine(entityName.toLowerCase() + DOT_SET
                + entityTypeDetails.getPersistenceDetails().getIdentifierField().getFieldName()
                        .getSymbolNameCapitalisedFirstLetter()
                + "(" + entityTypeDetails.getPersistenceDetails().getIdentifierField().getFieldType()
                        .getSimpleTypeName().toLowerCase()
                + ");");
    } else {

        /*
         * MasterEntityName masterentityname =
         * MasterEntityName.findMasterEntityName(gvnixreference);
         * entityname.setRelationFieldName(masterentityname);
         */

        bodyBuilder.appendFormalLine(
                masterEntity.getNameIncludingTypeParameters(false, builder.getImportRegistrationResolver())
                        + " " + masterEntityName.toLowerCase() + EQUAL_OPE + masterEntityName + "."
                        + masterEntityJavaDetails.getPersistenceDetails().getFindMethod().getMethodName()
                        + GVNIX_REF_TAG);
        bodyBuilder.appendFormalLine(entityName.toLowerCase() + DOT_SET
                + relationField.getFieldName().getSymbolNameCapitalisedFirstLetter() + "("
                + masterEntityName.toLowerCase() + ");");
    }

    bodyBuilder.appendFormalLine("create(".concat(entity.getSimpleTypeName().toLowerCase())
            .concat(", bindingResult, uiModel, httpServletRequest);"));

    bodyBuilder.appendFormalLine("if ( bindingResult.hasErrors() ) {");
    bodyBuilder.indent();
    addBodyLinesForDialogBinding(bodyBuilder, DialogType.Error, "message_errorbinding_problemdescription");
    bodyBuilder.appendFormalLine(RETURN_QUOTE.concat(entityNamePlural.toLowerCase()).concat("/create\";"));
    bodyBuilder.indentRemove();
    bodyBuilder.appendFormalLine("}");

    bodyBuilder.appendFormalLine(
            RETURN_QUOTE.concat("redirect:/").concat(masterEntityJavaDetails.getPlural().toLowerCase())
                    .concat("?gvnixform&\" + refererQuery(httpServletRequest);"));

    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName,
            JavaType.STRING, methodParamTypes, methodParamNames, bodyBuilder);

    methodBuilder.setAnnotations(getRequestMappingAnnotationCreateUpdate(RequestMethod.POST, patternName));

    method = methodBuilder.build();
    controllerMethods.add(method);
    return method;
}

From source file:org.gvnix.addon.geo.addon.GvNIXGeoConversionServiceMetadata.java

/**
 * Gets <code>getStringToPolygonConverter</code> method. <br>
 * //from www.  j  a va  2  s .c o  m
 * @return
 */
private MethodMetadata getStringToPolygonConverterMethod() {
    // Define method parameter types
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();

    // Check if a method with the same signature already exists in the
    // target type
    final MethodMetadata method = methodExists(STRING_TO_POLYGON_METHOD, parameterTypes);
    if (method != null) {
        // If it already exists, just return the method and omit its
        // generation via the ITD
        return method;
    }

    // Define method annotations
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();

    // Define method throws types
    List<JavaType> throwsTypes = new ArrayList<JavaType>();

    // Define method parameter names
    List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();

    // Create the method body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    buildGetStringToPolygonConverterMethodBody(bodyBuilder);

    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC,
            STRING_TO_POLYGON_METHOD, CONVERTER_STRING_POLYGON, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    methodBuilder.setThrowsTypes(throwsTypes);

    return methodBuilder.build(); // Build and return a MethodMetadata
    // instance
}

From source file:org.codehaus.groovy.grails.compiler.injection.GrailsASTUtils.java

/**
 * Adds or modifies an existing constructor to delegate to the
 * given static constructor method for initialization logic.
 *
 * @param classNode The class node/*w  ww. j  av  a 2  s .c  o m*/
 * @param constructorMethod The constructor static method
 */
public static void addDelegateConstructor(ClassNode classNode, MethodNode constructorMethod,
        Map<String, ClassNode> genericsPlaceholders) {
    BlockStatement constructorBody = new BlockStatement();
    Parameter[] constructorParams = getRemainingParameterTypes(constructorMethod.getParameters());
    ArgumentListExpression arguments = createArgumentListFromParameters(constructorParams, true,
            genericsPlaceholders);
    MethodCallExpression constructCallExpression = new MethodCallExpression(
            new ClassExpression(constructorMethod.getDeclaringClass()), "initialize", arguments);
    constructCallExpression.setMethodTarget(constructorMethod);
    ExpressionStatement constructorInitExpression = new ExpressionStatement(constructCallExpression);
    if (constructorParams.length > 0) {
        constructorBody.addStatement(new ExpressionStatement(
                new ConstructorCallExpression(ClassNode.THIS, GrailsArtefactClassInjector.ZERO_ARGS)));
    }
    constructorBody.addStatement(constructorInitExpression);

    if (constructorParams.length == 0) {
        // handle default constructor

        ConstructorNode constructorNode = getDefaultConstructor(classNode);
        if (constructorNode != null) {
            List<AnnotationNode> annotations = constructorNode
                    .getAnnotations(new ClassNode(GrailsDelegatingConstructor.class));
            if (annotations.size() == 0) {
                Statement existingBodyCode = constructorNode.getCode();
                if (existingBodyCode instanceof BlockStatement) {
                    ((BlockStatement) existingBodyCode).addStatement(constructorInitExpression);
                } else {
                    constructorNode.setCode(constructorBody);
                }
            }
        } else {
            constructorNode = new ConstructorNode(Modifier.PUBLIC, constructorBody);
            classNode.addConstructor(constructorNode);
        }
        constructorNode.addAnnotation(new AnnotationNode(new ClassNode(GrailsDelegatingConstructor.class)));
    } else {
        // create new constructor, restoring default constructor if there is none
        ConstructorNode cn = findConstructor(classNode, constructorParams);
        if (cn == null) {
            cn = new ConstructorNode(Modifier.PUBLIC, copyParameters(constructorParams, genericsPlaceholders),
                    null, constructorBody);
            classNode.addConstructor(cn);
        } else {
            List<AnnotationNode> annotations = cn
                    .getAnnotations(new ClassNode(GrailsDelegatingConstructor.class));
            if (annotations.size() == 0) {
                Statement code = cn.getCode();
                constructorBody.addStatement(code);
                cn.setCode(constructorBody);
            }
        }

        ConstructorNode defaultConstructor = getDefaultConstructor(classNode);
        if (defaultConstructor == null) {
            // add empty
            classNode.addConstructor(new ConstructorNode(Modifier.PUBLIC, new BlockStatement()));
        }
        cn.addAnnotation(new AnnotationNode(new ClassNode(GrailsDelegatingConstructor.class)));
    }
}

From source file:com.adaptc.mws.plugins.testing.transformations.TestMixinTransformation.java

/**
 * Adds a static method to the given class node that delegates to the given method
 * and resolves the object to invoke the method on from the given expression.
 *
 * @param expression The expression/*from w ww .j a  va2  s . c om*/
 * @param classNode The class node
 * @param delegateMethod The delegate method
 * @return The added method node or null if it couldn't be added
 */
public static MethodNode addDelegateStaticMethod(Expression expression, ClassNode classNode,
        MethodNode delegateMethod) {
    Parameter[] parameterTypes = delegateMethod.getParameters();
    String declaredMethodName = delegateMethod.getName();
    if (classNode.hasDeclaredMethod(declaredMethodName, parameterTypes)) {
        return null;
    }

    BlockStatement methodBody = new BlockStatement();
    ArgumentListExpression arguments = new ArgumentListExpression();

    for (Parameter parameterType : parameterTypes) {
        arguments.addExpression(new VariableExpression(parameterType.getName()));
    }
    MethodCallExpression methodCallExpression = new MethodCallExpression(expression, declaredMethodName,
            arguments);
    methodCallExpression.setMethodTarget(delegateMethod);

    ThrowStatement missingMethodException = createMissingMethodThrowable(classNode, delegateMethod);
    VariableExpression apiVar = addApiVariableDeclaration(expression, delegateMethod, methodBody);
    IfStatement ifStatement = createIfElseStatementForApiMethodCall(methodCallExpression, apiVar,
            missingMethodException);

    methodBody.addStatement(ifStatement);
    ClassNode returnType = nonGeneric(delegateMethod.getReturnType());
    if (METHOD_MISSING_METHOD_NAME.equals(declaredMethodName)) {
        declaredMethodName = STATIC_METHOD_MISSING_METHOD_NAME;
    }
    MethodNode methodNode = classNode.getDeclaredMethod(declaredMethodName, parameterTypes);
    if (methodNode == null) {
        methodNode = new MethodNode(declaredMethodName, Modifier.PUBLIC | Modifier.STATIC, returnType,
                copyParameters(parameterTypes), EMPTY_CLASS_ARRAY, methodBody);
        methodNode.addAnnotations(delegateMethod.getAnnotations());

        classNode.addMethod(methodNode);
    }
    return methodNode;
}

From source file:org.codehaus.groovy.grails.compiler.web.ControllerActionTransformer.java

protected void transformClosureToMethod(ClassNode classNode, ClosureExpression closureAction,
        PropertyNode property, SourceUnit source, GeneratorContext context) {

    final MethodNode actionMethod = new MethodNode(property.getName(), Modifier.PUBLIC, property.getType(),
            closureAction.getParameters(), EMPTY_CLASS_ARRAY, closureAction.getCode());

    MethodNode convertedMethod = convertToMethodAction(classNode, actionMethod, source, context);
    if (convertedMethod != null) {
        classNode.addMethod(convertedMethod);
    }/* ww w . j  a va 2s .c  o m*/
    classNode.getProperties().remove(property);
    classNode.getFields().remove(property.getField());
    classNode.addMethod(actionMethod);
}

From source file:org.gvnix.addon.jpa.addon.batch.JpaBatchMetadata.java

/**
 * Return method <code>entityManager</code>
 * //from  ww w  .ja  v a 2  s. co m
 * @return
 */
private MethodMetadata getEntityManagerMethod() {
    // method name
    JavaSymbolName methodName = new JavaSymbolName("entityManager");

    // Check if a method exist in type
    final MethodMetadata method = methodExists(methodName, new ArrayList<AnnotatedJavaType>());
    if (method != null) {
        // If it already exists, just return the method
        return method;
    }

    // Define method annotations (none in this case)
    List<AnnotationMetadataBuilder> annotations = new ArrayList<AnnotationMetadataBuilder>();

    // Define method throws types (none in this case)
    List<JavaType> throwsTypes = new ArrayList<JavaType>();

    // Define method parameter types (none in this case)
    List<AnnotatedJavaType> parameterTypes = new ArrayList<AnnotatedJavaType>();

    // Define method parameter names (none in this case)
    List<JavaSymbolName> parameterNames = new ArrayList<JavaSymbolName>();

    // Create the method body
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    bodyBuilder.appendFormalLine(String.format("return %s.entityManager();", getFinalTypeName(entity)));

    // Use the MethodMetadataBuilder for easy creation of MethodMetadata
    MethodMetadataBuilder methodBuilder = new MethodMetadataBuilder(getId(), Modifier.PUBLIC, methodName,
            JpaJavaType.ENTITY_MANAGER, parameterTypes, parameterNames, bodyBuilder);
    methodBuilder.setAnnotations(annotations);
    methodBuilder.setThrowsTypes(throwsTypes);

    return methodBuilder.build(); // Build and return a MethodMetadata
    // instance
}