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

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

Introduction

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

Prototype

@Override
@Nullable
public String getHeader(String name) 

Source Link

Document

Return the primary value for the given header as a String, if any.

Usage

From source file:org.geowebcache.service.wmts.WMTSRestTest.java

@Test
public void testGetTileWithStyle() throws Exception {
    MockHttpServletRequest req = new MockHttpServletRequest();
    req.setPathInfo("geowebcache/service/wmts/rest/mockLayer/style-a/EPSG:4326/EPSG:4326:0/0/0");
    req.addParameter("format", "image/png");

    MockHttpServletResponse resp = dispatch(req);

    assertEquals(200, resp.getStatus());
    assertEquals("image/png", resp.getContentType());
    assertEquals("EPSG:4326", resp.getHeader("geowebcache-crs"));
    assertArrayEquals(getSampleTileContent().getContents(), resp.getContentAsByteArray());
}

From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java

/**
 * Same as {@link #doServeResourceCachedContentValidationMethodTest()}, but simulate browser
 * sending If-None-Match header with mismatched etag. Response is 200 with content and new etag
 * //from   ww  w .  j  a va  2  s  .c  o  m
 * @throws PortletException
 * @throws IOException
 * @throws PortletContainerException
 */
@Test
public void doServeResourceCachedContentValidationMethodIfNoneMatchInvalidTest()
        throws PortletException, IOException, PortletContainerException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.addHeader("If-None-Match", "123456");
    MockHttpServletResponse response = new MockHttpServletResponse();
    Date now = new Date();
    CacheControlImpl cacheControl = new CacheControlImpl();
    cacheControl.setUseCachedContent(true);
    cacheControl.setExpirationTime(300);
    cacheControl.setETag("123457");
    CachedPortletData cachedPortletData = new CachedPortletData();
    cachedPortletData.setContentType("application/json");
    byte[] content = "{ \"hello\": \"world\" }".getBytes();
    cachedPortletData.setByteData(content);
    cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime());
    cachedPortletData.setEtag("123457");
    cachedPortletData.setTimeStored(now);

    setupPortletExecutionMocks(request);

    when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response))
            .thenReturn(cacheControl);
    when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request))
            .thenReturn(cachedPortletData);

    portletRenderer.doServeResource(portletWindowId, request, response);
    // verify content matches what was in cache (no array support in Assert.assertEquals, check byte for byte)
    byte[] fromResponse = response.getContentAsByteArray();
    Assert.assertEquals(content.length, fromResponse.length);
    for (int i = 0; i < content.length; i++) {
        Assert.assertEquals(content[i], fromResponse[i]);
    }
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals("123457", response.getHeader("ETag"));
    // verify we enter the first branch and never execute portletContainer#doServeResource
    verify(portletContainer, never()).doServeResource(isA(PortletWindow.class),
            isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class));
    // verify we never enter the other branch of the "should render cached output" if statement
    verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class));
}

From source file:org.jasig.portal.portlet.rendering.PortletRendererImplTest.java

/**
 * Verify headers stored in cache are replayed on the response for cached doServeResource content.
 * //w ww .ja v a 2 s .  com
 * @throws PortletContainerException 
 * @throws IOException 
 * @throws PortletException 
 */
@Test
public void doServeResourceCachedContentReplayHeadersTest()
        throws PortletException, IOException, PortletContainerException {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    Date now = new Date();
    CacheControlImpl cacheControl = new CacheControlImpl();
    cacheControl.setUseCachedContent(true);
    cacheControl.setExpirationTime(300);
    CachedPortletData cachedPortletData = new CachedPortletData();
    cachedPortletData.setContentType("application/json");
    byte[] content = "{ \"hello\": \"world\" }".getBytes();
    Map<String, List<Object>> headers = ImmutableMap.<String, List<Object>>of("header1",
            Arrays.<Object>asList("value1"), "header2", Arrays.<Object>asList("value2", "value3"));

    cachedPortletData.setHeaders(headers);
    cachedPortletData.setByteData(content);
    cachedPortletData.setExpirationTimeSeconds(cacheControl.getExpirationTime());
    cachedPortletData.setTimeStored(now);

    setupPortletExecutionMocks(request);

    when(portletCacheControlService.getPortletResourceCacheControl(portletWindowId, request, response))
            .thenReturn(cacheControl);
    when(portletCacheControlService.getCachedPortletResourceOutput(portletWindowId, request))
            .thenReturn(cachedPortletData);

    portletRenderer.doServeResource(portletWindowId, request, response);
    // verify content matches what was in cache (no array support in Assert.assertEquals, check byte for byte)
    byte[] fromResponse = response.getContentAsByteArray();
    Assert.assertEquals(content.length, fromResponse.length);
    for (int i = 0; i < content.length; i++) {
        Assert.assertEquals(content[i], fromResponse[i]);
    }
    Assert.assertEquals("value1", response.getHeader("header1"));
    Assert.assertEquals(Arrays.asList(new String[] { "value2", "value3" }), response.getHeaders("header2"));
    // verify we enter the first branch and never execute portletContainer#doServeResource
    verify(portletContainer, never()).doServeResource(isA(PortletWindow.class),
            isA(PortletHttpServletRequestWrapper.class), isA(PortletHttpServletResponseWrapper.class));
    // verify we never enter the other branch of the "should render cached output" if statement
    verify(portletCacheControlService, never()).shouldOutputBeCached(isA(CacheControl.class));
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.openmrs1_9.FormResourceController1_9Test.java

@Test
public void shouldRetrieveResourceValueAsFile() throws Exception {
    // Get the clobData for the resource
    FormResource resource = formService.getFormResourceByUuid(getUuid());
    ClobDatatypeStorage clobData = datatypeService.getClobDatatypeStorageByUuid(resource.getValueReference());

    MockHttpServletResponse response = handle(newGetRequest(getURI() + "/" + getUuid() + "/value"));

    String expected = "attachment;filename=\"" + resource.getName() + "\"";
    Assert.assertTrue(StringUtils.equals((String) response.getHeader("Content-Disposition"), expected));
    Assert.assertEquals(clobData.getValue(), response.getContentAsString());
}

From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java

protected MockHttpServletResponse sendPost(String url, String xml, int statusCode,
        final String expectedUrlSuffix) throws Exception {
    LOG.debug("POST {}, expected status code = {}, expected URL suffix = {}", url, statusCode,
            expectedUrlSuffix);/*  w ww .  ja v  a  2s. c o m*/
    final MockHttpServletResponse response = sendData(POST, MediaType.APPLICATION_XML, url, xml, statusCode);
    if (expectedUrlSuffix != null) {
        final Object header = response.getHeader("Location");
        assertNotNull("Location header is null", header);
        final String location = URLDecoder.decode(header.toString(), "UTF-8");
        final String decodedExpectedUrlSuffix = URLDecoder.decode(expectedUrlSuffix, "UTF-8");
        assertTrue("location '" + location + "' should end with '" + decodedExpectedUrlSuffix + "'",
                location.endsWith(decodedExpectedUrlSuffix));
    }
    return response;
}

From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java

/**
 * @param url//from  www.  j a va 2  s  .  c  o m
 * @param formData
 * @param statusCode
 * @param expectedUrlSuffix
 */
protected MockHttpServletResponse sendPut(String url, String formData, int statusCode,
        final String expectedUrlSuffix) throws Exception {
    LOG.debug("PUT {}, formData = {}, expected status code = {}, expected URL suffix = {}", url, formData,
            statusCode, expectedUrlSuffix);
    final MockHttpServletResponse response = sendData(PUT, MediaType.APPLICATION_FORM_URLENCODED, url, formData,
            statusCode);
    if (expectedUrlSuffix != null) {
        final String location = response.getHeader("Location").toString();
        assertTrue("location '" + location + "' should end with '" + expectedUrlSuffix + "'",
                location.endsWith(expectedUrlSuffix));
    }
    return response;
}

From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java

protected String stringifyResponse(final MockHttpServletResponse response) {
    final StringBuilder string = new StringBuilder();
    try {//from w ww  . jav a2s.co  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("=").append(response.getHeader(name));
        }
        string.append("]").append("]");
    } catch (UnsupportedEncodingException e) {
        LOG.warn("Unable to get response content", e);
    }
    return string.toString();
}

From source file:org.opennms.core.test.rest.AbstractSpringJerseyRestTestCase.java

protected String sendRequest(MockHttpServletRequest request, int expectedStatus, final String expectedUrlSuffix)
        throws Exception, UnsupportedEncodingException {
    MockHttpServletResponse response = createResponse();
    dispatch(request, response);//from  w w  w .  j a v a2 s .c o m
    final String xml = response.getContentAsString();
    if (xml != null && !xml.isEmpty()) {
        try {
            System.err.println(StringUtils.prettyXml(xml));
        } catch (Exception e) {
            System.err.println(xml);
        }
    }
    assertEquals(expectedStatus, response.getStatus());
    if (expectedUrlSuffix != null) {
        final String location = response.getHeader("Location").toString();
        assertTrue("location '" + location + "' should end with '" + expectedUrlSuffix + "'",
                location.endsWith(expectedUrlSuffix));
    }
    Thread.sleep(50);
    return xml;
}

From source file:org.opennms.web.rest.AbstractSpringJerseyRestTestCase.java

/**
 * @param url/*from  ww w  . j a v a  2 s  . co m*/
 * @param xml
 * @param statusCode
 */
protected MockHttpServletResponse sendPost(String url, String xml, int statusCode,
        final String expectedUrlSuffix) throws Exception {
    LOG.debug("POST {}, expected status code = {}, expected URL suffix = {}", url, statusCode,
            expectedUrlSuffix);
    final MockHttpServletResponse response = sendData(POST, MediaType.APPLICATION_XML, url, xml, statusCode);
    if (expectedUrlSuffix != null) {
        final Object header = response.getHeader("Location");
        assertNotNull(header);
        final String location = URLDecoder.decode(header.toString(), "UTF-8");
        final String decodedExpectedUrlSuffix = URLDecoder.decode(expectedUrlSuffix, "UTF-8");
        assertTrue("location '" + location + "' should end with '" + decodedExpectedUrlSuffix + "'",
                location.endsWith(decodedExpectedUrlSuffix));
    }
    return response;
}

From source file:org.opennms.web.rest.AbstractSpringJerseyRestTestCase.java

protected String stringifyResponse(final MockHttpServletResponse response) {
    final StringBuilder string = new StringBuilder();
    try {//from  w w  w.  j  ava2 s  .c om
        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) {
        LOG.warn("Unable to get response content", e);
    }
    return string.toString();
}