Example usage for java.lang.reflect Type getTypeName

List of usage examples for java.lang.reflect Type getTypeName

Introduction

In this page you can find the example usage for java.lang.reflect Type getTypeName.

Prototype

default String getTypeName() 

Source Link

Document

Returns a string describing this type, including information about any type parameters.

Usage

From source file:io.sinistral.proteus.server.tools.swagger.Reader.java

@SuppressWarnings("deprecation")
private Operation parseMethod(Class<?> cls, Method method, AnnotatedMethod annotatedMethod,
        List<Parameter> globalParameters, List<ApiResponse> classApiResponses, List<String> pathParamNames) {
    Operation operation = new Operation();
    if (annotatedMethod != null) {
        method = annotatedMethod.getAnnotated();
    }//from  w  ww .  j  ava  2 s. c o  m
    ApiOperation apiOperation = ReflectionUtils.getAnnotation(method, ApiOperation.class);
    ApiResponses responseAnnotation = ReflectionUtils.getAnnotation(method, ApiResponses.class);

    String operationId;
    // check if it's an inherited or implemented method.
    boolean methodInSuperType = false;
    if (!cls.isInterface()) {
        methodInSuperType = ReflectionUtils.findMethod(method, cls.getSuperclass()) != null;
    }
    if (!methodInSuperType) {
        for (Class<?> implementedInterface : cls.getInterfaces()) {
            methodInSuperType = ReflectionUtils.findMethod(method, implementedInterface) != null;
            if (methodInSuperType) {
                break;
            }
        }
    }
    if (!methodInSuperType) {
        operationId = method.getName();
    } else {
        operationId = this.getOperationId(method.getName());
    }

    String responseContainer = null;

    Type responseType = null;
    Map<String, Property> defaultResponseHeaders = new LinkedHashMap<String, Property>();

    if (apiOperation != null) {
        if (apiOperation.hidden()) {
            return null;
        }
        if (operationId == null) {
            operationId = apiOperation.nickname();
        }

        defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders());

        operation.summary(apiOperation.value()).description(apiOperation.notes());

        if (!isVoid(apiOperation.response())) {
            responseType = apiOperation.response();
        }
        if (!apiOperation.responseContainer().isEmpty()) {
            responseContainer = apiOperation.responseContainer();
        }
        List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>();
        for (Authorization auth : apiOperation.authorizations()) {
            if (!auth.value().isEmpty()) {
                SecurityRequirement security = new SecurityRequirement();
                security.setName(auth.value());
                for (AuthorizationScope scope : auth.scopes()) {
                    if (!scope.scope().isEmpty()) {
                        security.addScope(scope.scope());
                    }
                }
                securities.add(security);
            }
        }
        for (SecurityRequirement sec : securities) {
            operation.security(sec);
        }
        if (!apiOperation.consumes().isEmpty()) {
            String[] consumesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.consumes() });
            for (String consume : consumesAr) {
                operation.consumes(consume);
            }
        }
        if (!apiOperation.produces().isEmpty()) {
            String[] producesAr = ReaderUtils.splitContentValues(new String[] { apiOperation.produces() });
            for (String produce : producesAr) {
                operation.produces(produce);
            }
        }
    }

    /*
     * @TODO
     * Use apiOperation response class instead of unwrapping ServerResponse's inner type
     */

    if (apiOperation != null && StringUtils.isNotEmpty(apiOperation.responseReference())) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);
        response.schema(new RefProperty(apiOperation.responseReference()));
        operation.addResponse(String.valueOf(apiOperation.code()), response);
    } else if (responseType == null) {
        // pick out response from method declaration
        LOGGER.debug("picking up response class from method {}", method);
        responseType = method.getGenericReturnType();
    }

    if (responseType != null) {
        final JavaType javaType = TypeFactory.defaultInstance().constructType(responseType);
        if (!isVoid(javaType)) {

            final Class<?> responseCls = javaType.getRawClass();

            if (responseCls != null) {
                if (responseCls.isAssignableFrom(ServerResponse.class)) {
                    responseType = javaType.containedType(0);
                } else if (responseCls.isAssignableFrom(CompletableFuture.class)) {
                    Class<?> futureCls = javaType.containedType(0).getRawClass();

                    if (futureCls.isAssignableFrom(ServerResponse.class)) {
                        final JavaType futureType = TypeFactory.defaultInstance()
                                .constructType(javaType.containedType(0));
                        responseType = futureType.containedType(0);
                    } else {
                        responseType = javaType.containedType(0);
                    }
                }
            }
        }
    }

    if (isValidResponse(responseType)) {
        final Property property = ModelConverters.getInstance().readAsProperty(responseType);
        if (property != null) {
            final Property responseProperty = ContainerWrapper.wrapContainer(responseContainer, property);
            final int responseCode = (apiOperation == null) ? 200 : apiOperation.code();
            operation.response(responseCode, new Response().description(SUCCESSFUL_OPERATION)
                    .schema(responseProperty).headers(defaultResponseHeaders));
            appendModels(responseType);
        }
    }

    operation.operationId(operationId);

    if (operation.getConsumes() == null || operation.getConsumes().isEmpty()) {
        final Consumes consumes = ReflectionUtils.getAnnotation(method, Consumes.class);
        if (consumes != null) {
            for (String mediaType : ReaderUtils.splitContentValues(consumes.value())) {
                operation.consumes(mediaType);
            }
        }
    }

    if (operation.getProduces() == null || operation.getProduces().isEmpty()) {
        final Produces produces = ReflectionUtils.getAnnotation(method, Produces.class);
        if (produces != null) {
            for (String mediaType : ReaderUtils.splitContentValues(produces.value())) {
                operation.produces(mediaType);
            }
        }
    }

    List<ApiResponse> apiResponses = new ArrayList<>();
    if (responseAnnotation != null) {
        apiResponses.addAll(Arrays.asList(responseAnnotation.value()));
    }

    Class<?>[] exceptionTypes = method.getExceptionTypes();
    for (Class<?> exceptionType : exceptionTypes) {
        ApiResponses exceptionResponses = ReflectionUtils.getAnnotation(exceptionType, ApiResponses.class);
        if (exceptionResponses != null) {
            apiResponses.addAll(Arrays.asList(exceptionResponses.value()));
        }
    }

    for (ApiResponse apiResponse : apiResponses) {
        addResponse(operation, apiResponse);
    }
    // merge class level @ApiResponse
    for (ApiResponse apiResponse : classApiResponses) {
        String key = (apiResponse.code() == 0) ? "default" : String.valueOf(apiResponse.code());
        if (operation.getResponses() != null && operation.getResponses().containsKey(key)) {
            continue;
        }
        addResponse(operation, apiResponse);
    }

    if (ReflectionUtils.getAnnotation(method, Deprecated.class) != null) {
        operation.setDeprecated(true);
    }

    // process parameters
    for (Parameter globalParameter : globalParameters) {

        LOGGER.debug("globalParameters TYPE: " + globalParameter);

        operation.parameter(globalParameter);
    }

    Annotation[][] paramAnnotations = ReflectionUtils.getParameterAnnotations(method);
    java.lang.reflect.Parameter[] methodParameters = method.getParameters();

    if (annotatedMethod == null) {
        Type[] genericParameterTypes = method.getGenericParameterTypes();

        for (int i = 0; i < genericParameterTypes.length; i++) {

            Type type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);

            if (type.getTypeName().contains("Optional")
                    || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) {
                if (type instanceof com.fasterxml.jackson.databind.type.SimpleType) {
                    com.fasterxml.jackson.databind.type.SimpleType simpleType = (com.fasterxml.jackson.databind.type.SimpleType) type;

                    type = simpleType.containedType(0);
                }

            }

            if (type.equals(ServerRequest.class) || type.equals(HttpServerExchange.class)
                    || type.equals(HttpHandler.class)
                    || type.getTypeName().contains("io.sinistral.proteus.server.ServerResponse")) {
                continue;
            }

            List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]),
                    methodParameters[i], pathParamNames);

            for (Parameter parameter : parameters) {
                operation.parameter(parameter);
            }
        }
    } else {
        for (int i = 0; i < annotatedMethod.getParameterCount(); i++) {
            AnnotatedParameter param = annotatedMethod.getParameter(i);

            if (param.getParameterType().equals(ServerRequest.class)
                    || param.getParameterType().equals(HttpServerExchange.class)
                    || param.getParameterType().equals(HttpHandler.class)
                    || param.getParameterType().getTypeName().contains("ServerResponse")) {
                continue;
            }

            Type type = TypeFactory.defaultInstance().constructType(param.getParameterType(), cls);

            List<Parameter> parameters = getParameters(type, Arrays.asList(paramAnnotations[i]),
                    methodParameters[i], pathParamNames);

            for (Parameter parameter : parameters) {

                operation.parameter(parameter);
            }
        }
    }

    if (operation.getResponses() == null) {
        Response response = new Response().description(SUCCESSFUL_OPERATION);

        operation.response(200, response);
    }

    processOperationDecorator(operation, method);

    return operation;
}

From source file:org.wso2.msf4j.internal.router.HttpResourceModelProcessor.java

@SuppressWarnings("unchecked")
private Object getContextParamValue(HttpResourceModel.ParameterInfo<Object> paramInfo, Request request,
        Response responder) throws FormUploadException, IOException {
    Type paramType = paramInfo.getParameterType();
    Object value = null;//from   w  w  w.j  av a  2  s  .com
    if (((Class) paramType).isAssignableFrom(Request.class)) {
        value = request;
    } else if (((Class) paramType).isAssignableFrom(Response.class)) {
        value = responder;
    } else if (((Class) paramType).isAssignableFrom(HttpStreamer.class)) {
        if (httpStreamer == null) {
            httpStreamer = new HttpStreamer();
        }
        value = httpStreamer;
    } else if (((Class) paramType).isAssignableFrom(FormParamIterator.class)) {
        value = new FormParamIterator(request);
    } else if (((Class) paramType).isAssignableFrom(MultivaluedMap.class)) {
        MultivaluedMap<String, Object> listMultivaluedMap = new MultivaluedHashMap<>();
        if (MediaType.MULTIPART_FORM_DATA.equals(request.getContentType())) {
            listMultivaluedMap = extractRequestFormParams(request, paramInfo, false);
        } else if (MediaType.APPLICATION_FORM_URLENCODED.equals(request.getContentType())) {
            ByteBuffer fullContent = BufferUtil.merge(request.getFullMessageBody());
            String bodyStr = BeanConverter
                    .getConverter(
                            (request.getContentType() != null) ? request.getContentType() : MediaType.WILDCARD)
                    .convertToObject(fullContent, paramInfo.getParameterType()).toString();
            QueryStringDecoderUtil queryStringDecoderUtil = new QueryStringDecoderUtil(bodyStr, false);
            MultivaluedMap<String, Object> finalListMultivaluedMap = listMultivaluedMap;
            queryStringDecoderUtil.parameters().entrySet().forEach(
                    entry -> finalListMultivaluedMap.put(entry.getKey(), new ArrayList(entry.getValue())));
        }
        value = listMultivaluedMap;
    }
    Objects.requireNonNull(value, String.format("Could not resolve parameter %s", paramType.getTypeName()));
    return value;
}

From source file:io.sinistral.proteus.server.tools.swagger.Reader.java

private List<Parameter> getParameters(Type type, List<Annotation> annotations,
        java.lang.reflect.Parameter methodParameter, List<String> pathParamNames) {
    final Iterator<SwaggerExtension> chain = SwaggerExtensions.chain();

    if (!chain.hasNext()) {
        return Collections.emptyList();
    }//from  w  w w.ja  v a  2 s  . c o m

    //   LOGGER.debug("getParameters for {}", type);
    Set<Type> typesToSkip = new HashSet<>();
    typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerRequest.class));
    typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpServerExchange.class));
    typesToSkip.add(TypeFactory.defaultInstance().constructType(ServerResponse.class));
    typesToSkip.add(TypeFactory.defaultInstance().constructType(HttpHandler.class));
    typesToSkip.add(TypeFactory.defaultInstance().constructType(io.undertow.server.session.Session.class));

    final SwaggerExtension extension = chain.next();

    if (typesToSkip.contains(type)) {
        return Collections.emptyList();
    }

    annotations = new ArrayList<>(annotations);

    if (!annotations.stream().filter(a -> a instanceof ApiParam).findFirst().isPresent()) {
        annotations.add(AnnotationHelper.createApiParam(methodParameter));
    }

    if (type.getTypeName().contains("java.nio.file.Path") || type.getTypeName().contains("java.nio.ByteBuffer")
            || type.getTypeName().contains("java.io.File")) {
        if (type.getTypeName().contains("java.nio.file.Path")
                || type.getTypeName().contains("java.nio.ByteBuffer")) {
            type = java.io.File.class;
        }

        annotations.add(AnnotationHelper.createFormParam(methodParameter));

    }

    if (annotations.size() == 1) {
        if (annotations.get(0) instanceof ApiParam) {
            // If there is only one ApiParam and the parameter type is a member of the java.lang and the name of that parameter is in the path operation's path make the assumption that this is a path param
            if (methodParameter.getType().getName().indexOf("java.lang") > -1
                    && pathParamNames.contains(methodParameter.getName())) {
                annotations.add(AnnotationHelper.createPathParam(methodParameter));

            }
            // If there is only one ApiParam and the parameter type is a member of the java.lang or java.util package we make the assumption that this is a query param
            else if (methodParameter.getType().getName().indexOf("java.lang") > -1
                    || methodParameter.getType().getName().indexOf("java.util") > -1) {
                annotations.add(AnnotationHelper.createQueryParam(methodParameter));
            }
        }
    }

    final List<Parameter> parameters = extension.extractParameters(annotations, type, typesToSkip, chain);
    if (!parameters.isEmpty()) {
        final List<Parameter> processed = new ArrayList<Parameter>(parameters.size());
        for (Parameter parameter : parameters) {

            //  LOGGER.debug("getParameters for {}", type);

            if (ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations) != null) {

                processed.add(parameter);
            }
        }
        return processed;
    } else {
        //  LOGGER.debug("no parameter found, looking at body params");
        final List<Parameter> body = new ArrayList<Parameter>();
        if (!typesToSkip.contains(type)) {

            Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations);
            if (param != null) {

                body.add(param);
            }
        }
        return body;
    }
}

From source file:org.evosuite.testcase.TestFactory.java

private List<VariableReference> getCandidatesForReuse(TestCase test, Type parameterType, int position,
        VariableReference exclude, boolean allowNull, boolean canUseMocks) {

    //look at all vars defined before pos
    List<VariableReference> objects = test.getObjects(parameterType, position);

    //if an exclude var was specified, then remove it
    if (exclude != null) {
        objects.remove(exclude);/*from w  w  w.  ja  va 2s .co  m*/
        if (exclude.getAdditionalVariableReference() != null)
            objects.remove(exclude.getAdditionalVariableReference());

        Iterator<VariableReference> it = objects.iterator();
        while (it.hasNext()) {
            VariableReference v = it.next();
            if (exclude.equals(v.getAdditionalVariableReference()))
                it.remove();
        }
    }

    List<VariableReference> additionalToRemove = new ArrayList<>();

    //no mock should be used more than once
    Iterator<VariableReference> iter = objects.iterator();
    while (iter.hasNext()) {
        VariableReference ref = iter.next();
        if (!(test.getStatement(ref.getStPosition()) instanceof FunctionalMockStatement)) {
            continue;
        }

        //check if current mock var is used anywhere: if so, then we cannot choose it
        for (int i = ref.getStPosition() + 1; i < test.size(); i++) {
            Statement st = test.getStatement(i);
            if (st.getVariableReferences().contains(ref)) {
                iter.remove();
                additionalToRemove.add(ref);
                break;
            }
        }
    }

    //check for null
    if (!allowNull) {
        iter = objects.iterator();
        while (iter.hasNext()) {
            VariableReference ref = iter.next();

            if (ConstraintHelper.isNull(ref, test)) {
                iter.remove();
                additionalToRemove.add(ref);
            }
        }
    }

    //check for mocks
    if (!canUseMocks) {
        iter = objects.iterator();
        while (iter.hasNext()) {
            VariableReference ref = iter.next();

            if (test.getStatement(ref.getStPosition()) instanceof FunctionalMockStatement) {
                iter.remove();
                additionalToRemove.add(ref);
            }
        }
    }

    //check for bounded variables
    if (Properties.JEE) {
        iter = objects.iterator();
        while (iter.hasNext()) {
            VariableReference ref = iter.next();

            if (ConstraintHelper.getLastPositionOfBounded(ref, test) >= position) {
                iter.remove();
                additionalToRemove.add(ref);
            }
        }
    }

    //further remove all other vars that have the deleted ones as additionals
    iter = objects.iterator();
    while (iter.hasNext()) {
        VariableReference ref = iter.next();
        VariableReference additional = ref.getAdditionalVariableReference();
        if (additional == null) {
            continue;
        }
        if (additionalToRemove.contains(additional)) {
            iter.remove();
        }
    }

    //avoid using characters as values for numeric types arguments
    iter = objects.iterator();
    String parCls = parameterType.getTypeName();
    if (Integer.TYPE.getTypeName().equals(parCls) || Long.TYPE.getTypeName().equals(parCls)
            || Float.TYPE.getTypeName().equals(parCls) || Double.TYPE.getTypeName().equals(parCls)) {
        while (iter.hasNext()) {
            VariableReference ref = iter.next();
            String cls = ref.getType().getTypeName();
            if ((Character.TYPE.getTypeName().equals(cls)))
                iter.remove();
        }
    }

    return objects;
}