Example usage for org.springframework.mock.web MockHttpServletRequest setQueryString

List of usage examples for org.springframework.mock.web MockHttpServletRequest setQueryString

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletRequest setQueryString.

Prototype

public void setQueryString(@Nullable String queryString) 

Source Link

Usage

From source file:com.doitnext.http.router.RestRouterServletTest.java

private void setUpRequest(Object[] testCase, MockHttpServletRequest request) {
    String httpMethod = (String) testCase[0];
    String pathPrefix = (String) testCase[1];
    String pathInfo = (String) testCase[2];
    String queryString = (String) testCase[3];
    String parts[] = queryString.split("&");
    String acceptHeader = (String) testCase[4];
    String contentTypeHeader = (String) testCase[5];

    request.setServletPath("");
    request.setContextPath(pathPrefix);/*from   w  ww  . ja va2s  .c  o  m*/
    request.setPathInfo(pathInfo);
    request.setMethod(httpMethod);
    request.setQueryString(queryString);
    for (String part : parts) {
        String pieces[] = part.split("=");
        if (pieces.length > 1)
            request.addParameter(pieces[0], pieces[1]);
    }
    if (acceptHeader != null)
        request.addHeader("Accept", acceptHeader);
    if (contentTypeHeader != null)
        request.setContentType(contentTypeHeader);
    HttpMethod mthd = HttpMethod.valueOf(httpMethod);
    if (mthd == HttpMethod.POST || mthd == HttpMethod.PUT) {

    }
}

From source file:com.baidu.jprotobuf.rpc.client.ProxyFactoryBeanTestBase.java

protected HttpServer createServer() throws Exception {

    servlet.init();// w  ww  .j a v  a2s . co m

    HttpServerProvider provider = HttpServerProvider.provider();
    HttpServer httpserver = provider.createHttpServer(new InetSocketAddress(8080), 10);

    httpserver.createContext(getPathInfo(), new HttpHandler() {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {

            MockHttpServletRequest request = new MockHttpServletRequest();
            request.setPathInfo(getPathInfo());

            String queryString = httpExchange.getRequestURI().getRawQuery();

            if (queryString != null) {
                if (queryString.indexOf(ServiceExporter.INPUT_IDL_PARAMETER) != -1) {
                    request.addParameter(ServiceExporter.INPUT_IDL_PARAMETER, "");
                }
                if (queryString.indexOf(ServiceExporter.OUTPUT_IDL_PARAMETER) != -1) {
                    request.addParameter(ServiceExporter.OUTPUT_IDL_PARAMETER, "");
                }
            }

            request.setQueryString(queryString);
            InputStream requestBody = httpExchange.getRequestBody();
            request.setContent(IOUtils.toByteArray(requestBody));

            MockHttpServletResponse response = new MockHttpServletResponse();
            response.setOutputStreamAccessAllowed(true);

            try {
                servlet.service(request, response);
            } catch (ServletException e) {
                e.printStackTrace();
            }
            httpExchange.sendResponseHeaders(200, response.getContentLength());
            OutputStream out = httpExchange.getResponseBody(); // ?
            out.write(response.getContentAsByteArray());
            out.flush();
            httpExchange.close();
        }
    });
    httpserver.setExecutor(null);
    httpserver.start();

    return httpserver;
}

From source file:com.doitnext.http.router.DefaultInvokerTest.java

private HttpServletRequest createHappyMockRequest(HttpMethod method, PathMatch pm)
        throws JsonGenerationException, JsonMappingException, IOException {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setMethod(method.name());//from   ww w.j a  va  2s.  c om
    if (method == HttpMethod.POST || method == HttpMethod.PUT) {
        TestTeamPojo pojo = createRandomPojo();
        req.setContentType("application/json");
        req.setContent(mapper.writeValueAsBytes(pojo));
    }
    String terminus = pm.getMatchedPath().getTerminus();
    if (!StringUtils.isEmpty(terminus)) {
        req.setQueryString(terminus);
        String parts[] = req.getQueryString().split("&");
        for (String part : parts) {
            if (!StringUtils.isEmpty(part)) {
                String pieces[] = part.split("=");
                if (!StringUtils.isEmpty(pieces[0])) {
                    String key = pieces[0];
                    String value = "";
                    if (pieces.length > 1) {
                        value = pieces[1].trim();
                    }
                    req.addParameter(key, value);
                }
            }
        }
    }
    return req;
}

From source file:com.alexshabanov.springrestapi.restapitest.RestOperationsTestClient.java

private MockHttpServletRequest toMockHttpServletRequest(URI url, HttpMethod method,
        ClientHttpRequest clientHttpRequest) throws IOException {
    final MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method.name(),
            url.getPath());/*from   www  . ja va  2s.c  o  m*/

    // copy headers
    final HttpHeaders headers = clientHttpRequest.getHeaders();
    for (final String headerKey : headers.toSingleValueMap().keySet()) {
        final List<String> headerValues = headers.get(headerKey);
        for (final String headerValue : headerValues) {
            mockHttpServletRequest.addHeader(headerKey, headerValue);
        }
    }

    // copy query parameters
    final String query = clientHttpRequest.getURI().getQuery();
    if (query != null) {
        mockHttpServletRequest.setQueryString(query);
        final String[] queryParameters = query.split("&");
        for (String keyValueParam : queryParameters) {
            final String[] components = keyValueParam.split("=");
            if (components.length == 1) {
                continue; // optional parameter
            }

            Assert.isTrue(components.length == 2,
                    "Can't split query parameters " + keyValueParam + " by key-value pair");
            mockHttpServletRequest.setParameter(components[0], components[1]);
        }
    }

    // copy request body
    // TODO: another byte copying approach here
    // TODO: for now we rely to the fact that request body is always presented as byte array output stream
    final OutputStream requestBodyStream = clientHttpRequest.getBody();
    if (requestBodyStream instanceof ByteArrayOutputStream) {
        mockHttpServletRequest.setContent(((ByteArrayOutputStream) requestBodyStream).toByteArray());
    } else {
        throw new AssertionError("Ooops, client http request has non-ByteArrayOutputStream body");
    }

    return mockHttpServletRequest;
}

From source file:org.cateproject.test.functional.mockmvc.HtmlUnitRequestBuilder.java

public MockHttpServletRequest buildRequest(ServletContext servletContext) {
    String charset = getCharset();
    String httpMethod = webRequest.getHttpMethod().name();
    UriComponents uriComponents = uriComponents();

    MockHttpServletRequest result = new HtmlUnitMockHttpServletRequest(servletContext, httpMethod,
            uriComponents.getPath());//w w w.  ja  v  a 2  s. c  o m
    parent(result, parentBuilder);
    result.setServerName(uriComponents.getHost()); // needs to be first for additional headers
    authType(result);
    result.setCharacterEncoding(charset);
    content(result, charset);
    contextPath(result, uriComponents);
    contentType(result);
    cookies(result);
    headers(result);
    locales(result);
    servletPath(uriComponents, result);
    params(result, uriComponents);
    ports(uriComponents, result);
    result.setProtocol("HTTP/1.1");
    result.setQueryString(uriComponents.getQuery());
    result.setScheme(uriComponents.getScheme());
    pathInfo(uriComponents, result);

    return parentPostProcessor == null ? result : parentPostProcessor.postProcessRequest(result);
}

From source file:org.n52.sos.service.it.MockHttpClient.java

private MockHttpServletRequest build() {
    try {//from  w  w  w  .j  av a2  s .  c o  m
        final MockHttpServletRequest req = new MockHttpServletRequest(context);
        req.setMethod(method);
        for (String header : headers.keySet()) {
            for (String value : headers.get(header)) {
                req.addHeader(header, value);
            }
        }
        final StringBuilder queryString = new StringBuilder();
        if (query != null && !query.isEmpty()) {
            boolean first = true;
            for (String key : query.keySet()) {
                final Set<String> values = query.get(key);
                req.addParameter(key, values.toArray(new String[values.size()]));
                if (first) {
                    queryString.append("?");
                    first = false;
                } else {
                    queryString.append("&");
                }
                queryString.append(key).append("=");
                Iterator<String> i = values.iterator();
                queryString.append(i.next());
                while (i.hasNext()) {
                    queryString.append(",").append(i.next());
                }
            }
            req.setQueryString(queryString.toString());
        }
        req.setRequestURI(path + queryString.toString());
        if (path == null) {
            path = "/";
        }
        req.setPathInfo(path);
        if (content != null) {
            req.setContent(content.getBytes(MockHttpExecutor.ENCODING));
        }
        return req;
    } catch (UnsupportedEncodingException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:org.finra.dm.ui.RequestLoggingFilterTest.java

private MockHttpServletRequest createServletRequest() {
    MockHttpServletRequest request = new MockHttpServletRequest(null, "/test");
    request.setQueryString("param=value");
    request.setMethod("POST");
    MockHttpSession session = new MockHttpSession();
    request.setContent(PAYLOAD_CONTENT.getBytes());
    request.setSession(session);/*from   w  w  w .jav  a2s  .  co m*/
    request.setRemoteUser("Test Remote User");
    return request;
}

From source file:org.geogig.geoserver.functional.GeoServerTestSupport.java

/**
 * Issue a POST request to the provided URL with the given file passed as form data.
 *
 * @param resourceUri the url to issue the request to
 * @param formFieldName the form field name for the file to be posted
 * @param file the file to post/*from  ww  w  .  j a v a2 s . c o  m*/
 *
 * @return the response to the request
 */
public MockHttpServletResponse postFile(String resourceUri, String formFieldName, File file) throws Exception {

    try (FileInputStream fis = new FileInputStream(file)) {
        MockMultipartFile mFile = new MockMultipartFile(formFieldName, fis);
        MockMultipartHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders
                .fileUpload(new URI(resourceUri)).file(mFile);

        MockHttpServletRequest request = requestBuilder.buildRequest(applicationContext.getServletContext());

        /**
         * Duplicated from GeoServerSystemTestSupport#createRequest to do the same work on the
         * MockMultipartHttpServletRequest
         */
        request.setScheme("http");
        request.setServerName("localhost");
        request.setServerPort(8080);
        request.setContextPath("/geoserver");
        request.setRequestURI(
                ResponseUtils.stripQueryString(ResponseUtils.appendPath("/geoserver/", resourceUri)));
        // request.setRequestURL(ResponseUtils.appendPath("http://localhost:8080/geoserver",
        // path ) );
        request.setQueryString(ResponseUtils.getQueryString(resourceUri));
        request.setRemoteAddr("127.0.0.1");
        request.setServletPath(ResponseUtils.makePathAbsolute(ResponseUtils.stripRemainingPath(resourceUri)));
        request.setPathInfo(ResponseUtils.makePathAbsolute(
                ResponseUtils.stripBeginningPath(ResponseUtils.stripQueryString(resourceUri))));
        request.addHeader("Host", "localhost:8080");

        // deal with authentication
        if (username != null) {
            String token = username + ":";
            if (password != null) {
                token += password;
            }
            request.addHeader("Authorization", "Basic " + new String(Base64.encodeBase64(token.getBytes())));
        }

        kvp(request, resourceUri);

        request.setUserPrincipal(null);
        /**
         * End duplication
         */

        return dispatch(request);
    }
}

From source file:org.jahia.bin.ErrorFileDumperTest.java

private void generateExceptions() {
    for (int i = 0; i < LOOP_COUNT; i++) {
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.setRequestURI("/cms");
        request.setQueryString("name=value");
        request.addHeader("headerName", "headerValue");
        try {//from www  . j a v  a  2 s . com
            ErrorFileDumper.dumpToFile(new Throwable("mock error " + i), (HttpServletRequest) request);
        } catch (IOException e) {
            logger.error("Error while dumping error", e);
        }
    }
}

From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java

protected String sendRequest(final String requestType, final String url, final Map<?, ?> parameters,
        final int expectedStatus, final String expectedUrlSuffix) throws Exception {
    final MockHttpServletRequest request = createRequest(servletContext, requestType, url, getUser(),
            getUserRoles());/*from ww w  . ja v a 2s . c om*/
    request.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    request.setParameters(parameters);
    request.setQueryString(getQueryString(parameters));
    return sendRequest(request, expectedStatus, expectedUrlSuffix);
}