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.finra.herd.swaggergen.RestControllerProcessor.java

/**
 * Processes a Spring MVC REST controller class that is annotated with RestController. Also collects any required model objects based on parameters and
 * return types of each endpoint into the specified model classes set.
 *
 * @param clazz the class to process/*  w  w w. j  av a  2  s  . c  om*/
 *
 * @throws MojoExecutionException if any errors were encountered.
 */
private void processRestControllerClass(Class<?> clazz) throws MojoExecutionException {
    // Get the Java class source information.
    JavaClassSource javaClassSource = sourceMap.get(clazz.getSimpleName());
    if (javaClassSource == null) {
        throw new MojoExecutionException("No source resource found for class \"" + clazz.getName() + "\".");
    }

    Api api = clazz.getAnnotation(Api.class);
    boolean hidden = api != null && api.hidden();

    if ((clazz.getAnnotation(RestController.class) != null) && (!hidden)) {
        log.debug("Processing RestController class \"" + clazz.getName() + "\".");

        // Default the tag name to the simple class name.
        String tagName = clazz.getSimpleName();

        // See if the "Api" annotation exists.
        if (api != null && api.tags().length > 0) {
            // The "Api" annotation was found so use it's configured tag.
            tagName = api.tags()[0];
        } else {
            // No "Api" annotation so try to get the tag name from the class name. If not, we will stick with the default simple class name.
            Matcher matcher = tagPattern.matcher(clazz.getSimpleName());
            if (matcher.find()) {
                // If our class has the form
                tagName = matcher.group("tag");
            }
        }
        log.debug("Using tag name \"" + tagName + "\".");

        // Add the tag and process each method.
        swagger.addTag(new Tag().name(tagName));

        List<Method> methods = Lists.newArrayList(clazz.getDeclaredMethods());
        // Based on the Java 8 doc, getDeclaredMethods() is not guaranteed sorted
        // In order to be sure we generate stable API when the URL's don't change
        // we can give it a sort order based on the first URI hit in the request mapping
        List<Method> outMethods = methods.stream().filter((method) -> {
            RequestMapping rm = method.getAnnotation(RequestMapping.class);
            ApiOperation apiOp = method.getAnnotation(ApiOperation.class);
            return rm != null && // Has RequestMapping
            rm.value().length > 0 && // has at least 1 URI
            rm.method().length > 0 && // has at least 1 HttpMethod
            (apiOp == null || !apiOp.hidden()); // marked as a hidden ApiOperation
        }).sorted(Comparator.comparing(a -> ((Method) a).getAnnotation(RequestMapping.class).value()[0])
                .thenComparing(a -> ((Method) a).getAnnotation(RequestMapping.class).method()[0]))
                .collect(Collectors.toList());

        for (Method method : outMethods) {
            // Get the method source information.
            List<Class<?>> methodParamClasses = new ArrayList<>();
            for (Parameter parameter : method.getParameters()) {
                methodParamClasses.add(parameter.getType());
            }
            MethodSource<JavaClassSource> methodSource = javaClassSource.getMethod(method.getName(),
                    methodParamClasses.toArray(new Class<?>[methodParamClasses.size()]));
            if (methodSource == null) {
                throw new MojoExecutionException("No method source found for class \"" + clazz.getName()
                        + "\" and method name \"" + method.getName() + "\".");
            }

            // Process the REST controller method along with its source information.
            processRestControllerMethod(method, clazz.getAnnotation(RequestMapping.class), tagName,
                    methodSource);
        }
    } else {
        log.debug("Skipping class \"" + clazz.getName()
                + "\" because it is either not a RestController or it is hidden.");
    }
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static void mapConsumedObjects(APIMethodModel methodModel, Parameter parameters[]) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    for (Parameter parameter : parameters) {
        //deterimine if this is "Body" object
        List<Annotation> paramAnnotation = new ArrayList<>();
        paramAnnotation.add(parameter.getAnnotation(QueryParam.class));
        paramAnnotation.add(parameter.getAnnotation(FormParam.class));
        paramAnnotation.add(parameter.getAnnotation(MatrixParam.class));
        paramAnnotation.add(parameter.getAnnotation(HeaderParam.class));
        paramAnnotation.add(parameter.getAnnotation(CookieParam.class));
        paramAnnotation.add(parameter.getAnnotation(PathParam.class));
        paramAnnotation.add(parameter.getAnnotation(BeanParam.class));

        boolean consumeObject = true;
        for (Annotation annotation : paramAnnotation) {
            if (annotation != null) {
                consumeObject = false;//w ww. ja va 2  s . c o  m
                break;
            }
        }

        if (consumeObject) {
            APIValueModel valueModel = new APIValueModel();
            try {
                valueModel.setValueObjectName(parameter.getType().getSimpleName());

                DataType dataType = (DataType) parameter.getAnnotation(DataType.class);
                if (dataType != null) {
                    String typeName = dataType.value().getSimpleName();
                    if (StringUtils.isNotBlank(dataType.actualClassName())) {
                        typeName = dataType.actualClassName();
                    }
                    valueModel.setTypeObjectName(typeName);

                    try {
                        valueModel
                                .setTypeObject(objectMapper.writeValueAsString(dataType.value().newInstance()));
                        Set<String> fieldList = mapValueField(valueModel.getTypeFields(),
                                ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true);
                        String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getTypeObject(),
                                fieldList);
                        valueModel.setTypeObject(cleanUpJson);
                        mapComplexTypes(valueModel.getAllComplexTypes(),
                                ReflectionUtil.getAllFields(dataType.value()).toArray(new Field[0]), true);

                        APIDescription aPIDescription = (APIDescription) dataType.value()
                                .getAnnotation(APIDescription.class);
                        if (aPIDescription != null) {
                            valueModel.setTypeDescription(aPIDescription.value());
                        }

                    } catch (InstantiationException iex) {
                        log.log(Level.WARNING,
                                MessageFormat.format(
                                        "Unable to instantiated type: {0} make sure the type is not abstract.",
                                        parameter.getType()));
                    }
                } else {
                    try {
                        valueModel.setValueObject(
                                objectMapper.writeValueAsString(parameter.getType().newInstance()));
                        Set<String> fieldList = mapValueField(valueModel.getValueFields(),
                                ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true);
                        String cleanUpJson = StringProcessor.stripeFieldJSON(valueModel.getValueObject(),
                                fieldList);
                        valueModel.setValueObject(cleanUpJson);
                        mapComplexTypes(valueModel.getAllComplexTypes(),
                                ReflectionUtil.getAllFields(parameter.getType()).toArray(new Field[0]), true);

                        APIDescription aPIDescription = (APIDescription) parameter.getType()
                                .getAnnotation(APIDescription.class);
                        if (aPIDescription != null) {
                            valueModel.setTypeDescription(aPIDescription.value());
                        }

                    } catch (InstantiationException iex) {
                        log.log(Level.WARNING,
                                MessageFormat.format(
                                        "Unable to instantiated type: {0} make sure the type is not abstract.",
                                        parameter.getType()));
                    }
                }
            } catch (IllegalAccessException | JsonProcessingException ex) {
                log.log(Level.WARNING, null, ex);
            }

            //There can only be one consume(Request Body Parameter) object
            //We take the first one and ignore the rest.
            methodModel.setConsumeObject(valueModel);
            break;
        }
    }
}

From source file:nl.kpmg.lcm.server.documentation.MethodDocumentator.java

private String addParameters(Method method, String description) {
    String parameters = "";
    int counter = 1;
    for (Parameter param : method.getParameters()) {
        String parameterString = StringUtils.replace(parameterTemplate, "{NUMBER}", Integer.toString(counter));
        String annotationString = "";
        for (Annotation annotation : param.getAnnotations()) {
            annotationString += annotation.annotationType().getSimpleName();
        }//w w w .  j  a v a2  s.  c  om

        if (annotationString.length() > 0) {
            annotationString = annotationString + ", ";
            parameterString = StringUtils.replace(parameterString, "{ANNOTATION}", annotationString);
        } else {
            parameterString = StringUtils.replace(parameterString, "{ANNOTATION}", "Payload, ");
        }

        parameterString = StringUtils.replace(parameterString, "{TYPE}",
                "type: " + param.getType().getSimpleName());
        parameters += parameterString;
        counter++;
    }
    if (parameters.length() > 0) {
        parameters = "<br> " + parameters;
    } else {
        parameters = "none.";
    }
    description = StringUtils.replace(description, "{PARAMETERS}", parameters);
    return description;
}

From source file:com.phoenixnap.oss.ramlapisync.data.ApiParameterMetadata.java

/**
 * Default constructor that creates a metadata object from a Java parameter
 * /*from  w ww.ja  va  2s.  co m*/
 * @param param Java Parameter representation
 */
public ApiParameterMetadata(Parameter param) {
    super();
    this.resourceId = false;
    this.nullable = false;

    String annotatedName = null;
    if (param == null) {
        throw new NullArgumentException("param");
    }

    RequestParam requestParam = param.getAnnotation(RequestParam.class);
    if (requestParam != null) {
        annotatedName = requestParam.value();
        nullable = !requestParam.required();
    }

    PathVariable pathVariable = param.getAnnotation(PathVariable.class);
    if (pathVariable != null) {
        resourceId = true;
        annotatedName = pathVariable.value();
    }

    RequestBody requestBody = param.getAnnotation(RequestBody.class);
    if (requestBody != null) {
        nullable = !requestBody.required();

    }

    this.name = resolveParameterName(annotatedName, param);
    this.param = param;
    if (param != null) {
        this.type = param.getType();
        this.genericType = (Class<?>) TypeHelper.inferGenericType(param.getParameterizedType());
    }

    Example parameterExample = param.getAnnotation(Example.class);
    if (parameterExample != null && StringUtils.hasText(parameterExample.value())) {
        this.example = parameterExample.value();
    }
}

From source file:edu.usu.sdl.openstorefront.doc.JaxrsProcessor.java

private static void mapMethodParameters(List<APIParamModel> parameterList, Parameter parameters[]) {
    for (Parameter parameter : parameters) {
        APIParamModel paramModel = new APIParamModel();
        paramModel.setFieldName(parameter.getName());

        QueryParam queryParam = (QueryParam) parameter.getAnnotation(QueryParam.class);
        FormParam formParam = (FormParam) parameter.getAnnotation(FormParam.class);
        MatrixParam matrixParam = (MatrixParam) parameter.getAnnotation(MatrixParam.class);
        HeaderParam headerParam = (HeaderParam) parameter.getAnnotation(HeaderParam.class);
        CookieParam cookieParam = (CookieParam) parameter.getAnnotation(CookieParam.class);
        PathParam pathParam = (PathParam) parameter.getAnnotation(PathParam.class);
        BeanParam beanParam = (BeanParam) parameter.getAnnotation(BeanParam.class);

        if (queryParam != null) {
            paramModel.setParameterType(QueryParam.class.getSimpleName());
            paramModel.setParameterName(queryParam.value());
        }/*from  w  w w . j  a va2  s.c o m*/
        if (formParam != null) {
            paramModel.setParameterType(FormParam.class.getSimpleName());
            paramModel.setParameterName(formParam.value());
        }
        if (matrixParam != null) {
            paramModel.setParameterType(MatrixParam.class.getSimpleName());
            paramModel.setParameterName(matrixParam.value());
        }
        if (pathParam != null) {
            paramModel.setParameterType(PathParam.class.getSimpleName());
            paramModel.setParameterName(pathParam.value());
        }
        if (headerParam != null) {
            paramModel.setParameterType(HeaderParam.class.getSimpleName());
            paramModel.setParameterName(headerParam.value());
        }
        if (cookieParam != null) {
            paramModel.setParameterType(CookieParam.class.getSimpleName());
            paramModel.setParameterName(cookieParam.value());
        }

        if (beanParam != null) {
            Class paramClass = parameter.getType();
            mapParameters(parameterList, ReflectionUtil.getAllFields(paramClass).toArray(new Field[0]));
        }
        if (StringUtils.isNotBlank(paramModel.getParameterType())) {
            APIDescription aPIDescription = (APIDescription) parameter.getAnnotation(APIDescription.class);
            if (aPIDescription != null) {
                paramModel.setParameterDescription(aPIDescription.value());
            }

            ParameterRestrictions restrictions = (ParameterRestrictions) parameter
                    .getAnnotation(ParameterRestrictions.class);
            if (restrictions != null) {
                paramModel.setRestrictions(restrictions.value());
            }

            RequiredParam requiredParam = (RequiredParam) parameter.getAnnotation(RequiredParam.class);
            if (requiredParam != null) {
                paramModel.setRequired(true);
            }

            DefaultValue defaultValue = (DefaultValue) parameter.getAnnotation(DefaultValue.class);
            if (defaultValue != null) {
                paramModel.setDefaultValue(defaultValue.value());
            }

            parameterList.add(paramModel);
        }
    }
}

From source file:io.stallion.restfulEndpoints.ResourceToEndpoints.java

public List<JavaRestEndpoint> convert(EndpointResource resource) {
    Class cls = resource.getClass();
    List<JavaRestEndpoint> endpoints = new ArrayList<>();

    // Get defaults from the resource

    Role defaultMinRole = Settings.instance().getUsers().getDefaultEndpointRoleObj();
    MinRole minRoleAnno = (MinRole) cls.getAnnotation(MinRole.class);
    if (minRoleAnno != null) {
        defaultMinRole = minRoleAnno.value();
    }// www.j  a  v a 2 s.c om

    String defaultProduces = "text/html";
    Produces producesAnno = (Produces) cls.getAnnotation(Produces.class);
    if (producesAnno != null && producesAnno.value().length > 0) {
        defaultProduces = producesAnno.value()[0];
    }

    Path pathAnno = (Path) cls.getAnnotation(Path.class);
    if (pathAnno != null) {
        basePath += pathAnno.value();
    }

    Class defaultJsonViewClass = null;
    DefaultJsonView jsonView = (DefaultJsonView) cls.getAnnotation(DefaultJsonView.class);
    if (jsonView != null) {
        defaultJsonViewClass = jsonView.value();
    }

    for (Method method : cls.getDeclaredMethods()) {
        JavaRestEndpoint endpoint = new JavaRestEndpoint();
        endpoint.setRole(defaultMinRole);
        endpoint.setProduces(defaultProduces);
        if (defaultJsonViewClass != null) {
            endpoint.setJsonViewClass(defaultJsonViewClass);
        }

        Log.finer("Resource class method: {0}", method.getName());
        for (Annotation anno : method.getDeclaredAnnotations()) {
            if (Path.class.isInstance(anno)) {
                Path pth = (Path) anno;
                endpoint.setRoute(getBasePath() + pth.value());
            } else if (GET.class.isInstance(anno)) {
                endpoint.setMethod("GET");
            } else if (POST.class.isInstance(anno)) {
                endpoint.setMethod("POST");
            } else if (DELETE.class.isInstance(anno)) {
                endpoint.setMethod("DELETE");
            } else if (PUT.class.isInstance(anno)) {
                endpoint.setMethod("PUT");
            } else if (Produces.class.isInstance(anno)) {
                endpoint.setProduces(((Produces) anno).value()[0]);
            } else if (MinRole.class.isInstance(anno)) {
                endpoint.setRole(((MinRole) anno).value());
            } else if (XSRF.class.isInstance(anno)) {
                endpoint.setCheckXSRF(((XSRF) anno).value());
            } else if (JsonView.class.isInstance(anno)) {
                Class[] classes = ((JsonView) anno).value();
                if (classes == null || classes.length != 1) {
                    throw new UsageException("JsonView annotation for method " + method.getName()
                            + " must have exactly one view class");
                }
                endpoint.setJsonViewClass(classes[0]);
            }
        }
        if (!empty(endpoint.getMethod()) && !empty(endpoint.getRoute())) {
            endpoint.setJavaMethod(method);
            endpoint.setResource(resource);
            endpoints.add(endpoint);
            Log.fine("Register endpoint {0} {1}", endpoint.getMethod(), endpoint.getRoute());
        } else {
            continue;
        }
        int x = -1;
        for (Parameter param : method.getParameters()) {
            x++;
            RequestArg arg = new RequestArg();
            for (Annotation anno : param.getAnnotations()) {
                arg.setAnnotationInstance(anno);
                Log.finer("Param Annotation is: {0}, {1}", anno, anno.getClass().getName());
                if (BodyParam.class.isInstance(anno)) {
                    BodyParam bodyAnno = (BodyParam) (anno);
                    arg.setType("BodyParam");
                    if (empty(bodyAnno.value())) {
                        arg.setName(param.getName());
                    } else {
                        arg.setName(((BodyParam) anno).value());
                    }
                    arg.setAnnotationClass(BodyParam.class);
                    arg.setRequired(bodyAnno.required());
                    arg.setEmailParam(bodyAnno.isEmail());
                    arg.setMinLength(bodyAnno.minLength());
                    arg.setAllowEmpty(bodyAnno.allowEmpty());
                    if (!empty(bodyAnno.validationPattern())) {
                        arg.setValidationPattern(Pattern.compile(bodyAnno.validationPattern()));
                    }
                } else if (ObjectParam.class.isInstance(anno)) {
                    ObjectParam oParam = (ObjectParam) anno;
                    arg.setType("ObjectParam");
                    arg.setName("noop");
                    if (oParam.targetClass() == null || oParam.targetClass().equals(Object.class)) {
                        arg.setTargetClass(param.getType());
                    } else {
                        arg.setTargetClass(oParam.targetClass());
                    }
                    arg.setAnnotationClass(ObjectParam.class);
                } else if (MapParam.class.isInstance(anno)) {
                    arg.setType("MapParam");
                    arg.setName("noop");
                    arg.setAnnotationClass(MapParam.class);
                } else if (QueryParam.class.isInstance(anno)) {
                    arg.setType("QueryParam");
                    arg.setName(((QueryParam) anno).value());
                    arg.setAnnotationClass(QueryParam.class);
                } else if (PathParam.class.isInstance(anno)) {
                    arg.setType("PathParam");
                    arg.setName(((PathParam) anno).value());
                    arg.setAnnotationClass(PathParam.class);
                } else if (DefaultValue.class.isInstance(anno)) {
                    arg.setDefaultValue(((DefaultValue) anno).value());
                } else if (NotNull.class.isInstance(anno)) {
                    arg.setRequired(true);
                } else if (Nullable.class.isInstance(anno)) {
                    arg.setRequired(false);
                } else if (NotEmpty.class.isInstance(anno)) {
                    arg.setRequired(true);
                    arg.setAllowEmpty(false);
                } else if (Email.class.isInstance(anno)) {
                    arg.setEmailParam(true);
                }
            }
            if (StringUtils.isEmpty(arg.getType())) {
                arg.setType("ObjectParam");
                arg.setName(param.getName());
                arg.setTargetClass(param.getType());
                arg.setAnnotationClass(ObjectParam.class);
            }

            if (StringUtils.isEmpty(arg.getName())) {
                arg.setName(param.getName());
            }
            endpoint.getArgs().add(arg);
        }
    }
    return endpoints;
}