Search in sources :

Example 1 with RequestMethod

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

the class RequestMappingHandlerMappingTests method assertComposedAnnotationMapping.

private RequestMappingInfo assertComposedAnnotationMapping(String methodName, String path, RequestMethod requestMethod) throws Exception {
    Class<?> clazz = ComposedAnnotationController.class;
    Method method = clazz.getMethod(methodName);
    RequestMappingInfo info = this.handlerMapping.getMappingForMethod(method, clazz);
    assertNotNull(info);
    Set<String> paths = info.getPatternsCondition().getPatterns();
    assertEquals(1, paths.size());
    assertEquals(path, paths.iterator().next());
    Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
    assertEquals(1, methods.size());
    assertEquals(requestMethod, methods.iterator().next());
    return info;
}
Also used : RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Method(java.lang.reflect.Method) RequestMethod(org.springframework.web.bind.annotation.RequestMethod)

Example 2 with RequestMethod

use of org.springframework.web.bind.annotation.RequestMethod in project nikita-noark5-core by HiOA-ABI.

the class AfterApplicationStartup method afterApplicationStarts.

/**
 * afterApplicationStarts, go through list of endpoints and make a list of
 * endpoints and the HTTP methods they support. Really this should be
 * handled by Spring. I do not know why I couldn't get spring to handle
 * this but we need to get spring to handle these things ... not me!!!
 *
 * Also create a list of Norwegian names to english names for handling OData
 */
public void afterApplicationStarts() {
    for (Map.Entry<RequestMappingInfo, HandlerMethod> entry : handlerMapping.getHandlerMethods().entrySet()) {
        RequestMappingInfo requestMappingInfo = entry.getKey();
        // Assuming there is always a non-null value
        String servletPaths = requestMappingInfo.getPatternsCondition().toString();
        // servletPath starts with "[" and ends with "]". Removing them if they are there
        if (true == servletPaths.startsWith("[")) {
            servletPaths = servletPaths.substring(1);
        }
        if (true == servletPaths.endsWith("]")) {
            servletPaths = servletPaths.substring(0, servletPaths.length() - 1);
        }
        String[] servletPathList = servletPaths.split("\\s+");
        for (String servletPath : servletPathList) {
            if (servletPath != null && false == servletPath.contains("|")) {
                // This is done to be consist on a lookup
                if (false == servletPath.endsWith("/")) {
                    servletPath += SLASH;
                }
                Set<RequestMethod> httpMethodRequests = requestMappingInfo.getMethodsCondition().getMethods();
                if (null != httpMethodRequests && null != servletPath) {
                    // RequestMethod and HTTPMethod are different types, have to convert them here
                    Set<HttpMethod> httpMethods = new TreeSet<>();
                    for (RequestMethod requestMethod : httpMethodRequests) {
                        if (requestMethod.equals(RequestMethod.GET)) {
                            httpMethods.add(HttpMethod.GET);
                        } else if (requestMethod.equals(RequestMethod.DELETE)) {
                            httpMethods.add(HttpMethod.DELETE);
                        } else if (requestMethod.equals(RequestMethod.OPTIONS)) {
                            httpMethods.add(HttpMethod.OPTIONS);
                        } else if (requestMethod.equals(RequestMethod.HEAD)) {
                            httpMethods.add(HttpMethod.HEAD);
                        } else if (requestMethod.equals(RequestMethod.PATCH)) {
                            httpMethods.add(HttpMethod.PATCH);
                        } else if (requestMethod.equals(RequestMethod.POST)) {
                            httpMethods.add(HttpMethod.POST);
                        } else if (requestMethod.equals(RequestMethod.PUT)) {
                            httpMethods.add(HttpMethod.PUT);
                        } else if (requestMethod.equals(RequestMethod.TRACE)) {
                            httpMethods.add(HttpMethod.TRACE);
                        }
                    }
                    out.println("Adding " + servletPath + " methods " + httpMethods);
                    CommonUtils.WebUtils.addRequestToMethodMap(servletPath, httpMethods);
                } else {
                    logger.warn("Missing HTTP Methods for the following servletPath [" + servletPath + "]");
                }
            }
        }
    }
    populateTranslatedNames();
}
Also used : RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) TreeSet(java.util.TreeSet) Map(java.util.Map) HandlerMethod(org.springframework.web.method.HandlerMethod) HttpMethod(org.springframework.http.HttpMethod)

Example 3 with RequestMethod

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

the class MockGenerator method test.

@Test
public void test() throws IOException {
    Gson gson = new Gson();
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = handlerMapping.getHandlerMethods();
    Map<Class<?>, List<Info>> map = handlerMethods.entrySet().stream().map(entry -> new Info(entry.getValue(), entry.getKey())).collect(Collectors.groupingBy(info -> info.getHandlerMethod().getMethod().getDeclaringClass()));
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw, true);
    for (Map.Entry<Class<?>, List<Info>> entry : map.entrySet()) {
        Class<?> key = entry.getKey();
        List<Info> value = entry.getValue();
        if (!accept(key, value)) {
            continue;
        }
        value.sort(Comparator.comparing(info -> info.getHandlerMethod().getMethod(), Comparator.comparing(method -> method.getDeclaringClass().getName().replace(".", "/") + "." + method.getName() + ":" + org.springframework.asm.Type.getMethodDescriptor(method), toMethodComparator(key))));
        TestClass testClass = new TestClass(key, "@AutoConfigureMockMvc", "@RunWith(SpringRunner.class)", "@Slf4j", "@SpringBootTest(classes = " + mainClass.getSimpleName() + ".class)", "@Transactional", "@WebAppConfiguration");
        testClass.addImport(mainClass);
        testClass.addImport(AutoConfigureMockMvc.class);
        testClass.addImport(RunWith.class);
        testClass.addImport(SpringRunner.class);
        testClass.addImport(Slf4j.class);
        testClass.addImport(SpringBootTest.class);
        testClass.addImport(Transactional.class);
        testClass.addImport(WebAppConfiguration.class);
        testClass.addImport(Autowired.class);
        testClass.addField(MockMvc.class, "mvc", "@Autowired");
        for (Info info : value) {
            RequestMappingInfo requestMappingInfo = info.getRequestMappingInfo();
            Set<RequestMethod> requestMethods = requestMappingInfo.getMethodsCondition().getMethods();
            String requestMethod = requestMethods.isEmpty() ? "post" : requestMethods.iterator().next().toString().toLowerCase();
            HandlerMethod handlerMethod = info.getHandlerMethod();
            String url = gson.toJson(requestMappingInfo.getPatternsCondition().getPatterns().iterator().next());
            generate(key, requestMappingInfo, handlerMethod, url, testClass, requestMethod);
        }
        testClass.write(out);
        Path to = outputDir.resolve(key.getName().replace(".", "/") + "Test.java");
        Files.createDirectories(to.getParent());
        Files.write(to, sw.toString().replace("\t", "    ").getBytes(StandardCharsets.UTF_8));
        sw.getBuffer().setLength(0);
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) ClassPool(org.apache.ibatis.javassist.ClassPool) Spliterators(java.util.Spliterators) Autowired(org.springframework.beans.factory.annotation.Autowired) HandlerMethod(org.springframework.web.method.HandlerMethod) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Gson(com.google.gson.Gson) Locale(java.util.Locale) Map(java.util.Map) MethodParameter(org.springframework.core.MethodParameter) SpringRunner(org.springframework.test.context.junit4.SpringRunner) Method(java.lang.reflect.Method) Path(java.nio.file.Path) PrintWriter(java.io.PrintWriter) WebAppConfiguration(org.springframework.test.context.web.WebAppConfiguration) ImmutableMap(com.google.common.collect.ImmutableMap) Predicate(java.util.function.Predicate) MediaType(org.springframework.http.MediaType) Set(java.util.Set) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Modifier(java.lang.reflect.Modifier) RequestMappingHandlerMapping(org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) Spliterator(java.util.Spliterator) RunWith(org.junit.runner.RunWith) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) MockMvc(org.springframework.test.web.servlet.MockMvc) RequestBody(org.springframework.web.bind.annotation.RequestBody) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) HttpServletRequest(javax.servlet.http.HttpServletRequest) Parameter(java.lang.reflect.Parameter) MvcResult(org.springframework.test.web.servlet.MvcResult) StreamSupport(java.util.stream.StreamSupport) Application(cn.edu.zjnu.acm.judge.Application) Files(java.nio.file.Files) StringWriter(java.io.StringWriter) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) Test(org.junit.Test) CtMethod(org.apache.ibatis.javassist.CtMethod) Consumer(java.util.function.Consumer) AutoConfigureMockMvc(org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc) Paths(java.nio.file.Paths) ReflectionUtils(org.springframework.util.ReflectionUtils) MultipartFile(org.springframework.web.multipart.MultipartFile) Comparator(java.util.Comparator) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) Transactional(org.springframework.transaction.annotation.Transactional) Path(java.nio.file.Path) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Gson(com.google.gson.Gson) RequestMappingInfo(org.springframework.web.servlet.mvc.method.RequestMappingInfo) HandlerMethod(org.springframework.web.method.HandlerMethod) StringWriter(java.io.StringWriter) List(java.util.List) ArrayList(java.util.ArrayList) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) LinkedHashMap(java.util.LinkedHashMap) PrintWriter(java.io.PrintWriter) SpringBootTest(org.springframework.boot.test.context.SpringBootTest) Test(org.junit.Test)

Example 4 with RequestMethod

use of org.springframework.web.bind.annotation.RequestMethod in project RestyPass by darren-fu.

the class RequestMappingProcessor method process.

@Override
public boolean process(RestyRequestTemplate requestTemplate, Annotation annotation) {
    RequestMapping methodMapping = ANNOTATION.cast(annotation);
    // HTTP Method
    RequestMethod[] methods = methodMapping.method();
    if (methods.length == 0) {
        methods = new RequestMethod[] { RequestMethod.GET };
    }
    checkOne(methods, "method");
    requestTemplate.setHttpMethod(methods[0].name());
    // path
    checkAtMostOne(methodMapping.value(), "value");
    if (methodMapping.value().length > 0) {
        String pathValue = emptyToNull(methodMapping.value()[0]);
        if (pathValue != null) {
            pathValue = resolve(pathValue);
            // Append path from @RequestMapping if value is present on httpMethod
            if (!pathValue.startsWith("/")) {
                pathValue = "/" + pathValue;
            }
            requestTemplate.setMethodUrl(pathValue);
        }
    }
    // produces #不需要解析consumes, 无视接口返回的content-type,只处理application/json
    // parseProduces(requestTemplate, method, methodMapping);
    // consumes #不需要解析consumes, 无视接口所需的content-type,只提交application/json
    // parseConsumes(requestTemplate, method, methodMapping);
    // params
    parseParams(requestTemplate, null, methodMapping);
    // headers
    parseHeaders(requestTemplate, null, methodMapping);
    return false;
}
Also used : RequestMethod(org.springframework.web.bind.annotation.RequestMethod) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 5 with RequestMethod

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

the class RequestMethodsRequestConditionTests method getMatchingConditionWithEmptyConditions.

@Test
public void getMatchingConditionWithEmptyConditions() {
    RequestMethodsRequestCondition condition = new RequestMethodsRequestCondition();
    for (RequestMethod method : RequestMethod.values()) {
        if (method != OPTIONS) {
            HttpServletRequest request = new MockHttpServletRequest(method.name(), "");
            assertThat(condition.getMatchingCondition(request)).isNotNull();
        }
    }
    testNoMatch(condition, OPTIONS);
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) MockHttpServletRequest(org.springframework.web.testfixture.servlet.MockHttpServletRequest) Test(org.junit.jupiter.api.Test)

Aggregations

RequestMethod (org.springframework.web.bind.annotation.RequestMethod)26 HandlerMethod (org.springframework.web.method.HandlerMethod)6 RequestMappingInfo (org.springframework.web.servlet.mvc.method.RequestMappingInfo)6 Method (java.lang.reflect.Method)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5 ArrayList (java.util.ArrayList)4 List (java.util.List)3 Visitor (com.baidu.disconf.web.service.user.dto.Visitor)2 ApiParamObject (com.terran4j.commons.api2doc.domain.ApiParamObject)2 ValueSource (com.terran4j.commons.util.value.ValueSource)2 LinkedHashMap (java.util.LinkedHashMap)2 Set (java.util.Set)2 TreeSet (java.util.TreeSet)2 Test (org.junit.jupiter.api.Test)2 CrossOrigin (org.springframework.web.bind.annotation.CrossOrigin)2 CorsConfiguration (org.springframework.web.cors.CorsConfiguration)2 Application (cn.edu.zjnu.acm.judge.Application)1 RoleResource (com.baidu.disconf.web.service.roleres.bo.RoleResource)1 AccessDeniedException (com.baidu.dsp.common.exception.AccessDeniedException)1