Example usage for java.lang.reflect Method getAnnotations

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

Introduction

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

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:com.geemvc.view.DefaultStreamViewHandler.java

@Override
public void handle(Result result, RequestContext requestCtx) throws ServletException, IOException {
    HttpServletResponse response = (HttpServletResponse) requestCtx.getResponse();

    if (result.length() > 0) {
        response.setContentLength((int) result.length());
    }/*from  ww w .  ja  v a2  s.  com*/

    if (result.filename() != null) {
        if (result.attachment()) {
            response.setHeader("Content-disposition", "attachment; filename=" + result.filename());
        } else {
            response.setHeader("Content-disposition", "filename=" + result.filename());
        }
    }

    if (result.contentType() != null) {
        response.setContentType(result.contentType());
    }

    if (result.rangeSupport()) {
        // TODO: range-support
    }

    if (result.result() != null) {
        RequestHandler requestHandler = requestCtx.requestHandler();
        Method handlerMethod = requestHandler.handlerMethod();

        if (configuration.isJaxRsEnabled()) {
            MessageBodyWriter mbw = injector.getInstance(Providers.class).getMessageBodyWriter(
                    handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(),
                    handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()));

            if (mbw != null
                    && mbw.isWriteable(handlerMethod.getReturnType(), handlerMethod.getGenericReturnType(),
                            handlerMethod.getAnnotations(), MediaType.valueOf(response.getContentType()))) {
                MultivaluedMap<String, Object> httpResponseHeaders = injector.getInstance(MultivaluedMap.class);

                mbw.writeTo(result.result(), handlerMethod.getReturnType(),
                        handlerMethod.getGenericReturnType(), handlerMethod.getAnnotations(),
                        MediaType.valueOf(response.getContentType()), httpResponseHeaders,
                        response.getOutputStream());
            } else {
                response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
            }
        } else {
            log.info(
                    "Unable to convert the result object of type '{}' to the media type '{}' as the JAX-RS runtime has been disabled.",
                    () -> result.result().getClass().getName(), () -> response.getContentType());
            response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
        }

        return;
    }

    if (result.stream() != null) {
        IOUtils.copy(result.stream(), response.getOutputStream());
    } else if (result.reader() != null) {
        IOUtils.copy(result.reader(), response.getOutputStream(), result.characterEncoding());
    } else if (result.output() != null) {
        response.getOutputStream().write(result.output().getBytes());
    } else {
        throw new IllegalStateException(
                "You must provide either a stream, a reader or a string output when using Results.stream(). ");
    }
}

From source file:com.videobox.web.util.dwr.AutoAnnotationDiscoveryContainer.java

private void addDataConverterObject(String className) {
    Class<?> cls;/*from w w w . j  a  v  a 2  s. c  o m*/
    try {
        cls = Class.forName(className);
    } catch (ClassNotFoundException e) {
        throw new IllegalStateException("No such class: " + className);
    }
    StringBuilder excludes = new StringBuilder();
    for (Method m : cls.getMethods()) {
        if (logger.isDebugEnabled()) {
            logger.debug("CHECKING " + cls.getSimpleName() + "." + m.getName() + "("
                    + m.getParameterTypes().length + ") -> " + Arrays.asList(m.getAnnotations()));
        }
        if (!m.isAnnotationPresent(RemoteProperty.class)) {
            if (logger.isDebugEnabled()) {
                logger.debug("EXCLUDING " + cls.getSimpleName() + "." + m.getName() + " -> "
                        + Arrays.asList(m.getAnnotations()));
            }
            excludes.append(propName(m)).append(',');
        }
    }
    BeanConverter beanConverter = new BeanConverter();
    beanConverter.setInstanceType(cls);
    beanConverter.setExclude(excludes.toString());
    ConverterManager cm = this.getBean(ConverterManager.class);
    cm.addConverter(cls.getName(), beanConverter);
    if (logger.isDebugEnabled()) {
        logger.debug("CONVERTER: " + cls.getName() + " -> " + excludes);
    }
}

From source file:com.spidertracks.datanucleus.spring.ConsistencyLevelAspect.java

/**
 * Scans the given method with the given parameter types. If a check
 * annotation is present, the annotated level will be returned
 * //from   w  ww  .j a  v  a 2  s  . c  o m
 * @param target
 * @param methodName
 * @param paramTypes
 * @return
 */
private ConsistencyLevel consistency(Class<?> target, String methodName, Class<?>[] paramTypes) {

    TargetKey key = new TargetKey(target, methodName, paramTypes);

    Boolean cached = hasAnnotation.get(key);

    if (cached != null) {
        if (cached) {
            return consistencyAnnotation.get(key);
        }
        return null;
    }

    // try a direct method lookup
    Method targetMethod = getMatchingAccessibleMethod(target, methodName, paramTypes);

    Annotation[] annotations = targetMethod.getAnnotations();

    for (int i = 0; i < annotations.length; i++) {
        if (annotations[i] instanceof Consistency) {

            ConsistencyLevel level = ((Consistency) annotations[i]).value();

            consistencyAnnotation.putIfAbsent(key, level);
            hasAnnotation.putIfAbsent(key, true);
            return level;
        }
    }

    return null;
}

From source file:com.datastax.hectorjpa.spring.ConsistencyLevelAspect.java

/**
 * Scans the given method with the given parameter types. If a check
 * annotation is present, the annotated level will be returned
 * /*from   w  w  w  . j ava 2 s .co  m*/
 * @param target
 * @param methodName
 * @param paramTypes
 * @return
 */
private HConsistencyLevel consistency(Class<?> target, String methodName, Class<?>[] paramTypes) {

    TargetKey key = new TargetKey(target, methodName, paramTypes);

    Boolean cached = hasAnnotation.get(key);

    if (cached != null) {
        if (cached) {
            return consistencyAnnotation.get(key);
        }
        return null;
    }

    // try a direct method lookup
    Method targetMethod = getMatchingAccessibleMethod(target, methodName, paramTypes);

    Annotation[] annotations = targetMethod.getAnnotations();

    for (int i = 0; i < annotations.length; i++) {
        if (annotations[i] instanceof Consistency) {

            HConsistencyLevel level = ((Consistency) annotations[i]).value();

            consistencyAnnotation.putIfAbsent(key, level);
            hasAnnotation.putIfAbsent(key, true);
            return level;
        }
    }

    return null;
}

From source file:org.seasar.struts.lessconfig.factory.TigerValidatorAnnotationHandler.java

@Override
protected void registerConfig(Field field, BeanDesc beanDesc, PropertyDesc propDesc) {
    Method method = getMethodForValidation(propDesc);
    if (!hasAnnotation(method)) {
        super.registerConfig(field, beanDesc, propDesc);
        return;/*from ww w .  j  a  v a2 s  . c  o m*/
    }

    registerAutoTypeValidatorConfig(field, propDesc);

    for (Annotation annotation : method.getAnnotations()) {
        Class<?> type = annotation.annotationType();
        ValidatorTarget target = type.getAnnotation(ValidatorTarget.class);
        if (target != null) {
            String validatorName = getValidatorName(type);
            if (hasConfigRegister(validatorName)) {
                Map<?, ?> parameter = TigerAnnotationConverter.getInstance().toMap(annotation);
                executeConfigRegister(field, validatorName, parameter);
            }
        }
    }
}

From source file:org.apache.stratos.metadata.service.handlers.StratosAuthorizingHandler.java

/**
 * Goes through the class hierarchy and figure out the supertenant
 * annotations coupled with operations/methods.
 *
 * @param clazz/*from w w  w.  j  av a 2 s. co  m*/
 * @param superTenantServiceSet
 */
private void findSuperTenantServices(Class<?> clazz, Set<String> superTenantServiceSet) {
    if (clazz == null || clazz == Object.class) {
        return;
    }
    for (Method m : clazz.getMethods()) {
        if (SKIP_METHODS.contains(m.getName())) {
            continue;
        }
        boolean isSuperTenantService = getSuperTenantServices(m.getAnnotations(), TENANT_ANNOTATION_CLASS_NAME);
        if (isSuperTenantService) {
            superTenantServiceSet.add(m.getName());
        }
    }
    if (!superTenantServiceSet.isEmpty()) {
        return;
    }

    findSuperTenantServices(clazz.getSuperclass(), superTenantServiceSet);

    if (!superTenantServiceSet.isEmpty()) {
        return;
    }

    for (Class<?> interfaceCls : clazz.getInterfaces()) {
        findSuperTenantServices(interfaceCls, superTenantServiceSet);
    }
}

From source file:org.sybila.parasim.core.impl.ProvidingMethod.java

public ProvidingMethod(Method method, Object target) {
    Validate.notNull(method);//w  ww .  j  ava  2  s.  co  m
    Validate.notNull(target);
    this.provide = method.getAnnotation(Provide.class);
    Validate.notNull(provide,
            "Field without " + Provide.class.getName() + " annotation can't be providing point.");
    this.method = method;
    this.target = target;
    this.qualifier = ReflectionUtils.loadQualifier(method.getAnnotations());
    injectionPoints = new InjectionPoint[method.getGenericParameterTypes().length];
    for (int i = 0; i < method.getGenericParameterTypes().length; i++) {
        injectionPoints[i] = new GenericInjectionPoint(method.getParameterAnnotations()[i],
                method.getGenericParameterTypes()[i]);
    }
}

From source file:org.apache.stratos.metadata.service.handlers.StratosAuthorizingHandler.java

/**
 * Goes through the class hierarchy and find the authorization annotations
 * attached to a certain/* w ww.j a  v  a2  s.c  o m*/
 * method.
 *
 * @param clazz                  class to be scanned
 * @param authorizationActionMap the map to be populated
 */
private void findAuthorizationActions(Class<?> clazz, Map<String, String> authorizationActionMap) {
    if (clazz == null || clazz == Object.class) {
        return;
    }
    String classAuthorizationActionsAllowed = getAuthorizationActions(clazz.getAnnotations(),
            AUTHORIZATION_ANNOTATION_CLASS_NAME);
    for (Method m : clazz.getMethods()) {
        if (SKIP_METHODS.contains(m.getName())) {
            continue;
        }
        String methodAuthorizationActionsAllowed = getAuthorizationActions(m.getAnnotations(),
                AUTHORIZATION_ANNOTATION_CLASS_NAME);
        String authorizationActions = methodAuthorizationActionsAllowed != null
                ? methodAuthorizationActionsAllowed
                : classAuthorizationActionsAllowed;
        if (authorizationActions != null) {
            authorizationActionMap.put(m.getName(), authorizationActions);
        }
    }
    if (!authorizationActionMap.isEmpty()) {
        return;
    }

    findAuthorizationActions(clazz.getSuperclass(), authorizationActionMap);

    if (!authorizationActionMap.isEmpty()) {
        return;
    }

    for (Class<?> interfaceCls : clazz.getInterfaces()) {
        findAuthorizationActions(interfaceCls, authorizationActionMap);
    }
}

From source file:com.msopentech.odatajclient.proxy.api.impl.EntityContainerInvocationHandler.java

@Override
@SuppressWarnings("unchecked")
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
    if (isSelfMethod(method, args)) {
        return invokeSelfMethod(method, args);
    } else if ("flush".equals(method.getName()) && ArrayUtils.isEmpty(args)) {
        new Container(client, factory).flush();
        return ClassUtils.returnVoid();
    } else {//from  w  w  w. ja  v  a 2  s  .  c om
        final Annotation[] methodAnnots = method.getAnnotations();
        // 1. access top-level entity sets
        if (methodAnnots.length == 0) {
            final Class<?> returnType = method.getReturnType();

            return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                    new Class<?>[] { returnType }, EntitySetInvocationHandler.getInstance(returnType, this));
        } // 2. invoke function imports
        else if (methodAnnots[0] instanceof Operation) {
            final com.msopentech.odatajclient.engine.metadata.edm.v3.EntityContainer container = getFactory()
                    .getMetadata().getSchema(schemaName).getEntityContainer(entityContainerName);
            final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp = container
                    .getFunctionImport(((Operation) methodAnnots[0]).name());

            final URIBuilder uriBuilder = client.getURIBuilder(factory.getServiceRoot())
                    .appendFunctionImportSegment(URIUtils.rootFunctionImportURISegment(container, funcImp));

            return functionImport((Operation) methodAnnots[0], method, args, uriBuilder.build(), funcImp);
        } else {
            throw new UnsupportedOperationException("Method not found: " + method);
        }
    }
}