Java Code Examples for org.springframework.http.HttpHeaders#setDate()

The following examples show how to use org.springframework.http.HttpHeaders#setDate() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: HeaderResultMatchers.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Assert the primary value of the named response header parsed into a date
 * using the preferred date format described in RFC 7231.
 * <p>The {@link ResultMatcher} returned by this method throws an
 * {@link AssertionError} if the response does not contain the specified
 * header, or if the supplied {@code value} does not match the primary value.
 * @since 4.2
 * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a>
 */
public ResultMatcher dateValue(final String name, final long value) {
	return result -> {
		MockHttpServletResponse response = result.getResponse();
		String headerValue = response.getHeader(name);
		assertNotNull("Response does not contain header '" + name + "'", headerValue);

		HttpHeaders headers = new HttpHeaders();
		headers.setDate("expected", value);
		headers.set("actual", headerValue);

		assertEquals("Response header '" + name + "'='" + headerValue + "' " +
						"does not match expected value '" + headers.getFirst("expected") + "'",
				headers.getFirstDate("expected"), headers.getFirstDate("actual"));
	};
}
 
Example 2
Source File: HeaderResultMatchers.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Assert the primary value of the named response header parsed into a date
 * using the preferred date format described in RFC 7231.
 * <p>The {@link ResultMatcher} returned by this method throws an
 * {@link AssertionError} if the response does not contain the specified
 * header, or if the supplied {@code value} does not match the primary value.
 * @since 4.2
 * @see <a href="https://tools.ietf.org/html/rfc7231#section-7.1.1.1">Section 7.1.1.1 of RFC 7231</a>
 */
public ResultMatcher dateValue(final String name, final long value) {
	return result -> {
		MockHttpServletResponse response = result.getResponse();
		String headerValue = response.getHeader(name);
		assertNotNull("Response does not contain header '" + name + "'", headerValue);

		HttpHeaders headers = new HttpHeaders();
		headers.setDate("expected", value);
		headers.set("actual", headerValue);

		assertEquals("Response header '" + name + "'='" + headerValue + "' " +
						"does not match expected value '" + headers.getFirst("expected") + "'",
				headers.getFirstDate("expected"), headers.getFirstDate("actual"));
	};
}
 
Example 3
Source File: HttpEntityMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void handleReturnTypeLastModified() throws Exception {
	long currentTime = new Date().getTime();
	long oneMinuteAgo  = currentTime - (1000 * 60);
	servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, dateFormat.format(currentTime));
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
	ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.OK);

	given(messageConverter.canWrite(String.class, null)).willReturn(true);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);

	processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);

	assertResponseNotModified();
	assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size());
	assertEquals(dateFormat.format(oneMinuteAgo), servletResponse.getHeader(HttpHeaders.LAST_MODIFIED));
}
 
Example 4
Source File: HttpEntityMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void handleReturnTypeETagAndLastModified() throws Exception {
	long currentTime = new Date().getTime();
	long oneMinuteAgo  = currentTime - (1000 * 60);
	String etagValue = "\"deadb33f8badf00d\"";
	servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, dateFormat.format(currentTime));
	servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
	responseHeaders.set(HttpHeaders.ETAG, etagValue);
	ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.OK);

	given(messageConverter.canWrite(String.class, null)).willReturn(true);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);

	processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);

	assertResponseNotModified();
	assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size());
	assertEquals(dateFormat.format(oneMinuteAgo), servletResponse.getHeader(HttpHeaders.LAST_MODIFIED));
	assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.ETAG).size());
	assertEquals(etagValue, servletResponse.getHeader(HttpHeaders.ETAG));
}
 
Example 5
Source File: HttpEntityMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void handleReturnTypeNotModified() throws Exception {
	long currentTime = new Date().getTime();
	long oneMinuteAgo  = currentTime - (1000 * 60);
	String etagValue = "\"deadb33f8badf00d\"";
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
	responseHeaders.set(HttpHeaders.ETAG, etagValue);
	ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.NOT_MODIFIED);

	given(messageConverter.canWrite(String.class, null)).willReturn(true);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);

	processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);

	assertResponseNotModified();
	assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size());
	assertEquals(dateFormat.format(oneMinuteAgo), servletResponse.getHeader(HttpHeaders.LAST_MODIFIED));
	assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.ETAG).size());
	assertEquals(etagValue, servletResponse.getHeader(HttpHeaders.ETAG));
}
 
Example 6
Source File: ProjectController.java    From jandy with GNU General Public License v3.0 6 votes vote down vote up
@RequestMapping(value = "/{account}/{projectName}/{branchName}.svg")
public ResponseEntity<String> getBadge(@PathVariable String account, @PathVariable String projectName, @PathVariable String branchName) throws Exception {
  QBuild b = QBuild.build;
  Page<Build> buildPage = buildRepository.findAll(b.branch.name.eq(branchName).and(b.branch.project.account.eq(account)).and(b.branch.project.name.eq(projectName)), new QPageRequest(0, 2, b.number.desc()));
  if (buildPage.getTotalPages() == 0)
    throw new BadgeUnknownException();
  Build latest = buildPage.getContent().get(0);

  long current = System.currentTimeMillis();
  HttpHeaders headers = new HttpHeaders(); // see #7
  headers.setExpires(current);
  headers.setDate(current);

  return ResponseEntity
      .ok()
      .headers(headers)
      .cacheControl(CacheControl.noCache())
      .lastModified(current)
      .eTag(Long.toString(latest.getId()))
      .body(FreeMarkerTemplateUtils.processTemplateIntoString(configurer.getConfiguration().getTemplate("badge/mybadge.ftl"), latest));
}
 
Example 7
Source File: HeaderAssertionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void stringWithMatcherAndIncorrectResponseHeaderValue() throws Exception {
	long secondLater = this.currentTime + 1000;
	String expected = this.dateFormat.format(new Date(secondLater));
	assertIncorrectResponseHeader(header().string(LAST_MODIFIED, expected), expected);
	assertIncorrectResponseHeader(header().string(LAST_MODIFIED, equalTo(expected)), expected);
	// Comparison by date uses HttpHeaders to format the date in the error message.
	HttpHeaders headers = new HttpHeaders();
	headers.setDate("expected", secondLater);
	assertIncorrectResponseHeader(header().dateValue(LAST_MODIFIED, secondLater), headers.getFirst("expected"));
}
 
Example 8
Source File: HeaderResultMatchersTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-17330
public void matchDateFormattedWithHttpHeaders() throws Exception {

	long epochMilli = ZonedDateTime.of(2018, 10, 5, 0, 0, 0, 0, ZoneId.of("GMT")).toInstant().toEpochMilli();
	HttpHeaders headers = new HttpHeaders();
	headers.setDate("myDate", epochMilli);
	this.response.setHeader("d", headers.getFirst("myDate"));

	this.matchers.dateValue("d", epochMilli).match(this.mvcResult);
}
 
Example 9
Source File: HeaderAssertionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void stringWithMatcherAndIncorrectResponseHeaderValue() throws Exception {
	long secondLater = this.currentTime + 1000;
	String expected = this.dateFormat.format(new Date(secondLater));
	assertIncorrectResponseHeader(header().string(LAST_MODIFIED, expected), expected);
	assertIncorrectResponseHeader(header().string(LAST_MODIFIED, equalTo(expected)), expected);
	// Comparison by date uses HttpHeaders to format the date in the error message.
	HttpHeaders headers = new HttpHeaders();
	headers.setDate("expected", secondLater);
	assertIncorrectResponseHeader(header().dateValue(LAST_MODIFIED, secondLater), headers.getFirst("expected"));
}
 
Example 10
Source File: HeaderResultMatchersTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test // SPR-17330
public void matchDateFormattedWithHttpHeaders() throws Exception {

	long epochMilli = ZonedDateTime.of(2018, 10, 5, 0, 0, 0, 0, ZoneId.of("GMT")).toInstant().toEpochMilli();
	HttpHeaders headers = new HttpHeaders();
	headers.setDate("myDate", epochMilli);
	this.response.setHeader("d", headers.getFirst("myDate"));

	this.matchers.dateValue("d", epochMilli).match(this.mvcResult);
}
 
Example 11
Source File: HttpEntityMethodProcessorMockTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void handleReturnTypeChangedETagAndLastModified() throws Exception {
	long currentTime = new Date().getTime();
	long oneMinuteAgo  = currentTime - (1000 * 60);
	String etagValue = "\"deadb33f8badf00d\"";
	String changedEtagValue = "\"changed-etag-value\"";
	servletRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, dateFormat.format(currentTime));
	servletRequest.addHeader(HttpHeaders.IF_NONE_MATCH, etagValue);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setDate(HttpHeaders.LAST_MODIFIED, oneMinuteAgo);
	responseHeaders.set(HttpHeaders.ETAG, changedEtagValue);
	ResponseEntity<String> returnValue = new ResponseEntity<String>("body", responseHeaders, HttpStatus.OK);

	given(messageConverter.canWrite(String.class, null)).willReturn(true);
	given(messageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(MediaType.TEXT_PLAIN));
	given(messageConverter.canWrite(String.class, MediaType.TEXT_PLAIN)).willReturn(true);

	processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest);

	assertTrue(mavContainer.isRequestHandled());
	assertEquals(HttpStatus.OK.value(), servletResponse.getStatus());
	assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.LAST_MODIFIED).size());
	assertEquals(dateFormat.format(oneMinuteAgo), servletResponse.getHeader(HttpHeaders.LAST_MODIFIED));
	assertEquals(1, servletResponse.getHeaderValues(HttpHeaders.ETAG).size());
	assertEquals(changedEtagValue, servletResponse.getHeader(HttpHeaders.ETAG));
	assertEquals(0, servletResponse.getContentAsByteArray().length);
}
 
Example 12
Source File: ApiClient.java    From spring-hmac-rest with MIT License 4 votes vote down vote up
public <I, O extends AbstractResponseWrapper<I>> O echo(I request, Class<O> clazz) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        final AuthScope authScope = new AuthScope(host, port, AuthScope.ANY_REALM, scheme);
        final Credentials credentials = credentialsProvider.getCredentials(authScope);

        if (credentials == null) {
            throw new RuntimeException("Can't find credentials for AuthScope: " + authScope);
        }

        String apiKey = credentials.getUserPrincipal().getName();
        String apiSecret = credentials.getPassword();

        String nonce = UUID.randomUUID().toString();

        headers.setDate(clock.millis());
        String dateString = headers.getFirst(HttpHeaders.DATE);

        RequestWrapper<I> requestWrapper = new RequestWrapper<>(request);
        requestWrapper.setData(request);

        final String valueAsString;
        try {
            valueAsString = objectMapper.writeValueAsString(requestWrapper);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        final String resource = "/api/echo";
        final HmacSignatureBuilder signatureBuilder = new HmacSignatureBuilder()
                .scheme(scheme)
                .host(host+":" + port)
                .method("POST")
                .resource(resource)
                .apiKey(apiKey)
                .contentType(MediaType.APPLICATION_JSON_VALUE)
                .nonce(nonce)
                .date(dateString)
                .apiSecret(apiSecret)
                .payload(valueAsString.getBytes(StandardCharsets.UTF_8));
        final String signature = signatureBuilder
                .buildAsBase64String();

        final String authHeader = signatureBuilder.getAlgorithm() + " " + apiKey + ":" + nonce + ":" + signature;
        headers.add(HttpHeaders.AUTHORIZATION, authHeader);

        headers.add(HttpHeaders.USER_AGENT, USER_AGENT);

        HttpEntity<String> entity = new HttpEntity<>(valueAsString, headers);

        final O payloadWrapper = restTemplate.postForObject(
                scheme + "://" + host + ":" + port + resource,
                entity,
                clazz);

        return payloadWrapper;
    }