Example usage for org.springframework.mock.web MockHttpServletResponse getContentAsString

List of usage examples for org.springframework.mock.web MockHttpServletResponse getContentAsString

Introduction

In this page you can find the example usage for org.springframework.mock.web MockHttpServletResponse getContentAsString.

Prototype

public String getContentAsString() throws UnsupportedEncodingException 

Source Link

Document

Get the content of the response body as a String , using the charset specified for the response by the application, either through HttpServletResponse methods or through a charset parameter on the Content-Type .

Usage

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.ConceptController1_8Test.java

@Test
public void shouldGetAConceptByUuidInXML() throws Exception {
    MockHttpServletRequest req = request(RequestMethod.GET, getURI() + "/15f83cd6-64e9-4e06-a5f9-364d3b14a43d");
    req.addHeader("Accept", "application/xml");
    MockHttpServletResponse result = handle(req);

    String xml = result.getContentAsString();
    printXML(xml);// www . j  a  v  a 2s. co m

    Assert.assertEquals("15f83cd6-64e9-4e06-a5f9-364d3b14a43d", evaluateXPath(xml, "//uuid"));
    Assert.assertEquals("ASPIRIN", evaluateXPath(xml, "//name/name"));
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_8.ConceptController1_8Test.java

@Test
public void shouldReturnFullRepXML() throws Exception {
    MockHttpServletRequest request = newGetRequest(getURI() + "/" + getUuid(), new Parameter(
            RestConstants.REQUEST_PROPERTY_FOR_REPRESENTATION, RestConstants.REPRESENTATION_FULL));
    request.addHeader("Accept", "application/xml");

    MockHttpServletResponse result = handle(request);

    String xml = result.getContentAsString();
    printXML(xml);/* ww  w. j av  a 2  s .  c  o m*/
}

From source file:org.opennms.netmgt.ncs.rest.AbstractSpringJerseyRestTestCase.java

private String stringifyResponse(final MockHttpServletResponse response) {
    final StringBuilder string = new StringBuilder();
    try {//  w  ww  .  j  ava 2  s.  c  o  m
        string.append("HttpServletResponse[").append("status=").append(response.getStatus()).append(",content=")
                .append(response.getContentAsString()).append(",headers=[");
        boolean first = true;
        for (final Iterator<String> i = response.getHeaderNames().iterator(); i.hasNext(); first = false) {
            if (!first) {
                string.append(",");
            }
            final String name = i.next();
            string.append("name=").append(response.getHeader(name));
        }
        string.append("]").append("]");
    } catch (UnsupportedEncodingException e) {
        s_log.warn("Unable to get response content", e);
    }
    return string.toString();
}

From source file:org.geogig.geoserver.rest.GeoGigWebAPIIntegrationTest.java

@Test
public void testGeoPackageImport() throws Exception {

    URL url = getClass().getResource("places.gpkg");

    // create transaction
    final String beginTransactionUrl = BASE_URL + "/beginTransaction";

    Document dom = getAsDOM(beginTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);
    String transactionId = XMLUnit.newXpathEngine().evaluate("/response/Transaction/ID", dom);

    // import geopackage
    final String importUrl = BASE_URL + "/import?format=gpkg&message=Import%20GeoPackage&transactionId="
            + transactionId;/*from   w w w .  j  a  v  a 2s  . c  o  m*/
    final String endTransactionUrl = BASE_URL + "/endTransaction?transactionId=" + transactionId;

    // construct a multipart request with the fileUpload
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    File f = new File(url.getFile());
    builder.addBinaryBody("fileUpload", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM,
            f.getName());

    HttpEntity multipart = builder.build();

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    multipart.writeTo(outputStream);
    MockHttpServletResponse response = postAsServletResponse(importUrl, outputStream.toByteArray(),
            multipart.getContentType().getValue());

    assertEquals(200, response.getStatus());

    dom = dom(new ByteArrayInputStream(response.getContentAsString().getBytes()), true);
    String taskId = XMLUnit.newXpathEngine().evaluate("/task/id", dom);
    final String taskUrl = "/geogig/tasks/" + taskId + ".xml";
    while ("RUNNING".equals(XMLUnit.newXpathEngine().evaluate("/task/status", dom))) {
        Thread.sleep(100);
        dom = getAsDOM(taskUrl);
    }
    assertXpathEvaluatesTo("FINISHED", "/task/status", dom);
    String commitId = XMLUnit.newXpathEngine().evaluate("//commit/id", dom);

    // close transaction
    dom = getAsDOM(endTransactionUrl);
    assertXpathEvaluatesTo("true", "/response/success", dom);

    // verify the repo contains the import
    Repository repository = geogigData.getGeogig().getRepository();
    RevCommit head = repository.getCommit(repository.getHead().get().getObjectId());
    assertEquals(commitId, head.getId().toString());
    assertEquals("Import GeoPackage", head.getMessage());
}

From source file:ar.com.fdvs.dj.test.HtmlExportReportTest.java

@Override
public void testReport() throws Exception {
    dr = buildReport();/*from   w  w w  .  jav a 2 s . c  o m*/

    /**
     * Get a JRDataSource implementation
     */
    JRDataSource ds = getDataSource();

    /**
     * Creates the JasperReport object, we pass as a Parameter
     * the DynamicReport, a new ClassicLayoutManager instance (this
     * one does the magic) and the JRDataSource
     */
    jr = DynamicJasperHelper.generateJasperReport(dr, getLayoutManager(), params);

    /**
     * Creates the JasperPrint object, we pass as a Parameter
     * the JasperReport object, and the JRDataSource
     */
    log.debug("Filling the report");
    if (ds != null)
        jp = JasperFillManager.fillReport(jr, params, ds);
    else
        jp = JasperFillManager.fillReport(jr, params);

    log.debug("Filling done!");
    log.debug("Exporting the report (pdf, xls, etc)");

    //Exporting directly to a Response
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    DJServletHelper.exportToHtml(request, response, "/images", jp, null);

    //Exporting and returning an InputStream
    MockHttpServletRequest request2 = new MockHttpServletRequest();
    DJServletHelper.setPageTreshold(0);
    InputStream is = DJServletHelper.exportToHtml(request2, "/images", jp, null);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ReportWriter.copyStreams(is, out);

    //Comparing both generated html. They should be the same
    assertEquals(response.getContentAsString(), new String(out.toByteArray()));

    log.debug("test finished");

}

From source file:com.liferay.frontend.js.loader.modules.extender.internal.JSLoaderModulesServletTest.java

@Test
public void testBasicOutput() throws Exception {
    JSLoaderModulesServlet jsLoaderModulesServlet = buildJSLoaderModulesServlet();

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    jsLoaderModulesServlet.service(mockHttpServletRequest, mockHttpServletResponse);

    Assert.assertNotNull(mockHttpServletResponse.getContentAsString());
    Assert.assertEquals(Details.CONTENT_TYPE, mockHttpServletResponse.getContentType());
}

From source file:org.xmlactions.web.PagerFilter.java

public void doFilter(ServletRequest req, ServletResponse rsp, FilterChain chain)
        throws IOException, ServletException {
    logger.debug("PagerFilter.doFilter");

    MockHttpServletResponse mockResponse = new MockHttpServletResponse();
    PagerServlet pagerServlet = new PagerServlet();
    try {//from w  ww .  j av  a 2  s .com
        pagerServlet.init(filterConfig);
        if (req instanceof HttpServletRequest && rsp instanceof HttpServletResponse) {
            pagerServlet.setupExecContext((HttpServletRequest) req, (HttpServletResponse) rsp);
        }
        chain.doFilter(req, mockResponse);
        RequestExecContext.remove();
    } catch (FileUploadException e) {
        throw new IllegalArgumentException(e.getMessage(), e);
    } finally {
        String page = mockResponse.getContentAsString();
        pagerServlet.processPageFromFilter(req, rsp, page);
    }
}

From source file:ch.silviowangler.dox.web.DocumentControllerTest.java

@Test
public void getTheDocumentContent()
        throws DocumentNotFoundException, DocumentNotInStoreException, UnsupportedEncodingException {

    MockHttpServletResponse response = new MockHttpServletResponse();

    PhysicalDocument physicalDocument = new PhysicalDocument(new DocumentClass("hhh"), "hello".getBytes(), null,
            "hello.txt");
    physicalDocument.setMimeType("aaa/bbb");
    when(documentService.findPhysicalDocument(1L)).thenReturn(physicalDocument);

    controller.getDocument(1L, response);

    assertThat(response.getStatus(), is(SC_OK));
    assertThat(response.getContentAsString(), is("hello"));
    assertThat(response.getContentType(), is("aaa/bbb"));
    assertThat(response.getHeader("Content-Disposition"), is("inline; filename=\"hello.txt\""));
}

From source file:com.liferay.frontend.js.loader.modules.extender.internal.JSLoaderModulesServletTest.java

@Test
public void testSingleModuleOutput() throws Exception {
    JSLoaderModulesServlet jsLoaderModulesServlet = buildJSLoaderModulesServlet(
            Collections.<String, Object>singletonMap("applyVersioning", Boolean.TRUE));

    JSLoaderModulesTracker jsLoaderModulesTracker = jsLoaderModulesServlet.getJSLoaderModulesTracker();

    ServiceReference<ServletContext> serviceReference = buildServiceReference("test", new Version("1.0.0"),
            true, 0, getResource("dependencies/config1.js"));

    jsLoaderModulesTracker.addingService(serviceReference);

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    jsLoaderModulesServlet.service(mockHttpServletRequest, mockHttpServletResponse);

    String content = mockHttpServletResponse.getContentAsString();

    content = content.replace('"', '\'');

    assertContains("'test': '/test-1.0.0'", content);
    assertContains("'test@1.0.0': '/test-1.0.0'", content);
    assertContains("'test/some.es':{'dependencies':['exports','test@1.0.0/other.es']}", content);
    assertContains("'test/other.es':{'dependencies':['exports']}", content);
    assertContains("'test@1.0.0/some.es':{'dependencies':['exports'," + "'test@1.0.0/other.es']}", content);
    assertContains("'test@1.0.0/other.es':{'dependencies':['exports']}", content);
}

From source file:com.liferay.frontend.js.loader.modules.extender.internal.JSLoaderModulesServletTest.java

@Test
public void testSingleModuleOutputIdempotent() throws Exception {
    JSLoaderModulesServlet jsLoaderModulesServlet = buildJSLoaderModulesServlet(
            Collections.<String, Object>singletonMap("applyVersioning", Boolean.TRUE));

    JSLoaderModulesTracker jsLoaderModulesTracker = jsLoaderModulesServlet.getJSLoaderModulesTracker();

    ServiceReference<ServletContext> serviceReference = buildServiceReference("test", new Version("1.0.0"),
            true, 0, getResource("dependencies/config1.js"));

    jsLoaderModulesTracker.addingService(serviceReference);
    jsLoaderModulesTracker.addingService(serviceReference);

    MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest();
    MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();

    jsLoaderModulesServlet.service(mockHttpServletRequest, mockHttpServletResponse);

    String content = mockHttpServletResponse.getContentAsString();

    content = content.replace('"', '\'');

    assertOccurrences("'test': '/test-1.0.0'", content, 1);
    assertOccurrences("'test@1.0.0': '/test-1.0.0'", content, 1);
    assertOccurrences("'test/some.es':{'dependencies':['exports','test@1.0.0/other.es']}", content, 1);
    assertOccurrences("'test/other.es':{'dependencies':['exports']}", content, 1);
    assertOccurrences("'test@1.0.0/some.es':{'dependencies':['exports'," + "'test@1.0.0/other.es']}", content,
            1);/*from   w w w  .  j  av  a2s. c  om*/
    assertOccurrences("'test@1.0.0/other.es':{'dependencies':['exports']}", content, 1);
}