Search in sources :

Example 6 with RequestHeader

use of org.springframework.web.bind.annotation.RequestHeader in project spring-framework by spring-projects.

the class RequestHeaderMethodArgumentResolver method createNamedValueInfo.

@Override
protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) {
    RequestHeader ann = parameter.getParameterAnnotation(RequestHeader.class);
    Assert.state(ann != null, "No RequestHeader annotation");
    return new RequestHeaderNamedValueInfo(ann);
}
Also used : RequestHeader(org.springframework.web.bind.annotation.RequestHeader)

Example 7 with RequestHeader

use of org.springframework.web.bind.annotation.RequestHeader in project judge by zjnu-acm.

the class MockGenerator method generate.

private void generate(Class<?> key, RequestMappingInfo requestMappingInfo, HandlerMethod handlerMethod, String url, TestClass testClass, String lowerMethod) {
    Method method = handlerMethod.getMethod();
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    out.println("/**");
    out.println(" * Test of " + method.getName() + " method, of class " + key.getSimpleName() + ".");
    for (Class<?> type : method.getParameterTypes()) {
        testClass.addImport(type);
    }
    out.println(" *");
    out.println(" * {@link " + key.getSimpleName() + "#" + method.getName() + Arrays.stream(method.getParameterTypes()).map(Class::getSimpleName).collect(Collectors.joining(", ", "(", ")}")));
    out.println(" */");
    testClass.addImport(Test.class);
    out.println("@Test");
    out.println("public void test" + StringUtils.capitalize(method.getName()) + "() throws Exception {");
    out.println("\tlog.info(\"" + method.getName() + "\");");
    List<String> variableDeclares = new ArrayList<>(4);
    Map<String, Class<?>> params = new LinkedHashMap<>(4);
    String body = null;
    Class<?> bodyType = null;
    MethodParameter[] methodParameters = handlerMethod.getMethodParameters();
    Parameter[] parameters = method.getParameters();
    List<String> files = new ArrayList<>(4);
    List<String> pathVariables = new ArrayList<>(4);
    Map<String, String> headers = Maps.newTreeMap();
    String locale = null;
    for (MethodParameter methodParameter : methodParameters) {
        Class<?> type = methodParameter.getParameterType();
        String typeName = type.getSimpleName();
        String name = "";
        testClass.addImport(type);
        boolean unknown = false;
        RequestParam requestParam = methodParameter.getParameterAnnotation(RequestParam.class);
        PathVariable pathVariable = methodParameter.getParameterAnnotation(PathVariable.class);
        RequestHeader requestHeader = methodParameter.getParameterAnnotation(RequestHeader.class);
        if (requestParam != null) {
            name = requestParam.value();
            if (name.isEmpty()) {
                name = requestParam.name();
            }
        } else if (pathVariable != null) {
            name = pathVariable.value();
            if (name.isEmpty()) {
                name = pathVariable.name();
            }
            if (name.isEmpty()) {
                name = parameters[methodParameter.getParameterIndex()].getName();
            }
            pathVariables.add(name);
            variableDeclares.add("\t" + typeName + " " + name + " = " + getDefaultValue(type) + ";");
            continue;
        } else if (methodParameter.hasParameterAnnotation(RequestBody.class)) {
            body = "request";
            bodyType = type;
            variableDeclares.add("\t" + typeName + " request = " + getDefaultValue(type) + ";");
            continue;
        } else if (requestHeader != null) {
            name = requestHeader.value();
            if (name.isEmpty()) {
                name = requestHeader.name();
            }
            if (name.isEmpty()) {
                name = parameters[methodParameter.getParameterIndex()].getName();
            }
            String camelCase = camelCase(name);
            headers.put(name, camelCase);
            variableDeclares.add("\t" + typeName + " " + camelCase + " = " + getDefaultValue(type) + ";");
            continue;
        } else if (HttpServletResponse.class == type || HttpServletRequest.class == type) {
            continue;
        } else if (Locale.class == type) {
            locale = "locale";
            variableDeclares.add("\t" + typeName + " " + locale + " = Locale.getDefault();");
            continue;
        } else {
            unknown = true;
        }
        if (name.isEmpty()) {
            name = parameters[methodParameter.getParameterIndex()].getName();
        }
        if (unknown && type.getClassLoader() != null && type != MultipartFile.class) {
            ReflectionUtils.doWithFields(type, field -> process(field.getName(), camelCase(field.getName()), field.getType(), params, files, variableDeclares, testClass, method, lowerMethod), field -> !Modifier.isStatic(field.getModifiers()));
            continue;
        } else if (unknown) {
            System.err.println("param " + methodParameter.getParameterIndex() + " with type " + typeName + " in " + method + " has no annotation");
        }
        process(name, camelCase(name), type, params, files, variableDeclares, testClass, method, lowerMethod);
    }
    for (String variableDeclare : variableDeclares) {
        out.println(variableDeclare);
    }
    testClass.addImport(MvcResult.class);
    if (files.isEmpty()) {
        testClass.addStaticImport(MockMvcRequestBuilders.class, lowerMethod);
        out.print("\tMvcResult result = mvc.perform(" + lowerMethod + "(" + url);
        for (String pathVariable : pathVariables) {
            out.print(", " + pathVariable);
        }
        out.print(")");
    } else {
        String methodName = "multipart";
        if (!ClassUtils.hasMethod(MockMvcRequestBuilders.class, "multipart", String.class, String[].class)) {
            methodName = "fileUpload";
        }
        testClass.addStaticImport(MockMvcRequestBuilders.class, methodName);
        out.print("\tMvcResult result = mvc.perform(" + methodName + "(" + url);
        for (String pathVariable : pathVariables) {
            out.print(", " + pathVariable);
        }
        out.print(")");
        for (String file : files) {
            out.print(".file(" + file + ")");
        }
    }
    boolean newLine = params.size() >= 2;
    for (Map.Entry<String, Class<?>> entry : params.entrySet()) {
        String paramName = entry.getKey();
        String variableName = camelCase(paramName);
        Class<?> paramType = entry.getValue();
        String value;
        if (paramType.isPrimitive()) {
            value = com.google.common.primitives.Primitives.wrap(paramType).getSimpleName() + ".toString(" + variableName + ")";
        } else if (paramType == String.class) {
            value = variableName;
        } else {
            testClass.addImport(Objects.class);
            value = "Objects.toString(" + variableName + ", \"\")";
        }
        if (newLine) {
            out.println();
            out.print("\t\t\t");
        }
        out.print(".param(\"" + paramName + "\", " + value + ")");
    }
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        out.println();
        out.print("\t\t\t.header(\"" + entry.getKey() + "\", " + entry.getValue() + ")");
    }
    if (locale != null) {
        out.println();
        out.print("\t\t\t.locale(" + locale + ")");
    }
    switch(lowerMethod) {
        case "get":
        case "delete":
            if (body != null) {
                System.err.println("RequestBody annotation found on " + method + " with request method " + lowerMethod);
            }
            if (!requestMappingInfo.getConsumesCondition().isEmpty()) {
                System.err.println("request consumes " + requestMappingInfo.getConsumesCondition() + " found on " + method);
            }
    }
    if (body != null) {
        out.println();
        if (bodyType == String.class || bodyType == byte[].class) {
            out.print("\t\t\t.content(" + body + ")");
        } else {
            testClass.addField(ObjectMapper.class, "objectMapper", "@Autowired");
            out.print("\t\t\t.content(objectMapper.writeValueAsString(" + body + "))");
        }
        testClass.addImport(MediaType.class);
        out.print(".contentType(MediaType.APPLICATION_JSON)");
    }
    testClass.addStaticImport(MockMvcResultMatchers.class, "status");
    out.println(")");
    out.println("\t\t\t.andExpect(status().isOk())");
    out.println("\t\t\t.andReturn();");
    out.println("}");
    testClass.addMethod(sw.toString());
}
Also used : Locale(java.util.Locale) RequestParam(org.springframework.web.bind.annotation.RequestParam) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) HttpServletRequest(javax.servlet.http.HttpServletRequest) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) StringWriter(java.io.StringWriter) PrintWriter(java.io.PrintWriter) HttpServletResponse(javax.servlet.http.HttpServletResponse) HandlerMethod(org.springframework.web.method.HandlerMethod) Method(java.lang.reflect.Method) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) CtMethod(org.apache.ibatis.javassist.CtMethod) Objects(java.util.Objects) MethodParameter(org.springframework.core.MethodParameter) Parameter(java.lang.reflect.Parameter) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) MockMvcRequestBuilders(org.springframework.test.web.servlet.request.MockMvcRequestBuilders) MethodParameter(org.springframework.core.MethodParameter) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap) PathVariable(org.springframework.web.bind.annotation.PathVariable)

Aggregations

RequestHeader (org.springframework.web.bind.annotation.RequestHeader)7 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 HttpServletRequest (javax.servlet.http.HttpServletRequest)2 HttpServletResponse (javax.servlet.http.HttpServletResponse)2 PathVariable (org.springframework.web.bind.annotation.PathVariable)2 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)2 RequestParam (org.springframework.web.bind.annotation.RequestParam)2 Counter (com.codahale.metrics.Counter)1 Meter (com.codahale.metrics.Meter)1 MetricRegistry (com.codahale.metrics.MetricRegistry)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableMap (com.google.common.collect.ImmutableMap)1 DataType (com.revolsys.datatype.DataType)1 Closeable (java.io.Closeable)1 IOException (java.io.IOException)1 OutputStream (java.io.OutputStream)1