Example usage for java.lang.reflect Parameter getType

List of usage examples for java.lang.reflect Parameter getType

Introduction

In this page you can find the example usage for java.lang.reflect Parameter getType.

Prototype

public Class<?> getType() 

Source Link

Document

Returns a Class object that identifies the declared type for the parameter represented by this Parameter object.

Usage

From source file:org.jspare.server.transaction.TransactionExecutorImpl.java

/**
 * Resolve parameter./*from w w  w  .j  av  a 2  s .c  o m*/
 *
 * @param parameter
 *            the parameter
 * @param request
 *            the request
 * @param response
 *            the response
 * @return the object
 */
private Object resolveParameter(Parameter parameter, Request request, Response response) {

    if (parameter.getType().equals(Request.class)) {

        return request;
    }
    if (parameter.getType().equals(Response.class)) {

        return response;
    }
    if (!StringUtils.isEmpty(request.getParameter(parameter.getName()))) {

        return request.getParameter(parameter.getName());
    }

    if (parameter.getType().getPackage().getName().endsWith(".model")
            || parameter.getType().isAnnotationPresent(Model.class)
            || parameter.isAnnotationPresent(Model.class)) {

        try {

            return my(Serializer.class).fromJSON(String.valueOf(request.getEntity().get()),
                    parameter.getType());
        } catch (SerializationException e) {

            log.warn("Invalid content of entity for class [{}] on parameter [{}]", parameter.getClass(),
                    parameter.getName());
            return null;
        }
    }
    if (parameter.isAnnotationPresent(org.jspare.server.mapping.Parameter.class)) {

        String parameterName = parameter.getAnnotation(org.jspare.server.mapping.Parameter.class).value();
        return request.getParameter(parameterName);
    }

    return null;
}

From source file:org.jspare.forvertx.web.handler.DefaultHandler.java

/**
 * Resolve parameter./*from   ww w.j  a v  a 2 s  .  c  om*/
 *
 * @param parameter
 *            the parameter
 * @param routingContext
 *            the routing context
 * @return the object
 */
@SuppressWarnings("unchecked")
protected Object resolveParameter(Parameter parameter, RoutingContext routingContext) {

    if (parameter.getType().equals(RoutingContext.class)) {

        return routingContext;
    }
    if (parameter.getType().equals(HttpServerRequest.class)) {

        return routingContext.request();
    }

    if (parameter.getType().equals(HttpServerResponse.class)) {

        return routingContext.response();
    }
    if (StringUtils.isNotEmpty(routingContext.request().getParam(parameter.getName()))) {

        return routingContext.request().getParam(parameter.getName());
    }

    if (parameter.isAnnotationPresent(ArrayModel.class)) {

        ArrayModel am = parameter.getAnnotation(ArrayModel.class);
        Class<? extends Collection<?>> collection = (Class<? extends Collection<?>>) am.collectionClass();
        Class<?> clazz = am.value();
        return ArrayModelParser.toList(routingContext.getBody().toString(), collection, clazz);
    }

    if (parameter.isAnnotationPresent(MapModel.class)) {

        MapModel mm = parameter.getAnnotation(MapModel.class);
        Class<?> mapClazz = mm.mapClass();
        Class<?> key = mm.key();
        Class<?> value = mm.value();
        return MapModelParser.toMap(routingContext.getBody().toString(), mapClazz, key, value);
    }

    if (parameter.getType().getPackage().getName().endsWith(".model")
            || parameter.getType().isAnnotationPresent(Model.class)
            || parameter.isAnnotationPresent(Model.class)) {

        try {
            if (routingContext.getBody() == null) {

                return null;
            }
            return my(Json.class).fromJSON(routingContext.getBody().toString(), parameter.getType());
        } catch (SerializationException e) {

            log.debug("Invalid content of body for class [{}] on parameter [{}]", parameter.getClass(),
                    parameter.getName());
            return null;
        }
    }
    if (parameter.isAnnotationPresent(org.jspare.forvertx.web.mapping.handling.Parameter.class)) {

        String parameterName = parameter.getAnnotation(org.jspare.forvertx.web.mapping.handling.Parameter.class)
                .value();
        // Test types
        Type typeOfParameter = parameter.getType();
        if (typeOfParameter.equals(Integer.class)) {
            return Integer.parseInt(routingContext.request().getParam(parameterName));
        }
        if (typeOfParameter.equals(Double.class)) {
            return Double.parseDouble(routingContext.request().getParam(parameterName));
        }
        if (typeOfParameter.equals(Long.class)) {
            return Long.parseLong(routingContext.request().getParam(parameterName));
        }
        return routingContext.request().getParam(parameterName);
    }
    if (parameter.isAnnotationPresent(org.jspare.forvertx.web.mapping.handling.Header.class)) {

        String headerName = parameter.getAnnotation(org.jspare.forvertx.web.mapping.handling.Header.class)
                .value();
        return routingContext.request().getHeader(headerName);
    }

    return null;
}

From source file:guru.qas.martini.jmeter.sampler.MartiniSampler.java

protected SampleResult getSubResult(Step step, Method method, Pattern pattern) {
    String label = getLabel(step);
    SampleResult result = new SampleResult();
    result.setSuccessful(true);//w  w  w.  j a v a  2s .  c om
    result.sampleStart();

    SamplerContext samplerContext = new SamplerContext(super.getThreadContext());

    try {
        ApplicationContext applicationContext = this.getApplicationContext();
        Parameter[] parameters = method.getParameters();
        Object[] arguments = new Object[parameters.length];

        if (parameters.length > 0) {
            String text = step.getText();
            Matcher matcher = pattern.matcher(text);
            checkState(matcher.find(), "unable to locate substitution parameters for pattern %s with input %s",
                    pattern.pattern(), text);

            ConversionService conversionService = applicationContext.getBean(ConversionService.class);

            int groupCount = matcher.groupCount();
            for (int i = 0; i < groupCount; i++) {
                String parameterAsString = matcher.group(i + 1);
                Parameter parameter = parameters[i];
                Class<?> parameterType = parameter.getType();
                Object converted = conversionService.convert(parameterAsString, parameterType);
                arguments[i] = converted;
            }
        }

        samplerContext.setStatus(Status.PASSED);
        Class<?> declaringClass = method.getDeclaringClass();
        Object bean = applicationContext.getBean(declaringClass);
        Object returnValue = method.invoke(bean, arguments);
        if (HttpEntity.class.isInstance(returnValue)) {
            HttpEntity entity = HttpEntity.class.cast(returnValue);
            samplerContext.setHttpEntities(Collections.singleton(entity));
        }
    } catch (Exception e) {
        samplerContext.setStatus(Status.FAILED);
        samplerContext.setException(e);
        result.setSuccessful(false);
        label = "FAIL: " + label;
    } finally {
        result.sampleEnd();
        result.setSampleLabel(label);
    }
    return result;
}

From source file:org.silverpeas.core.test.extention.SilverTestEnv.java

/**
 * Resolves the parameter referred by the parameter context by valuing it according to its
 * annotation: if annotated with {@link TestManagedBean}, the parameter will be instantiated with
 * its default constructor; if annotated with {@link TestManagedMock}, the parameter will be mocked.
 * @param parameterContext the context of the parameter.
 * @param extensionContext the context of the extension.
 * @return the value of the parameter to inject.
 *///from ww w.  j  a va 2  s  . co  m
@Override
public Object resolveParameter(final ParameterContext parameterContext,
        final ExtensionContext extensionContext) {
    Object bean;
    final Parameter parameter = parameterContext.getParameter();
    if (parameter.getType().equals(MavenTestEnv.class)) {
        bean = new MavenTestEnv(extensionContext.getRequiredTestInstance());
    } else if (parameterContext.isAnnotated(TestManagedMock.class)) {
        bean = TestBeanContainer.getMockedBeanContainer().getBeanByType(parameter.getType());
        if (bean == null) {
            bean = mock(parameter.getType());
            registerInBeanContainer(bean);
        }
    } else if (parameterContext.isAnnotated(TestManagedBean.class)) {
        bean = TestBeanContainer.getMockedBeanContainer().getBeanByType(parameter.getType());
        if (bean == null) {
            bean = instantiate(parameter.getType());
            manageBean(bean, parameter.getType());
        }
    } else {
        bean = null;
    }
    return bean;
}

From source file:org.structr.core.entity.SchemaMethod.java

private boolean getSignature(final Class type, final String methodName, final ActionEntry entry) {

    // superclass is AbstractNode
    for (final Method method : type.getMethods()) {

        if (methodName.equals(method.getName()) && (method.getModifiers() & Modifier.STATIC) == 0) {

            final Type[] parameterTypes = method.getGenericParameterTypes();
            final Type returnType = method.getGenericReturnType();
            final List<Type> types = new LinkedList<>();

            // compile list of types to check for generic type parameter
            types.addAll(Arrays.asList(parameterTypes));
            types.add(returnType);//  ww  w  .jav  a 2  s.  c o  m

            final String genericTypeParameter = getGenericMethodParameter(types, method);

            // check for generic return type, and if the method defines its own generic type
            if (returnType instanceof TypeVariable
                    && ((TypeVariable) returnType).getGenericDeclaration().equals(method)) {

                // method defines its own generic type
                entry.setReturnType(genericTypeParameter + returnType.getTypeName());

            } else {

                // non-generic return type
                final Class returnClass = method.getReturnType();
                if (returnClass.isArray()) {

                    entry.setReturnType(genericTypeParameter + returnClass.getComponentType().getName() + "[]");

                } else {

                    entry.setReturnType(genericTypeParameter + method.getReturnType().getName());
                }
            }

            for (final Parameter parameter : method.getParameters()) {

                String typeName = parameter.getParameterizedType().getTypeName();
                String name = parameter.getType().getSimpleName();

                if (typeName.contains("$")) {
                    typeName = typeName.replace("$", ".");
                }

                entry.addParameter(typeName, parameter.getName());
            }

            for (final Class exception : method.getExceptionTypes()) {
                entry.addException(exception.getName());
            }

            entry.setOverrides(getProperty(overridesExisting));
            entry.setCallSuper(getProperty(callSuper));

            // success
            return true;
        }
    }

    return false;
}

From source file:io.silverware.microservices.providers.cdi.internal.RestInterface.java

@SuppressWarnings("checkstyle:JavadocMethod")
public void callMethod(final RoutingContext routingContext) {
    final String microserviceName = routingContext.request().getParam("microservice");
    final String methodName = routingContext.request().getParam("method");
    final Bean bean = gatewayRegistry.get(microserviceName);

    routingContext.request().bodyHandler(buffer -> {
        final JsonObject mainJsonObject = new JsonObject(buffer.toString());

        try {// w  w w.  ja va  2 s  .  c  o  m
            final Class<?> beanClass = bean.getBeanClass();
            List<Method> methods = Arrays.asList(beanClass.getDeclaredMethods()).stream()
                    .filter(method -> method.getName().equals(methodName)
                            && method.getParameterCount() == mainJsonObject.size())
                    .collect(Collectors.toList());

            if (methods.size() == 0) {
                throw new IllegalStateException(
                        String.format("No such method %s with compatible parameters.", methodName));
            }

            if (methods.size() > 1) {
                throw new IllegalStateException("Overridden methods are not supported yet.");
            }

            final Method m = methods.get(0);

            final Parameter[] methodParams = m.getParameters();
            final Object[] paramValues = new Object[methodParams.length];
            final ConvertUtilsBean convert = new ConvertUtilsBean();
            for (int i = 0; i < methodParams.length; i++) {
                final Parameter methodParameter = methodParams[i];
                final String paramName = getParamName(methodParameter, m, beanClass);
                final Object jsonObject = mainJsonObject.getValue(paramName);
                paramValues[i] = convert.convert(jsonObject, methodParameter.getType());
            }

            @SuppressWarnings("unchecked")
            Set<Object> services = context.lookupLocalMicroservice(
                    new MicroserviceMetaData(microserviceName, beanClass, bean.getQualifiers()));
            JsonObject response = new JsonObject();
            try {
                Object result = m.invoke(services.iterator().next(), paramValues);
                response.put("result", Json.encodePrettily(result));
                response.put("resultPlain", JsonWriter.objectToJson(result));
            } catch (Exception e) {
                response.put("exception", e.toString());
                response.put("stackTrace", stackTraceAsString(e));
                log.warn("Could not call method: ", e);
            }

            routingContext.response().end(response.encodePrettily());
        } catch (Exception e) {
            log.warn(String.format("Unable to call method %s#%s: ", microserviceName, methodName), e);
            routingContext.response().setStatusCode(503).end("Resource not available.");
        }
    });
}

From source file:com.phoenixnap.oss.ramlapisync.parser.ResourceParser.java

/**
 * Extracts parameters from a method call and attaches these with the comments extracted from the javadoc
 * //from   w w w.  java 2  s . c o m
 * @param apiAction The Verb of the action containing these parametes
 * @param method The method to inspect
 * @param parameterComments The parameter comments associated with these parameters
 * @return A collection of parameters keyed by name
 */
protected Map<String, QueryParameter> extractQueryParameters(ActionType apiAction, Method method,
        Map<String, String> parameterComments) {
    // Since POST requests have a body we choose to keep all request data in one place as much as possible
    if (apiAction.equals(ActionType.POST) || method.getParameterCount() == 0) {
        return Collections.emptyMap();
    }
    Map<String, QueryParameter> queryParams = new LinkedHashMap<>();

    for (Parameter param : method.getParameters()) {
        if (isQueryParameter(param)) { // Lets skip resourceIds since these are going to be going in the URL
            ParamType simpleType = SchemaHelper.mapSimpleType(param.getType());

            if (simpleType == null) {
                queryParams.putAll(SchemaHelper.convertClassToQueryParameters(param,
                        javaDocs.getJavaDoc(param.getType())));
            } else {
                // Check if we have comments
                String paramComment = parameterComments.get(param.getName());
                queryParams.putAll(SchemaHelper.convertParameterToQueryParameter(param, paramComment));
            }
        }
    }
    return queryParams;
}

From source file:com.kelveden.rastajax.core.ResourceClassLoader.java

private List<Parameter> loadMethodParameters(Class<?> resourceClass, Method method) {

    final String logPrefix = " |-";

    final List<Parameter> parameters = new ArrayList<Parameter>();

    final Class<?>[] parameterTypes = method.getParameterTypes();

    for (int i = 0; i < parameterTypes.length; i++) {
        final Parameter parameter = loadMethodParameter(resourceClass, method, i);

        if (parameter != null) {
            LOGGER.debug("{} Found {} parameter '{}' of type '{}'.", logPrefix,
                    parameter.getJaxRsAnnotationType().getSimpleName(), parameter.getName(),
                    parameter.getType().getName());

            parameters.add(parameter);//from   w  ww . j  a  v  a 2  s.c o  m
        }
    }
    return parameters;
}

From source file:com.kelveden.rastajax.core.ResourceClassLoader.java

private List<Parameter> loadClassFields(final Class<?> resourceClass) {

    final String logPrefix = " |-";

    final List<Parameter> fields = new ArrayList<Parameter>();

    for (Field field : resourceClass.getFields()) {
        final Set<Annotation> annotations = JaxRsAnnotationScraper.scrapeJaxRsAnnotationsFrom(field);

        try {/*  w ww.  ja v a2s. co  m*/
            final Parameter parameter = buildParameterFromJaxRsAnnotations(annotations, field.getType());

            if (parameter != null) {
                LOGGER.debug("{} Found {} field '{}' of type '{}'.", logPrefix,
                        parameter.getJaxRsAnnotationType().getSimpleName(), parameter.getName(),
                        parameter.getType().getName());

                fields.add(parameter);
            }

        } catch (IllegalAccessException e) {
            throw new ResourceClassLoadingException(String.format("Could not load field '%s' on class '%s'",
                    field.getName(), resourceClass.getName()), e);

        } catch (InvocationTargetException e) {
            throw new ResourceClassLoadingException(String.format("Could not load field '%s' on class '%s'",
                    field.getName(), resourceClass.getName()), e);

        } catch (NoSuchMethodException e) {
            throw new ResourceClassLoadingException(String.format("Could not load field '%s' on class '%s'",
                    field.getName(), resourceClass.getName()), e);
        }
    }

    return fields;
}

From source file:com.kelveden.rastajax.core.ResourceClassLoader.java

private List<Parameter> loadClassProperties(final Class<?> resourceClass) {

    final String logPrefix = " |-";

    final List<Parameter> fields = new ArrayList<Parameter>();

    for (Method method : resourceClass.getDeclaredMethods()) {
        final Set<Annotation> annotations = JaxRsAnnotationScraper.scrapeJaxRsAnnotationsFrom(resourceClass,
                method);//www .j a v  a 2s  .  c o m

        try {
            final Parameter parameter = buildParameterFromJaxRsAnnotations(annotations, method.getReturnType());

            if (parameter != null) {
                LOGGER.debug("{} Found {} property '{}' of type '{}'.", logPrefix,
                        parameter.getJaxRsAnnotationType().getSimpleName(), parameter.getName(),
                        parameter.getType().getName());

                fields.add(parameter);
            } else {
                LOGGER.debug(
                        "{} Method {} was not annotated with any annotations that describe the JAX-RS parameter type and so will be ignored.",
                        logPrefix, method.getName());
            }

        } catch (IllegalAccessException e) {
            throw new ResourceClassLoadingException(String.format("Could not load property '%s' on class '%s'",
                    method.getName(), resourceClass.getName()), e);

        } catch (InvocationTargetException e) {
            throw new ResourceClassLoadingException(String.format("Could not load property '%s' on class '%s'",
                    method.getName(), resourceClass.getName()), e);

        } catch (NoSuchMethodException e) {
            throw new ResourceClassLoadingException(String.format("Could not load property'%s' on class '%s'",
                    method.getName(), resourceClass.getName()), e);
        }
    }

    return fields;
}