Example usage for java.lang.reflect Method isAnnotationPresent

List of usage examples for java.lang.reflect Method isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Method isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:wicket.app.event.AnnotationEventDispatcher.java

@Override
public void dispatchEvent(Object sink, IEvent<?> event, Component component) {
    Class<?> sinkClass = sink.getClass();
    Object payload = event.getPayload();
    Class<?> payloadClass = payload.getClass();

    if (payload != null) {
        Set<MethodDescriptor> descriptors = new HashSet<>();
        Class<?> clazz = sinkClass;
        ClassDescriptor classDescriptor = new ClassDescriptor(clazz);
        Set<MethodDescriptor> cachedMethods = classMap.get(classDescriptor);

        if (cachedMethods == null) {
            Set<MethodDescriptor> methods = new HashSet<>();
            classMap.put(classDescriptor, methods);

            while (clazz != null && !clazz.equals(Object.class)) {
                for (Method method : clazz.getDeclaredMethods()) {
                    method.setAccessible(true);
                    MethodDescriptor methodDescriptor = new MethodDescriptor(clazz, method);

                    // ??????????????
                    // ???????????????
                    if (!descriptors.contains(methodDescriptor)) {
                        descriptors.add(methodDescriptor);
                        if (method.isAnnotationPresent(EventHandler.class)) {
                            methods.add(methodDescriptor);
                            Class<?>[] paramTypes = method.getParameterTypes();
                            if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(payloadClass)) {
                                invokeHandler(method, sink, payload);
                            }//from  w  ww.j  a  v a  2s . c  o  m
                        }
                    }
                }

                clazz = clazz.getSuperclass();
            }
        } else {
            for (MethodDescriptor methodDescriptor : cachedMethods) {
                try {
                    Method method = methodDescriptor.toMethod();
                    Class<?>[] paramTypes = method.getParameterTypes();
                    if (paramTypes.length == 1 && paramTypes[0].isAssignableFrom(payloadClass)) {
                        invokeHandler(method, sink, payload);
                    }
                } catch (ReflectiveOperationException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

From source file:org.apache.brooklyn.rest.client.BrooklynApi.java

@SuppressWarnings("unchecked")
private <T> T proxy(Class<T> clazz) {
    final T result0 = ProxyFactory.create(clazz, target, clientExecutor);
    return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[] { clazz },
            new InvocationHandler() {
                @Override//from   www  . j av  a 2s. c o  m
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    try {
                        Object result1 = method.invoke(result0, args);
                        Class<?> type = String.class;
                        if (result1 instanceof Response) {
                            Response resp = (Response) result1;
                            if (isStatusCodeHealthy(resp.getStatus())
                                    && method.isAnnotationPresent(ApiOperation.class)) {
                                type = getClassFromMethodAnnotationOrDefault(method, type);
                            }
                            // wrap the original response so it self-closes
                            result1 = BuiltResponsePreservingError.copyResponseAndClose(resp, type);
                        }
                        return result1;
                    } catch (Throwable e) {
                        if (e instanceof InvocationTargetException) {
                            // throw the original exception
                            e = ((InvocationTargetException) e).getTargetException();
                        }
                        throw Exceptions.propagate(e);
                    }
                }

                private boolean isStatusCodeHealthy(int code) {
                    return (code >= 200 && code <= 299);
                }

                private Class<?> getClassFromMethodAnnotationOrDefault(Method method, Class<?> def) {
                    Class<?> type;
                    try {
                        type = method.getAnnotation(ApiOperation.class).response();
                    } catch (Exception e) {
                        type = def;
                        LOG.debug("Unable to get class from annotation: {}.  Defaulting to {}", e.getMessage(),
                                def.getName());
                        Exceptions.propagateIfFatal(e);
                    }
                    return type;
                }
            });
}

From source file:com.laxser.blitz.web.ControllerInterceptorAdapter.java

/**
 * true??//from   ww w.  j  ava 2s.  co m
 * 
 * @param controllerClazz
 * @param actionMethod
 * @return
 */
protected final boolean checkDenyAnnotations(Class<?> controllerClazz, Method actionMethod) {
    List<Class<? extends Annotation>> denyAnnotations = getDenyAnnotationClasses();
    if (denyAnnotations == null || denyAnnotations.size() == 0) {
        return false;
    }
    for (Class<? extends Annotation> denyAnnotation : denyAnnotations) {
        if (denyAnnotation == null) {
            continue;
        }
        BitSet scopeSet = getAnnotationScope(denyAnnotation);
        if (scopeSet.get(AnnotationScope.METHOD.ordinal())) {
            if (actionMethod.isAnnotationPresent(denyAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.CLASS.ordinal())) {
            if (controllerClazz.isAnnotationPresent(denyAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.ANNOTATION.ordinal())) {
            for (Annotation annotation : actionMethod.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(denyAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
                }
            }
            for (Annotation annotation : controllerClazz.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(denyAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(denyAnnotation));
                }
            }
        }
    }
    return false;
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

private static boolean isComplex(Class<?> javaType, Method method, ColumnMetadata foreignReference) {
    final int dimensions = ReflectionUtils.getArrayDimensions(javaType);
    javaType = ReflectionUtils.mapType(ReflectionUtils.getComponentType(javaType));
    if (dimensions > 1) {
        throw new UnsupportedColumnTypeError("Arrays of dimension > 1 are not supported");
    }/*from   w  ww  .  j  ava  2  s . c  o  m*/
    return !(Byte.class.equals(javaType) && dimensions == 0) && !Short.class.equals(javaType)
            && !Integer.class.equals(javaType) && !Long.class.equals(javaType) && !Float.class.equals(javaType)
            && !Double.class.equals(javaType) && !BigDecimal.class.equals(javaType)
            && !BigInteger.class.equals(javaType) && !Character.class.equals(javaType)
            && !(String.class.equals(javaType) || Class.class.equals(javaType))
            && !Date.class.isAssignableFrom(javaType) && !(Byte.class.equals(javaType) && dimensions > 0)
            && !Enum.class.isAssignableFrom(javaType) && !Boolean.class.equals(javaType)
            && (!Collection.class.isAssignableFrom(javaType)
                    || !method.isAnnotationPresent(BasicCollection.class))
            && foreignReference == null;
}

From source file:org.switchyard.component.resteasy.util.ClientInvoker.java

/**
 * Create a RESTEasy invoker client./*from   ww w  .  ja va  2s  .  co  m*/
 *
 * @param basePath The base path for the class
 * @param resourceClass The JAX-RS Resource Class
 * @param method The JAX-RS Resource Class's method
 * @param model Configuration model
 */
public ClientInvoker(String basePath, Class<?> resourceClass, Method method, RESTEasyBindingModel model) {
    Set<String> httpMethods = IsHttpMethod.getHttpMethods(method);
    _baseUri = createUri(basePath);
    if ((httpMethods == null || httpMethods.size() == 0) && method.isAnnotationPresent(Path.class)
            && method.getReturnType().isInterface()) {
        _subResourcePath = createSubResourcePath(basePath, method);
    } else if (httpMethods == null || httpMethods.size() != 1) {
        throw RestEasyMessages.MESSAGES
                .youMustUseAtLeastOneButNoMoreThanOneHttpMethodAnnotationOn(method.toString());
    }
    _httpMethod = httpMethods.iterator().next();
    _resourceClass = resourceClass;
    _method = method;
    try {
        _uri = (UriBuilder) URIBUILDER_CLASS.newInstance();
    } catch (InstantiationException ie) {
        throw new RuntimeException(ie);
    } catch (IllegalAccessException iae) {
        throw new RuntimeException(iae);
    }
    _uri.uri(_baseUri);
    if (_resourceClass.isAnnotationPresent(Path.class)) {
        _uri.path(_resourceClass);
    }
    if (_method.isAnnotationPresent(Path.class)) {
        _uri.path(_method);
    }

    _providerFactory = new ResteasyProviderFactory();

    boolean useBuiltins = true; // use builtin @Provider classes by default
    if (model.getContextParamsConfig() != null) {
        Map<String, String> contextParams = model.getContextParamsConfig().toMap();

        // Set use builtin @Provider classes
        String registerBuiltins = contextParams.get(ResteasyContextParameters.RESTEASY_USE_BUILTIN_PROVIDERS);
        if (registerBuiltins != null) {
            useBuiltins = Boolean.parseBoolean(registerBuiltins);
        }

        // Register @Provider classes
        List<Class<?>> providerClasses = RESTEasyUtil.getProviderClasses(contextParams);
        if (providerClasses != null) {
            for (Class<?> pc : providerClasses) {
                _providerFactory.registerProvider(pc);
            }
        }

        List<ClientErrorInterceptor> interceptors = RESTEasyUtil.getClientErrorInterceptors(contextParams);
        if (interceptors != null) {
            for (ClientErrorInterceptor interceptor : interceptors) {
                _providerFactory.addClientErrorInterceptor(interceptor);
            }
        }
    }
    if (useBuiltins) {
        _providerFactory.setRegisterBuiltins(true);
        RegisterBuiltin.register(_providerFactory);
    }

    _extractorFactory = new DefaultEntityExtractorFactory();
    _extractor = _extractorFactory.createExtractor(_method);
    _marshallers = ClientMarshallerFactory.createMarshallers(_resourceClass, _method, _providerFactory, null);
    _accepts = MediaTypeHelper.getProduces(_resourceClass, method, null);
    ClientInvokerInterceptorFactory.applyDefaultInterceptors(this, _providerFactory, _resourceClass, _method);

    // Client executor
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    int port = _baseUri.getPort();
    if (_baseUri.getScheme().startsWith("https")) {
        if (port == -1) {
            port = 443;
        }
        SSLSocketFactory sslFactory = getSSLSocketFactory(model.getSSLContextConfig());
        if (sslFactory == null) {
            sslFactory = SSLSocketFactory.getSocketFactory();
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, sslFactory));
    } else {
        if (port == -1) {
            port = 80;
        }
        schemeRegistry.register(new Scheme(_baseUri.getScheme(), port, PlainSocketFactory.getSocketFactory()));
    }
    PoolingClientConnectionManager cm = new PoolingClientConnectionManager(schemeRegistry);
    cm.setMaxTotal(200);
    cm.setDefaultMaxPerRoute(20);
    HttpClient httpClient = new DefaultHttpClient(cm);
    _executor = new ApacheHttpClient4Executor(httpClient);
    // register ApacheHttpClient4ExceptionMapper manually for local instance of ResteasyProviderFactory
    Type exceptionType = Types.getActualTypeArgumentsOfAnInterface(ApacheHttpClient4ExceptionMapper.class,
            ClientExceptionMapper.class)[0];
    _providerFactory.addClientExceptionMapper(new ApacheHttpClient4ExceptionMapper(), exceptionType);

    // Authentication settings
    if (model.hasAuthentication()) {
        // Set authentication
        AuthScope authScope = null;
        Credentials credentials = null;
        if (model.isBasicAuth()) {
            authScope = createAuthScope(model.getBasicAuthConfig().getHost(),
                    model.getBasicAuthConfig().getPort(), model.getBasicAuthConfig().getRealm());
            credentials = new UsernamePasswordCredentials(model.getBasicAuthConfig().getUser(),
                    model.getBasicAuthConfig().getPassword());
            // Create AuthCache instance
            AuthCache authCache = new BasicAuthCache();
            authCache.put(new HttpHost(authScope.getHost(), authScope.getPort()),
                    new BasicScheme(ChallengeState.TARGET));
            BasicHttpContext context = new BasicHttpContext();
            context.setAttribute(ClientContext.AUTH_CACHE, authCache);
            ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
        } else {
            authScope = createAuthScope(model.getNtlmAuthConfig().getHost(),
                    model.getNtlmAuthConfig().getPort(), model.getNtlmAuthConfig().getRealm());
            credentials = new NTCredentials(model.getNtlmAuthConfig().getUser(),
                    model.getNtlmAuthConfig().getPassword(), "", model.getNtlmAuthConfig().getDomain());
        }
        ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, credentials);
    } else {
        ProxyModel proxy = model.getProxyConfig();
        if (proxy != null) {
            HttpHost proxyHost = null;
            if (proxy.getPort() != null) {
                proxyHost = new HttpHost(proxy.getHost(), Integer.valueOf(proxy.getPort()).intValue());
            } else {
                proxyHost = new HttpHost(proxy.getHost(), -1);
            }
            if (proxy.getUser() != null) {
                AuthScope authScope = new AuthScope(proxy.getHost(),
                        Integer.valueOf(proxy.getPort()).intValue(), AuthScope.ANY_REALM);
                Credentials credentials = new UsernamePasswordCredentials(proxy.getUser(), proxy.getPassword());
                AuthCache authCache = new BasicAuthCache();
                authCache.put(proxyHost, new BasicScheme(ChallengeState.PROXY));
                ((DefaultHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope,
                        credentials);
                BasicHttpContext context = new BasicHttpContext();
                context.setAttribute(ClientContext.AUTH_CACHE, authCache);
                ((ApacheHttpClient4Executor) _executor).setHttpContext(context);
            }
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxyHost);
        }
    }
    Integer timeout = model.getTimeout();
    if (timeout != null) {
        HttpParams httpParams = httpClient.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
        HttpConnectionParams.setSoTimeout(httpParams, timeout);
    }
}

From source file:com.p5solutions.core.utils.ReflectionUtility.java

/**
 * Checks if a method is {@link Transient} either by specifying the transient modifier
 * or the {@link Transient} annotation.//  w ww .  ja v a 2 s  . com
 * 
 * @param method
 *          the method
 * @return true, if is transient
 */
public static boolean isTransient(Method method) {
    if (Modifier.isTransient(method.getModifiers())) {
        return true;
    }

    if (method.isAnnotationPresent(Transient.class)) {
        return true;
    }

    return false;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

private List<IEntityArgumentGetter> createListGetters(String columnPrefix, Class entityClass,
        Map<String, Integer> types, ParameterConverterService converterService, int aParameterIndex) {
    List<IEntityArgumentGetter> getters = new LinkedList<IEntityArgumentGetter>();
    for (Method method : entityClass.getMethods()) {
        if (method.isAnnotationPresent(Column.class)) {

            Column column = method.getAnnotation(Column.class);
            Assert.notNull(column, "Method " + method + " has no Column annotation");
            Assert.hasText(column.name(), "Column annotation has no name parameter in method " + method);

            String columnName = columnPrefix + column.name();

            Integer dataType = types.get(columnName);
            Assert.notNull(dataType,//from  www  .j  av a 2s  .  c o  m
                    "No information about cPreparedSolumn " + columnName + " in method " + method);

            IParameterConverter paramConverter = converterService.getConverter(dataType,
                    method.getReturnType());

            aParameterIndex++;
            getters.add(new EntityArgumentGetter(method, paramConverter,
                    new StatementArgument(columnName, aParameterIndex)));

        } else if (method.isAnnotationPresent(OneToOne.class) || method.isAnnotationPresent(ManyToOne.class)) {
            Class oneToOneClass = method.getReturnType();
            if (method.isAnnotationPresent(JoinColumn.class)) {

                // table name
                JoinColumn joinColumn = method.getAnnotation(JoinColumn.class);
                Assert.hasText(joinColumn.table(),
                        "JoinColumn annotation has no table parameter in method " + method);
                String tableName = joinColumn.table();

                //
                List<IEntityArgumentGetter> oneToOneClassGetters = createListGetters(tableName + "_",
                        oneToOneClass, types, converterService, aParameterIndex);
                for (IEntityArgumentGetter oneToOneClassGetter : oneToOneClassGetters) {
                    EntityArgumentGetterOneToOne oneToOneConverter = new EntityArgumentGetterOneToOne(method,
                            oneToOneClassGetter);
                    getters.add(oneToOneConverter);
                }
            }

        }
    }
    return getters;
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

/**
 * Creates entity block/*from   w ww .j a v a2 s  . c  om*/
 *
 * @param converterService converter manager
 * @param procedureInfo    procedure into
 * @param entityClass      entity class
 * @return block
 */
private IParametersSetterBlock createEntityBlock(ParameterConverterService converterService,
        StoredProcedureInfo procedureInfo, Class entityClass, final int[] nonListArgumentIndexes) {
    List<EntityArgumentGetter> getters = new LinkedList<EntityArgumentGetter>();
    for (Method getterMethod : entityClass.getMethods()) {
        if (getterMethod.isAnnotationPresent(Column.class)) {
            Column columnAnnotation = getterMethod.getAnnotation(Column.class);
            StoredProcedureArgumentInfo argumentInfo = procedureInfo.getArgumentInfo(columnAnnotation.name());
            if (argumentInfo == null) {
                throw new IllegalStateException("Column " + columnAnnotation.name() + " was not found in "
                        + procedureInfo.getProcedureName());
            }
            if (argumentInfo.getColumnType() == 1) {
                IParameterConverter paramConverter = converterService.getConverter(argumentInfo.getDataType(),
                        getterMethod.getReturnType());
                getters.add(new EntityArgumentGetter(getterMethod, paramConverter,
                        argumentInfo.getStatementArgument()));
            }
        } else if (getterMethod.isAnnotationPresent(OneToOne.class)
                || getterMethod.isAnnotationPresent(ManyToOne.class)) {

            if (getterMethod.isAnnotationPresent(JoinColumn.class)) {
                JoinColumn joinColumn = getterMethod.getAnnotation(JoinColumn.class);

                if (StringUtils.hasText(joinColumn.name())) {
                    StoredProcedureArgumentInfo argumentInfo = procedureInfo.getArgumentInfo(joinColumn.name());

                    if (argumentInfo == null) {
                        throw new IllegalStateException("Column " + joinColumn.name() + " was not found in "
                                + procedureInfo.getProcedureName());
                    }
                    getters.add(new EntityArgumentGetterOneToOneJoinColumn(getterMethod,
                            argumentInfo.getStatementArgument()));
                } else {
                    throw new IllegalStateException("@JoinColumn.name is empty for "
                            + entityClass.getSimpleName() + "." + getterMethod.getName() + "()");
                }
            } else {
                throw new IllegalStateException("No @JoinColumn annotation was found in "
                        + entityClass.getSimpleName() + "." + getterMethod.getName() + "()");
            }
        }
    }
    return new ParametersSetterBlockEntity(getters, nonListArgumentIndexes);
}

From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java

public List<Method> findAnnotatedMethods(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();//from  www  .j a  va 2s  . c  om
    List<ClassInfo> seen = new ArrayList<ClassInfo>();
    List<Method> methods = new ArrayList<Method>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof MethodInfo && !"<init>".equals(info.getName())) {
            MethodInfo methodInfo = (MethodInfo) info;
            ClassInfo classInfo = methodInfo.getDeclaringClass();

            if (seen.contains(classInfo))
                continue;

            seen.add(classInfo);

            try {
                Class clazz = classInfo.get();
                for (Method method : clazz.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(annotation)) {
                        methods.add(method);
                    }
                }
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Error loading class [#0]", e, classInfo.getName());
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return methods;
}

From source file:com.laxser.blitz.web.ControllerInterceptorAdapter.java

/**
 * false?/*ww  w. j  a  va 2s . co  m*/
 * 
 * @param controllerClazz
 *            
 * @param actionMethod
 *            ?
 * @return
 */
protected final boolean checkRequiredAnnotations(Class<?> controllerClazz, Method actionMethod) {
    List<Class<? extends Annotation>> requiredAnnotations = getRequiredAnnotationClasses();
    if (requiredAnnotations == null || requiredAnnotations.size() == 0) {
        return true;
    }
    for (Class<? extends Annotation> requiredAnnotation : requiredAnnotations) {
        if (requiredAnnotation == null) {
            continue;
        }
        BitSet scopeSet = getAnnotationScope(requiredAnnotation);
        if (scopeSet.get(AnnotationScope.METHOD.ordinal())) {
            if (actionMethod.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.CLASS.ordinal())) {
            if (controllerClazz.isAnnotationPresent(requiredAnnotation)) {
                return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
            }
        }
        if (scopeSet.get(AnnotationScope.ANNOTATION.ordinal())) {
            for (Annotation annotation : actionMethod.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
            for (Annotation annotation : controllerClazz.getAnnotations()) {
                if (annotation.annotationType().isAnnotationPresent(requiredAnnotation)) {
                    return checkAnnotation(actionMethod.getAnnotation(requiredAnnotation));
                }
            }
        }
    }
    return false;
}