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:com.searchbox.framework.service.SearchAdapterService.java

@Override
public void afterPropertiesSet() throws Exception {

    // Reset maps for adapters.
    this.searchAdapterMethods = new HashMap<SearchAdapter.Time, Map<Method, Object>>();

    // Scan the classpath for adapters
    for (Entry<String, Object> bean : context.getBeansWithAnnotation(SearchAdapter.class).entrySet()) {
        Object adapter = bean.getValue();
        for (Method method : adapter.getClass().getDeclaredMethods()) {
            SearchAdapter.Time t = method.getAnnotation(SearchAdapterMethod.class).execute();
            LOGGER.debug("Registering adapter " + t + "\t-- " + method.getName());
            this.addSearchAdapterMethod(t, method, adapter);
        }/*from  w ww  .j  ava 2s . co  m*/
    }
}

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

@Around("getSingleAssign()")
public Object cacheAssign(final ProceedingJoinPoint pjp) throws Throwable {
    // If we've disabled the caching programmatically (or via properties file) just flow through.
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return pjp.proceed();
    }/*from w w  w  . ja va 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.
    final String cacheKey;
    final AnnotationInfo info;
    try {
        final Method methodToCache = getMethodToCache(pjp);
        final ReadThroughAssignCache annotation = methodToCache.getAnnotation(ReadThroughAssignCache.class);
        info = getAnnotationInfo(annotation, methodToCache.getName(), getJitterDefault());
        cacheKey = buildCacheKey(info.getAsString(AType.ASSIGN_KEY), info.getAsString(AType.NAMESPACE),
                info.getAsString(AType.KEY_PREFIX));
        final Object result = cache.get(cacheKey);
        if (result != null) {
            return (result instanceof PertinentNegativeNull) ? null : result;
        }
    } catch (Throwable ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
        } else {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error: " + ex.getMessage());
        }
        return pjp.proceed();
    }

    final Object result = pjp.proceed();

    // 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 Object submission = (result == null) ? new PertinentNegativeNull() : result;
        boolean cacheable = true;
        if (submission instanceof CacheConditionally) {
            cacheable = ((CacheConditionally) submission).isCacheable();
        }
        if (cacheable) {
            cache.set(cacheKey, calculateJitteredExpiration(info.getAsInteger(AType.EXPIRATION),
                    info.getAsInteger(AType.JITTER)), submission);
        }

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

From source file:com.sinosoft.one.data.jade.statement.StatementMetaData.java

public StatementMetaData(DAOMetaData daoMetaData, Method method, String sqlQuerie) {
    this.daoMetaData = daoMetaData;
    this.method = method;
    this.sql = method.getAnnotation(SQL.class) == null ? sqlQuerie : method.getAnnotation(SQL.class).value();

    this.genericReturnTypes = GenericUtils.getActualClass(method.getGenericReturnType());

    Annotation[][] annotations = method.getParameterAnnotations();
    this.parameterCount = annotations.length;
    this.sqlParams = new Param[annotations.length];
    int shardByIndex = -1;
    for (int index = 0; index < annotations.length; index++) {
        for (Annotation annotation : annotations[index]) {
            if (annotation instanceof ShardBy) {
                if (shardByIndex >= 0) {
                    throw new IllegalArgumentException("duplicated @" + ShardBy.class.getName());
                }//from  ww  w  .  j a  va 2  s.c  o  m
                shardByIndex = index;
            } else if (annotation instanceof Param) {
                this.sqlParams[index] = (Param) annotation;
            }
        }
    }
    this.shardByIndex = shardByIndex;
}

From source file:de.zib.gndms.infra.system.PluggableTaskFlowProvider.java

public void loadPlugins(boolean checkDeps) {

    Map<String, TaskFlowFactory> plugins = new HashMap<String, TaskFlowFactory>(10);

    ServiceLoader<TaskFlowFactory> sl;
    if (getCl() != null)
        sl = ServiceLoader.load(TaskFlowFactory.class, getCl());
    else/*from w w w  . j ava 2s.  c o  m*/
        sl = ServiceLoader.load(TaskFlowFactory.class);

    for (TaskFlowFactory bp : sl) {
        try {
            register(bp, plugins);
        } catch (IllegalStateException e) {
            logger.warn(e.getMessage());
        }
    }

    setFactories(plugins);

    if (checkDeps)
        checkDeps();

    // call all PostConstruct methods
    for (TaskFlowFactory bp : sl) {
        for (Method method : bp.getClass().getDeclaredMethods()) {
            if (method.getAnnotation(PostConstruct.class) != null) {
                ReflectionUtils.makeAccessible(method);
                try {
                    method.invoke(bp, (Object[]) null);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(
                            "THIS IS NOT HAPPENING!!! Method had been made accessible but is not accessible anyway",
                            e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(
                            "Could not call PostConstruct method (" + method.toGenericString() + ")", e);
                }
            }
        }
    }

    // todo this is just for development change this for releases:
    //        if ( getFactories().size() == 0 )
    //            throw new IllegalStateException( "no plugs found" );
}

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

@Around("getSingle()")
public Object cacheSingle(final ProceedingJoinPoint pjp) throws Throwable {
    // If we've disabled the caching programmatically (or via properties file) just flow through.
    if (isCacheDisabled()) {
        LOG.debug("Caching is disabled.");
        return pjp.proceed();
    }/*from w  w w .ja v a  2 s .  c o m*/

    // 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.
    final String baseKey;
    final String cacheKey;
    final L2ReadThroughSingleCache annotation;
    final AnnotationInfo info;
    final Object[] args = pjp.getArgs();
    try {
        final Method methodToCache = getMethodToCache(pjp);
        annotation = methodToCache.getAnnotation(L2ReadThroughSingleCache.class);
        info = getAnnotationInfo(annotation, methodToCache.getName());
        baseKey = generateBaseKeySingle(args, info, methodToCache.toString());
        cacheKey = buildCacheKey(baseKey, info.getAsString(AType.NAMESPACE, null),
                info.getAsString(AType.KEY_PREFIX, null));

        final Map<String, Object> results = getCache().getBulk(Arrays.asList(cacheKey),
                info.<Duration>getAsType(AType.WINDOW, null));
        final Object result = results == null ? null : results.get(cacheKey);
        if (result != null) {
            //               LOG.debug("Cache hit for key " + cacheKey);
            return (result instanceof PertinentNegativeNull) ? null : result;
        }
    } catch (Throwable ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
        } else {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error: " + ex.getMessage());
        }
        return pjp.proceed();
    }

    final Object result = pjp.proceed();

    // 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 Object submission = (result == null) ? new PertinentNegativeNull() : result;
        boolean cacheable = true;
        if (submission instanceof CacheConditionally) {
            cacheable = ((CacheConditionally) submission).isCacheable();
        }
        if (cacheable) {
            getCache().setBulk(ImmutableMap.of(cacheKey, submission),
                    info.<Duration>getAsType(AType.WINDOW, null));
        }
    } catch (Throwable ex) {
        if (LOG.isDebugEnabled()) {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error.", ex);
        } else {
            LOG.warn("Caching on " + pjp.toShortString() + " aborted due to an error: " + ex.getMessage());
        }
    }
    return result;
}

From source file:jp.rough_diamond.framework.web.struts.BaseAction.java

@Override
protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response, String name) throws Exception {
    Method method = null;
    try {/*from   w ww .j a  v  a  2 s.co  m*/
        method = getMethod(name);
        NoCache noCache = method.getAnnotation(NoCache.class);
        if (noCache != null) {
            log.debug("LbVNGXg?B");
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
            response.addHeader("Expires", "-1");
        }
        ContentType ct = method.getAnnotation(ContentType.class);
        if (ct != null) {
            if (log.isDebugEnabled()) {
                log.debug("ContentType:" + ct.value());
            }
            response.setContentType(ct.value());
        }
        //?
    } catch (NoSuchMethodException e) {
        String message = messages.getMessage("dispatch.method", mapping.getPath(), name);
        log.error(message, e);
        throw e;
    }

    ActionForward forward = null;
    try {
        Object args[] = { mapping, form, request, response };
        forward = (ActionForward) method.invoke(this, args);
        if (form instanceof BaseForm) {
            BaseForm baseForm = (BaseForm) form;
            Messages msg;
            msg = baseForm.getMessage();
            if (msg.hasError()) {
                saveMessages(request, MessagesTranslator.translate(msg));
            }
            msg = baseForm.getErrors();
            if (msg.hasError()) {
                saveErrors(request, MessagesTranslator.translate(msg));
            }
        }
    } catch (ClassCastException e) {
        String message = messages.getMessage("dispatch.return", mapping.getPath(), name);
        log.error(message, e);
        throw e;

    } catch (IllegalAccessException e) {
        String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
        log.error(message, e);
        throw e;

    } catch (InvocationTargetException e) {
        // Rethrow the target exception if possible so that the
        // exception handling machinery can deal with it
        Throwable t = e.getTargetException();
        if (t instanceof Exception) {
            throw ((Exception) t);
        } else {
            String message = messages.getMessage("dispatch.error", mapping.getPath(), name);
            log.error(message, e);
            throw new ServletException(t);
        }
    }

    // Return the returned ActionForward instance
    return (forward);
}

From source file:net.firejack.platform.core.validation.NotBlankProcessor.java

@Override
public List<ValidationMessage> validate(Method readMethod, String property, Object value, ValidationMode mode)
        throws RuleValidationException {
    List<ValidationMessage> validationMessages = new ArrayList<ValidationMessage>();
    Annotation annotation = readMethod.getAnnotation(NotBlank.class);
    if (annotation != null) {
        NotBlank notBlank = (NotBlank) annotation;
        String parameterName = StringUtils.isNotBlank(notBlank.parameterName()) ? notBlank.parameterName()
                : property;/*from w  w  w  .  jav a 2 s  .  co  m*/
        boolean validate = ArrayUtils.contains(notBlank.modes(), mode);
        if (validate) {
            if (value == null) {
                validationMessages.add(new ValidationMessage(property, notBlank.msgKey(), parameterName));
            } else if (!(value instanceof String)) {
                validationMessages.add(new ValidationMessage(property,
                        "Argument '" + parameterName + "' should be of type java.lang.String"));
            } else if (StringUtils.isBlank((String) value)) {
                validationMessages.add(new ValidationMessage(property, notBlank.msgKey(), parameterName));
            }
        }
    }
    return validationMessages;
}

From source file:net.projectmonkey.spring.acl.enhancement.identity.strategy.method.DefaultMethodInvocationObjectIdRetrievalStrategy.java

/**
 * Extension point: Locate the class we want to look up acl's against for the method we're securing. 
 * @param method/*from   w  w  w  .  j ava 2s .co m*/
 * @return
 */
protected Class<?> resolveSecuredClass(final Method method) {
    Class<?> classToFind = processDomainObjectClass;
    SecuredAgainst securedAgainst = method.getAnnotation(SecuredAgainst.class);
    if (securedAgainst != null && securedAgainst.value() != null) {
        classToFind = securedAgainst.value();
    }
    if (classToFind == null) {
        throw new AuthenticationServiceException("No secured class specified for method " + method);
    }
    return classToFind;
}

From source file:org.jellycastle.build.JellyBuild.java

private void loadDependencies(Project project) {
    DependencyManagement dependencyManagement = project.getDependencyManagement();
    if (dependencyManagement == null) {
        dependencyManagement = new ObjectFactory().createDependencyManagement();
        dependencyManagement.setDependencies(new ObjectFactory().createDependencyManagementDependencies());
        project.setDependencyManagement(dependencyManagement);
    }/*from  ww w .ja  v a 2s .c o  m*/

    Project.Dependencies dependencies = project.getDependencies();
    if (dependencies == null) {
        dependencies = new ObjectFactory().createProjectDependencies();
        project.setDependencies(dependencies);
    }

    addJellyBuild(dependencyManagement, dependencies);

    for (Method method : configuration.getDeclaredMethods()) {
        if (method.getAnnotation(org.jellycastle.annotation.dependency.Dependency.class) != null) {
            org.jellycastle.annotation.dependency.Dependency annotation = method
                    .getAnnotation(org.jellycastle.annotation.dependency.Dependency.class);

            if (StringUtils.hasText(annotation.version())) {
                Dependency dependency = new ObjectFactory().createDependency();
                dependency.setGroupId(annotation.groupId());
                dependency.setArtifactId(annotation.artifactId());
                dependency.setVersion(annotation.version());

                dependencyManagement.getDependencies().getDependencies().add(dependency);
            }

            Dependency dependency = new ObjectFactory().createDependency();
            dependency.setGroupId(annotation.groupId());
            dependency.setArtifactId(annotation.artifactId());

            dependencies.getDependencies().add(dependency);
        }
    }
}

From source file:com.ebay.jetstream.management.HtmlResourceFormatter.java

protected void formatProperty(Object bean, PropertyDescriptor pd) throws Exception {
    PrintWriter pw = getWriter();
    Method getter = pd.getReadMethod();
    Class<?> pclass = pd.getPropertyType();
    ManagedAttribute attr = getter.getAnnotation(ManagedAttribute.class);
    String text = attr != null ? attr.description() : null;
    if (CommonUtils.isEmptyTrimmed(text)) {
        text = pd.getDisplayName();//w  w w . j  a v a  2  s .c  om
    } else {
        text = pd.getDisplayName() + " (" + text + ")";
    }
    pw.print(text + ": " + pclass.getName() + " = ");
    getter.setAccessible(true);
    Object value = getter.invoke(bean);
    Method setter = pd.getWriteMethod();
    attr = setter == null ? null : setter.getAnnotation(ManagedAttribute.class);
    boolean isComplex = !(String.class.isAssignableFrom(pclass) || ClassUtils.isPrimitiveOrWrapper(pclass));
    if (isComplex) {
        value = StringEscapeUtils.escapeXml(getSerializer().getXMLStringRepresentation(value));
    }
    if (attr == null) {
        if (isComplex) {
            pushElement("code", null);
        }
        pw.println(value);
        if (isComplex) {
            popElement();
        }
    } else {
        pw.println(attr.description());
        pushElement("form",
                "action=" + makePath(getPrefix(), getPath(), isComplex ? "?form" : "?" + pd.getName())
                        + " method=" + (isComplex ? "POST" : "GET"));
        if (isComplex) {
            pw.print("<TEXTAREA name=" + pd.getName() + " rows=4 cols=32>" + value + "</TEXTAREA>");
        } else {
            pw.print("<input type=text name=" + pd.getName() + " value=\"" + value + "\"/>");
        }
        pw.println("<input type=submit Value=\"Go\"/>");
        popElement();
    }
    pw.println("<P/>");
}