Java Code Examples for org.springframework.mock.web.MockHttpServletResponse#getContentAsByteArray()
The following examples show how to use
org.springframework.mock.web.MockHttpServletResponse#getContentAsByteArray() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JsonRpcServerTest.java From jsonrpc4j with MIT License | 8 votes |
@Test public void testGzipRequest() throws IOException { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post"); request.addHeader(CONTENT_ENCODING, "gzip"); request.setContentType("application/json"); byte[] bytes = "{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); gos.write(bytes); gos.close(); request.setContent(baos.toByteArray()); MockHttpServletResponse response = new MockHttpServletResponse(); jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true); jsonRpcServer.handle(request, response); String responseContent = new String(response.getContentAsByteArray(), StandardCharsets.UTF_8); Assert.assertEquals(responseContent, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}\n"); Assert.assertNull(response.getHeader(CONTENT_ENCODING)); }
Example 2
Source File: TestServlet.java From tds with BSD 3-Clause "New" or "Revised" License | 6 votes |
void dodmr(TestCase testcase) throws Exception { String url = testcase.makeurl(RequestMode.DMR); String little = (USEBIG ? "0" : "1"); String nocsum = (NOCSUM ? "1" : "0"); MvcResult result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TESTTAG, "true"); // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); // Test by converting the raw output to a string String sdmr = new String(byteresult, UTF8); if (prop_visual) visual(testcase.title + ".dmr", sdmr); if (prop_baseline) { writefile(testcase.baselinepath + ".dmr", sdmr); } else if (prop_diff) { // compare with baseline // Read the baseline file String baselinecontent = readfile(testcase.baselinepath + ".dmr"); System.err.println("DMR Comparison"); Assert.assertTrue("***Fail", same(getTitle(), baselinecontent, sdmr)); } }
Example 3
Source File: ResourceControllerTest.java From geomajas-project-server with GNU Affero General Public License v3.0 | 6 votes |
@Test public void testCompression() throws ServletException, IOException { // create an empty mock context MockServletContext context = new TestServletContext(true); MockHttpServletRequest request = new MockHttpServletRequest(context); request.addHeader("Accept-Encoding", "gzip"); request.setPathInfo("/org/geomajas/servlet/test.js"); request.setMethod("GET"); MockHttpServletResponse response = new MockHttpServletResponse(); ResourceController resourceController = new ResourceController(); resourceController.setServletContext(context); resourceController.getResource(request, response); Resource resource = new ClassPathResource("/org/geomajas/servlet/test.js"); GZIPInputStream gzipInputStream = new GZIPInputStream( new ByteArrayInputStream(response.getContentAsByteArray())); Assert.assertArrayEquals(IOUtils.toByteArray(resource.getInputStream()), IOUtils.toByteArray(gzipInputStream)); }
Example 4
Source File: JsonRpcServerTest.java From jsonrpc4j with MIT License | 6 votes |
@Test public void testGzipRequestAndResponse() throws IOException { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post"); request.addHeader(CONTENT_ENCODING, "gzip"); request.addHeader(ACCEPT_ENCODING, "gzip"); request.setContentType("application/json"); byte[] bytes = "{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8); ByteArrayOutputStream baos = new ByteArrayOutputStream(); GZIPOutputStream gos = new GZIPOutputStream(baos); gos.write(bytes); gos.close(); request.setContent(baos.toByteArray()); MockHttpServletResponse response = new MockHttpServletResponse(); jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true); jsonRpcServer.handle(request, response); byte[] compressed = response.getContentAsByteArray(); String sb = getCompressedResponseContent(compressed); Assert.assertEquals(sb, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}"); Assert.assertEquals("gzip", response.getHeader(CONTENT_ENCODING)); }
Example 5
Source File: JsonRpcServerTest.java From jsonrpc4j with MIT License | 6 votes |
@Test public void testGzipResponseMultipleAcceptEncoding() throws IOException { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post"); request.addHeader(ACCEPT_ENCODING, "gzip,deflate"); request.setContentType("application/json"); request.setContent("{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8)); MockHttpServletResponse response = new MockHttpServletResponse(); jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true); jsonRpcServer.handle(request, response); byte[] compressed = response.getContentAsByteArray(); String sb = getCompressedResponseContent(compressed); Assert.assertEquals(sb, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}"); Assert.assertEquals("gzip", response.getHeader(CONTENT_ENCODING)); }
Example 6
Source File: JsonRpcServerTest.java From jsonrpc4j with MIT License | 6 votes |
@Test public void testGzipResponse() throws IOException { MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test-post"); request.addHeader(ACCEPT_ENCODING, "gzip"); request.setContentType("application/json"); request.setContent("{\"jsonrpc\":\"2.0\",\"id\":123,\"method\":\"testMethod\",\"params\":[\"Whir?inaki\"]}".getBytes(StandardCharsets.UTF_8)); MockHttpServletResponse response = new MockHttpServletResponse(); jsonRpcServer = new JsonRpcServer(Util.mapper, mockService, ServiceInterface.class, true); jsonRpcServer.handle(request, response); byte[] compressed = response.getContentAsByteArray(); String sb = getCompressedResponseContent(compressed); Assert.assertEquals(sb, "{\"jsonrpc\":\"2.0\",\"id\":123,\"result\":null}"); Assert.assertEquals("gzip", response.getHeader(CONTENT_ENCODING)); }
Example 7
Source File: TestDSR.java From tds with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testDSR() throws Exception { String url = FAKEURLPATH; // no file specified // Figure out the baseline String baselinepath = canonjoin(this.resourceroot, BASELINEDIR, FAKEDATASET) + ".dsr"; MvcResult result = perform(url, this.mockMvc, RESOURCEPATH); // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); // Convert the raw output to a string String dsr = new String(byteresult, UTF8); if (prop_visual) visual("TestDSR", dsr); if (prop_baseline) { writefile(baselinepath, dsr); } else if (prop_diff) { // compare with baseline // Read the baseline file String baselinecontent = readfile(baselinepath); System.out.println("DSR Comparison:"); Assert.assertTrue("***Fail", same(getTitle(), baselinecontent, dsr)); } }
Example 8
Source File: ServletNettyHandler.java From nettyholdspringmvc with Apache License 2.0 | 5 votes |
@Override public void messageReceived(ChannelHandlerContext ctx, HttpRequest request) throws Exception { if (!request.getDecoderResult().isSuccess()) { sendError(ctx, BAD_REQUEST); return; } MockHttpServletRequest servletRequest = createServletRequest(request); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); this.servlet.service(servletRequest, servletResponse); HttpResponseStatus status = HttpResponseStatus.valueOf(servletResponse.getStatus()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); for (String name : servletResponse.getHeaderNames()) { for (Object value : servletResponse.getHeaderValues(name)) { response.addHeader(name, value); } } // Write the initial line and the header. ctx.write(response); InputStream contentStream = new ByteArrayInputStream(servletResponse.getContentAsByteArray()); // Write the content. ChannelFuture writeFuture = ctx.write(new ChunkedStream(contentStream)); writeFuture.addListener(ChannelFutureListener.CLOSE); }
Example 9
Source File: BaseMockServletTestCase.java From cosmo with Apache License 2.0 | 5 votes |
/** * Reads xml response. * @param response The response. * @return xml response. * @throws Exception - if something is wrong this exception is thrown. */ protected Document readXmlResponse(MockHttpServletResponse response) throws Exception { ByteArrayInputStream in = new ByteArrayInputStream(response.getContentAsByteArray()); BUILDER_FACTORY.setNamespaceAware(true); return BUILDER_FACTORY.newDocumentBuilder().parse(in); }
Example 10
Source File: ServletNettyChannelHandler.java From netty-cookbook with Apache License 2.0 | 5 votes |
@Override protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception { if (!fullHttpRequest.getDecoderResult().isSuccess()) { sendError(channelHandlerContext, BAD_REQUEST); return; } MockHttpServletRequest servletRequest = createHttpServletRequest(fullHttpRequest); MockHttpServletResponse servletResponse = new MockHttpServletResponse(); this.servlet.service(servletRequest, servletResponse); HttpResponseStatus status = HttpResponseStatus.valueOf(servletResponse.getStatus()); HttpResponse response = new DefaultHttpResponse(HTTP_1_1, status); for (String name : servletResponse.getHeaderNames()) { for (String value : servletResponse.getHeaders(name)) { response.headers().add(name, value); } } // Write the initial line and the header. channelHandlerContext.write(response); InputStream contentStream = new ByteArrayInputStream(servletResponse.getContentAsByteArray()); // Write the content and flush it. ChannelFuture writeFuture = channelHandlerContext.writeAndFlush(new ChunkedStream(contentStream)); writeFuture.addListener(ChannelFutureListener.CLOSE); }
Example 11
Source File: TestServletConstraints.java From tds with BSD 3-Clause "New" or "Revised" License | 5 votes |
void dodmr(TestCase testcase) throws Exception { String url = testcase.makeurl(RequestMode.DMR); String query = testcase.makequery(); String basepath = testcase.makeBasepath(RequestMode.DMR); String little = (USEBIG ? "0" : "1"); String nocsum = (NOCSUM ? "1" : "0"); MvcResult result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.CONSTRAINTTAG, query, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TESTTAG, "true"); // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); // Test by converting the raw output to a string String sdmr = new String(byteresult, UTF8); if (prop_visual) visual(testcase.title + ".dmr", sdmr); if (prop_baseline) { writefile(basepath, sdmr); } else if (prop_diff) { // compare with baseline // Read the baseline file String baselinecontent = readfile(basepath); System.err.println("DMR Comparison"); Assert.assertTrue("***Fail", same(getTitle(), baselinecontent, sdmr)); } }
Example 12
Source File: TestFrontPage.java From tds with BSD 3-Clause "New" or "Revised" License | 5 votes |
@Test public void testFrontPage() throws Exception { String url = FAKEURLPREFIX; // no file specified // Figure out the baseline String baselinepath = canonjoin(this.resourceroot, BASELINEDIR, TESTFILE); MvcResult result = perform(url, this.mockMvc, RESOURCEPATH); // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); // Convert the raw output to a string String html = new String(byteresult, UTF8); if (DEBUG || prop_visual) visual("Front Page", html); if (prop_baseline) { writefile(baselinepath, html); } else if (prop_diff) { // compare with baseline // Read the baseline file String baselinecontent = readfile(baselinepath); System.out.println("HTML Comparison:"); Assert.assertTrue("***Fail", same(getTitle(), baselinecontent, html)); } }
Example 13
Source File: DapTestCommon.java From tds with BSD 3-Clause "New" or "Revised" License | 4 votes |
public HttpResponse execute(HttpRequestBase rq) throws IOException { URI uri = rq.getURI(); DapController controller = getController(uri); StandaloneMockMvcBuilder mvcbuilder = MockMvcBuilders.standaloneSetup(controller); mvcbuilder.setValidator(new TestServlet.NullValidator()); MockMvc mockMvc = mvcbuilder.build(); MockHttpServletRequestBuilder mockrb = MockMvcRequestBuilders.get(uri); // We need to use only the path part mockrb.servletPath(uri.getPath()); // Move any headers from rq to mockrb Header[] headers = rq.getAllHeaders(); for (int i = 0; i < headers.length; i++) { Header h = headers[i]; mockrb.header(h.getName(), h.getValue()); } // Since the url has the query parameters, // they will automatically be parsed and added // to the rb parameters. // Finally set the resource dir mockrb.requestAttr("RESOURCEDIR", this.resourcepath); // Now invoke the servlet MvcResult result; try { result = mockMvc.perform(mockrb).andReturn(); } catch (Exception e) { throw new IOException(e); } // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); // Convert to HttpResponse HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, res.getStatus(), ""); if (response == null) throw new IOException("HTTPMethod.executeMock: Response was null"); Collection<String> keys = res.getHeaderNames(); // Move headers to the response for (String key : keys) { List<String> values = res.getHeaders(key); for (String v : values) { response.addHeader(key, v); } } ByteArrayEntity entity = new ByteArrayEntity(byteresult); String sct = res.getContentType(); entity.setContentType(sct); response.setEntity(entity); return response; }
Example 14
Source File: MockHttpClient.java From karate with MIT License | 4 votes |
@Override protected HttpResponse makeHttpRequest(HttpBody entity, ScenarioContext context) { logger.info("making mock http client request: {} - {}", request.getMethod(), getRequestUri()); MockHttpServletRequest req = requestBuilder.buildRequest(getServletContext()); byte[] bytes; if (entity != null) { bytes = entity.getBytes(); req.setContentType(entity.getContentType()); if (entity.isMultiPart()) { for (MultiPartItem item : entity.getParts()) { MockMultiPart part = new MockMultiPart(item); req.addPart(part); if (!part.isFile()) { req.addParameter(part.getName(), part.getValue()); } } } else if (entity.isUrlEncoded()) { req.addParameters(entity.getParameters()); } else { req.setContent(bytes); } } else { bytes = null; } MockHttpServletResponse res = new MockHttpServletResponse(); logRequest(req, bytes); long startTime = System.currentTimeMillis(); try { getServlet(request).service(req, res); } catch (Exception e) { String message = e.getMessage(); if (message == null && e.getCause() != null) { message = e.getCause().getMessage(); } logger.error("mock servlet request failed: {}", message); throw new RuntimeException(e); } HttpResponse response = new HttpResponse(startTime, System.currentTimeMillis()); bytes = res.getContentAsByteArray(); logResponse(res, bytes); response.setUri(getRequestUri()); response.setBody(bytes); response.setStatus(res.getStatus()); for (Cookie c : res.getCookies()) { com.intuit.karate.http.Cookie cookie = new com.intuit.karate.http.Cookie(c.getName(), c.getValue()); cookie.put(DOMAIN, c.getDomain()); cookie.put(PATH, c.getPath()); cookie.put(SECURE, c.getSecure() + ""); cookie.put(MAX_AGE, c.getMaxAge() + ""); cookie.put(VERSION, c.getVersion() + ""); response.addCookie(cookie); } for (String headerName : res.getHeaderNames()) { response.putHeader(headerName, res.getHeaders(headerName)); } return response; }
Example 15
Source File: TestServletConstraints.java From tds with BSD 3-Clause "New" or "Revised" License | 4 votes |
void dodata(TestCase testcase) throws Exception { String url = testcase.makeurl(RequestMode.DAP); String query = testcase.makequery(); String basepath = testcase.makeBasepath(RequestMode.DAP); String little = (USEBIG ? "0" : "1"); String nocsum = (NOCSUM ? "1" : "0"); MvcResult result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.CONSTRAINTTAG, query, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TESTTAG, "true"); // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); if (prop_debug || DEBUG) { DapDump.dumpbytestream(byteresult, ByteOrder.nativeOrder(), "TestServletConstraint.dodata"); } if (prop_generate) { // Dump the serialization into a file; this also includes the dmr String target = testcase.generatepath + ".raw"; writefile(target, byteresult); } // Setup a ChunkInputStream ByteArrayInputStream bytestream = new ByteArrayInputStream(byteresult); ChunkInputStream reader = new ChunkInputStream(bytestream, RequestMode.DAP, ByteOrder.nativeOrder()); String sdmr = reader.readDMR(); // Read the DMR if (prop_visual) visual(testcase.title + ".dmr.dap", sdmr); Dump printer = new Dump(); String sdata = printer.dumpdata(reader, testcase.checksumming, reader.getRemoteByteOrder(), testcase.template); if (prop_visual) visual(testcase.title + ".dap", sdata); if (prop_baseline) writefile(basepath, sdata); if (prop_diff) { // compare with baseline // Read the baseline file System.err.println("Data Comparison:"); String baselinecontent = readfile(testcase.baselinepath + ".dap"); Assert.assertTrue("***Fail", same(getTitle(), baselinecontent, sdata)); } }
Example 16
Source File: GenerateRaw.java From tds with BSD 3-Clause "New" or "Revised" License | 4 votes |
protected void doOne(TestCase tc) throws Exception { String inputpath = tc.inputpath(); String dappath; String dmrpath; if (USEDAPDMR) { dappath = tc.generatepath(DAPDIR) + ".dap"; dmrpath = tc.generatepath(DMRDIR) + ".dmr"; } else { dappath = tc.generatepath(RAWDIR) + ".dap"; dmrpath = tc.generatepath(RAWDIR) + ".dmr"; } String url = tc.makeurl(); String ce = tc.makequery(); System.err.println("Input: " + inputpath); System.err.println("Generated (DMR):" + dmrpath); System.err.println("Generated (DAP):" + dappath); System.err.println("URL: " + url); if (ce != null) System.err.println("CE: " + ce); if (CEPARSEDEBUG) CEParserImpl.setGlobalDebugLevel(1); String little = tc.bigendian ? "0" : "1"; String nocsum = tc.nochecksum ? "1" : "0"; MvcResult result; if (ce == null) { result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TRANSLATETAG, "nc4"); } else { result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.CONSTRAINTTAG, ce, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TRANSLATETAG, "nc4"); } // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); if (prop_debug || DEBUGDATA) { DapDump.dumpbytestream(byteresult, ByteOrder.nativeOrder(), "GenerateRaw"); } // Dump the dap serialization into a file if (prop_generate || GENERATE) writefile(dappath, byteresult); // Dump the dmr into a file by extracting from the dap serialization ByteArrayInputStream bytestream = new ByteArrayInputStream(byteresult); ChunkInputStream reader = new ChunkInputStream(bytestream, RequestMode.DAP, ByteOrder.nativeOrder()); String sdmr = reader.readDMR(); // Read the DMR if (prop_generate || GENERATE) writefile(dmrpath, sdmr); if (prop_visual) { visual(tc.dataset + ".dmr", sdmr); FileDSP src = new FileDSP(); src.open(byteresult); StringWriter writer = new StringWriter(); DSPPrinter printer = new DSPPrinter(src, writer); printer.print(); printer.close(); writer.close(); String sdata = writer.toString(); visual(tc.dataset + ".dap", sdata); } }
Example 17
Source File: TestServlet.java From tds with BSD 3-Clause "New" or "Revised" License | 4 votes |
void dodata(TestCase testcase) throws Exception { String url = testcase.makeurl(RequestMode.DAP); String little = (USEBIG ? "0" : "1"); String nocsum = (NOCSUM ? "1" : "0"); MvcResult result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TESTTAG, "true"); // Collect the output MockHttpServletResponse res = result.getResponse(); byte[] byteresult = res.getContentAsByteArray(); if (DEBUGDATA) { DapDump.dumpbytestream(byteresult, ByteOrder.nativeOrder(), "TestServlet.dodata"); } if (prop_generate) { // Dump the serialization into a file; this also includes the dmr String target = testcase.generatepath + ".raw"; writefile(target, byteresult); } // Setup a ChunkInputStream ByteArrayInputStream bytestream = new ByteArrayInputStream(byteresult); ChunkInputStream reader = new ChunkInputStream(bytestream, RequestMode.DAP, ByteOrder.nativeOrder()); String sdmr = reader.readDMR(); // Read the DMR if (prop_visual) visual(testcase.title + ".dmr.dap", sdmr); Dump printer = new Dump(); String sdata = printer.dumpdata(reader, testcase.checksumming, reader.getRemoteByteOrder(), testcase.template); if (prop_visual) visual(testcase.title + ".dap", sdata); if (prop_baseline) writefile(testcase.baselinepath + ".dap", sdata); if (prop_diff) { // compare with baseline // Read the baseline file System.err.println("Data Comparison:"); String baselinecontent = readfile(testcase.baselinepath + ".dap"); Assert.assertTrue("***Fail", same(getTitle(), baselinecontent, sdata)); } }