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

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

Introduction

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

Prototype

@Override
public List<String> getHeaders(String name) 

Source Link

Document

Return all values for the given header as a List of Strings.

Usage

From source file:io.spring.initializr.web.test.MockMvcClientHttpRequestFactory.java

private HttpHeaders getResponseHeaders(MockHttpServletResponse response) {
    HttpHeaders headers = new HttpHeaders();
    for (String name : response.getHeaderNames()) {
        List<String> values = response.getHeaders(name);
        for (String value : values) {
            headers.add(name, value);/*from  w w w  . j  a v  a  2s .c om*/
        }
    }
    return headers;
}

From source file:org.ambraproject.wombat.util.HttpMessageUtilTest.java

@Test
public void testCopyResponseWithHeaders() throws IOException {
    byte[] testContent = "Test content".getBytes();

    HttpResponse input = new BasicHttpResponse(null, HttpStatus.OK.value(), "");
    BasicHttpEntity outputEntity = new BasicHttpEntity();
    outputEntity.setContent(new ByteArrayInputStream(testContent));
    input.setEntity(outputEntity);/* ww w. j  av a  2 s . c o  m*/
    input.setHeader("includeMe", "foo");
    input.setHeader("excludeMe", "bar");
    input.setHeader("alterMe", "toBeAltered");

    HeaderFilter headerFilter = header -> {
        String name = header.getName();
        if ("includeMe".equalsIgnoreCase(name))
            return header.getValue();
        if ("alterMe".equalsIgnoreCase(name))
            return "altered";
        return null;
    };

    MockHttpServletResponse output = new MockHttpServletResponse();

    copyResponseWithHeaders(input, output, headerFilter);

    assertEquals(output.getContentAsByteArray(), testContent);

    assertEquals(output.getHeaderNames().size(), 2);
    assertEquals(output.getHeaders("includeMe"), ImmutableList.of("foo"));
    assertEquals(output.getHeaders("alterMe"), ImmutableList.of("altered"));
    assertEquals(output.getHeaders("excludeMe"), ImmutableList.of());
}

From source file:com.redblackit.web.server.EchoServletTest.java

/**
 * Do test/* w  w w .j av a2 s  . com*/
 *
 * @param method
 * @param hasBody if content should be expected
 */
private void doTest(String method, boolean hasBody) throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    request.setMethod(method);
    request.setRequestURI(this.requestURI);

    final String msg = "doTest:" + method + ":hasBody=" + hasBody;
    logger.debug(msg + ":this=" + this);

    for (String headerName : headersMap.keySet()) {
        List<String> values = headersMap.get(headerName);
        if (values.size() == 1) {
            request.addHeader(headerName, values.get(0));
        } else {
            request.addHeader(headerName, values);
        }
        Enumeration<String> headerValues = request.getHeaders(headerName);
        int hi = 0;
        while (headerValues.hasMoreElements()) {
            logger.debug(msg + "request:header[" + headerName + "," + hi + "]=" + headerValues.nextElement());
            ++hi;
        }

        Assert.assertTrue(msg + "TEST ERROR:request:header[" + headerName + "]=" + values
                + ":shouldn't be empty (" + values.getClass() + ")", hi > 0);

    }

    int expectedContentLength = 0;
    if (hasBody && body != null && body.length() > 0) {
        request.setContent(body.getBytes());
        expectedContentLength = request.getContentLength();
    }

    MockHttpServletResponse response = new MockHttpServletResponse();
    echoServlet.service(request, response);

    String responseBody = response.getContentAsString();

    Assert.assertEquals("response code:" + response, HttpServletResponse.SC_OK, response.getStatus());
    Assert.assertEquals("requestURI and Location", requestURI, response.getHeader("Location"));

    Map<String, List<String>> responseHeadersMap = new TreeMap<String, List<String>>();
    for (String headerName : response.getHeaderNames()) {
        List<String> values = response.getHeaders(headerName);
        int hi = 0;
        for (String value : values) {
            logger.debug(msg + ":response:header[" + headerName + "," + hi + "]=" + value);
            ++hi;
        }

        if (hi == 0) {
            logger.debug(msg + ":response:header[" + headerName + "]=" + values + ":is empty ("
                    + values.getClass() + ")");
            values = Arrays.asList(new String[] { "" });
        }

        if (!(headerName.equals("Location") || headerName.equals("Content-Length"))) {
            responseHeadersMap.put(headerName, values);
        }
    }

    Assert.assertEquals("headers (excluding Location and Content-Length)", headersMap, responseHeadersMap);
    if (hasBody) {
        Assert.assertEquals("body", (body == null ? "" : body), responseBody);
    } else {
        Assert.assertEquals("body", "", responseBody);
    }

    Assert.assertEquals("contentLength", expectedContentLength, response.getContentLength());

}

From source file:io.restassured.module.mockmvc.internal.MockMvcRequestSenderImpl.java

private Object assembleHeaders(MockHttpServletResponse response) {
    Collection<String> headerNames = response.getHeaderNames();

    List<Header> headers = new ArrayList<Header>();
    for (String headerName : headerNames) {
        List<String> headerValues = response.getHeaders(headerName);
        for (String headerValue : headerValues) {
            headers.add(new Header(headerName, headerValue));
        }/*from  w w  w  . ja v a 2s.c o m*/
    }
    return new Headers(headers);
}

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

/**
 * Verify headers stored in cache are replayed on the response for cached doServeResource content.
 * //from  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));
}