Example usage for java.lang.reflect Method getAnnotation

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

Introduction

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

Prototype

public <T extends Annotation> T getAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:be.fedict.hsm.admin.webapp.security.SecurityInterceptor.java

@AroundInvoke
public Object securityVerification(InvocationContext invocationContext) throws Exception {
    Method method = invocationContext.getMethod();
    Class<?> clazz = invocationContext.getMethod().getDeclaringClass();
    LOG.trace("security verification: " + clazz.getSimpleName() + "." + method.getName());
    RolesAllowed rolesAllowedAnnotation = method.getAnnotation(RolesAllowed.class);
    if (null == rolesAllowedAnnotation) {
        rolesAllowedAnnotation = clazz.getAnnotation(RolesAllowed.class);
    }//ww w.  j a  va 2 s. c  om
    String[] allowedRoles = rolesAllowedAnnotation.value();

    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletRequest httpServletRequest = (HttpServletRequest) externalContext.getRequest();
    Principal userPrincipal = httpServletRequest.getUserPrincipal();
    if (null == userPrincipal) {
        throw new SecurityException("user not logged in");
    }

    boolean userInRole = false;
    for (String allowedRole : allowedRoles) {
        if (httpServletRequest.isUserInRole(allowedRole)) {
            LOG.trace("user in role: " + allowedRole);
            userInRole = true;
            break;
        }
    }
    if (false == userInRole) {
        throw new SecurityException("user not in allowed roles");
    }

    return invocationContext.proceed();
}

From source file:be.fedict.trust.service.snmp.SNMPInterceptor.java

private Object process(InvocationContext invocationContext) throws Exception {

    this.values = new HashMap<String, Long>();
    Object target = invocationContext.getTarget();
    LOG.debug("process SNMP on " + target.getClass().getCanonicalName());

    /*//from  w ww. j a  va  2s. c  o m
     * Process the possible SNMP annotation on the method
     */
    SNMP methodSnmp = invocationContext.getMethod().getAnnotation(SNMP.class);
    if (null != methodSnmp) {
        increment(methodSnmp.oid(), methodSnmp.service(), 1L);
    }

    /*
     * Process the possible SNMP annotation on the fields
     */
    injectSnmpFields(target);

    /*
     * Invoke
     */
    Object result = invocationContext.proceed();

    /*
     * Post-process the possible SNMP annotation on the fields
     */
    updateSnmpFields(target);

    /*
     * Check for SNMPCounter methods
     */
    SNMPCounter snmpCounter = invocationContext.getMethod().getAnnotation(SNMPCounter.class);
    if (null == snmpCounter) {
        // check if other methods are annotated this way, if so execute them
        for (Method method : target.getClass().getMethods()) {
            if (null != method.getAnnotation(SNMPCounter.class)) {
                method.invoke(target);
            }
        }
    }

    /*
     * Update the SNMP derived fields
     */
    updateSnmpDerivedFields(target);

    /*
     * Return the invocation result
     */
    return result;
}

From source file:com.netflix.hystrix.contrib.javanica.aop.aspectj.HystrixCommandAspect.java

@Around("hystrixCommandAnnotationPointcut()")
public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {

    Method method = getMethodFromTarget(joinPoint);
    Object obj = joinPoint.getTarget();
    Object[] args = joinPoint.getArgs();
    Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);
    HystrixCommand hystrixCommand = method.getAnnotation(HystrixCommand.class);
    HystrixCollapser hystrixCollapser = method.getAnnotation(HystrixCollapser.class);
    ExecutionType executionType = ExecutionType.getExecutionType(method.getReturnType());
    Method cacheKeyMethod = getMethodFromTarget(joinPoint, hystrixCommand.cacheKeyMethod());
    MetaHolder metaHolder = MetaHolder.builder().args(args).method(method).obj(obj)
            .proxyObj(joinPoint.getThis()).cacheKeyMethod(cacheKeyMethod).executionType(executionType)
            .hystrixCommand(hystrixCommand).hystrixCollapser(hystrixCollapser)
            .defaultCommandKey(method.getName()).defaultCollapserKey(method.getName())
            .defaultGroupKey(obj.getClass().getSimpleName()).build();
    HystrixExecutable executable;//from  w  ww. j  a v a2  s  .  c om
    if (hystrixCollapser != null) {
        executable = new CommandCollapser(metaHolder);
    } else {
        executable = GenericHystrixCommandFactory.getInstance().create(metaHolder, null);
    }
    Object result;
    try {
        result = CommandExecutor.execute(executable, executionType);
    } catch (HystrixBadRequestException e) {
        throw e.getCause();
    } catch (Throwable throwable) {
        throw throwable;
    }
    return result;
}

From source file:org.flite.cach3.aop.UpdateAssignCacheAdvice.java

@AfterReturning(pointcut = "updateAssign()", returning = "retVal")
public Object cacheUpdateAssign(final JoinPoint jp, final Object retVal) throws Throwable {
    // If we've disabled the caching programmatically (or via properties file) just flow through.
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return retVal;
    }//from  w  w w  .  j  ava 2  s  .c om

    final MemcachedClientIF cache = getMemcachedClient();
    // This is injected caching.  If anything goes wrong in the caching, LOG the crap outta it,
    // but do not let it surface up past the AOP injection itself.
    try {
        final Method methodToCache = getMethodToCache(jp);
        final UpdateAssignCache annotation = methodToCache.getAnnotation(UpdateAssignCache.class);
        final AnnotationInfo info = getAnnotationInfo(annotation, methodToCache.getName(), getJitterDefault());
        final String cacheKey = buildCacheKey(info.getAsString(AType.ASSIGN_KEY),
                info.getAsString(AType.NAMESPACE), info.getAsString(AType.KEY_PREFIX));
        final int dataIndex = info.getAsInteger(AType.DATA_INDEX, -2).intValue();
        final Object dataObject = dataIndex == -1 ? retVal
                : getIndexObject(dataIndex, jp.getArgs(), methodToCache.toString());
        final Object submission = (dataObject == null) ? new PertinentNegativeNull() : dataObject;
        boolean cacheable = true;
        if (submission instanceof CacheConditionally) {
            cacheable = ((CacheConditionally) submission).isCacheable();
        }
        if (cacheable) {
            cache.set(cacheKey, info.getAsInteger(AType.JITTER), submission);
        }

        // Notify the observers that a cache interaction happened.
        final List<UpdateAssignCacheListener> listeners = getPertinentListeners(UpdateAssignCacheListener.class,
                info.getAsString(AType.NAMESPACE));
        if (listeners != null && !listeners.isEmpty()) {
            for (final UpdateAssignCacheListener listener : listeners) {
                try {
                    listener.triggeredUpdateAssignCache(info.getAsString(AType.NAMESPACE),
                            info.getAsString(AType.ASSIGN_KEY), dataObject, retVal, jp.getArgs());
                } catch (Exception ex) {
                    LOG.warn("Problem when triggering a listener.", ex);
                }
            }
        }
    } catch (Exception ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error.", ex);
        } else {
            LOG.warn("Caching on " + jp.toShortString() + " aborted due to an error: " + ex.getMessage());
        }
    }

    return retVal;
}

From source file:org.pmp.budgeto.app.SwaggerDispatcherConfigTest.java

@Test
public void springConf() throws Exception {

    Class<?> clazz = swaggerDispatcherConfig.getClass();
    Assertions.assertThat(clazz.getAnnotations()).hasSize(4);
    Assertions.assertThat(clazz.isAnnotationPresent(Configuration.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableWebMvc.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(EnableSwagger.class)).isTrue();
    Assertions.assertThat(clazz.isAnnotationPresent(ComponentScan.class)).isTrue();
    Assertions.assertThat(clazz.getAnnotation(ComponentScan.class).basePackages())
            .containsExactly("com.ak.swaggerspringmvc.shared.app", "com.ak.spring3.music");

    Field fSpringSwaggerConfig = clazz.getDeclaredField("springSwaggerConfig");
    Assertions.assertThat(fSpringSwaggerConfig.getAnnotations()).hasSize(1);
    Assertions.assertThat(fSpringSwaggerConfig.isAnnotationPresent(Autowired.class)).isTrue();

    Method mCustomImplementation = clazz.getDeclaredMethod("customImplementation", new Class[] {});
    Assertions.assertThat(mCustomImplementation.getAnnotations()).hasSize(1);
    Assertions.assertThat(mCustomImplementation.getAnnotation(Bean.class)).isNotNull();
}

From source file:com.google.inject.persist.jpa.KuneJpaLocalTxnInterceptor.java

/**
 * Read transaction metadata.// www.  j  ava2 s.com
 * 
 * @param methodInvocation
 *          the method invocation
 * @return the kune transactional
 */
private KuneTransactional readTransactionMetadata(final MethodInvocation methodInvocation) {
    KuneTransactional transactional;
    final Method method = methodInvocation.getMethod();
    final Class<?> targetClass = methodInvocation.getThis().getClass();

    transactional = method.getAnnotation(KuneTransactional.class);
    if (null == transactional) {
        // If none on method, try the class.
        transactional = targetClass.getAnnotation(KuneTransactional.class);
    }
    if (null == transactional) {
        // If there is no transactional annotation present, use the default
        transactional = Internal.class.getAnnotation(KuneTransactional.class);
    }

    return transactional;
}

From source file:com.jgui.ttscrape.webclient.VelocityHandler.java

/**
 * Called by the Spring container after construction, this method initializes
 * the velocity engine for web administration of the PCEF. Templates must be
 * placed in a directory called "webapp" at the same level as the where the
 * application configuration files are located (e.g. configdir/../webapp).
 *//* w  ww.  j av a2 s.com*/
@PostConstruct
public void init() {
    try {
        BasicConfigurator.configure();
        engine = new VelocityEngine();
        Properties p = new Properties();
        p.put(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.Log4JLogChute");
        p.put("runtime.log.logsystem.log4j.logger", VelocityHandler.class.getName());
        p.put("resource.loader", "file");
        p.put("file.resource.loader.path", "webapp");
        p.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader");
        p.put("file.resource.loader.cache", "true");
        p.put("file.resource.loader.modificationCheckInterval", "2");
        engine.init(p);
        logger.trace("velocity engine initialized");
    } catch (Exception ex) {
        logger.error("failed to initialize velocity engine");
    }

    if (urlMethodNameMap == null) {
        urlMethodNameMap = new HashMap<String, InvocationInfo>();
    }

    // scan the delegate for Spring RequestMapping annotations.
    for (Method m : delegate.getClass().getMethods()) {
        RequestMapping mapping = m.getAnnotation(RequestMapping.class);
        if (mapping != null) {
            String[] values = mapping.value();
            for (String s : values) {
                boolean isVelocity = false;
                boolean isJson = false;
                Class<?>[] args = m.getParameterTypes();
                for (Class<?> k : args) {
                    if (k == VelocityContext.class) {
                        isVelocity = true;
                    } else if (k == JSONObject.class) {
                        isJson = true;
                    }
                }
                urlMethodNameMap.put(s, new InvocationInfo(m, isVelocity, isJson));
            }
        }
    }
}

From source file:com.fiveamsolutions.nci.commons.search.OneCriterionSpecifiedCallback.java

private void checkFields(Method m, Object result)
        throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    String[] fields = m.getAnnotation(Searchable.class).fields();
    boolean nested = m.getAnnotation(Searchable.class).nested();
    if (result instanceof Collection<?>) {
        checkCollectionResultForCriteria((Collection<?>) result, fields, nested);
    } else if (!ArrayUtils.isEmpty(fields)) {
        checkSubFieldsForCriteria(result, fields);
    } else if (nested) {
        if (!nestedHistory.containsKey(result)) {
            nestedHistory.put(result, result);
            SearchableUtils.iterateAnnotatedMethods(result, this);
        }//from  ww w .  j  a  v  a 2 s  . c om
    } else {
        // not a collection, and no subfields selected, so because it is non-null, a criterion was found
        if (isStringAndBlank(result)) {
            return;
        }
        hasOneCriterion = true;
    }
}

From source file:com.dbs.sdwt.jpa.JpaUtil.java

private boolean isManuallyAssigned(Method method) {
    if (method.getAnnotation(Id.class) != null) {
        return method.getAnnotation(GeneratedValue.class) == null;
    }/*from w w  w  . j av a2 s. co m*/

    return method.getAnnotation(EmbeddedId.class) != null;
}

From source file:com.netflix.hystrix.contrib.javanica.utils.MethodProvider.java

/**
 * Gets fallback method for command method.
 *
 * @param type          type/*from  ww  w. j a  va  2 s . c  om*/
 * @param commandMethod the command method. in the essence it can be a fallback
 *                      method annotated with HystrixCommand annotation that has a fallback as well.
 * @param extended      true if the given commandMethod was derived using additional parameter, otherwise - false
 * @return new instance of {@link FallbackMethod} or {@link FallbackMethod#ABSENT} if there is no suitable fallback method for the given command
 */
public FallbackMethod getFallbackMethod(Class<?> type, Method commandMethod, boolean extended) {
    if (commandMethod.isAnnotationPresent(HystrixCommand.class)) {
        HystrixCommand hystrixCommand = commandMethod.getAnnotation(HystrixCommand.class);
        if (StringUtils.isNotBlank(hystrixCommand.fallbackMethod())) {
            Class<?>[] parameterTypes = commandMethod.getParameterTypes();
            if (extended && parameterTypes[parameterTypes.length - 1] == Throwable.class) {
                parameterTypes = ArrayUtils.remove(parameterTypes, parameterTypes.length - 1);
            }
            Class<?>[] exParameterTypes = Arrays.copyOf(parameterTypes, parameterTypes.length + 1);
            exParameterTypes[parameterTypes.length] = Throwable.class;
            Optional<Method> exFallbackMethod = getMethod(type, hystrixCommand.fallbackMethod(),
                    exParameterTypes);
            Optional<Method> fMethod = getMethod(type, hystrixCommand.fallbackMethod(), parameterTypes);
            Method method = exFallbackMethod.or(fMethod).orNull();
            if (method == null) {
                throw new FallbackDefinitionException("fallback method wasn't found: "
                        + hystrixCommand.fallbackMethod() + "(" + Arrays.toString(parameterTypes) + ")");
            }
            return new FallbackMethod(method, exFallbackMethod.isPresent());
        }
    }
    return FallbackMethod.ABSENT;
}