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.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleProperties(Class<?> classz, StringBuilder sb, Map<String, String> declarations,
        String uriPrefix) {/*from  www .  j  a  va  2 s .  co  m*/
    boolean result = false;
    String prepend = "";
    Set<String> processedFields = new HashSet<String>();
    sb.append("{");
    for (Field field : classz.getFields()) {
        JsonSchemaProperty propertyDecl = field.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null) {
            Class<?> propClassz = field.getType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    for (Method method : classz.getMethods()) {
        JsonSchemaProperty propertyDecl = method.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null && !processedFields.contains(propertyDecl.name())) {
            Class<?> propClassz = method.getReturnType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    sb.append("}");
    return result;
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

public static String getCode(Method m) {
    if (m.isAnnotationPresent(I18n.class)) {
        if (m.getAnnotation(I18n.class).value().length() > 0) {
            return m.getAnnotation(I18n.class).value();
        } else {//w w w .  j a  v  a2  s .c  o  m
            return m.getDeclaringClass().getCanonicalName() + CODE_SEPARATOR + findGetterFieldName(m);
        }
    }
    // else if(m.isAnnotationPresent(I18nRef.class)) {
    //    Object ref = m.getAnnotation(I18nRef.class).value();
    //    if(((Class<?>)ref).isEnum()) {
    //       return getCode((Enum<?>)ref);
    //    } else {
    //       return getCode((Class<?>)ref);
    //    }
    // }
    return m.getDeclaringClass().getCanonicalName() + CODE_SEPARATOR + findGetterFieldName(m);
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

@SuppressWarnings("unchecked")
public static <T> T clone(T object, boolean deep) {
    try {/*from w w w.  j a v a 2 s.  c o m*/
        if (object == null)
            throw new InvalidParameterException("'object' must not be null.");

        Class<? extends Object> clazz = object.getClass();

        MCElement e = clazz.getAnnotation(MCElement.class);
        if (e == null)
            throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

        BeanWrapperImpl dst = new BeanWrapperImpl(clazz);
        BeanWrapperImpl src = new BeanWrapperImpl(object);

        for (Method m : clazz.getMethods()) {
            if (!m.getName().startsWith("set"))
                continue;
            String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
            MCAttribute a = m.getAnnotation(MCAttribute.class);
            if (a != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCChildElement c = m.getAnnotation(MCChildElement.class);
            if (c != null) {
                if (deep) {
                    dst.setPropertyValue(propertyName, cloneInternal(src.getPropertyValue(propertyName), deep));
                } else {
                    dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
                }
            }
            MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
            if (o != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
            MCTextContent t = m.getAnnotation(MCTextContent.class);
            if (t != null) {
                dst.setPropertyValue(propertyName, src.getPropertyValue(propertyName));
            }
        }

        return (T) dst.getRootInstance();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:ca.sqlpower.testutil.TestUtils.java

/**
 * Returns the set of property names which have both a getter and a setter
 * method and are annotated to be persisted through the {@link SPPersister}
 * classes.// w w  w  . j  a  v  a 2 s  .co m
 * 
 * @param objectUnderTest
 *            The object that contains the persistable properties we want to
 *            find.
 * @param includeTransient
 *            If true the properties marked as transient will also be
 *            included. If false only the properties that are persisted and
 *            not transient are returned.
 * @param includeConstructorMutators
 *            If true the properties that have getters but can only be set
 *            through a constructor due to being final will be included. If
 *            false the persisted properties provided must have a setter.
 */
public static Set<String> findPersistableBeanProperties(SPObject objectUnderTest, boolean includeTransient,
        boolean includeConstructorMutators) throws Exception {
    Set<String> getters = new HashSet<String>();
    Set<String> setters = new HashSet<String>();
    for (Method m : objectUnderTest.getClass().getMethods()) {
        if (m.getName().equals("getClass"))
            continue;

        //skip non-public methods as they are not visible for persisting anyways.
        if (!Modifier.isPublic(m.getModifiers()))
            continue;
        //skip static methods
        if (Modifier.isStatic(m.getModifiers()))
            continue;

        if (m.getName().startsWith("get") || m.getName().startsWith("is")) {
            Class<?> parentClass = objectUnderTest.getClass();
            boolean accessor = false;
            boolean ignored = false;
            boolean isTransient = false;
            parentClass.getMethod(m.getName(), m.getParameterTypes());//test
            while (parentClass != null) {
                Method parentMethod;
                try {
                    parentMethod = parentClass.getMethod(m.getName(), m.getParameterTypes());
                } catch (NoSuchMethodException e) {
                    parentClass = parentClass.getSuperclass();
                    continue;
                }
                if (parentMethod.getAnnotation(Accessor.class) != null) {
                    accessor = true;
                    if (parentMethod.getAnnotation(Transient.class) != null) {
                        isTransient = true;
                    }
                    break;
                } else if (parentMethod.getAnnotation(NonProperty.class) != null
                        || parentMethod.getAnnotation(NonBound.class) != null) {
                    ignored = true;
                    break;
                }
                parentClass = parentClass.getSuperclass();
            }
            if (accessor) {
                if (includeTransient || !isTransient) {
                    if (m.getName().startsWith("get")) {
                        getters.add(m.getName().substring(3));
                    } else if (m.getName().startsWith("is")) {
                        getters.add(m.getName().substring(2));
                    }
                }
            } else if (ignored) {
                //ignored so skip
            } else {
                fail("The method " + m.getName() + " of " + objectUnderTest.toString()
                        + " is a getter that is not annotated "
                        + "to be an accessor or transient. The exiting annotations are "
                        + Arrays.toString(m.getAnnotations()));
            }
        } else if (m.getName().startsWith("set")) {
            if (m.getAnnotation(Mutator.class) != null) {
                if ((includeTransient || m.getAnnotation(Transient.class) == null)
                        && (includeConstructorMutators
                                || !m.getAnnotation(Mutator.class).constructorMutator())) {
                    setters.add(m.getName().substring(3));
                }
            } else if (m.getAnnotation(NonProperty.class) != null || m.getAnnotation(NonBound.class) != null) {
                //ignored so skip and pass
            } else {
                fail("The method " + m.getName() + " is a setter that is not annotated "
                        + "to be a mutator or transient.");
            }
        }
    }

    Set<String> beanNames = new HashSet<String>();
    for (String beanName : getters) {
        if (setters.contains(beanName)) {
            String firstLetter = new String(new char[] { beanName.charAt(0) });
            beanNames.add(beanName.replaceFirst(firstLetter, firstLetter.toLowerCase()));
        }
    }
    return beanNames;
}

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

/**
 * Get the methods on a given object that are searchable.
 * /*from   w  w w  .  j a v a 2  s. c o  m*/
 * @param o object to get methods from
 * @return list of searchable methods
 */
public static List<Method> getSearchableMethods(Object o) {
    List<Method> methods = new ArrayList<Method>();
    for (Method m : o.getClass().getMethods()) {
        if (m.getAnnotation(Searchable.class) != null) {
            if (m.getReturnType().equals(Void.TYPE)) {
                throw new IllegalArgumentException(
                        String.format("The @Searchable annotation cannot be applied to %s.%s() [void return]",
                                o.getClass(), m));
            }
            methods.add(m);
        }
    }
    return methods;
}

From source file:com.qingstor.sdk.utils.QSJSONUtil.java

private static boolean initParameter(JSONObject o, Field[] declaredField, Class objClass, Object targetObj)
        throws NoSuchMethodException {
    boolean hasParam = false;
    for (Field field : declaredField) {
        String methodField = QSParamInvokeUtil.capitalize(field.getName());
        String getMethodName = field.getType() == Boolean.class ? "is" + methodField : "get" + methodField;
        String setMethodName = "set" + methodField;
        Method[] methods = objClass.getDeclaredMethods();
        for (Method m : methods) {
            if (m.getName().equals(getMethodName)) {
                ParamAnnotation annotation = m.getAnnotation(ParamAnnotation.class);
                if (annotation == null) {
                    continue;
                }/*from  w  w  w.j a  va  2 s  . co m*/
                String dataKey = annotation.paramName();

                if (o.has(dataKey)) {
                    hasParam = true;
                    Object data = toObject(o, dataKey);
                    Method setM = objClass.getDeclaredMethod(setMethodName, field.getType());
                    setParameterToMap(setM, targetObj, field, data);
                }
            }
        }
    }
    return hasParam;
}

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

private static String createSubResourcePath(String base, Method method) {
    if (!base.endsWith("/")) {
        base = base + "/";
    }// w w w  .j a v  a  2 s .  c  o  m
    String path = method.getAnnotation(Path.class).value();
    if (path.startsWith("/")) {
        path = path.substring(1);
    }
    Annotation[][] params = method.getParameterAnnotations();
    int index = 1;
    for (Annotation[] param : params) {
        for (Annotation a : param) {
            if (a instanceof PathParam) {
                String name = ((PathParam) a).value();
                path = path.replace("{" + name + "}", "%" + index + "$s");
                break;
            }
        }
        index++;
    }
    return base + path;
}

From source file:org.openmrs.module.webservices.docs.ResourceDocCreator.java

/**
 * Gets a request method description specified for a given web service request handling method.
 * // w w w.jav a 2 s. com
 * @param requestMapping the request mapping annotation.
 * @param operation the HTTP operation method.
 * @param method the method.
 * @param supportsSearching specified if the controller the method belongs supports searching
 * @return the method description string.
 */
private static String getMethodDescription(RequestMapping requestMapping, String operation, Method method,
        boolean supportsSearching) {

    //If the documentation annotation exists, then no need for auto generating the description.
    WSDoc docAnnotation = (WSDoc) method.getAnnotation(WSDoc.class);
    if (docAnnotation != null)
        return docAnnotation.value();

    String value = null;
    if (requestMapping.value().length > 0 && StringUtils.isNotEmpty(requestMapping.value()[0]))
        value = requestMapping.value()[0];

    if (operation.equals("GET")) {
        if (value != null && value.contains("uuid"))
            return "Fetch by unique uuid";
        if (!supportsSearching)
            return "Fetch all non-retired";
        return "Fetch all non-retired that match any specified parameters otherwise fetch all non-retired";

    } else if (operation.equals("POST")) {
        if (value != null && value.contains("uuid"))
            return "Edit with given uuid, only modifying properties in request";
        else
            return "Create with properties in request";

    } else if (operation.equals("DELETE")) {
        if (!requestMapping.params()[0].startsWith("!"))
            return "Delete this object from the database";
        else
            return "Retire/Void this object";
    }

    return null;
}

From source file:com.ms.commons.summer.web.handler.DataBinderUtil.java

/**
 * ?/*w  w  w. j  a  va 2  s  .c  o m*/
 * 
 * @param method
 * @param model
 * @param request
 * @param response
 * @param c
 * @return
 */
@SuppressWarnings("unchecked")
public static Object[] getArgs(Method method, Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response, Class<?> c) {
    Class<?>[] paramTypes = method.getParameterTypes();
    Object[] args = new Object[paramTypes.length];
    Map<String, Object> argMap = new HashMap<String, Object>(args.length);
    Map<String, String> pathValues = null;
    PathPattern pathPattern = method.getAnnotation(PathPattern.class);
    if (pathPattern != null) {
        String path = request.getRequestURI();
        int index = path.lastIndexOf('.');
        if (index != -1) {
            path = path.substring(0, index);
            String[] patterns = pathPattern.patterns();
            pathValues = getPathValues(patterns, path);
        }
    }
    MapBindingResult errors = new MapBindingResult(argMap, "");
    ParameterNameDiscoverer parameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();
    for (int i = 0; i < paramTypes.length; i++) {
        Class<?> paramType = paramTypes[i];

        MethodParameter methodParam = new MethodParameter(method, i);
        methodParam.initParameterNameDiscovery(parameterNameDiscoverer);
        GenericTypeResolver.resolveParameterType(methodParam, c.getClass());

        String paramName = methodParam.getParameterName();
        // map
        if (Map.class.isAssignableFrom(paramType)) {
            args[i] = model;
        }
        // HttpServletRequest
        else if (HttpServletRequest.class.isAssignableFrom(paramType)) {
            args[i] = request;
        }
        // HttpServletResponse
        else if (HttpServletResponse.class.isAssignableFrom(paramType)) {
            args[i] = response;
        }
        // HttpSession
        else if (HttpSession.class.isAssignableFrom(paramType)) {
            args[i] = request.getSession();
        }
        // Errors
        else if (Errors.class.isAssignableFrom(paramType)) {
            args[i] = errors;
        }
        // MultipartFile
        else if (MultipartFile.class.isAssignableFrom(paramType)) {
            MultipartFile[] files = resolveMultipartFiles(request, errors, paramName);
            if (files != null && files.length > 0) {
                args[i] = files[0];
            }
        }
        // MultipartFile[]
        else if (MultipartFile[].class.isAssignableFrom(paramType)) {
            args[i] = resolveMultipartFiles(request, errors, paramName);
        } else {
            // ??
            if (BeanUtils.isSimpleProperty(paramType)) {
                SimpleTypeConverter converter = new SimpleTypeConverter();
                Object value;
                // ?
                if (paramType.isArray()) {
                    value = request.getParameterValues(paramName);
                } else {
                    Object[] parameterAnnotations = methodParam.getParameterAnnotations();
                    value = null;
                    if (parameterAnnotations != null && parameterAnnotations.length > 0) {
                        if (pathValues != null && pathValues.size() > 0) {
                            for (Object object : parameterAnnotations) {
                                if (PathVariable.class.isInstance(object)) {
                                    PathVariable pv = (PathVariable) object;
                                    if (StringUtils.isEmpty(pv.value())) {
                                        value = pathValues.get(paramName);
                                    } else {
                                        value = pathValues.get(pv.value());
                                    }
                                    break;
                                }
                            }
                        }
                    } else {
                        value = request.getParameter(paramName);
                    }
                }
                try {
                    args[i] = converter.convertIfNecessary(value, paramType, methodParam);
                    model.put(paramName, args[i]);
                } catch (TypeMismatchException e) {
                    errors.addError(new FieldError(paramName, paramName, e.getMessage()));
                }
            } else {
                // ???POJO
                if (paramType.isArray()) {
                    ObjectArrayDataBinder binder = new ObjectArrayDataBinder(paramType.getComponentType(),
                            paramName);
                    args[i] = binder.bind(request);
                    model.put(paramName, args[i]);
                } else {
                    Object bindObject = BeanUtils.instantiateClass(paramType);
                    SummerServletRequestDataBinder binder = new SummerServletRequestDataBinder(bindObject,
                            paramName);
                    binder.bind(request);
                    BindException be = new BindException(binder.getBindingResult());
                    List<FieldError> fieldErrors = be.getFieldErrors();
                    for (FieldError fieldError : fieldErrors) {
                        errors.addError(fieldError);
                    }
                    args[i] = binder.getTarget();
                    model.put(paramName, args[i]);
                }
            }
        }
    }
    return args;
}

From source file:com.github.cherimojava.data.mongo.entity.EntityUtils.java

/**
 * retrieves the name of the property which is used on mongodb side. Accepts only get methods, will throw an
 * exception for all other methods//from  w  w w .ja v  a  2s.  c o  m
 *
 * @param m method to retrieve mongo name from
 * @return mongo name for the given getter method (parameter)
 */
static String getMongoNameFromMethod(Method m) {
    checkArgument(m.getName().startsWith("get") || m.getName().startsWith("is"),
            "Mongo name can only be retrieved from get/is methods, but was %s", m.getName());
    checkArgument(!(m.isAnnotationPresent(Named.class) && m.isAnnotationPresent(Id.class)),
            "You can not annotate a property with @Name and @Id");
    if (m.isAnnotationPresent(Named.class)) {
        checkArgument(!Entity.ID.equals(m.getAnnotation(Named.class).value()),
                "It's not allowed to use @Name annotation to declare id field, instead use @Id annotation");
        return m.getAnnotation(Named.class).value();
    }
    if (m.isAnnotationPresent(Id.class) || "id".equals(getPojoNameFromMethod(m).toLowerCase(Locale.US))) {
        return Entity.ID;
    }
    // differentiate between get and is methods
    return decapitalize(m.getName().substring(m.getName().startsWith("get") ? 3 : 2));
}