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.springframework.data.rest.webmvc.mongodb.MongoWebTests.java

/**
 * @see DATAREST-160/*from www. ja  v  a2s .  c o m*/
 */
@Test
public void returnConflictWhenConcurrentlyEditingVersionedEntity() throws Exception {

    Link receiptLink = client.discoverUnique("receipts");

    Receipt receipt = new Receipt();
    receipt.amount = new BigDecimal(50);
    receipt.saleItem = "Springy Tacos";

    String stringReceipt = mapper.writeValueAsString(receipt);

    MockHttpServletResponse createdReceipt = postAndGet(receiptLink, stringReceipt, MediaType.APPLICATION_JSON);
    Link tacosLink = client.assertHasLinkWithRel("self", createdReceipt);
    assertJsonPathEquals("$.saleItem", "Springy Tacos", createdReceipt);

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(tacosLink.getHref());
    String concurrencyTag = createdReceipt.getHeader("ETag");

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
            .contentType(MediaType.APPLICATION_JSON).header("If-Match", concurrencyTag))
            .andExpect(status().is2xxSuccessful());

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
            .contentType(MediaType.APPLICATION_JSON).header("If-Match", concurrencyTag))
            .andExpect(status().isPreconditionFailed());
}

From source file:org.springframework.data.rest.tests.mongodb.MongoWebTests.java

/**
 * @see DATAREST-160/*from w  w  w . j  a va2  s.c om*/
 */
@Test
public void returnConflictWhenConcurrentlyEditingVersionedEntity() throws Exception {

    Link receiptLink = client.discoverUnique("receipts");

    Receipt receipt = new Receipt();
    receipt.amount = new BigDecimal(50);
    receipt.saleItem = "Springy Tacos";

    String stringReceipt = mapper.writeValueAsString(receipt);

    MockHttpServletResponse createdReceipt = postAndGet(receiptLink, stringReceipt, MediaType.APPLICATION_JSON);
    Link tacosLink = client.assertHasLinkWithRel("self", createdReceipt);
    assertJsonPathEquals("$.saleItem", "Springy Tacos", createdReceipt);

    UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(tacosLink.getHref());
    String concurrencyTag = createdReceipt.getHeader("ETag");

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyBurritos\" }")
            .contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, concurrencyTag))
            .andExpect(status().is2xxSuccessful());

    mvc.perform(patch(builder.build().toUriString()).content("{ \"saleItem\" : \"SpringyTequila\" }")
            .contentType(MediaType.APPLICATION_JSON).header(IF_MATCH, concurrencyTag))
            .andExpect(status().isPreconditionFailed());
}

From source file:org.geoserver.gwc.GWCIntegrationTest.java

@Test
public void testDirectWMSIntegrationMaxAge() throws Exception {
    final GWC gwc = GWC.get();
    gwc.getConfig().setDirectWMSIntegrationEnabled(true);
    final String layerName = BASIC_POLYGONS.getPrefix() + ":" + BASIC_POLYGONS.getLocalPart();
    final String path = buildGetMap(true, layerName, "EPSG:4326", null) + "&tiled=true";
    final String qualifiedName = super.getLayerId(BASIC_POLYGONS);
    final GeoServerTileLayer tileLayer = (GeoServerTileLayer) gwc.getTileLayerByName(qualifiedName);
    tileLayer.getLayerInfo().getResource().getMetadata().put(ResourceInfo.CACHING_ENABLED, "true");
    tileLayer.getLayerInfo().getResource().getMetadata().put(ResourceInfo.CACHE_AGE_MAX, 3456);

    MockHttpServletResponse response = getAsServletResponse(path);
    String cacheControl = response.getHeader("Cache-Control");
    assertEquals("max-age=3456", cacheControl);
    assertNotNull(response.getHeader("Last-Modified"));

    tileLayer.getLayerInfo().getResource().getMetadata().put(ResourceInfo.CACHING_ENABLED, "false");
    response = getAsServletResponse(path);
    cacheControl = response.getHeader("Cache-Control");
    assertEquals("no-cache", cacheControl);

    // make sure a boolean is handled, too - see comment in CachingWebMapService
    tileLayer.getLayerInfo().getResource().getMetadata().put(ResourceInfo.CACHING_ENABLED, Boolean.FALSE);
    response = getAsServletResponse(path);
    cacheControl = response.getHeader("Cache-Control");
    assertEquals("no-cache", cacheControl);
}

From source file:com.tasktop.c2c.server.common.service.tests.http.HttpProxyTest.java

protected void doTestSetCookieNameTranslated(String setCookieHeaderName) throws IOException {
    setupMock(HttpStatus.OK);//from  w  w w. ja va2  s .  com

    MockHttpServletRequest request = new MockHttpServletRequest("GET", "unused");
    MockHttpServletResponse response = new MockHttpServletResponse();

    final String jsessionId = UUID.randomUUID().toString();
    final String originalHeaderValue = "JSESSIONID=\"" + jsessionId + "\"; Version=\"1\"; Path=\"/acme\"";

    proxyResponseHeaders.add(new Header(setCookieHeaderName, originalHeaderValue));

    proxy.proxyRequest("foo", request, response);

    String setCookieValue = (String) response.getHeader(setCookieHeaderName);
    Assert.assertNotNull(setCookieValue);
    Assert.assertEquals("almp." + originalHeaderValue, setCookieValue);

    context.assertIsSatisfied();
}

From source file:com.enonic.cms.framework.util.HttpServletRangeUtilTest.java

@Test
public void test_no_range() throws Exception {
    final MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
    httpServletRequest.setMethod("GET");
    httpServletRequest.setPathInfo("/input.dat");

    final MockHttpServletResponse mockHttpServletResponse = new MockHttpServletResponse();
    HttpServletRangeUtil.processRequest(httpServletRequest, mockHttpServletResponse, "input.dat",
            "application/pdf", INPUT_FILE, false);

    assertEquals(readFromFile("input.dat"), mockHttpServletResponse.getContentAsString());

    assertEquals(HttpServletResponse.SC_OK, mockHttpServletResponse.getStatus());
    assertEquals("52", mockHttpServletResponse.getHeader(HttpHeaders.CONTENT_LENGTH));
}

From source file:com.gisgraphy.servlet.AbstractAddressServletTest.java

@Test
public void testServletShouldReturnCorrectContentType() {

    for (OutputFormat format : OutputFormat.values()) {
        try {/* w w w  .ja v  a2  s  .  com*/
            MockHttpServletResponse response = new MockHttpServletResponse();

            MockHttpServletRequest request = new MockHttpServletRequest();
            request.setParameter(AbstractAddressServlet.ADDRESS_PARAMETER, "address");
            request.setParameter(AbstractAddressServlet.COUNTRY_PARAMETER, "us");
            request.setParameter(AbstractAddressServlet.FORMAT_PARAMETER, format.name());
            servlet.doGet(request, response);

            String contentType = (String) response.getHeader("Content-Type");
            if (OutputFormatHelper.isFormatSupported(format, servlet.getGisgraphyServiceType())) {
                Assert.assertEquals(format.getContentType(), contentType);
            }
        } catch (IOException e) {
            Assert.fail("An exception has occured " + e.getMessage());
        }
    }

}

From source file:org.springsource.restbucks.PaymentProcessIntegrationTest.java

/**
 * Creates a new {@link Order} by looking up the orders link from the source and posting the content of
 * {@code orders.json} to it. Verifies we get receive a {@code 201 Created} and a {@code Location} header. Follows the
 * location header to retrieve the {@link Order} just created.
 * // w w w.  ja  v  a 2  s . c  om
 * @param source
 * @return
 * @throws Exception
 */
private MockHttpServletResponse createNewOrder(MockHttpServletResponse source) throws Exception {

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

    ClassPathResource resource = new ClassPathResource("order.json");
    byte[] data = Files.readAllBytes(resource.getFile().toPath());

    MockHttpServletResponse result = mvc
            .perform(post(ordersLink.getHref()).contentType(MediaType.APPLICATION_JSON).content(data)). //
            andExpect(status().isCreated()). //
            andExpect(header().string("Location", is(notNullValue()))). //
            andReturn().getResponse();

    return mvc.perform(get(result.getHeader("Location"))).andReturn().getResponse();
}

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

@Test
public void testLastModified() throws Exception {
    String stage = systemInfo.getStagingProfile();
    systemInfo.setStagingProfile(SystemInfo.STAGE_PRODUCTION);
    try {//  w ww .  ja  v  a  2  s  .  co  m
        metadataRepository.update(id, new Updater<Metadata>() {
            @Override
            public void apply(@Nonnull Metadata entity) {
                entity.getDataInfo().setChangeDate(new ISODate("2012-01-18T15:04:43"));
            }
        });
        dataManager.indexMetadata(Lists.newArrayList("" + this.id));

        final String formatterName = "full_view";

        MockHttpServletRequest request = new MockHttpServletRequest();
        request.getSession();
        request.addParameter("h2IdentInfo", "true");

        MockHttpServletResponse response = new MockHttpServletResponse();
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        final String lastModified = response.getHeader("Last-Modified");
        assertEquals("no-cache", response.getHeader("Cache-Control"));
        final String viewString = response.getContentAsString();
        assertNotNull(viewString);

        request = new MockHttpServletRequest();
        request.getSession();
        request.setMethod("GET");
        response = new MockHttpServletResponse();

        request.addHeader("If-Modified-Since", lastModified);
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        assertEquals(HttpStatus.SC_NOT_MODIFIED, response.getStatus());
        final ISODate newChangeDate = new ISODate();
        metadataRepository.update(id, new Updater<Metadata>() {
            @Override
            public void apply(@Nonnull Metadata entity) {
                entity.getDataInfo().setChangeDate(newChangeDate);
            }
        });

        dataManager.indexMetadata(Lists.newArrayList("" + this.id));

        request = new MockHttpServletRequest();
        request.getSession();
        request.setMethod("GET");
        response = new MockHttpServletResponse();

        request.addHeader("If-Modified-Since", lastModified);
        formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
                new ServletWebRequest(request, response));
        assertEquals(HttpStatus.SC_OK, response.getStatus());
    } finally {
        systemInfo.setStagingProfile(stage);
    }
}

From source file:ch.ralscha.extdirectspring.controller.ApiControllerWithConfigurationTest.java

private void testGroup1(Configuration config, String fingerprint) throws Exception {
    ApiRequestParams params = ApiRequestParams.builder().apiNs("Ext.ns").actionNs("actionns").group("group1")
            .configuration(config).build();

    doTest("/api-debug-doc.js", params, ApiControllerTest.group1Apis("actionns"));
    doTest("/api-debug.js", params, ApiControllerTest.group1Apis("actionns"));

    if (fingerprint == null) {
        doTest("/api.js", params, ApiControllerTest.group1Apis("actionns"));
    } else {//from   w  w  w .  j a  va  2 s  .  co m
        MvcResult result = doTest("/api" + fingerprint + ".js", params,
                ApiControllerTest.group1Apis("actionns"));

        MockHttpServletResponse response = result.getResponse();

        assertThat(response.getHeaderNames()).hasSize(5);
        assertThat(response.getHeader("ETag")).isNotNull();
        assertThat(response.getHeader("Cache-Control")).isEqualTo("public, max-age=" + 6 * 30 * 24 * 60 * 60);

        Long expiresMillis = (Long) response.getHeaderValue("Expires");
        DateTime expires = new DateTime(expiresMillis, DateTimeZone.UTC);
        DateTime inSixMonths = DateTime.now(DateTimeZone.UTC).plusSeconds(6 * 30 * 24 * 60 * 60);
        assertThat(expires.getYear()).isEqualTo(inSixMonths.getYear());
        assertThat(expires.getMonthOfYear()).isEqualTo(inSixMonths.getMonthOfYear());
        assertThat(expires.getDayOfMonth()).isEqualTo(inSixMonths.getDayOfMonth());
        assertThat(expires.getHourOfDay()).isEqualTo(inSixMonths.getHourOfDay());
        assertThat(expires.getMinuteOfDay()).isEqualTo(inSixMonths.getMinuteOfDay());
    }
}

From source file:com.comcast.video.dawg.show.video.VideoSnapTest.java

@Test
public void testAddImagesToZipFile() throws IOException {
    String imageIds[] = { "", "", "" };
    MockHttpSession session = new MockHttpSession();
    MockHttpServletResponse response = new MockHttpServletResponse();
    UniqueIndexedCache<BufferedImage> imgCache = ClientCache.getClientCache(session).getImgCache();
    imageIds[0] = imgCache.storeItem(PC_IMG);
    imageIds[1] = imgCache.storeItem(PC_IMG);
    imageIds[2] = null;/*from w  w  w. j a  va  2 s . c o m*/
    String deviceIds[] = { "000000000001", "000000000002", "000000000003" };
    int expectedZipSizeInBytes = 28954;

    VideoSnap videoSnap = new VideoSnap();

    videoSnap.addImagesToZipFile(imageIds, deviceIds, response, session);
    Assert.assertEquals(response.getContentType(), "application/zip", "Content type is not in zip format");
    String header = response.getHeader("Content-Disposition");
    Assert.assertTrue(header.contains("attachment"), "Response header does not indicates attachment");
    Assert.assertTrue(header.contains(".zip"), "Attached file is not in zip format");
    Assert.assertEquals(response.getContentAsByteArray().length, expectedZipSizeInBytes,
            "Zip file size in http response is not matching with expected zip size.");

}