Example usage for java.lang.reflect Method getParameterAnnotations

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

Introduction

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

Prototype

@Override
public Annotation[][] getParameterAnnotations() 

Source Link

Usage

From source file:net.minder.config.impl.DefaultConfigurationInjector.java

private void injectMethodValue(Method method, Object target, ConfigurationAdapter adapter,
        ConfigurationBinding binding) throws ConfigurationException {
    Configure methodTag = method.getAnnotation(Configure.class);
    if (methodTag != null) {
        Alias aliasTag = method.getAnnotation(Alias.class);
        String methodName = getConfigName(method, aliasTag);
        Class[] argTypes = method.getParameterTypes();
        Object[] args = new Object[argTypes.length];
        Annotation[][] argTags = method.getParameterAnnotations();
        for (int i = 0; i < argTypes.length; i++) {
            String argName = getConfigName(methodName, argTags[i]);
            String bndName = getBindName(target, argName, binding);
            Object argValue = retrieveValue(target, bndName, argName, argTypes[i], adapter, binding);
            if (argValue == null) {
                Default defTag = findAnnotation(argTags[i], Default.class);
                if (defTag != null) {
                    String strValue = defTag.value();
                    argValue = convertValue(target, argName, strValue, argTypes[i]);
                } else {
                    throw new ConfigurationException(
                            String.format("Failed to find configuration for %s of %s via %s", bndName, argName,
                                    target.getClass().getName(), adapter.getClass().getName()));
                }//from  ww w . j  a v  a  2 s .c  o m
            }
            args[i] = argValue;
        }
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        try {
            method.invoke(target, args);
        } catch (Exception e) {
            throw new ConfigurationException(String.format("Failed to inject method configuration via %s of %s",
                    methodName, target.getClass().getName()), e);
        }
    }
}

From source file:org.apache.hadoop.gateway.config.impl.DefaultConfigurationInjector.java

private void injectMethodValue(Method method, Object target, ConfigurationAdapter adapter,
        ConfigurationBinding binding) throws ConfigurationException {
    Configure methodTag = method.getAnnotation(Configure.class);
    if (methodTag != null) {
        Alias aliasTag = method.getAnnotation(Alias.class);
        String methodName = getConfigName(method, aliasTag);
        Class[] argTypes = method.getParameterTypes();
        Object[] args = new Object[argTypes.length];
        Annotation[][] argTags = method.getParameterAnnotations();
        for (int i = 0; i < argTypes.length; i++) {
            String argName = getConfigName(methodName, argTags[i]);
            String bndName = getBindName(target, argName, binding);
            Object argValue = retrieveValue(target, bndName, argName, argTypes[i], adapter, binding);
            if (argValue == null) {
                Default defTag = findAnnotation(argTags[i], Default.class);
                if (defTag != null) {
                    String strValue = defTag.value();
                    argValue = convertValue(target, argName, strValue, argTypes[i]);
                } else {
                    throw new ConfigurationException(
                            String.format("Failed to find configuration for %s as %s of %s via %s", bndName,
                                    argName, target.getClass().getName(), adapter.getClass().getName()));
                }/*w  ww  . j a v  a 2s .  co  m*/
            }
            args[i] = argValue;
        }
        if (!method.isAccessible()) {
            method.setAccessible(true);
        }
        try {
            method.invoke(target, args);
        } catch (Exception e) {
            throw new ConfigurationException(String.format("Failed to inject method configuration via %s of %s",
                    methodName, target.getClass().getName()), e);
        }
    }
}

From source file:org.sybila.parasim.core.impl.ProvidingMethod.java

public ProvidingMethod(Method method, Object target) {
    Validate.notNull(method);/*from   ww  w  . j a va  2 s  .  c  o m*/
    Validate.notNull(target);
    this.provide = method.getAnnotation(Provide.class);
    Validate.notNull(provide,
            "Field without " + Provide.class.getName() + " annotation can't be providing point.");
    this.method = method;
    this.target = target;
    this.qualifier = ReflectionUtils.loadQualifier(method.getAnnotations());
    injectionPoints = new InjectionPoint[method.getGenericParameterTypes().length];
    for (int i = 0; i < method.getGenericParameterTypes().length; i++) {
        injectionPoints[i] = new GenericInjectionPoint(method.getParameterAnnotations()[i],
                method.getGenericParameterTypes()[i]);
    }
}

From source file:com.centurylink.mdw.hub.service.SwaggerReader.java

private void read(ReaderContext context) {
    final SwaggerDefinition swaggerDefinition = context.getCls().getAnnotation(SwaggerDefinition.class);
    if (swaggerDefinition != null) {
        readSwaggerConfig(swaggerDefinition);
    }/* w ww  . j a v a  2  s.c o m*/
    for (Method method : context.getCls().getMethods()) {
        if (ReflectionUtils.isOverriddenMethod(method, context.getCls())) {
            continue;
        }
        final Operation operation = new Operation();
        String operationPath = null;
        String httpMethod = null;

        final Type[] genericParameterTypes = method.getGenericParameterTypes();
        final Annotation[][] paramAnnotations = method.getParameterAnnotations();

        // Avoid java.util.ServiceLoader mechanism which finds ServletReaderExtension
        // for (ReaderExtension extension : ReaderExtensions.getExtensions()) {
        for (ReaderExtension extension : getExtensions()) {
            if (operationPath == null) {
                operationPath = extension.getPath(context, method);
            }
            if (httpMethod == null) {
                httpMethod = extension.getHttpMethod(context, method);
            }
            if (operationPath == null || httpMethod == null) {
                continue;
            }

            if (extension.isReadable(context)) {
                extension.setDeprecated(operation, method);
                extension.applyConsumes(context, operation, method);
                extension.applyProduces(context, operation, method);
                extension.applyOperationId(operation, method);
                extension.applySummary(operation, method);
                extension.applyDescription(operation, method);
                extension.applySchemes(context, operation, method);
                extension.applySecurityRequirements(context, operation, method);
                extension.applyTags(context, operation, method);
                extension.applyResponses(context, operation, method);
                extension.applyImplicitParameters(context, operation, method);
                for (int i = 0; i < genericParameterTypes.length; i++) {
                    extension.applyParameters(context, operation, genericParameterTypes[i],
                            paramAnnotations[i]);
                }
            }
        }

        if (httpMethod != null && operationPath != null) {
            if (operation.getResponses() == null) {
                operation.defaultResponse(new Response().description("OK"));
            } else {
                for (String k : operation.getResponses().keySet()) {
                    if (k.equals("200")) {
                        Response response = operation.getResponses().get(k);
                        if ("successful operation".equals(response.getDescription()))
                            response.setDescription("OK");
                    }
                }
            }

            final Map<String, String> regexMap = new HashMap<String, String>();
            final String parsedPath = PathUtils.parsePath(operationPath, regexMap);

            Path path = swagger.getPath(parsedPath);
            if (path == null) {
                path = new Path();
                swagger.path(parsedPath, path);
            }
            path.set(httpMethod.toLowerCase(), operation);
        }
    }
}

From source file:com.xeiam.xchange.rest.RestMethodMetadata.java

public RestMethodMetadata(Method method, Object[] args) {

    Consumes consumes = AnnotationUtils.getFromMethodOrClass(method, Consumes.class);
    this.contentType = consumes != null ? consumes.value()[0] : MediaType.APPLICATION_FORM_URLENCODED;

    paramsMap = new HashMap<Class<? extends Annotation>, Params>();
    for (Class<? extends Annotation> annotationClass : PARAM_ANNOTATION_CLASSES) {
        Params params = Params.of();/*from   w w w  .j ava  2 s. co  m*/
        params.setRestMethodMetadata(this);
        paramsMap.put(annotationClass, params);
    }

    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    for (int i = 0; i < paramAnnotations.length; i++) {
        Annotation[] paramAnns = paramAnnotations[i];
        if (paramAnns.length == 0) {
            unannanotatedParams.add(args[i]);
        }
        for (Annotation paramAnn : paramAnns) {
            String paramName = getParamName(paramAnn);
            if (paramName != null) {
                this.paramsMap.get(paramAnn.annotationType()).add(paramName, args[i]);
            }
        }
    }

    // Support using method method name as a parameter.
    for (Class<? extends Annotation> paramAnnotationClass : PARAM_ANNOTATION_CLASSES) {
        if (method.isAnnotationPresent(paramAnnotationClass)) {
            Annotation paramAnn = method.getAnnotation(paramAnnotationClass);
            String paramName = getParamName(paramAnn);
            this.paramsMap.get(paramAnnotationClass).add(paramName, method.getName());
        }
    }
}

From source file:com.justcloud.osgifier.servlet.OsgifierServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String path = buildUrl(req);/* w w w  .  java  2s. co  m*/
    Map<String, ?> params = new HashMap<String, Object>();

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

    try {
        params = deserializer.deserialize(req.getReader());
        if ("/login".equals(path)) {
            SessionService sessionService = (SessionService) findInstance(SessionServiceImpl.class);
            User user = sessionService.login((String) params.get("username"), (String) params.get("password"));
            resultMap.put("outcome", "success");
            req.getSession().setAttribute("user", user);
            if (user != null) {
                resultMap.put("result", serializer.deepSerialize(user));
            }
        } else if ("/logout".equals(path)) {
            req.getSession().removeAttribute("user");
            req.getSession().invalidate();
            resultMap.put("outcome", "success");
        } else {
            Method m = findRestMethod(RESTMethod.POST, path);
            @SuppressWarnings("unchecked")
            Service instance = findInstance((Class<? extends Service>) m.getDeclaringClass());
            Object args[] = new Object[m.getParameterTypes().length];

            int i = 0;

            for (Annotation[] annotations : m.getParameterAnnotations()) {
                RESTParam restAnnotation = null;

                for (Annotation a : annotations) {
                    if (a.annotationType() == RESTParam.class) {
                        restAnnotation = (RESTParam) a;
                        break;
                    }
                }
                if (restAnnotation == null) {
                    throw new RuntimeException("REST method has non REST annotated parameter");
                }
                Class<?> targetClass = m.getParameterTypes()[i];
                Object value;
                if (restAnnotation.session()) {
                    value = convert(req.getSession().getAttribute(restAnnotation.value()), targetClass);
                } else {
                    value = convert(params.get(restAnnotation.value()), targetClass);
                }
                if (value == null) {
                    throw new RuntimeException(
                            "Parameter " + restAnnotation.value() + " not found in request for " + path);
                }
                args[i++] = value;
            }

            Object result = m.invoke(instance, args);
            resultMap.put("outcome", "success");
            if (result != null) {
                resultMap.put("result", serializer.deepSerialize(result));
            }
        }

    } catch (Exception e) {
        Throwable t = e;
        if (e instanceof InvocationTargetException) {
            t = e.getCause();
        }
        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);

        t.printStackTrace(writer);

        resultMap.put("outcome", "error");
        resultMap.put("message", t.getMessage());
        resultMap.put("type", t.getClass().getCanonicalName());
        resultMap.put("stacktrace", stringWriter.getBuffer().toString());
    }

    resp.setContentType("application/json");
    resp.setCharacterEncoding("UTF-8");

    serializer.deepSerialize(resultMap, resp.getWriter());
}

From source file:com.msopentech.odatajclient.proxy.api.impl.AbstractInvocationHandler.java

protected Object functionImport(final Operation annotation, final Method method, final Object[] args,
        final URI target, final com.msopentech.odatajclient.engine.metadata.edm.v3.FunctionImport funcImp)
        throws InstantiationException, IllegalAccessException, NoSuchMethodException, IllegalArgumentException,
        InvocationTargetException {

    // 1. invoke params (if present)
    final Map<String, ODataValue> parameters = new HashMap<String, ODataValue>();
    if (!ArrayUtils.isEmpty(args)) {
        final Annotation[][] parAnnots = method.getParameterAnnotations();
        final Class<?>[] parTypes = method.getParameterTypes();

        for (int i = 0; i < args.length; i++) {
            if (!(parAnnots[i][0] instanceof Parameter)) {
                throw new IllegalArgumentException("Paramter " + i + " is not annotated as @Param");
            }//from w ww  .  j  a  v  a  2s  .  c o  m
            final Parameter parAnnot = (Parameter) parAnnots[i][0];

            if (!parAnnot.nullable() && args[i] == null) {
                throw new IllegalArgumentException(
                        "Parameter " + parAnnot.name() + " is not nullable but a null value was provided");
            }

            final ODataValue paramValue = args[i] == null ? null
                    : EngineUtils.getODataValue(client, containerHandler.getFactory().getMetadata(),
                            new EdmV3Type(containerHandler.getFactory().getMetadata(), parAnnot.type()),
                            args[i]);

            parameters.put(parAnnot.name(), paramValue);
        }
    }

    // 2. IMPORTANT: flush any pending change *before* invoke if this operation is side effecting
    if (annotation.isSideEffecting()) {
        new Container(client, containerHandler.getFactory()).flush();
    }

    // 3. invoke
    final ODataInvokeResult result = client.getInvokeRequestFactory()
            .getInvokeRequest(target, containerHandler.getFactory().getMetadata(), funcImp, parameters)
            .execute().getBody();

    // 3. process invoke result
    if (StringUtils.isBlank(annotation.returnType())) {
        return ClassUtils.returnVoid();
    }

    final EdmType edmType = new EdmV3Type(containerHandler.getFactory().getMetadata(), annotation.returnType());
    if (edmType.isEnumType()) {
        throw new UnsupportedOperationException("Usupported enum type " + edmType.getTypeExpression());
    }
    if (edmType.isSimpleType() || edmType.isComplexType()) {
        return EngineUtils.getValueFromProperty(containerHandler.getFactory().getMetadata(),
                (ODataProperty) result, method.getGenericReturnType());
    }
    if (edmType.isEntityType()) {
        if (edmType.isCollection()) {
            final ParameterizedType collType = (ParameterizedType) method.getReturnType()
                    .getGenericInterfaces()[0];
            final Class<?> collItemType = (Class<?>) collType.getActualTypeArguments()[0];
            return getEntityCollection(collItemType, method.getReturnType(), null, (ODataEntitySet) result,
                    target, false);
        } else {
            return getEntityProxy((ODataEntity) result, null, null, method.getReturnType(), false);
        }
    }

    throw new IllegalArgumentException("Could not process the functionImport information");
}

From source file:org.aludratest.testcase.data.impl.xml.XmlBasedTestDataProvider.java

private List<InternalSingleDataSource> getDataObjects(Method method, int paramIndex,
        Map<String, TestData> loadedFileModels) {
    Annotation[][] annots = method.getParameterAnnotations();
    String paramName = method.getName() + " param #" + paramIndex;
    Source src = getRequiredSourceAnnotation(annots[paramIndex], paramName);

    // try to load the referenced file, or reuse from cache
    String uri = src.uri();//from  w w w .ja  v  a  2  s .  c om
    if (uri == null || "".equals(uri)) {
        throw new AutomationException("@Source annotation does not specify required uri parameter");
    }
    if (src.segment() == null || "".equals(src.segment())) {
        throw new AutomationException("@Source annotation does not specify required segment parameter");
    }

    final TestData testData;
    if (loadedFileModels.containsKey(uri)) {
        testData = loadedFileModels.get(uri);
    } else {
        InputStream in = null;
        try {
            // real URI?
            in = tryFindXml(uri, method);
            testData = TestData.read(in);
            // some base validations
            if (testData.getMetadata() == null || testData.getMetadata().getSegments() == null
                    || testData.getConfigurations() == null) {
                throw new AutomationException(
                        "Test data XML " + uri + " has an invalid format or is incomplete.");
            }
            loadedFileModels.put(uri, testData);
        } catch (Exception e) {
            throw new AutomationException("Could not read test data XML at " + uri, e);
        } finally {
            IOUtils.closeQuietly(in);
        }
    }

    List<InternalSingleDataSource> dataElements = new ArrayList<InternalSingleDataSource>();

    // get metadata for requested segment
    TestDataSegmentMetadata segmentMeta = null;
    for (TestDataSegmentMetadata segment : testData.getMetadata().getSegments()) {
        if (segment.getName().equals(src.segment())) {
            segmentMeta = segment;
            break;
        }
    }
    if (segmentMeta == null) {
        throw new AutomationException("Could not find segment " + src.segment() + " in XML file " + uri);
    }

    final TestDataSegmentMetadata finalSegmentMeta = segmentMeta;

    // for each configuration entry, find values
    for (final TestDataConfiguration config : testData.getConfigurations()) {
        if (containsSegment(config, segmentMeta.getName())) {
            dataElements.add(new InternalSingleDataSource() {
                @Override
                public Data getObject() {
                    return buildObject(testData, config, finalSegmentMeta.getName());
                }
            });
        } else {
            dataElements.add(null);
        }
    }

    return dataElements;
}

From source file:org.tangram.components.MetaLinkHandler.java

private TargetDescriptor callAction(HttpServletRequest request, HttpServletResponse response, Matcher matcher,
        Method method, TargetDescriptor descriptor, Object target) throws Throwable, IllegalAccessException {
    TargetDescriptor result = null;//from w  w  w  . ja va 2 s.  c om
    LOG.debug("callAction() {} @ {}", method, target);

    if (method != null) {
        descriptor.action = null;
        List<Object> parameters = new ArrayList<>();
        Annotation[][] allAnnotations = method.getParameterAnnotations();
        Class<? extends Object>[] parameterTypes = method.getParameterTypes();
        for (int typeIndex = 0; typeIndex < parameterTypes.length; typeIndex++) {
            Annotation[] annotations = allAnnotations[typeIndex];
            Class<? extends Object> type = parameterTypes[typeIndex];
            if (type.equals(HttpServletRequest.class)) {
                parameters.add(request);
            } // if
            if (type.equals(HttpServletResponse.class)) {
                parameters.add(response);
            } // if
            Map<String, String[]> parameterMap = null;
            for (Annotation annotation : annotations) {
                if (annotation instanceof LinkPart) {
                    String valueString = matcher.group(((LinkPart) annotation).value());
                    LOG.debug("callAction() parameter #{}='{}' should be of type {}", typeIndex, valueString,
                            type.getName());
                    parameters.add(propertyConverter.getStorableObject(null, valueString, type, request));
                } // if
                if (annotation instanceof ActionParameter) {
                    String parameterName = ((ActionParameter) annotation).value();
                    if ("--empty--".equals(parameterName)) {
                        parameterName = type.getSimpleName().toLowerCase();
                    } // if
                    if (parameterMap == null) {
                        parameterMap = viewUtilities.createParameterAccess(request).getParameterMap();
                    } // if
                    LOG.debug("callAction() parameter {} should be of type {}", parameterName, type.getName());
                    Object value = propertyConverter.getStorableObject(null,
                            request.getParameter(parameterName), type, request);
                    parameters.add(value);
                } // if
                if (annotation instanceof ActionForm) {
                    try {
                        Object form = type.newInstance();
                        JavaBean wrapper = new JavaBean(form);
                        for (String propertyName : wrapper.propertyNames()) {
                            String valueString = request.getParameter(propertyName);
                            Object value = propertyConverter.getStorableObject(null, valueString,
                                    wrapper.getType(propertyName), request);
                            wrapper.set(propertyName, value);
                        } // for
                        parameters.add(form);
                    } catch (Exception e) {
                        LOG.error("callAction() cannot create and fill form " + type.getName());
                    } // try/catch
                } // if
            } // for
        } // for

        LOG.info("callAction() calling method {} with {} parameters", method.getName(), parameters.size());
        try {
            descriptor = (TargetDescriptor) method.invoke(target, parameters.toArray());
        } catch (InvocationTargetException ite) {
            throw ite.getTargetException();
        } // try/catch
        LOG.info("callAction() result is {}", descriptor);
        result = descriptor;
    } // if
    LOG.info("callAction() link={}", result);
    return result;
}

From source file:com.centurylink.mdw.service.api.SwaggerAnnotationsReader.java

private void read(ReaderContext context) {
    final SwaggerDefinition swaggerDefinition = context.getCls().getAnnotation(SwaggerDefinition.class);
    if (swaggerDefinition != null) {
        readSwaggerConfig(swaggerDefinition);
    }/* www  .  j  ava  2s  . c o  m*/
    for (Method method : context.getCls().getMethods()) {
        if (ReflectionUtils.isOverriddenMethod(method, context.getCls())) {
            continue;
        }
        final Operation operation = new Operation();
        String operationPath = null;
        String httpMethod = null;

        final Type[] genericParameterTypes = method.getGenericParameterTypes();
        final Annotation[][] paramAnnotations = method.getParameterAnnotations();

        // Avoid java.util.ServiceLoader mechanism which finds ServletReaderExtension
        // for (ReaderExtension extension : ReaderExtensions.getExtensions()) {
        for (ReaderExtension extension : getExtensions()) {
            if (operationPath == null) {
                operationPath = extension.getPath(context, method);
            }
            if (httpMethod == null) {
                httpMethod = extension.getHttpMethod(context, method);
            }
            if (operationPath == null || httpMethod == null) {
                continue;
            }

            if (extension.isReadable(context)) {
                extension.setDeprecated(operation, method);
                extension.applyConsumes(context, operation, method);
                extension.applyProduces(context, operation, method);
                extension.applyOperationId(operation, method);
                extension.applySummary(operation, method);
                extension.applyDescription(operation, method);
                extension.applySchemes(context, operation, method);
                extension.applySecurityRequirements(context, operation, method);
                extension.applyTags(context, operation, method);
                extension.applyResponses(context, operation, method);
                extension.applyImplicitParameters(context, operation, method);
                for (int i = 0; i < genericParameterTypes.length; i++) {
                    extension.applyParameters(context, operation, genericParameterTypes[i],
                            paramAnnotations[i]);
                }
            }
        }

        if (httpMethod != null && operationPath != null) {
            if (operation.getResponses() == null) {
                operation.defaultResponse(new Response().description("OK"));
            } else {
                for (String k : operation.getResponses().keySet()) {
                    if (k.equals("200")) {
                        Response response = operation.getResponses().get(k);
                        if ("successful operation".equals(response.getDescription()))
                            response.setDescription("OK");
                    }
                }
            }

            final Map<String, String> regexMap = new HashMap<String, String>();
            final String parsedPath = PathUtils.parsePath(operationPath, regexMap);

            if (parsedPath != null) {
                // check for curly path params
                for (String seg : parsedPath.split("/")) {
                    if (seg.startsWith("{") && seg.endsWith("}")) {
                        String segName = seg.substring(1, seg.length() - 1);
                        boolean declared = false;
                        for (Parameter opParam : operation.getParameters()) {
                            if ("path".equals(opParam.getIn()) && segName.equals(opParam.getName())) {
                                declared = true;
                                break;
                            }
                        }
                        if (!declared) {
                            // add it for free
                            PathParameter pathParam = new PathParameter();
                            pathParam.setName(segName);
                            pathParam.setRequired(false);
                            pathParam.setDefaultValue("");
                            operation.parameter(pathParam);
                        }
                    }
                }
            }

            Path path = swagger.getPath(parsedPath);
            if (path == null) {
                path = new Path();
                swagger.path(parsedPath, path);
            }
            path.set(httpMethod.toLowerCase(), operation);
        }
    }
}