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.liuguangqiang.permissionhelper.PermissionHelper.java

/**
 * Invoke a method with annotation PermissionDenied.
 *
 * @param obj/*w w  w .  j ava  2  s.  c  om*/
 * @param permission
 */
private void invokeDeniedMethod(Object obj, String permission) {
    Class clazz = obj.getClass();
    PermissionDenied permissionDenied;

    for (Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(PermissionDenied.class)) {
            permissionDenied = method.getAnnotation(PermissionDenied.class);
            if (permissionDenied.permission().equals(permission)) {
                if (method.getModifiers() != Modifier.PUBLIC) {
                    throw new IllegalArgumentException(
                            String.format("Annotation method %s must be public.", method));
                }

                if (method.getParameterTypes().length > 0) {
                    throw new RuntimeException(String.format("Cannot execute non-void method %s.", method));
                }

                try {
                    method.invoke(obj);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:fr.imag.model2roo.addon.graph.GraphMetadata.java

private MethodMetadata getSampleMethod() {
    // Specify the desired method name
    JavaSymbolName methodName = new JavaSymbolName("sampleMethod");

    // Check if a method with the same signature already exists in the
    // target type
    final MethodMetadata method = methodExists(methodName, new ArrayList<AnnotatedJavaType>());
    if (method != null) {
        // If it already exists, just return the method and omit its
        // generation via the ITD
        return method;
    }/*from w w  w  .  j a  v a  2s  .  c  o m*/

    // 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("System.out.println(\"Hello World\");");

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

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

From source file:com.khs.sherpa.servlet.request.DefaultSherpaRequest.java

@SuppressWarnings("unchecked")
protected Object proccess() throws SherpaRuntimeException {
    if (!isRestful()) {
        requestProcessor = new DefaultRequestProcessor();
    } else {// w w  w  .j  av a2  s.  c om
        requestProcessor = new RestfulRequestProcessor(applicationContext);
    }

    String endpoint = requestProcessor.getEndpoint(request);
    String action = requestProcessor.getAction(request);
    String httpMethod = request.getMethod();

    if (StringUtils.isEmpty(endpoint)) {
        if (action.equals(Constants.AUTHENTICATE_ACTION)) {
            return this.processAuthenication();
        } else if (action.equals(Constants.VALID)) {
            return this.processValid();
        }
    }

    Object target = null;
    Set<Method> methods = null;

    try {
        String userid = request.getHeader("userid");
        if (userid == null) {
            userid = request.getParameter("userid");
        }
        String token = request.getHeader("token");
        if (token == null) {
            token = request.getParameter("token");
        }

        this.hasPermission(applicationContext.getType(endpoint), userid, token);

        target = applicationContext.getManagedBean(endpoint);

        if (ApplicationContextAware.class.isAssignableFrom(target.getClass())) {
            ((ApplicationContextAware) target).setApplicationContext(applicationContext);
        }

        methods = Reflections.getAllMethods(applicationContext.getType(endpoint),
                Predicates.and(Predicates.not(SherpaPredicates.withAssignableFrom(Object.class)),
                        ReflectionUtils.withModifier(Modifier.PUBLIC),
                        Predicates.not(ReflectionUtils.withModifier(Modifier.ABSTRACT)),
                        Predicates.not(SherpaPredicates.withGeneric()),
                        Predicates.and(SherpaPredicates.withAssignableFrom(
                                Enhancer.isEnhanced(target.getClass()) ? target.getClass().getSuperclass()
                                        : target.getClass())),
                        Predicates.or(ReflectionUtils.withName(action),
                                Predicates.and(ReflectionUtils.withAnnotation(Action.class),
                                        SherpaPredicates.withActionAnnotationValueEqualTo(action)))));

        if (methods.size() == 0) {
            throw new SherpaActionNotFoundException(action);
        }

    } catch (NoSuchManagedBeanExcpetion e) {
        throw new SherpaRuntimeException(e);
    }

    return this.processEndpoint(target, methods.toArray(new Method[] {}), httpMethod);
}

From source file:de.micromata.tpsb.doc.parser.japa.TestCaseVisitor.java

/**
 * Checks if the methods is a test method ==&gt; Either starts with test or has an annotation @Test
 * // w  w w  . j  a v a2  s  . c om
 * @param n the methoddeclaration which is to test if it is a test
 * @return true if it is a test method TODO consider check if the test method is void, etc and with no args?
 */
protected boolean isTest(MethodDeclaration n) {
    if ((n.getModifiers() & Modifier.PUBLIC) != Modifier.PUBLIC) {
        return false;
    }
    if ((n.getModifiers() & Modifier.STATIC) == Modifier.STATIC) {
        return false;
    }
    if (n.getName().startsWith("test")) {
        return true;
    }
    if (n.getAnnotations() == null) {
        return false;
    }

    for (AnnotationExpr ae : n.getAnnotations()) {
        if (ae.getName().getName().equals("Test")) {
            return true;
        }
        if (ae.getName().getName().equals("TpsbMetaMethod") == true) {
            return true;
        }
    }

    return false;
}

From source file:org.gvnix.addon.gva.security.providers.safe.SafeSecurityProviderMetadata.java

public SafeSecurityProviderMetadata(String identifier, JavaType aspectName,
        PhysicalTypeMetadata governorPhysicalTypeMetadata) {
    super(identifier, aspectName, governorPhysicalTypeMetadata);

    // Helper itd generation
    this.helper = new ItdBuilderHelper(this, governorPhysicalTypeMetadata,
            builder.getImportRegistrationResolver());

    this.governorsPackage = governorPhysicalTypeMetadata.getType().getPackage();
    // Imports/*from w  w w  .j a  v a  2  s.c o m*/
    helper.getFinalTypeName(
            new JavaType("org.springframework.security.authentication.encoding.PlaintextPasswordEncoder"));

    // Adding Fields
    builder.addField(getField("logger", "Logger.getLogger(SafeProvider.class.getName())",
            new JavaType("org.apache.log4j.Logger"), Modifier.PRIVATE + Modifier.STATIC, null));

    builder.addField(getField("passwordEncoder", "new PlaintextPasswordEncoder()",
            new JavaType("org.springframework.security.authentication.encoding.PasswordEncoder"),
            Modifier.PRIVATE, null));

    builder.addField(getField("saltSource", null,
            new JavaType("org.springframework.security.authentication.dao.SaltSource"), Modifier.PRIVATE,
            null));

    builder.addField(getField("applicationId", null, JAVA_TYPE_STRING, Modifier.PRIVATE, null));

    builder.addField(getField("environment", null, JAVA_TYPE_STRING, Modifier.PRIVATE, null));

    builder.addField(getField("prop", null, new JavaType(JAVA_UTIL_PROPERTIES), Modifier.PUBLIC, null));

    builder.addField(getField("loader", null, new JavaType("java.lang.ClassLoader"), Modifier.PUBLIC, null));

    builder.addField(getField("stream", null, new JavaType("java.io.InputStream"), Modifier.PUBLIC, null));

    builder.addField(getField("mapRoles", "true", JavaType.BOOLEAN_PRIMITIVE, Modifier.PRIVATE, null));

    builder.addField(getField("active", null, JavaType.BOOLEAN_PRIMITIVE, Modifier.PRIVATE, null));

    builder.addField(
            getField("filtrarPorAplicacion", null, JavaType.BOOLEAN_PRIMITIVE, Modifier.PRIVATE, null));

    // Adding Field annotations
    List<AnnotationMetadataBuilder> autenticationAnnotations = new ArrayList<AnnotationMetadataBuilder>();

    // Add @Autowired annotation
    AnnotationMetadataBuilder autowiredAnnotation = new AnnotationMetadataBuilder(
            new JavaType("org.springframework.beans.factory.annotation.Autowired"));
    autenticationAnnotations.add(autowiredAnnotation);

    builder.addField(getField("safeAutenticacionClient", null,
            new JavaType("es.gva.dgm.ayf.war.definitions.v2u00.AutenticacionArangiPortType"), Modifier.PRIVATE,
            autenticationAnnotations));

    builder.addField(getField("safeAutorizacionClient", null,
            new JavaType("es.gva.dgm.ayf.war.definitions.v2u00.AutorizacionPortType"), Modifier.PRIVATE,
            autenticationAnnotations));

    // Creating getters and setters
    builder.addMethod(getGetterMethod("saltSource",
            new JavaType("org.springframework.security.authentication.dao.SaltSource")));
    builder.addMethod(getSetterMethod("saltSource",
            new JavaType("org.springframework.security.authentication.dao.SaltSource")));
    builder.addMethod(getGetterMethod("passwordEncoder",
            new JavaType("org.springframework.security.authentication.encoding.PasswordEncoder")));
    builder.addMethod(getSetterMethod("passwordEncoder",
            new JavaType("org.springframework.security.authentication.encoding.PasswordEncoder")));
    builder.addMethod(getGetterMethod("applicationId", JAVA_TYPE_STRING));
    builder.addMethod(getSetterMethod("applicationId", JAVA_TYPE_STRING));
    builder.addMethod(getGetterMethod("environment", JAVA_TYPE_STRING));
    builder.addMethod(getSetterMethod("environment", JAVA_TYPE_STRING));
    builder.addMethod(getGetterMethod("mapRoles", JavaType.BOOLEAN_PRIMITIVE));
    builder.addMethod(getSetterMethod("mapRoles", JavaType.BOOLEAN_PRIMITIVE));
    builder.addMethod(getGetterMethod("active", JavaType.BOOLEAN_PRIMITIVE));
    builder.addMethod(getSetterMethod("active", JavaType.BOOLEAN_PRIMITIVE));
    builder.addMethod(getGetterMethod("filtrarPorAplicacion", JavaType.BOOLEAN_PRIMITIVE));
    builder.addMethod(getSetterMethod("filtrarPorAplicacion", JavaType.BOOLEAN_PRIMITIVE));

    // Creating methods
    builder.addMethod(getAdditionalAuthenticationChecksMethod());
    builder.addMethod(getRetrieveUserMethod());
    builder.addMethod(getConvertWSInfoToUserMethod());
    builder.addMethod(getConvertWSInfoToUserTodasAplicacionesMethod());
    builder.addMethod(getConvertToApplicationRolMethod());

    // Create a representation of the desired output ITD
    itdTypeDetails = builder.build();
}

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

private void injectToStringMethod(ClassNode classNode) {
    final boolean hasToString = /*GrailsASTUtils.*/implementsZeroArgMethod(classNode, "toString");

    if (!hasToString) {
        GStringExpression ge = new GStringExpression(classNode.getName() + " : ${id}");
        ge.addString(new ConstantExpression(classNode.getName() + " : "));
        ge.addValue(new VariableExpression("id"));
        Statement s = new ReturnStatement(ge);
        MethodNode mn = new MethodNode("toString", Modifier.PUBLIC, new ClassNode(String.class),
                new Parameter[0], new ClassNode[0], s);
        //if(LOG.isDebugEnabled()) {
        //    LOG.debug("[GrailsDomainInjector] Adding method [toString()] to class [" + classNode.getName() + "]");
        //}/*ww w . j ava 2  s . com*/
        classNode.addMethod(mn);
    }
}

From source file:org.gvnix.service.roo.addon.addon.ws.export.WSExportXmlElementMetadata.java

/**
 * Add annotation and method to avoid cycles converting to XML.
 * //from   w  ww .jav a  2s .  c  o m
 * @param id Declared by metadata id
 */
protected void addCycleDetection(String id) {

    // Implements class and create method to avoid XML cycles
    builder.addImplementsType(new JavaType("com.sun.xml.bind.CycleRecoverable"));

    // Create method executed when cycle detected
    JavaSymbolName methodName = new JavaSymbolName("onCycleDetected");
    JavaType returnType = new JavaType(Object.class.getName());
    List<AnnotatedJavaType> paramTypes = new ArrayList<AnnotatedJavaType>(1);
    paramTypes.add(new AnnotatedJavaType(new JavaType("com.sun.xml.bind.CycleRecoverable.Context"),
            new ArrayList<AnnotationMetadata>()));
    List<JavaSymbolName> paramNames = new ArrayList<JavaSymbolName>(1);
    paramNames.add(new JavaSymbolName("context"));
    InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    bodyBuilder.appendFormalLine("return new " + governorTypeDetails.getName() + " ();");

    builder.addMethod(new MethodMetadataBuilder(id, Modifier.PUBLIC, methodName, returnType, paramTypes,
            paramNames, bodyBuilder));
}

From source file:org.gvnix.service.roo.addon.addon.JavaParserServiceImpl.java

/**
 * {@inheritDoc}/*from  ww w.j  a va  2 s .com*/
 * <p>
 * Only creates the class if not exists in project.
 * </p>
 */
public void createGvNixWebServiceClass(JavaType type, List<AnnotationMetadata> annots,
        GvNIXAnnotationType gvNixAnnot, List<FieldMetadata> fields, List<MethodMetadata> methods,
        List<ConstructorMetadata> constrs, List<JavaType> exts, PhysicalTypeCategory physicalType,
        List<JavaSymbolName> enumConsts) {

    // Metadata Id.
    String id = PhysicalTypeIdentifier.createIdentifier(type, LogicalPath.getInstance(Path.SRC_MAIN_JAVA, ""));

    // Determine the canonical filename
    String physicalPath = typeLocationService.getPhysicalTypeCanonicalPath(id);

    // Check the file doesn't already exist
    if (!fileManager.exists(physicalPath)) {

        if (!physicalType.equals(PhysicalTypeCategory.ENUMERATION)) {
            enumConsts = null;
        }

        // Create class
        ClassOrInterfaceTypeDetailsBuilder typeDetails = new ClassOrInterfaceTypeDetailsBuilder(id,
                Modifier.PUBLIC, type, physicalType);
        for (AnnotationMetadata annotationMetadata : annots) {
            typeDetails.addAnnotation(annotationMetadata);
        }
        for (FieldMetadata field : fields) {
            typeDetails.addField(field);
        }
        for (ConstructorMetadata constr : constrs) {
            typeDetails.addConstructor(constr);
        }
        for (MethodMetadata method : methods) {
            typeDetails.addMethod(method);
        }
        for (JavaType ext : exts) {
            typeDetails.addExtendsTypes(ext);
        }
        if (enumConsts != null) {
            for (JavaSymbolName enumConst : enumConsts) {
                typeDetails.addEnumConstant(enumConst);
            }
        }

        typeManagementService.createOrUpdateTypeOnDisk(typeDetails.build());
    }
}

From source file:fr.imag.model2roo.addon.graph.NodeEntityMetadata.java

private MethodMetadataBuilder getIdentifierAccessor() {
    if (parent != null) {
        final MethodMetadataBuilder parentIdAccessor = parent.getIdentifierAccessor();
        if (parentIdAccessor != null && parentIdAccessor.getReturnType().equals(idType)) {
            return parentIdAccessor;
        }/*  w w w  . j av a2 s.  c  o m*/
    }

    JavaSymbolName requiredAccessorName = BeanInfoUtils.getAccessorMethodName(idField);

    // See if the user provided the field
    if (!getId().equals(idField.getDeclaredByMetadataId())) {
        // Locate an existing accessor
        final MethodMetadata method = memberDetails.getMethod(requiredAccessorName, new ArrayList<JavaType>());
        if (method != null) {
            if (Modifier.isPublic(method.getModifier())) {
                // Method exists and is public so return it
                return new MethodMetadataBuilder(method);
            }

            // Method is not public so make the required accessor name
            // unique
            requiredAccessorName = new JavaSymbolName(requiredAccessorName.getSymbolName() + "_");
        }
    }

    // We declared the field in this ITD, so produce a public accessor for
    // it
    final InvocableMemberBodyBuilder bodyBuilder = new InvocableMemberBodyBuilder();
    bodyBuilder.appendFormalLine("return this." + idField.getFieldName().getSymbolName() + ";");

    return new MethodMetadataBuilder(getId(), Modifier.PUBLIC, requiredAccessorName, idField.getFieldType(),
            bodyBuilder);
}

From source file:permissionhelper.PermissionHelper.java

/**
 * Invoke a method with annotation PermissionDenied.
 *
 * @param obj/*from ww  w . j  a v a 2s . c o m*/
 * @param permission
 */
private void invokeDeniedMethod(Object obj, String permission) {
    Class clazz = obj.getClass();
    PermissionDenied permissionDenied;

    for (Method method : clazz.getMethods()) {
        if (method.isAnnotationPresent(PermissionDenied.class)) {
            permissionDenied = method.getAnnotation(PermissionDenied.class);
            if (permissionDenied.permission().equals(permission)) {
                if (method.getModifiers() != Modifier.PUBLIC) {
                    throw new IllegalArgumentException(
                            String.format("Annotation method %s must be public.", method));
                }

                if (method.getParameterTypes().length > 0) {
                    throw new RuntimeException(String.format("Cannot execute non-void method %s.", method));
                }

                try {
                    method.invoke(obj);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}