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.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testXmlFormatUrl() throws Exception {
    final Element sampleMetadataXml = getSampleMetadataXml();
    final Element element = Xml.selectElement(sampleMetadataXml, "*//gmd:MD_Format",
            Lists.newArrayList(ISO19139Namespaces.GMD));
    final String url = "http://FormatIntegrationTest.com:8080";
    final MockXmlRequest mockRequest = new MockXmlRequest("FormatIntegrationTest.com", 8080, "http");
    mockRequest.when(url).thenReturn(element);

    requestFactory.registerRequest(true, mockRequest.getHost(), mockRequest.getPort(),
            mockRequest.getProtocol(), mockRequest);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();//from ww w.  jav  a  2  s  . c o m
    MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.execXml("eng", "xml", "partial_view", null, url, "iso19139", _100, null,
            new ServletWebRequest(request, response));

    final String view = response.getContentAsString();
    assertTrue(view.contains("KML (1)"));
    assertTrue(view.contains("Format"));
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testXmlFormatRelativeUrl() throws Exception {
    final Element sampleMetadataXml = getSampleMetadataXml();
    final Element element = Xml.selectElement(sampleMetadataXml, "*//gmd:MD_Format",
            Lists.newArrayList(ISO19139Namespaces.GMD));
    final String url = "http://localhost:8080/srv/eng/request";
    final MockXmlRequest mockRequest = new MockXmlRequest("localhost", 8080, "http");
    mockRequest.setAddress("/srv/eng/request");
    mockRequest.when(url).thenReturn(element);

    requestFactory.registerRequest(true, mockRequest.getHost(), mockRequest.getPort(),
            mockRequest.getProtocol(), mockRequest);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();/*from ww w .  j  a v  a  2s.  co m*/
    MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.execXml("eng", "xml", "partial_view", null, "request", "iso19139", _100, null,
            new ServletWebRequest(request, response));

    final String view = response.getContentAsString();
    assertTrue(view.contains("KML (1)"));
    assertTrue(view.contains("Format"));
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testXmlFormatUpload() throws Exception {
    final Element sampleMetadataXml = getSampleMetadataXml();
    final Element element = Xml.selectElement(sampleMetadataXml, "*//gmd:MD_Format",
            Lists.newArrayList(ISO19139Namespaces.GMD));

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();//from   ww w.j a va2  s.c  o  m
    MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.execXml("eng", "xml", "partial_view", Xml.getString(element), null, "iso19139", _100, null,
            new ServletWebRequest(request, response));

    final String view = response.getContentAsString();
    assertTrue(view.contains("KML (1)"));
    assertTrue(view.contains("Format"));
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testExecXslt() throws Exception {
    final ServletContext context = _applicationContext.getBean(ServletContext.class);
    MockHttpServletRequest request = new MockHttpServletRequest(context, "GET",
            "http://localhost:8080/geonetwork/srv/eng/md.formatter");
    request.getSession();//from   ww w  . j av a2s.  com
    request.setPathInfo("/eng/md.formatter");

    final String applicationContextAttributeKey = "srv";
    request.getServletContext().setAttribute(applicationContextAttributeKey, _applicationContext);
    ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);

    RequestContextHolder.setRequestAttributes(requestAttributes);
    final String formatterName = "xsl-test-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.xsl");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    Files.deleteIfExists(formatterDir.resolve("functions.xsl"));
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve("functions.xsl"), formatterDir, true);
    JeevesDelegatingFilterProxy.setApplicationContextAttributeKey(applicationContextAttributeKey);

    final MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
            new ServletWebRequest(request, response));
    final String viewXml = response.getContentAsString();
    final Element view = Xml.loadString(viewXml, false);
    assertEqualsText("fromFunction", view, "*//p");
    assertEqualsText("Title", view, "*//div[@class='tr']");
}

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

public void testReport2() throws Exception {
    dr = buildReport();/*from   w w w  . j  a v a2s .c om*/

    /**
     * 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);

    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", dr, getLayoutManager(), getDataSource(),
            new HashMap(), null);

    //Exporting and returning an InputStream
    MockHttpServletRequest request2 = new MockHttpServletRequest();
    InputStream is = DJServletHelper.exportToHtml(request2, "/images", dr, getLayoutManager(), getDataSource(),
            new HashMap(), 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:it.geosolutions.httpproxy.service.ProxyServiceDefaultTest.java

/**
 * Test IProxyService execute as HTTP GET
 *///w  w w.j  ava  2  s .c  o m
@Test
public void testExecuteGet() {
    try {
        // Generate mocked request and response
        MockHttpServletRequest mockRequest = new MockHttpServletRequest("GET", "/proxy/");
        mockRequest.addParameter("url", TEST_URL);
        MockHttpServletResponse mockResponse = new MockHttpServletResponse();

        // Call proxy execute
        proxy.execute(mockRequest, mockResponse);

        // Assert the response
        assertNotNull(mockResponse);
        assertEquals(mockResponse.getStatus(), HttpStatus.SC_OK);
        assertNotNull(mockResponse.getOutputStream());
        assertNotNull(mockResponse.getContentType());
        assertTrue(mockResponse.getContentType().contains("application/vnd.ogc.wms_xml"));

        LOGGER.info("Success proxy GET in '" + TEST_URL + "'");
        LOGGER.info("************************ Response ************************");
        LOGGER.info(mockResponse.getContentAsString());
        LOGGER.info("********************** EoF Response **********************");

    } catch (Exception e) {
        fail("Exception executing proxy-->\t" + e.getLocalizedMessage());
    }
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void test_refresh_token_after_key_rotation() throws Exception {
    createClientAndUserInRandomZone();/* ww w.  j av a  2s.  c o m*/
    zone.getConfig().getTokenPolicy().setActiveKeyId("key2");
    zone = identityZoneProvisioning.update(zone);

    MockHttpServletResponse refreshResponse = useRefreshToken(refreshToken, client.getClientId(), SECRET,
            getZoneHostUrl(zone));
    assertEquals(HttpStatus.SC_OK, refreshResponse.getStatus());
    validateAccessTokenExists(refreshResponse.getContentAsString());

    keys.put("key2", signingKey2);
    keys.put("key3", signingKey3);
    zone.getConfig().getTokenPolicy().setKeys(keys);
    zone.getConfig().getTokenPolicy().setActiveKeyId("key3");
    zone = identityZoneProvisioning.update(zone);

    MockHttpServletResponse refreshResponse2 = useRefreshToken(refreshToken, client.getClientId(), SECRET,
            getZoneHostUrl(zone));
    assertEquals(HttpStatus.SC_OK, refreshResponse2.getStatus());
    validateAccessTokenExists(refreshResponse2.getContentAsString());

    keys.remove("key1");
    zone.getConfig().getTokenPolicy().setKeys(keys);
    zone = identityZoneProvisioning.update(zone);

    MockHttpServletResponse refreshResponse3 = useRefreshToken(refreshToken, client.getClientId(), SECRET,
            getZoneHostUrl(zone));
    assertEquals(HttpStatus.SC_UNAUTHORIZED, refreshResponse3.getStatus());
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testXmlFormatUploadWithXpath() throws Exception {
    final URL resource = AbstractCoreIntegrationTest.class
            .getResource("kernel/valid-getrecordbyidresponse.iso19139.xml");
    final Element sampleMetadataXml = Xml.loadStream(resource.openStream());
    final Element element = Xml.selectElement(sampleMetadataXml, "*//csw:GetRecordByIdResponse",
            Lists.newArrayList(Namespace.getNamespace("csw", "http://www.opengis.net/cat/csw/2.0.2")));

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.getSession();/*from  www. j a va 2 s.com*/
    MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.execXml("eng", "xml", "partial_view", Xml.getString(sampleMetadataXml), null, "iso19139",
            _100, "gmd:MD_Metadata", new ServletWebRequest(request, response));

    final String view = response.getContentAsString();
    assertTrue(view.contains("KML (1)"));
}

From source file:org.cloudfoundry.identity.uaa.mock.token.RefreshTokenMockMvcTests.java

@Test
void refreshTokenGrantType_doesNotReturnIdToken_toNonOpenIdClients() throws Exception {
    client = setUpClients("nonopenidclient", "", "scim.me", "password,refresh_token", true);
    user = setUpUser("joe-user", "", OriginKeys.UAA, "uaa");
    String refreshToken = getJwtRefreshToken(client.getClientId(), SECRET, user.getUserName(), SECRET,
            "localhost");

    MockHttpServletResponse refreshResponse = useRefreshToken(refreshToken, client.getClientId(), SECRET,
            "localhost");

    assertEquals(HttpStatus.SC_OK, refreshResponse.getStatus());
    CompositeToken compositeToken = JsonUtils.readValue(refreshResponse.getContentAsString(),
            CompositeToken.class);
    assertNull(compositeToken.getIdTokenValue());
}

From source file:edu.internet2.middleware.shibboleth.idp.system.conf1.SAML1ArtifactResolutionTest.java

public void testArtifactResolution() throws Exception {
    String relyingPartyId = "urn:example.org:sp1";
    SAMLArtifactMapEntry artifactEntry = stageArtifact(relyingPartyId);
    String soapMessage = buildRequestMessage(relyingPartyId, artifactEntry.getArtifact());

    MockHttpServletRequest servletRequest = new MockHttpServletRequest();
    servletRequest.setMethod("POST");
    servletRequest.setPathInfo("/saml1/SOAP/ArtifactResolution");
    servletRequest.setContent(soapMessage.getBytes());

    MockHttpServletResponse servletResponse = new MockHttpServletResponse();

    ProfileHandlerManager handlerManager = (ProfileHandlerManager) getApplicationContext()
            .getBean("shibboleth.HandlerManager");
    ProfileHandler handler = handlerManager.getProfileHandler(servletRequest);
    assertNotNull(handler);/*from w w w. jav a2 s  . co m*/

    // Process request
    HTTPInTransport profileRequest = new HttpServletRequestAdapter(servletRequest);
    HTTPOutTransport profileResponse = new HttpServletResponseAdapter(servletResponse, false);
    handler.processRequest(profileRequest, profileResponse);

    String response = servletResponse.getContentAsString();
    assertTrue(response.contains("saml1p:Success"));
    assertTrue(response.contains("saml1:Assertion"));
}