List of usage examples for org.springframework.mock.web MockHttpServletResponse getContentAsString
public String getContentAsString() throws UnsupportedEncodingException
From source file:org.springsource.restbucks.PaymentProcessIntegrationTest.java
/** * Looks up the first {@link Order} from the orders representation using a JSONPath expression of * {@value #FIRST_ORDER_EXPRESSION}. Looks up the {@value Link#REL_SELF} link from the nested object and follows it to * lookup the representation. Verifies the {@code self}, {@code cancel}, and {@code update} link to be present. * /*from w w w. j a v a2 s .c om*/ * @param source * @return * @throws Exception */ private MockHttpServletResponse accessFirstOrder(MockHttpServletResponse source) throws Exception { String content = source.getContentAsString(); String order = JsonPath.read(content, FIRST_ORDER_EXPRESSION).toString(); Link orderLink = links.findLinkWithRel("self", order); log.info(String.format("Picking first order using JSONPath expression %s", FIRST_ORDER_EXPRESSION)); log.info(String.format("Discovered self link pointing to %s Following", orderLink)); return mvc.perform(get(orderLink.getHref())). // andExpect(linkWithRelIsPresent("self")). // andExpect(linkWithRelIsPresent(CANCEL_REL)). // andExpect(linkWithRelIsPresent(UPDATE_REL)).andExpect(linkWithRelIsPresent(PAYMENT_REL)).// andReturn().getResponse(); }
From source file:org.springsource.restbucks.PaymentProcessIntegrationTest.java
/** * Creates a new {@link Order} by looking up the orders link from the source and posting the content of * {@code orders.json} to it. Verifies we get receive a {@code 201 Created} and a {@code Location} header. Follows the * location header to retrieve the {@link Order} just created. * /*from www . j a va2s . c o m*/ * @param source * @return * @throws Exception */ private MockHttpServletResponse createNewOrder(MockHttpServletResponse source) throws Exception { String content = source.getContentAsString(); Link ordersLink = links.findLinkWithRel(ORDERS_REL, content); ClassPathResource resource = new ClassPathResource("order.json"); byte[] data = Files.readAllBytes(resource.getFile().toPath()); MockHttpServletResponse result = mvc .perform(post(ordersLink.getHref()).contentType(MediaType.APPLICATION_JSON).content(data)). // andExpect(status().isCreated()). // andExpect(header().string("Location", is(notNullValue()))). // andReturn().getResponse(); return mvc.perform(get(result.getHeader("Location"))).andReturn().getResponse(); }
From source file:org.springframework.data.rest.tests.mongodb.MongoWebTests.java
@Test public void testname() throws Exception { Link usersLink = client.discoverUnique("users"); Link userLink = assertHasContentLinkWithRel("self", client.request(usersLink)); MockHttpServletResponse response = patchAndGet(userLink, "{\"lastname\" : null, \"address\" : { \"zipCode\" : \"ZIP\"}}", MediaType.APPLICATION_JSON); assertThat(JsonPath.read(response.getContentAsString(), "$.lastname"), is(nullValue())); assertThat(JsonPath.read(response.getContentAsString(), "$.address.zipCode"), is((Object) "ZIP")); }
From source file:net.node42.filter.SimpleTimeoutLoadLimitingFilterTest.java
@Test public void testTimeoutResponseReturned() throws Exception { final SimpleTimeoutLoadLimitingFilter target = new SimpleTimeoutLoadLimitingFilter(); final MockFilterConfig filterConfig = new MockFilterConfig(new MockServletContext()); // Nothing gets through, and it times out immediately... filterConfig.addInitParameter("request_count_concurrent_max", "0"); filterConfig.addInitParameter("request_timeout", "-1000"); target.init(filterConfig);/*from w w w . j a v a 2 s. c o m*/ final MockHttpServletRequest request = new MockHttpServletRequest(); final MockHttpServletResponse response = new MockHttpServletResponse(); response.setWriterAccessAllowed(true); final FilterChain filterChain = mock(FilterChain.class); runLoadLimitingFilter(target, request, response, filterChain); await().atMost(2, TimeUnit.SECONDS).untilAtomic(target.ACTIVE_REQUESTS, equalTo(0)); assertThat(response.getContentAsString()).isNotNull().isNotEmpty() .isEqualTo(SimpleTimeoutLoadLimitingFilter.CONTENT_TIMEOUT_DEFAULT); }
From source file:org.opennms.netmgt.ncs.rest.AbstractSpringJerseyRestTestCase.java
protected String sendRequest(MockHttpServletRequest request, int spectedStatus) throws Exception, UnsupportedEncodingException { MockHttpServletResponse response = createResponse(); dispatch(request, response);/*from ww w . ja va 2 s . c om*/ String xml = response.getContentAsString(); if (xml != null) { System.err.println(xml); } assertEquals(spectedStatus, response.getStatus()); return xml; }
From source file:org.pentaho.platform.dataaccess.datasource.wizard.csv.FileUploadServiceTest.java
@Test public void testUpload() throws Exception { PentahoSystemHelper.init();//from w ww . j a v a 2 s. c o m StandaloneSession pSession = new StandaloneSession("12345678901234567890"); PentahoSessionHolder.setSession(pSession); UUID uuid = UUIDUtil.getUUID(); String fileName = uuid.toString(); MockHttpSession session = new MockHttpSession(null, "12345678901234567890"); //$NON-NLS-1$ MockHttpServletRequest request = new MockHttpServletRequest("POST", ""); //$NON-NLS-1$ //$NON-NLS-2$ request.setSession(session); request.addParameter("file_name", fileName); //$NON-NLS-1$ request.addParameter("mark_temporary", "true"); //$NON-NLS-1$ //$NON-NLS-2$ request.setContentType("multipart/form-data; boundary=boundary"); //$NON-NLS-1$ StringBuffer content = new StringBuffer(); content.append("--boundary\r\n"); //$NON-NLS-1$ content.append( "Content-Disposition: form-data; name=uploadFormElement; filename=test_file.csv\r\nContent-Type: multipart/form-data\r\n\r\n"); //$NON-NLS-1$ content.append("REGIONC,NWEIGHT,HD65,xdate,Location,charlen,xfactor,Flag\r\n"); //$NON-NLS-1$ content.append("3,25677.96525,1231,1/1/10,Afghanistan,11,111.9090909,0\r\n"); //$NON-NLS-1$ content.append("4,24261.81026,1663,1/2/10,Albania,7,237.5714286,0\r\n"); //$NON-NLS-1$ content.append("2,31806.29502,5221,1/3/10,Algeria,7,745.8571429,1\r\n");//$NON-NLS-1$ content.append("4,22345.39749,5261,1/4/10,American Samoa,14,375.7857143,1\r\n");//$NON-NLS-1$ content.append("4,22345.39749,5261,1/4/10,American Samoa,14,375.7857143,1\r\n");//$NON-NLS-1$ content.append("3,25677.96525,1231,1/1/10,Afghanistan,11,111.9090909,0\r\n");//$NON-NLS-1$ content.append("4,24261.81026,1663,1/2/10,Albania,7,237.5714286,0\r\n");//$NON-NLS-1$ content.append("2,31806.29502,5221,1/3/10,Algeria,7,745.8571429,1\r\n");//$NON-NLS-1$ content.append("4,22345.39749,5261,1/4/10,American Samoa,14,375.7857143,1\r\n");//$NON-NLS-1$ content.append("--boundary--\r\n"); //$NON-NLS-1$ request.setContent(content.toString().getBytes()); UploadFileDebugServlet uploadServlet = new UploadFileDebugServlet(); MockHttpServletResponse response = new MockHttpServletResponse(); uploadServlet.service(request, response); response.getWriter().flush(); response.getWriter().close(); fileName = response.getContentAsString(); String path = PentahoSystem.getApplicationContext().getSolutionPath(TMP_FILE_PATH); String filenameWithPath = path + File.separatorChar + fileName; File file = new File(filenameWithPath); assertTrue(file.exists()); if (file.exists()) { file.delete(); } }
From source file:ch.rasc.extclassgenerator.ModelGeneratorBeanWithGenericValidationTest.java
@Test public void testWriteModelHttpServletRequestHttpServletResponseModelBeanOutputFormat() throws IOException { MockHttpServletResponse response = new MockHttpServletResponse(); ModelBean model = ModelGenerator.createModel(BeanWithGenericValidation.class, IncludeValidation.ALL); ModelGenerator.writeModel(new MockHttpServletRequest(), response, model, OutputFormat.EXTJS4); GeneratorTestUtil.compareExtJs4Code("BeanWithGenericValidation", response.getContentAsString(), false, false);//w w w . j a va 2 s . c om response = new MockHttpServletResponse(); ModelGenerator.writeModel(new MockHttpServletRequest(), response, model, OutputFormat.TOUCH2); GeneratorTestUtil.compareTouch2Code("BeanWithGenericValidation", response.getContentAsString(), false, false); }
From source file:org.springsource.restbucks.PaymentProcessIntegrationTest.java
/** * Triggers the payment of an {@link Order} by following the {@code payment} link and submitting a credit card number * to it. Verifies that we get a {@code 201 Created} and the response contains an {@code order} link. After the * payment has been triggered we fake a cancellation to make sure it is rejected with a {@code 404 Not found}. * /*from w w w .jav a 2s . c o m*/ * @param response * @return * @throws Exception */ private MockHttpServletResponse triggerPayment(MockHttpServletResponse response) throws Exception { String content = response.getContentAsString(); Link paymentLink = links.findLinkWithRel(PAYMENT_REL, content); log.info(String.format("Discovered payment link pointing to %s", paymentLink)); assertThat(paymentLink, not(nullValue())); log.info("Triggering payment"); ResultActions action = mvc.perform( put(paymentLink.getHref()).content("\"1234123412341234\"").contentType(MediaType.APPLICATION_JSON)); MockHttpServletResponse result = action.andExpect(status().isCreated()). // andExpect(linkWithRelIsPresent(ORDER_REL)). // andReturn().getResponse(); log.info("Payment triggered"); // Make sure we cannot cheat and cancel the order after it has been payed log.info("Faking a cancel request to make sure it's forbidden"); Link selfLink = links.findLinkWithRel(Link.REL_SELF, content); mvc.perform(get(selfLink.getHref() + "/cancel")).andExpect(status().isNotFound()); return result; }
From source file:nl.lumc.nanopub.store.api.NanopubControllerIntegrationTest.java
@DirtiesContext @Test//w w w.ja va2 s . c om public void testRetrieveNanopub() throws Exception { String expectedContent = getNanopubAsString("example_stored"); addNanopub(this.repository, EXAMPLE_STORED_NANOPUB_NAME); MockHttpServletRequest request = new MockHttpServletRequest(); request.setMethod("GET"); request.setRemotePort(8080); request.setParameter("key", "RAI9hDzzF6TSvwAOwwZkRB-hq_d9OzrURvwia0FtuIPHc"); request.setRequestURI("/nanopubs/RAI9hDzzF6TSvwAOwwZkRB-hq_d9OzrURvwia0FtuIPHc"); MockHttpServletResponse response = new MockHttpServletResponse(); Object handler = handlerMapping.getHandler(request).getHandler(); handlerAdapter.handle(request, response, handler); InputStream isExpected = new ByteArrayInputStream(expectedContent.getBytes()); Model modelExpected = Rio.parse(isExpected, "", RDFFormat.TRIG); String result = response.getContentAsString(); InputStream isActual = new ByteArrayInputStream(result.getBytes()); Model modelActual = Rio.parse(isActual, "", RDFFormat.TRIG); assertTrue(ModelUtil.equals(modelExpected, modelActual)); }
From source file:com.xemantic.tadedon.guice.servlet.mock.FakeServletContainerTest.java
/** * Tests {@link SessionIdReturningServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. * * @throws IOException if an input or output error is detected during request handling * @throws ServletException if container cannot handle request. *//*from ww w.j a va 2s. co m*/ @Test public void shouldPreserveSessionAcrossRequest() throws IOException, ServletException { // given servletContainer.newSession("42"); // magic number MockHttpServletRequest request1 = servletContainer.newRequest("GET", "/SessionIdReturningServlet"); MockHttpServletResponse response1 = new MockHttpServletResponse(); MockHttpServletRequest request2 = servletContainer.newRequest("GET", "/SessionIdReturningServlet"); MockHttpServletResponse response2 = new MockHttpServletResponse(); // when servletContainer.service(request1, response1); servletContainer.service(request2, response2); // then assertThat(response1.getContentAsString(), is("42")); assertThat((String) response1.getHeader("Foo"), is("foo")); assertThat(response2.getContentAsString(), is("42")); assertThat((String) response2.getHeader("Foo"), is("foo")); }