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:es.osoco.grails.plugins.otp.access.AnnotationMultipleVoterFilterInvocationDefinition.java

private Map<String, Set<String>> findActionRoles(final Class<?> clazz) {
    // since action closures are defined as "def foo = ..." they're
    // fields, but they end up as private
    Map<String, Set<String>> actionRoles = new HashMap<String, Set<String>>();
    for (Field field : clazz.getDeclaredFields()) {
        Annotation annotation = findAnnotation(field.getAnnotations());
        if (annotation != null) {
            actionRoles.put(field.getName(), asSet(getValue(annotation)));
        }// w w  w  .j  a va  2s.  com
    }
    for (Method method : clazz.getDeclaredMethods()) {
        Annotation annotation = findAnnotation(method.getAnnotations());
        if (annotation != null) {
            actionRoles.put(method.getName(), asSet(getValue(annotation)));
        }
    }
    return actionRoles;
}

From source file:net.navasoft.madcoin.backend.services.vo.request.SuccessRequestVOWrapper.java

/**
 * Gets the error processing values.// w w w  . j  a va2 s .  co m
 * 
 * @return the error processing values
 * @since 27/07/2014, 06:49:08 PM
 */
@Override
public ControllerExceptionArgument[] getErrorProcessingValues() {
    ControllerExceptionArgument[] errors = (ControllerExceptionArgument[]) Array
            .newInstance(ControllerExceptionArgument.class, 0);
    for (Method accessor : helper.getDeclaredMethods()) {
        for (Annotation expected : accessor.getAnnotations()) {
            if (expected.annotationType() == ProcessingErrorValue.class) {
                try {
                    ProcessingErrorValue expectedReal = ((ProcessingErrorValue) expected);
                    Object requestValue = null;
                    switch (expectedReal.precedence()) {
                    case BASIC_OPTIONAL:

                        requestValue = accessor.invoke(hidden, ArrayUtils.EMPTY_OBJECT_ARRAY);

                        requestValue = (requestValue != null) ? requestValue : "No data provided";
                        errors = (ControllerExceptionArgument[]) ArrayUtils.add(errors,
                                new ControllerExceptionArgument(requestValue));
                        break;
                    case BASIC_REQUIRED:
                        requestValue = accessor.invoke(hidden, ArrayUtils.EMPTY_OBJECT_ARRAY);
                        errors = (ControllerExceptionArgument[]) ArrayUtils.add(errors,
                                new ControllerExceptionArgument(requestValue));
                        break;
                    case COMPLEX_OPTIONAL:
                        break;
                    case COMPLEX_REQUIRED:
                        break;
                    default:
                        break;
                    }
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    return errors;
}

From source file:org.apache.axis2.jaxws.server.endpoint.injection.impl.WebServiceContextInjectorImpl.java

private Method searchMethodsResourceAnnotation(Class bean) {
    if (bean == null) {
        return null;
    }//  www  .  jav  a2  s  .  c o m
    List<Method> methods = getMethods(bean);
    for (Method method : methods) {
        Annotation[] annotations = method.getAnnotations();
        for (Annotation an : annotations) {
            if (Resource.class.isAssignableFrom(an.getClass())) {
                //check to make sure it is a @Resource for WebServiceContext.
                Resource atResource = (Resource) an;
                if (isWebServiceContextResource(atResource, method)) {
                    return method;
                }
            }
        }
    }
    return null;
}

From source file:com.sinosoft.one.mvc.web.impl.module.ControllerRef.java

private Map<ReqMethod, String[]> collectsShotcutMappings(Method method) {
    Map<ReqMethod, String[]> restMethods = new HashMap<ReqMethod, String[]>();
    Annotation[] annotations = method.getAnnotations();
    for (Annotation annotation : annotations) {
        if (annotation instanceof Delete) {
            restMethods.put(ReqMethod.DELETE, ((Delete) annotation).value());
        } else if (annotation instanceof Get) {
            restMethods.put(ReqMethod.GET, ((Get) annotation).value());
        } else if (annotation instanceof Head) {
            restMethods.put(ReqMethod.HEAD, ((Head) annotation).value());
        } else if (annotation instanceof Options) {
            restMethods.put(ReqMethod.OPTIONS, ((Options) annotation).value());
        } else if (annotation instanceof Post) {
            restMethods.put(ReqMethod.POST, ((Post) annotation).value());
        } else if (annotation instanceof Put) {
            restMethods.put(ReqMethod.PUT, ((Put) annotation).value());
        } else if (annotation instanceof Trace) {
            restMethods.put(ReqMethod.TRACE, ((Trace) annotation).value());
        } else {/*ww w  .  j  a  va 2 s .c om*/
        }
    }

    for (String[] paths : restMethods.values()) {
        for (int i = 0; i < paths.length; i++) {
            if (paths[i].equals("/")) {
                paths[i] = "";
            } else if (paths[i].length() > 0 && paths[i].charAt(0) != '/') {
                paths[i] = "/" + paths[i];
            }
            if (paths[i].length() > 1 && paths[i].endsWith("/")) {
                if (paths[i].endsWith("//")) {
                    throw new IllegalArgumentException(
                            "invalid path '" + paths[i] + "' for method " + method.getDeclaringClass().getName()
                                    + "#" + method.getName() + ": don't end with more than one '/'");
                }
                paths[i] = paths[i].substring(0, paths[i].length() - 1);
            }
        }
    }
    return restMethods;
}

From source file:de.grobmeier.jjson.convert.JSONAnnotationEncoder.java

private void serializeMethods(Object c, StringBuilder builder, int count) throws JSONException {
    boolean first = (count == 0);

    Method[] methods = ArrayUtils.addAll(c.getClass().getDeclaredMethods(), c.getClass().getMethods());
    for (Method method : methods) {
        Annotation[] anons = method.getAnnotations();
        for (Annotation annotation : anons) {
            if (annotation.annotationType().isAssignableFrom(JSON.class)) {
                if (!first) {
                    builder.append(COMMA);
                } else {
                    first = false;//  ww  w  .  j a v a 2  s . com
                }

                try {
                    Object result = method.invoke(c, (Object[]) null);
                    String name = method.getName();
                    if (name.startsWith("is")) {
                        name = name.replaceFirst("is", "");
                        name = name.substring(0, 1).toLowerCase() + name.substring(1);
                    }
                    if (name.startsWith("get")) {
                        name = name.replaceFirst("get", "");
                        name = name.substring(0, 1).toLowerCase() + name.substring(1);
                    }
                    encodeString(name, builder, (JSON) annotation);
                    builder.append(COLON);
                    encode(result, builder, (JSON) annotation);
                } catch (SecurityException e) {
                    throw new JSONException(e);
                } catch (IllegalArgumentException e) {
                    throw new JSONException(e);
                } catch (IllegalAccessException e) {
                    throw new JSONException(e);
                } catch (InvocationTargetException e) {
                    throw new JSONException(e);
                }
            }
        }
    }
}

From source file:com.conversantmedia.mapreduce.tool.annotation.handler.MaraAnnotationUtil.java

/**
 * Use any relevant annotations on the supplied class to configure
 * the given job./*from   www  .  j a va 2s .co  m*/
 * 
 * @param clazz            the class to reflect for mara-related annotations
 * @param job            the job being configured
 * @throws ToolException   if reflection fails for any reason
 */
public void configureJobFromClass(Class<?> clazz, Job job) throws ToolException {

    configureJobFromAnnotations(job, clazz.getAnnotations(), clazz);

    for (Field field : clazz.getDeclaredFields()) {
        configureJobFromAnnotations(job, field.getAnnotations(), field);
    }
    for (Method method : clazz.getDeclaredMethods()) {
        configureJobFromAnnotations(job, method.getAnnotations(), method);
    }
}

From source file:com.ettrema.httpclient.calsync.parse.CalDavBeanPropertyMapper.java

public String toVCard(Object bean) {
    net.fortuna.ical4j.model.Calendar calendar = new net.fortuna.ical4j.model.Calendar();
    calendar.getProperties().add(new ProdId("-//spliffy.org//iCal4j 1.0//EN"));
    calendar.getProperties().add(Version.VERSION_2_0);
    VEvent vevent = new VEvent();
    calendar.getComponents().add(vevent);

    PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
    for (PropertyDescriptor pd : pds) {
        if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
            Method read = pd.getReadMethod();
            Annotation[] annotations = read.getAnnotations();
            for (Annotation anno : annotations) {
                Mapper mapper = mapOfMappers.get(anno.annotationType());
                if (mapper != null) {
                    mapper.mapToCard(calendar, bean, pd);
                }/*from  w w  w.java2  s  .c om*/
            }
        }
    }

    CalendarOutputter outputter = new CalendarOutputter();
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    try {
        outputter.output(calendar, bout);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    } catch (ValidationException ex) {
        throw new RuntimeException(ex);
    }
    return bout.toString();
}

From source file:org.opencastproject.runtimeinfo.Activator.java

private void writeServiceDocumentation(final String docPath, HttpServletRequest req, HttpServletResponse resp)
        throws IOException {
    ServiceReference reference = null;/*from   w ww. j  a  va  2  s .  co m*/
    for (ServiceReference ref : getRestEndpointServices()) {
        String alias = (String) ref.getProperty(SERVICE_PATH_PROPERTY);
        if (docPath.equalsIgnoreCase(alias)) {
            reference = ref;
            break;
        }
    }

    final StringBuilder docs = new StringBuilder();

    if (reference == null) {
        docs.append("REST docs unavailable for ");
        docs.append(docPath);
    } else {
        final Object restService = bundleContext.getService(reference);
        findRestAnnotation(restService.getClass()).fold(new Option.Match<RestService, Void>() {
            @Override
            public Void some(RestService annotation) {
                globalMacro.put("SERVICE_CLASS_SIMPLE_NAME", restService.getClass().getSimpleName());
                RestDocData data = new RestDocData(annotation.name(), annotation.title(), docPath,
                        annotation.notes(), restService, globalMacro);
                data.setAbstract(annotation.abstractText());

                for (Method m : restService.getClass().getMethods()) {
                    RestQuery rq = (RestQuery) m.getAnnotation(RestQuery.class);
                    String httpMethodString = null;
                    for (Annotation a : m.getAnnotations()) {
                        HttpMethod httpMethod = (HttpMethod) a.annotationType().getAnnotation(HttpMethod.class);
                        if (httpMethod != null) {
                            httpMethodString = httpMethod.value();
                        }
                    }
                    Produces produces = (Produces) m.getAnnotation(Produces.class);
                    Path path = (Path) m.getAnnotation(Path.class);
                    Class<?> returnType = m.getReturnType();
                    if ((rq != null) && (httpMethodString != null) && (path != null)) {
                        data.addEndpoint(rq, returnType, produces, httpMethodString, path);
                    }
                }
                String template = DocUtil.loadTemplate("/ui/restdocs/template.xhtml");
                docs.append(DocUtil.generate(data, template));
                return null;
            }

            @Override
            public Void none() {
                docs.append("No documentation has been found for ")
                        .append(restService.getClass().getSimpleName());
                return null;
            }
        });
    }

    resp.setContentType("text/html");
    resp.getWriter().write(docs.toString());
}

From source file:com.ettrema.httpclient.calsync.parse.CalDavBeanPropertyMapper.java

public void toBean(Object bean, String icalText) {
    ByteArrayInputStream fin = null;
    try {//ww w .  j  a  va  2  s .c om
        fin = new ByteArrayInputStream(icalText.getBytes("UTF-8"));
        CalendarBuilder builder = new CalendarBuilder();
        net.fortuna.ical4j.model.Calendar cal4jCalendar;
        try {
            cal4jCalendar = builder.build(fin);
        } catch (IOException ex) {
            throw new RuntimeException(icalText, ex);
        } catch (ParserException ex) {
            throw new RuntimeException(icalText, ex);
        }
        PropertyDescriptor[] pds = PropertyUtils.getPropertyDescriptors(bean);
        for (PropertyDescriptor pd : pds) {
            if (pd.getReadMethod() != null && pd.getWriteMethod() != null) {
                Method read = pd.getReadMethod();
                Annotation[] annotations = read.getAnnotations();
                for (Annotation anno : annotations) {
                    Mapper mapper = mapOfMappers.get(anno.annotationType());
                    if (mapper != null) {
                        mapper.mapToBean(cal4jCalendar, bean, pd);
                    }
                }
            }
        }
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    } finally {
        IOUtils.closeQuietly(fin);
    }
}

From source file:com.nominanuda.hyperapi.HyperApiHttpInvocationHandler.java

private HttpUriRequest encode(String uriPrefix, Class<?> hyperApi2, Method method, Object[] args) {
    String httpMethod = null;//from w  ww .ja  v a 2s .  c o  m
    URISpec<DataObject> spec = null;
    DataObject uriParams = new DataObjectImpl();
    @SuppressWarnings("unused")
    String[] consumedMediaTypes = null;
    Annotation[] methodAnnotations = method.getAnnotations();
    HttpEntity entity = null;
    for (Annotation a : methodAnnotations) {
        if (a instanceof POST) {
            httpMethod = "POST";
        } else if (a instanceof GET) {
            httpMethod = "GET";
        } else if (a instanceof PUT) {
            httpMethod = "PUT";
        } else if (a instanceof DELETE) {
            httpMethod = "DELETE";
        } else if (a instanceof Path) {
            spec = new DataObjectURISpec(uriPrefix + ((Path) a).value());
        } else if (a instanceof Consumes) {
            consumedMediaTypes = (((Consumes) a).value());
        }
    }
    Annotation[][] parameterAnnotations = method.getParameterAnnotations();
    Class<?>[] parameterTypes = method.getParameterTypes();
    for (int i = 0; i < parameterTypes.length; i++) {
        Class<?> parameterType = parameterTypes[i];
        Annotation[] annotations = parameterAnnotations[i];
        Object arg = args[i];
        boolean annotationFound = false;
        for (Annotation annotation : annotations) {
            if (annotation instanceof PathParam) {
                annotationFound = true;
                if (arg != null) {
                    uriParams.put(((PathParam) annotation).value(), arg.toString());//TODO multivalue or complex transformations
                }
                break;
            } else if (annotation instanceof QueryParam) {
                annotationFound = true;
                if (arg != null) {
                    uriParams.put(((QueryParam) annotation).value(), arg.toString());//TODO multivalue or complex transformations
                }
                break;
            }
        }
        if (!annotationFound) {
            Check.unsupportedoperation.assertNull(entity);
            entity = getEntity(arg, parameterType, annotations);
        }
    }
    String uri = spec.template(uriParams);
    HttpUriRequest result = createRequest(uri, httpMethod);
    if (result instanceof HttpEntityEnclosingRequest && entity != null) {
        ((HttpEntityEnclosingRequest) result).setEntity(entity);
    }
    return result;
}