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:com.gu.management.manifest.ManifestReportingControllerTest.java

@Test
public void shouldAcceptMultipleManifests() throws Exception {
    Manifest secondManifest = Mockito.mock(Manifest.class);
    when(secondManifest.getRevisionNumber()).thenReturn(42L);
    when(manifest.getRevisionNumber()).thenReturn(666L);
    when(secondManifest.getManifestInformation()).thenReturn("View Manifest Information");

    MockHttpServletResponse responseMock = new MockHttpServletResponse();

    ManifestReportingServlet servlet = new ManifestReportingServlet(Arrays.asList(manifest, secondManifest));
    servlet.doGet(null, responseMock);/*  w  w w.ja va2  s. com*/

    assertThat(responseMock.getContentType(), equalTo("text/plain"));
    assertThat(responseMock.getContentAsString(),
            equalTo("Code Manifest Information\nView Manifest Information\n"));

    verify(manifest).reload();

}

From source file:at.molindo.notify.servlet.NotifyFilterTest.java

@Test
public void pull() throws Exception {
    new MockTest() {

        NotifyFilterBean filter;/*from  w  w w .  j  a  va  2 s . com*/
        FilterChain mockFilterChain;
        MockFilterConfig config;

        @Override
        @SuppressWarnings(value = "NP_NULL_PARAM_DEREF_ALL_TARGETS_DANGEROUS", justification = "mocks accept null")
        protected void setup(EasyMockContext context) throws Exception {
            filter = new NotifyFilterBean();
            mockFilterChain = new MockFilterChain();
            config = new MockFilterConfig();
            config.addInitParameter(NotifyFilterBean.PARAMTER_BASE_URL, "http://www.example.com/");

            context.create(IPullChannel.class);

            expect(context.get(IPullChannel.class).getId()).andReturn(CHANNELID).anyTimes();
            expect(context.get(IPullChannel.class).getNotificationTypes()).andReturn(Type.TYPES_ALL).anyTimes();
            expect(context.get(IPullChannel.class).pull(eq(USERID),
                    anyObject(ConfigurableChannelPreferences.class))).andReturn(BODY);
            expect(context.get(IPullChannel.class).newDefaultPreferences())
                    .andReturn(new ConfigurableChannelPreferences());

            eq(USERID);
            reportMatcher(new IArgumentMatcher() {

                @Override
                public boolean matches(Object argument) {
                    ConfigurableChannelPreferences cPrefs = (ConfigurableChannelPreferences) argument;
                    return SECRET.equals(cPrefs.getParams().get(AbstractPullChannel.SECRET));
                }

                @Override
                public void appendTo(StringBuffer buffer) {
                    buffer.append("secret not included");
                }
            });
            expect(context.get(IPullChannel.class).isAuthorized(null, null)).andReturn(true);

            expect(context.get(IPullChannel.class).isConfigured(anyObject(Params.class))).andReturn(true);

            // toPullPath
            expect(context.get(IPullChannel.class).newDefaultPreferences())
                    .andReturn(new PushChannelPreferences());
        }

        @Override
        protected void test(EasyMockContext context) throws Exception {
            filter.setChannels(CollectionUtils.set(context.get(IPullChannel.class)));
            filter.init(config);

            MockHttpServletRequest request = new MockHttpServletRequest("GET",
                    "/notify/" + NotifyFilterBean.DEFAULT_PULL_PREFIX + "/" + CHANNELID + "/" + USERID);

            request.setServletPath("/notify");
            request.setParameter(AbstractPullChannel.SECRET.getName(), SECRET);

            MockHttpServletResponse response = new MockHttpServletResponse();

            filter.doFilter(request, response, mockFilterChain);

            assertEquals(200, response.getStatus());
            assertEquals(BODY, response.getContentAsString());

            Confirmation confirmation = new Confirmation(new Notification());
            assertEquals("http://www.example.com/notify/confirm/" + confirmation.getKey(),
                    filter.toConfirmPath(confirmation));

            assertEquals("http://www.example.com/notify/pull/test-channel/test-user",
                    filter.toPullPath(CHANNELID, USERID, new Params()));
        }

    }.run();
}

From source file:nl.lumc.nanopub.store.api.NanopubControllerIntegrationTest.java

@DirtiesContext
@Test/*from   www. j a va2 s. c  om*/
public void testListNanopubs() throws Exception {
    addNanopub(this.repository, EXAMPLE_STORED_NANOPUB_NAME);

    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/nanopubs");

    MockHttpServletResponse response = new MockHttpServletResponse();

    Object handler = handlerMapping.getHandler(request).getHandler();
    handlerAdapter.handle(request, response, handler);

    assertEquals("[\"" + EXAMPLE_STORED_URI + "\"]", response.getContentAsString());
}

From source file:org.springsource.restbucks.engine.web.EngineControllerIntegrationTests.java

@Test
public void customControllerReturnsDefaultMediaType() throws Exception {

    MockHttpServletResponse response = mvc.perform(get("/")).//
            andDo(MockMvcResultHandlers.print()).//
            andExpect(linkWithRelIsPresent(ENGINE_REL)). //
            andReturn().getResponse();//from  w  w w.  j a v  a  2s.com

    LinkDiscoverer discoverer = links.getLinkDiscovererFor(response.getContentType());
    Link link = discoverer.findLinkWithRel(ENGINE_REL, response.getContentAsString());

    mvc.perform(get(link.getHref())). //
            andExpect(content().contentTypeCompatibleWith(MediaTypes.HAL_JSON));
}

From source file:com.github.jrialland.ajpclient.servlet.TestServletProxy.java

@Test
public void doTestPost() throws Exception {

    final String cookie = slurp(TestServletProxy.class.getResource("cookie.txt").openStream());

    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("POST");
    request.setRequestURI("/test_post");
    request.addHeader("Host", "test.samplesite.com");

    request.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    request.addHeader("Accept-Encoding", "gzip, deflate");
    request.addHeader("Accept-Language", "fr,fr-fr;q=0.8,en-us;q=0.5,en;q=0.3");
    request.addHeader("Connection", "keep-alive");
    request.addHeader("Cookie", cookie);

    request.addHeader("Referer",
            "https://test.samplesite.com/fr/group/control_panel/manage?p_auth=1bo6fC5N&p_p_id=dbSettingsPortlet_WAR_eloportalservicesportlet&p_p_lifecycle=1&p_p_state=maximized&p_p_mode=view&doAsGroupId=10157&refererPlid=10160&_dbSettingsPortlet_WAR_eloportalservicesportlet_action=showUpdate&_dbSettingsPortlet_WAR_eloportalservicesportlet_client=TMG");
    request.addHeader("User-Agent",
            "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:32.0) Gecko/20100101 Firefox/32.0");
    request.addHeader("Content-Type", "application/x-www-form-urlencoded");
    request.setContent(/*from  ww w.  j  a v a 2 s  .c  o m*/
            "_dbSettingsPortlet_WAR_eloportalservicesportlet_client=xxx&_dbSettingsPortlet_WAR_eloportalservicesportlet_url=jdbc%3Ajtds%3Asqlserver%3A%2F%2Fxxx.xxx.xxx.xxx%2FBD_FR533&_dbSettingsPortlet_WAR_eloportalservicesportlet_user=sa&_dbSettingsPortlet_WAR_eloportalservicesportlet_password=123abcd+&_dbSettingsPortlet_WAR_eloportalservicesportlet_poolmax=5"
                    .getBytes());

    final MockHttpServletResponse response = new MockHttpServletResponse();
    AjpServletProxy.forHost("localhost", getPort()).forward(request, response);
    if (response.getStatus() != 200) {
        System.out.println(response.getContentAsString());
        Assert.fail(response.getErrorMessage());
    }

    Assert.assertEquals("5", response.getContentAsString());
}

From source file:com.github.jrialland.ajpclient.servlet.TestServletProxy.java

@Test
public void doTestGet() throws Exception {
    final MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod("GET");
    request.setRequestURI("/dizzy.mp4");
    final MockHttpServletResponse response = new MockHttpServletResponse();
    AjpServletProxy.forHost("localhost", getPort()).forward(request, response, 10, TimeUnit.SECONDS, true);
    if (response.getStatus() != 200) {
        System.out.println(response.getContentAsString());
        Assert.fail(response.getErrorMessage());
    }/*from   w w w  .j ava  2s  . c  o m*/
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriterTest.java

private String writeToResponse(Object value) throws IOException {
    MockHttpServletResponse response = new MockHttpServletResponse();
    ServletResponseResultWriter writer = new ServletResponseResultWriter(response, null);
    writer.write(value);/*from   ww w .  j a va 2s  . c  o m*/
    return response.getContentAsString();
}

From source file:org.springsource.restbucks.training.payment.web.PaymentProcessIntegrationTest.java

/**
 * Cancels the order by issuing a delete request. Verifies the resource being inavailable after that.
 * /*w  ww . j a v  a  2  s. co m*/
 * @param response the response that retrieved an order resource
 * @throws Exception
 */
private void cancelOrder(MockHttpServletResponse response) throws Exception {

    String content = response.getContentAsString();

    LinkDiscoverer discoverer = getDiscovererFor(response);
    Link selfLink = discoverer.findLinkWithRel(Link.REL_SELF, content);
    Link cancellationLink = discoverer.findLinkWithRel(CANCEL_REL, content);

    mvc.perform(delete(cancellationLink.getHref())).andExpect(status().isNoContent());
    mvc.perform(get(selfLink.getHref())).andExpect(status().isNotFound());
}

From source file:org.springsource.restbucks.training.payment.web.PaymentProcessIntegrationTest.java

/**
 * Follows the {@code orders} link returns the {@link Order}s found.
 * /*from   w ww .  j  a  v  a  2  s  . co  m*/
 * @param source
 * @return
 * @throws Exception
 */
private MockHttpServletResponse discoverOrdersResource(MockHttpServletResponse source) throws Exception {

    String content = source.getContentAsString();
    Link ordersLink = getDiscovererFor(source).findLinkWithRel(ORDERS_REL, content);

    log.info("Root resource returned: " + content);
    log.info(String.format("Found orders link pointing to %s Following", ordersLink));

    MockHttpServletResponse response = mvc.perform(get(ordersLink.expand().getHref())). //
            andExpect(status().isOk()). //
            andReturn().getResponse();

    log.info("Found orders: " + response.getContentAsString());
    return response;
}

From source file:org.springsource.restbucks.training.payment.web.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 . ja  v  a  2 s . co  m*/
 * @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 = getDiscovererFor(source).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(Link.REL_SELF)). //
            andExpect(linkWithRelIsPresent(CANCEL_REL)). //
            andExpect(linkWithRelIsPresent(UPDATE_REL)). //
            andExpect(linkWithRelIsPresent(PAYMENT_REL)).//
            andReturn().getResponse();
}