org.springframework.http.HttpHeaders#setDate ( )源码实例Demo

下面列出了org.springframework.http.HttpHeaders#setDate ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * 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"));
	};
}
 
/**
 * 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"));
	};
}
 
@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));
}
 
@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));
}
 
@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));
}
 
源代码6 项目: jandy   文件: ProjectController.java
@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));
}
 
@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"));
}
 
@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);
}
 
@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"));
}
 
@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);
}
 
@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);
}
 
源代码12 项目: spring-hmac-rest   文件: ApiClient.java
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;
    }