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:org.jspare.server.router.RouterImpl.java

/**
 * Builds the and registry command map./*w w w  .j a  v  a 2s .  c  o m*/
 *
 * @param cmdClazz
 *            the cmd clazz
 */
private void buildAndRegistryCommandMap(Class<?> cmdClazz) {

    if (!isValidCommand(cmdClazz)) {

        throw new InvalidControllerException(
                String.format("Cannot find name Controller on class [%s]", cmdClazz.getName()));
    }

    for (

    Method method : cmdClazz.getDeclaredMethods()) {

        if (method.isAnnotationPresent(Mapping.class)) {

            CommandData cmdData = new CommandData(cmdClazz, method);
            addCommand(cmdData);

            if (cmdData.isStartCommand() && !cmdData.getCommand().equals(StringUtils.EMPTY)
                    && !cmdData.getCommand().equals(START_PATTERN)) {

                CommandData startCommand = cmdData.clone();
                startCommand.setCommand(START_PATTERN);
                addCommand(startCommand);
            }
        }
    }
}

From source file:com.khs.sherpa.endpoint.SherpaEndpoint.java

@SuppressWarnings("unchecked")
//   @RolesAllowed("SHERPA_ADMIN")
@Action(mapping = "/sherpa/admin/describe/{value}")
public Object describe(@Param("value") String value) {

    List<Map<String, Object>> actions = new ArrayList<Map<String, Object>>();

    Set<Method> methods = null;

    try {/* w w w  .j a v  a  2s. c om*/
        methods = Reflections.getAllMethods(applicationContext.getType(value),
                Predicates.and(Predicates.not(SherpaPredicates.withAssignableFrom(Object.class)),
                        ReflectionUtils.withModifier(Modifier.PUBLIC),
                        Predicates.not(ReflectionUtils.withModifier(Modifier.ABSTRACT)),
                        Predicates.not(SherpaPredicates.withGeneric())));
    } catch (NoSuchManagedBeanExcpetion e) {
        throw new SherpaRuntimeException(e);
    }

    for (Method method : methods) {

        Map<String, Object> action = new HashMap<String, Object>();
        actions.add(action);

        action.put("name", MethodUtil.getMethodName(method));

        if (method.isAnnotationPresent(DenyAll.class)) {
            action.put("permission", "DenyAll");
        } else if (method.isAnnotationPresent(RolesAllowed.class)) {
            action.put("permission", "RolesAllowed");
            action.put("roles", method.getAnnotation(RolesAllowed.class).value());
        } else {
            action.put("permission", "PermitAll");
        }

        Map<String, String> params = new HashMap<String, String>();

        Class<?>[] types = method.getParameterTypes();
        Annotation[][] parameters = method.getParameterAnnotations();
        for (int i = 0; i < parameters.length; i++) {
            Class<?> type = types[i];
            Param annotation = null;
            if (parameters[i].length > 0) {
                for (Annotation an : parameters[i]) {
                    if (an.annotationType().isAssignableFrom(Param.class)) {
                        annotation = (Param) an;
                        break;
                    }
                }

            }
            if (annotation != null) {
                params.put(annotation.value(), type.getName());
            }
        }

        if (params.size() > 0) {
            action.put("params", params);
        } else {
            action.put("params", null);
        }

    }

    return actions;
}

From source file:org.archone.ad.rpc.RpcServiceImpl.java

public HashMap<String, Object> process(HttpSession session, HashMap<String, Object> request)
        throws SecurityViolationException, IllegalArgumentException, InvocationTargetException,
        IllegalAccessException {//from  w ww.  j a va  2s.  c  o m

    HashMap rpcCall = this.callMap.get((String) request.get("rpcAction"));
    Assert.notNull(rpcCall, "Action not found");

    try {

        String[] requiredFields = (String[]) rpcCall.get("required");
        for (String field : requiredFields) {

            String[] fieldReqParts = field.split(":");
            String fieldName = fieldReqParts[0];

            if (!request.containsKey(fieldName)) {
                throw new MalformedRequestException("Field " + field + " required for this request");
            }
        }

        Method method = (Method) rpcCall.get("method");

        /*
         * Performing security checks if method is annotated with SecuredMethod
         */
        if (method.isAnnotationPresent(SecuredMethod.class)) {
            String[] constraints = method.getAnnotation(SecuredMethod.class).constraints();

            for (String constraint : constraints) {
                HashMap<String, Object> scUnit = scMap.get(constraint);
                if (scUnit != null) {
                    Method scMethod = (Method) scUnit.get("method");
                    scMethod.invoke(scUnit.get("object"), new OperationContext(session, request));
                } else {
                    throw new RuntimeException("Failed to find a required security constraint");
                }
            }
        }

        return (HashMap<String, Object>) method.invoke(rpcCall.get("object"),
                new OperationContext(session, request));

    } catch (RuntimeException ex) {

        if (true) {
            throw ex;
        }

        Logger.getLogger(this.getClass().getName()).log(Level.INFO, ex.getMessage());

        HashMap<String, Object> response = new HashMap<String, Object>();
        response.put("success", false);

        if (ex instanceof MalformedRequestException) {
            response.put("errors", new String[] { ex.getMessage() });
        } else if (ex instanceof SecurityViolationException) {
            response.put("errors", new String[] { "Access Denied" });
        } else {
            response.put("errors", new String[] { "Unknown Error" });
        }

        return response;
    }
}

From source file:net.solarnetwork.web.support.SimpleCsvView.java

private List<String> getCSVFields(Object row, final Collection<String> fieldOrder) {
    assert row != null;
    List<String> result = new ArrayList<String>();
    if (row instanceof Map) {
        Map<?, ?> map = (Map<?, ?>) row;
        if (fieldOrder != null) {
            for (String key : fieldOrder) {
                result.add(key);//from w  w  w .  j  av  a 2s .com
            }
        } else {
            for (Object key : map.keySet()) {
                result.add(key.toString());
            }
        }
    } else {
        // use bean properties
        if (getPropertySerializerRegistrar() != null) {
            // try whole-bean serialization first
            Object o = getPropertySerializerRegistrar().serializeProperty("row", row.getClass(), row, row);
            if (o != row) {
                if (o != null) {
                    result = getCSVFields(o, fieldOrder);
                    return result;
                }
            }
        }
        BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(row);
        PropertyDescriptor[] props = wrapper.getPropertyDescriptors();
        Set<String> resultSet = new LinkedHashSet<String>();
        for (PropertyDescriptor prop : props) {
            String name = prop.getName();
            if (getJavaBeanIgnoreProperties() != null && getJavaBeanIgnoreProperties().contains(name)) {
                continue;
            }
            if (wrapper.isReadableProperty(name)) {
                // test for SerializeIgnore
                Method getter = prop.getReadMethod();
                if (getter != null && getter.isAnnotationPresent(SerializeIgnore.class)) {
                    continue;
                }
                resultSet.add(name);
            }
        }
        if (fieldOrder != null && fieldOrder.size() > 0) {
            for (String key : fieldOrder) {
                if (resultSet.contains(key)) {
                    result.add(key);
                }
            }
        } else {
            result.addAll(resultSet);
        }

    }
    return result;
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Build JSP function models from an annotated class
 * @param type class with annotated static methods
 * @return JSP function models//from   w  w w .  j  a  v a  2 s .c  o  m
 */
public Collection<JspFunctionModel> getFunctionMetadata(Class<?> type) {
    Collection<JspFunctionModel> functions = new ArrayList<JspFunctionModel>();
    for (Method method : type.getMethods()) {
        if (Modifier.isStatic(method.getModifiers()) && Modifier.isPublic(method.getModifiers())
                && method.isAnnotationPresent(JspFunction.class)) {
            JspFunction functionAnnotation = method.getAnnotation(JspFunction.class);
            JspFunctionModel metadata = new JspFunctionModel();
            metadata.name = functionAnnotation.name();
            metadata.functionClass = type.getName();
            JspFunctionSignature signature = new JspFunctionSignature();
            signature.name = method.getName();
            signature.argumentTypes = method.getParameterTypes();
            signature.returnType = method.getReturnType();
            metadata.signature = signature;
            functions.add(metadata);
        }
    }
    return functions;
}

From source file:org.rifidi.edge.configuration.RifidiService.java

/**
 * Constructor.//from  ww  w  . j ava2 s  . c o  m
 */
public RifidiService() {
    this.nameToProperty = new HashMap<String, Property>();
    this.nameToOperation = new HashMap<String, Operation>();
    this.nameToMethod = new HashMap<String, Method>();
    Class<?> clazz = this.getClass();
    if (clazz.isAnnotationPresent(JMXMBean.class)) {
        // check method annotations
        for (Method method : clazz.getMethods()) {
            // scan for operations annotation
            if (method.isAnnotationPresent(Operation.class)) {
                nameToOperation.put(method.getName(), (Operation) method.getAnnotation(Operation.class));
            }
            // scan for property annotation
            if (method.isAnnotationPresent(Property.class)) {
                nameToProperty.put(method.getName().substring(3),
                        (Property) method.getAnnotation(Property.class));
                nameToMethod.put(method.getName().substring(3), method);
            }
        }
    }
}

From source file:de.extra.client.core.annotation.PropertyPlaceholderPluginConfigurer.java

private void setPluginProperties(final ConfigurableListableBeanFactory beanFactory, final Properties properties,
        final String beanName, final Class<?> clazz) {
    final PluginConfiguration annotationConfigutation = clazz.getAnnotation(PluginConfiguration.class);
    final MutablePropertyValues mutablePropertyValues = beanFactory.getBeanDefinition(beanName)
            .getPropertyValues();/*from w  ww .  j  av  a  2 s .  com*/

    for (final PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
        final Method setter = property.getWriteMethod();
        PluginValue valueAnnotation = null;
        if (setter != null && setter.isAnnotationPresent(PluginValue.class)) {
            valueAnnotation = setter.getAnnotation(PluginValue.class);
        }
        if (valueAnnotation != null) {
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            final String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (StringUtils.isEmpty(value)) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
            if (LOG.isDebugEnabled()) {
                LOG.debug("setting property=[" + clazz.getName() + "." + property.getName() + "] value=[" + key
                        + "=" + value + "]");
            }
            mutablePropertyValues.addPropertyValue(property.getName(), value);
        }
    }

    for (final Field field : clazz.getDeclaredFields()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("examining field=[" + clazz.getName() + "." + field.getName() + "]");
        }
        if (field.isAnnotationPresent(PluginValue.class)) {
            final PluginValue valueAnnotation = field.getAnnotation(PluginValue.class);
            final PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

            if (property == null || property.getWriteMethod() == null) {
                throw new BeanCreationException(beanName,
                        "setter for property=[" + clazz.getName() + "." + field.getName() + "] not available.");
            }
            final String key = extractKey(annotationConfigutation, valueAnnotation, clazz);
            String value = resolvePlaceholder(key, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
            if (value == null) {
                // DEFAULT Value suchen
                final int separatorIndex = key.indexOf(VALUE_SEPARATOR);
                if (separatorIndex != -1) {
                    final String actualPlaceholder = key.substring(0, separatorIndex);
                    final String defaultValue = key.substring(separatorIndex + VALUE_SEPARATOR.length());
                    value = resolvePlaceholder(actualPlaceholder, properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                    if (value == null) {
                        value = defaultValue;
                    }
                }
            }

            if (value != null) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug("setting property=[" + clazz.getName() + "." + field.getName() + "] value=[" + key
                            + "=" + value + "]");
                }
                mutablePropertyValues.addPropertyValue(field.getName(), value);
            } else if (!ignoreNullValues) {
                throw new BeanCreationException(beanName,
                        "No such property=[" + key + "] found in properties.");
            }
        }
    }
}

From source file:org.lexevs.cache.AbstractMethodCachingBean.java

/**
 * Cache method.//w ww . jav a2s .  c om
 * 
 * @param pjp the pjp
 * 
 * @return the object
 * 
 * @throws Throwable the throwable
 */
protected Object doCacheMethod(T joinPoint) throws Throwable {

    if (!CacheSessionManager.getCachingStatus()) {
        return this.proceed(joinPoint);
    }

    Method method = this.getMethod(joinPoint);

    if (method.isAnnotationPresent(CacheMethod.class) && method.isAnnotationPresent(ClearCache.class)) {
        throw new RuntimeException("Cannot both Cache method results and clear the Cache in "
                + "the same method. Please only use @CacheMethod OR @ClearCache -- not both. "
                + " This occured on method: " + method.toString());
    }

    Object target = this.getTarget(joinPoint);

    Annotation[][] parameterAnnotations = method.getParameterAnnotations();

    String key = this.getKeyFromMethod(target.getClass().getName(), method.getName(),
            this.getArguments(joinPoint), parameterAnnotations);

    Cacheable cacheableAnnotation = AnnotationUtils.findAnnotation(target.getClass(), Cacheable.class);
    CacheMethod cacheMethodAnnotation = AnnotationUtils.findAnnotation(method, CacheMethod.class);

    CacheWrapper<String, Object> cache = this.getCacheFromName(cacheableAnnotation.cacheName(), true);

    if (method.isAnnotationPresent(ClearCache.class)) {
        return this.clearCache(joinPoint, method);
    }

    Object value = cache.get(key);
    if (value != null) {
        this.logger.debug("Cache hit on: " + key);
        if (value.equals(NULL_VALUE_CACHE_PLACEHOLDER)) {
            return null;
        } else {
            return returnResult(value, cacheMethodAnnotation);
        }
    } else {
        this.logger.debug("Caching miss on: " + key);
    }

    Object result = this.proceed(joinPoint);

    if (this.isolateCachesOnClear == false
            || (this.isolateCachesOnClear == true && (this.cacheRegistry.getInThreadCacheClearingState() == null
                    || this.cacheRegistry.getInThreadCacheClearingState() == false))) {
        this.logger.debug("Thread is not in @Clear state, caching can continue for key: " + key);

        if (result != null) {
            cache.put(key, result);
        } else {
            cache.put(key, NULL_VALUE_CACHE_PLACEHOLDER);
        }
    } else {
        this.logger.debug("Thread is in @Clear state, caching skipped for key: " + key);
    }

    return returnResult(result, cacheMethodAnnotation);
}

From source file:org.aver.fft.impl.FlatFileTransformer.java

/**
 * Reads the specified class and loads into (if not already loaded) a map
 * containing the bean class name to a {@link Record} instance. The Record
 * instance will contain metadata about the record format.
 * /*from w  w w  .j av  a 2s.c o m*/
 * @param destClazz
 */
private void parseRecordMappingDetails() {
    if (!recordMap.containsKey(clazz.getName())) {
        synchronized (recordMap) {
            Record rec = new Record(clazz.getName());
            recordMap.put(rec.getName(), rec);
            for (Method m : clazz.getMethods()) {
                if (m.isAnnotationPresent(org.aver.fft.annotations.Column.class)) {
                    String colname = m.getName();
                    if (m.getName().startsWith("get") || m.getName().startsWith("set")) {
                        colname = colname.substring(3);
                    }
                    colname = Character.toLowerCase(colname.charAt(0)) + colname.substring(1);
                    org.aver.fft.annotations.Column annot = m
                            .getAnnotation(org.aver.fft.annotations.Column.class);
                    // String name, String type, boolean required, int
                    // index, String format, boolean skip
                    Column col = new Column(colname, m.getReturnType().getName(), annot.required(),
                            annot.position(), annot.format(), annot.skip());
                    col.setStartColumn(annot.start());
                    col.setEndColumn(annot.end());
                    rec.addColumn(col);
                }
            }
        }
    }
}

From source file:org.carewebframework.ui.xml.ZK2XML.java

/**
 * Adds the root component to the XML document at the current level along with all bean
 * properties that return String or primitive types. Then, recurses over all of the root
 * component's children./*from  www  . ja  v a  2s.  co m*/
 * 
 * @param root The root component.
 * @param parent The parent XML node.
 */
private void toXML(Component root, Node parent) {
    TreeMap<String, String> properties = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    Class<?> clazz = root.getClass();
    ComponentDefinition def = root.getDefinition();
    String cmpname = def.getName();

    if (def.getImplementationClass() != clazz) {
        properties.put("use", clazz.getName());
    }

    if (def.getApply() != null) {
        properties.put("apply", def.getApply());
    }

    Node child = doc.createElement(cmpname);
    parent.appendChild(child);

    for (PropertyDescriptor propDx : PropertyUtils.getPropertyDescriptors(root)) {
        Method getter = propDx.getReadMethod();
        Method setter = propDx.getWriteMethod();
        String name = propDx.getName();

        if (getter != null && setter != null && !isExcluded(name, cmpname, null)
                && !setter.isAnnotationPresent(Deprecated.class)
                && (getter.getReturnType() == String.class || getter.getReturnType().isPrimitive())) {
            try {
                Object raw = getter.invoke(root);
                String value = raw == null ? null : raw.toString();

                if (StringUtils.isEmpty(value) || ("id".equals(name) && value.startsWith("z_"))
                        || isExcluded(name, cmpname, value)) {
                    continue;
                }

                properties.put(name, value.toString());
            } catch (Exception e) {
            }
        }
    }

    for (Entry<String, String> entry : properties.entrySet()) {
        Attr attr = doc.createAttribute(entry.getKey());
        child.getAttributes().setNamedItem(attr);
        attr.setValue(entry.getValue());
    }

    properties = null;

    for (Component cmp : root.getChildren()) {
        toXML(cmp, child);
    }
}