org.apache.http.client.utils.DateUtils Java Examples

The following examples show how to use org.apache.http.client.utils.DateUtils. 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: AtomClientTest.java    From microservice-atom with Apache License 2.0 6 votes vote down vote up
@Test
public void requestWithLastModifiedReturns304() {
	Order order = new Order();
	order.setCustomer(customerRepository.findAll().iterator().next());
	orderRepository.save(order);
	ResponseEntity<Feed> response = restTemplate.exchange(feedUrl(), HttpMethod.GET, new HttpEntity(null),
			Feed.class);

	Date lastModified = DateUtils.parseDate(response.getHeaders().getFirst("Last-Modified"));

	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("If-Modified-Since", DateUtils.formatDate(lastModified));
	HttpEntity requestEntity = new HttpEntity(requestHeaders);

	response = restTemplate.exchange(feedUrl(), HttpMethod.GET, requestEntity, Feed.class);

	assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());
}
 
Example #2
Source File: FastweixinTest.java    From fastweixin with Apache License 2.0 6 votes vote down vote up
public void getArticleData(ApiConfig config) {
    DataCubeAPI dataCubeAPI = new DataCubeAPI(config);
    String[] format = {"yyyy-MM-dd"};
    Date beginDate = DateUtils.parseDate("2015-01-25", format);
    Date endDate = DateUtils.parseDate("2015-01-26", format);
    GetArticleSummaryResponse articleSummary = dataCubeAPI.getArticleSummary(endDate);
    GetArticleTotalResponse articleTotal = dataCubeAPI.getArticleTotal(endDate);
    GetUserReadResponse userRead = dataCubeAPI.getUserRead(beginDate, endDate);
    GetUserReadHourResponse userReadHour = dataCubeAPI.getUserReadHour(endDate);
    GetUserShareResponse userShare = dataCubeAPI.getUserShare(beginDate, endDate);
    GetUserShareHourResponse userShareHour = dataCubeAPI.getUserShareHour(endDate);
    LOG.debug("------------------articleSummary----------------------");
    LOG.debug(articleSummary.toJsonString());
    LOG.debug("------------------articleTotal----------------------");
    LOG.debug(articleTotal.toJsonString());
    LOG.debug("------------------userRead----------------------");
    LOG.debug(userRead.toJsonString());
    LOG.debug("------------------userReadHour----------------------");
    LOG.debug(userReadHour.toJsonString());
    LOG.debug("------------------userShare----------------------");
    LOG.debug(userShare.toJsonString());
    LOG.debug("------------------userShareHour----------------------");
    LOG.debug(userShareHour.toJsonString());
}
 
Example #3
Source File: ApplicationTests.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void sendMessageTest1() {
      for(int i = 0; i < 1; i ++){
   	   try {
	       Map<String, Object> properties = new HashMap<String, Object>();
	       properties.put("SERIAL_NUMBER", "12345");
	       properties.put("BANK_NUMBER", "abc");
	       properties.put("PLAT_SEND_TIME", DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
    	   rabbitmqSender.sendMessage("Hello, I am amqp sender num :" + i, properties);
             
          } catch (Exception e) {
       	   System.out.println("--------error-------");
              e.printStackTrace(); 
          }
      }
      //TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);
}
 
Example #4
Source File: Cache.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Check freshness return value if
 * a) s-maxage specified
 * b) max-age specified
 * c) expired specified
 * otherwise return {@code null}</p>
 *
 * @see <a href="https://tools.ietf.org/html/rfc7234">RFC 7234</a>
 *
 * @param response
 * @param createdAt
 * @return freshnessLifetime
 */
private boolean isStillFresh(final long now) {
    long freshnessLifetime = 0;
    if (!HeaderUtils.containsPrivate(response_) && HeaderUtils.containsSMaxage(response_)) {
        // check s-maxage
        freshnessLifetime = HeaderUtils.sMaxage(response_);
    }
    else if (HeaderUtils.containsMaxAge(response_)) {
        // check max-age
        freshnessLifetime = HeaderUtils.maxAge(response_);
    }
    else if (response_.getResponseHeaderValue(HttpHeader.EXPIRES) != null) {
        final Date expires = parseDateHeader(response_, HttpHeader.EXPIRES);
        if (expires != null) {
            // use the same logic as in isCacheableContent()
            return expires.getTime() - now > DELAY;
        }
    }
    else {
        return true;
    }
    return now - createdAt_ < freshnessLifetime * org.apache.commons.lang3.time.DateUtils.MILLIS_PER_SECOND;
}
 
Example #5
Source File: CookieManagerTest.java    From htmlunit with Apache License 2.0 6 votes vote down vote up
/**
 * Tests for expiration date.
 * Tests as well for bug 3421201 (with expiration date enclosed with quotes).
 * @throws Exception if the test fails
 */
@Test
@Alerts("second=2; visitor=f2")
public void setCookieExpired() throws Exception {
    final Date aBitLater = new Date(new Date().getTime() + 60 * 60 * 1000); // one hour later
    final List<NameValuePair> responseHeader1 = new ArrayList<>();
    responseHeader1.add(new NameValuePair("Set-Cookie", "first=1;expires=Fri, 02-Jan-1970 00:00:00 GMT"));
    responseHeader1.add(new NameValuePair("Set-Cookie",
        "second=2;expires=" + DateUtils.formatDate(aBitLater)));
    responseHeader1.add(new NameValuePair("Set-Cookie", "visit=fo; expires=\"Sat, 07-Apr-2002 13:11:33 GMT\";"));
    responseHeader1.add(new NameValuePair("Set-Cookie", "visitor=f2; expires=\"Sat, 07-Apr-2092 13:11:33 GMT\";"));
    getMockWebConnection().setResponse(URL_FIRST, HTML_ALERT_COOKIE, 200, "OK", MimeType.TEXT_HTML,
            responseHeader1);

    loadPageWithAlerts2(URL_FIRST);
}
 
Example #6
Source File: PartialFetchHandler.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private static DateTime parseDateTime(final String stringValue) {
  if (!Strings.isNullOrEmpty(stringValue)) {
    final Date date = DateUtils.parseDate(stringValue);
    if (date != null) {
      return new DateTime(date.getTime());
    }
  }
  return null;
}
 
Example #7
Source File: AptProxyFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
private DateTime getDateHeader(HttpResponse response, String name) {
  Header h = response.getLastHeader(name);
  if (h != null) {
    try {
      return new DateTime(DateUtils.parseDate(h.getValue()).getTime());
    }
    catch (Exception ex) {
      log.warn("Invalid date '{}', will skip", h);
    }
  }
  return null;
}
 
Example #8
Source File: AptHostedFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
private String buildReleaseFile(String distribution, Collection<String> architectures, String md5, String sha256) {
  Paragraph p = new Paragraph(Arrays.asList(
      new ControlFile.ControlField("Suite", distribution),
      new ControlFile.ControlField("Codename", distribution), new ControlFile.ControlField("Components", "main"),
      new ControlFile.ControlField("Date", DateUtils.formatDate(new Date())),
      new ControlFile.ControlField("Architectures", architectures.stream().collect(Collectors.joining(" "))),
      new ControlFile.ControlField("SHA256", sha256), new ControlFile.ControlField("MD5Sum", md5)));
  return p.toString();
}
 
Example #9
Source File: Maven2Client.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
public HttpResponse putIfUmmodified(String path, Date date, HttpEntity entity) throws IOException {
  final URI uri = resolve(path);
  final HttpPut put = new HttpPut(uri);
  put.addHeader(HttpHeaders.IF_UNMODIFIED_SINCE, DateUtils.formatDate(date));
  put.setEntity(entity);
  return execute(put);
}
 
Example #10
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private HttpGet buildFetchRequest(final Content oldVersion, final URI fetchUri) {
  HttpGet getRequest = new HttpGet(fetchUri);
  if (oldVersion != null) {
    DateTime lastModified = oldVersion.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class);
    if (lastModified != null) {
      getRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate()));
    }
    final String etag = oldVersion.getAttributes().get(Content.CONTENT_ETAG, String.class);
    if (etag != null) {
      getRequest.addHeader(HttpHeaders.IF_NONE_MATCH, "\"" + etag + "\"");
    }
  }
  return getRequest;
}
 
Example #11
Source File: AptProxyFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private DateTime getDateHeader(final HttpResponse response, final String name) {
  Header h = response.getLastHeader(name);
  if (h != null) {
    try {
      return new DateTime(DateUtils.parseDate(h.getValue()).getTime());
    }
    catch (Exception ex) {
      log.warn("Invalid date '{}', will skip. {}", h, log.isDebugEnabled() ? ex : null);
    }
  }
  return null;
}
 
Example #12
Source File: AptHostedFacet.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
private String buildReleaseFile(final String distribution, final Collection<String> architectures, final String md5, final String sha256) {
  Paragraph p = new Paragraph(Arrays.asList(
      new ControlFile.ControlField("Suite", distribution),
      new ControlFile.ControlField("Codename", distribution), new ControlFile.ControlField("Components", "main"),
      new ControlFile.ControlField("Date", DateUtils.formatDate(new Date())),
      new ControlFile.ControlField("Architectures", architectures.stream().collect(Collectors.joining(" "))),
      new ControlFile.ControlField("SHA256", sha256), new ControlFile.ControlField("MD5Sum", md5)));
  return p.toString();
}
 
Example #13
Source File: ProxyFacetSupport.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Extract Last-Modified date from response if possible, or {@code null}.
 */
@Nullable
private DateTime extractLastModified(final HttpRequestBase request, final HttpResponse response) {
  final Header lastModifiedHeader = response.getLastHeader(HttpHeaders.LAST_MODIFIED);
  if (lastModifiedHeader != null) {
    try {
      return new DateTime(DateUtils.parseDate(lastModifiedHeader.getValue()).getTime());
    }
    catch (Exception ex) {
      log.warn("Could not parse date '{}' received from {}; using system current time as item creation time",
          lastModifiedHeader, request.getURI());
    }
  }
  return null;
}
 
Example #14
Source File: AptProxyFacet.java    From nexus-repository-apt with Eclipse Public License 1.0 5 votes vote down vote up
private HttpGet buildFetchRequest(Content oldVersion, URI fetchUri) {
  HttpGet getRequest = new HttpGet(fetchUri);
  if (oldVersion != null) {
    DateTime lastModified = oldVersion.getAttributes().get(Content.CONTENT_LAST_MODIFIED, DateTime.class);
    if (lastModified != null) {
      getRequest.addHeader(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified.toDate()));
    }
    final String etag = oldVersion.getAttributes().get(Content.CONTENT_ETAG, String.class);
    if (etag != null) {
      getRequest.addHeader(HttpHeaders.IF_NONE_MATCH, "\"" + etag + "\"");
    }
  }
  return getRequest;
}
 
Example #15
Source File: HttpConditions.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Nullable
private static DateTime parseDateHeader(@Nullable final String httpDate) {
  if (!Strings.isNullOrEmpty(httpDate)) {
    final Date date = DateUtils.parseDate(httpDate);
    if (date != null) {
      return new DateTime(date.getTime());
    }
  }
  return null;
}
 
Example #16
Source File: HeaderResponseHandler.java    From InflatableDonkey with MIT License 5 votes vote down vote up
public Optional<Date> date() {
    return Optional.ofNullable(headers.get(HttpHeaders.DATE.toLowerCase(Locale.US)))
            .flatMap(u -> u.stream()
                    .map(Header::getValue)
                    .map(DateUtils::parseDate)
                    .findFirst());
}
 
Example #17
Source File: FastweixinTest.java    From fastweixin with Apache License 2.0 5 votes vote down vote up
public void getUserData(ApiConfig config) {
    DataCubeAPI dataAPI = new DataCubeAPI(config);
    String[] format = {"yyyy-MM-dd"};
    Date beginDate = DateUtils.parseDate("2015-01-01", format);
    Date endDate = DateUtils.parseDate("2015-01-07", format);
    GetUserSummaryResponse response = dataAPI.getUserSummary(beginDate, endDate);
    GetUserCumulateResponse cumulateResponse = dataAPI.getUserCumulate(beginDate, endDate);
    LOG.debug("-----------------getUserSummary---------------------");
    LOG.debug(response.toJsonString());
    LOG.debug("-----------------getUserCumulate---------------------");
    LOG.debug(cumulateResponse.toJsonString());
}
 
Example #18
Source File: CookieUtilTest.java    From esigate with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() throws Exception {

    format = new SimpleDateFormat(DateUtils.PATTERN_RFC1123, Locale.US);
    format.setTimeZone(TimeZone.getTimeZone("GMT"));
    cookieSpec = new CustomBrowserCompatSpecFactory().create(null);
    super.setUp();
}
 
Example #19
Source File: Webdav4FileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the last modified time of this file. Is only called if {@link #doGetType} does not return
 * {@link FileType#IMAGINARY}.
 */
@Override
protected long doGetLastModifiedTime() throws Exception {
    final DavProperty property = getProperty((GenericURLFileName) getName(), DavConstants.PROPERTY_GETLASTMODIFIED);
    if (property != null) {
        final String value = (String) property.getValue();
        return DateUtils.parseDate(value).getTime();
    }
    return 0;
}
 
Example #20
Source File: Client.java    From geoportal-server-harvester with Apache License 2.0 5 votes vote down vote up
private Date getRetryAfter(HttpResponse response) {
  org.apache.http.Header retryAfterHeader = response.getFirstHeader("Retry-After");
  if (retryAfterHeader != null) {
    Date parseDate = DateUtils.parseDate(retryAfterHeader.getValue());
    if (parseDate!=null) {
      return parseDate;
    }
    try {
      return new Date(System.currentTimeMillis() + 1000L * Integer.valueOf(retryAfterHeader.getValue()));
    } catch (NumberFormatException e) {
    }
  }
  return null;
}
 
Example #21
Source File: ShippingPoller.java    From microservice-atom with Apache License 2.0 5 votes vote down vote up
public void pollInternal() {
	HttpHeaders requestHeaders = new HttpHeaders();
	if (lastModified != null) {
		requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
	}
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ResponseEntity<Feed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Feed.class);

	if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
		log.trace("data has been modified");
		Feed feed = response.getBody();
		for (Entry entry : feed.getEntries()) {
			if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
				Shipment shipping = restTemplate
						.getForEntity(entry.getContents().get(0).getSrc(), Shipment.class).getBody();
				log.trace("saving shipping {}", shipping.getId());
				shipmentService.ship(shipping);
			}
		}
		if (response.getHeaders().getFirst("Last-Modified") != null) {
			lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
			log.trace("Last-Modified header {}", lastModified);
		}
	} else {
		log.trace("no new data");
	}
}
 
Example #22
Source File: InvoicePoller.java    From microservice-atom with Apache License 2.0 5 votes vote down vote up
public void pollInternal() {
	HttpHeaders requestHeaders = new HttpHeaders();
	if (lastModified != null) {
		requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
	}
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ResponseEntity<Feed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, Feed.class);

	if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
		log.trace("data has been modified");
		Feed feed = response.getBody();
		for (Entry entry : feed.getEntries()) {
			if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
				Invoice invoice = restTemplate
						.getForEntity(entry.getContents().get(0).getSrc(), Invoice.class).getBody();
				log.trace("saving invoice {}", invoice.getId());
				invoiceService.generateInvoice(invoice);
			}
		}
		if (response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED) != null) {
			lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
			log.trace("Last-Modified header {}", lastModified);
		}
	} else {
		log.trace("no new data");
	}
}
 
Example #23
Source File: RundeckMavenResource.java    From nexus3-rundeck-plugin with MIT License 5 votes vote down vote up
private RundeckXO his2RundeckXO(SearchHit hit) {
    String version = (String) hit.getSource().get("version");

    List<Map<String, Object>> assets = (List<Map<String, Object>>) hit.getSource().get("assets");
    Map<String, Object> attributes = (Map<String, Object>) assets.get(0).get("attributes");
    Map<String, Object> content = (Map<String, Object>) attributes.get("content");
    String lastModifiedTime = "null";
    if (content != null && content.containsKey("last_modified")) {
        Long lastModified = (Long) content.get("last_modified");
        lastModifiedTime = DateUtils.formatDate(new Date(lastModified), "yyyy-MM-dd HH:mm:ss");
    }

    return RundeckXO.builder().name(version + " (" + lastModifiedTime + ")").value(version).build();
}
 
Example #24
Source File: BackupDataTask.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    deleteOld();
    String date = DateUtils.formatDate(new Date(), Constants.DATE_PATTERN);
    backupPath = Constants.BACKUP_PRE + date + File.separator;
    File file = new File(backupPath);
    if (file.exists()) {
        return;
    }
    backup();
}
 
Example #25
Source File: BonusPoller.java    From microservice-istio with Apache License 2.0 5 votes vote down vote up
public void pollInternal() {
	HttpHeaders requestHeaders = new HttpHeaders();
	if (lastModified != null) {
		requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
	}
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class);

	if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
		log.trace("data has been modified");
		OrderFeed feed = response.getBody();
		for (OrderFeedEntry entry : feed.getOrders()) {
			if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
				Bonus bonus = restTemplate
						.getForEntity(entry.getLink(), Bonus.class).getBody();
				log.trace("saving bonus {}", bonus.getId());
				bonusService.calculateBonus(bonus);
			}
		}
		if (response.getHeaders().getFirst("Last-Modified") != null) {
			lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
			log.trace("Last-Modified header {}", lastModified);
		}
	} else {
		log.trace("no new data");
	}
}
 
Example #26
Source File: ShippingPoller.java    From microservice-istio with Apache License 2.0 5 votes vote down vote up
public void pollInternal() {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set(HttpHeaders.ACCEPT, "*/*");
	if (lastModified != null) {
		requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
	}
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class);

	if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
		log.trace("data has been modified");
		OrderFeed feed = response.getBody();
		for (OrderFeedEntry entry : feed.getOrders()) {
			if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
				Shipment shipping = restTemplate
						.getForEntity(entry.getLink(), Shipment.class).getBody();
				log.trace("saving shipping {}", shipping.getId());
				shipmentService.ship(shipping);
			}
		}
		if (response.getHeaders().getFirst("Last-Modified") != null) {
			lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
			log.trace("Last-Modified header {}", lastModified);
		}
	} else {
		log.trace("no new data");
	}
}
 
Example #27
Source File: InvoicePoller.java    From microservice-istio with Apache License 2.0 5 votes vote down vote up
public void pollInternal() {
	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set(HttpHeaders.ACCEPT, "*/*");
	if (lastModified != null) {
		requestHeaders.set(HttpHeaders.IF_MODIFIED_SINCE, DateUtils.formatDate(lastModified));
	}
	HttpEntity<?> requestEntity = new HttpEntity(requestHeaders);
	ResponseEntity<OrderFeed> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, OrderFeed.class);

	if (response.getStatusCode() != HttpStatus.NOT_MODIFIED) {
		log.trace("data has been modified");
		OrderFeed feed = response.getBody();
		for (OrderFeedEntry entry : feed.getOrders()) {
			if ((lastModified == null) || (entry.getUpdated().after(lastModified))) {
				Invoice invoice = restTemplate
						.getForEntity(entry.getLink(), Invoice.class).getBody();
				log.trace("saving invoice {}", invoice.getId());
				invoiceService.generateInvoice(invoice);
			}
		}
		if (response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED) != null) {
			lastModified = DateUtils.parseDate(response.getHeaders().getFirst(HttpHeaders.LAST_MODIFIED));
			log.trace("Last-Modified header {}", lastModified);
		}
	} else {
		log.trace("no new data");
	}
}
 
Example #28
Source File: HtmlUnitExpiresHandler.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
@Override
public void parse(final SetCookie cookie, String value) throws MalformedCookieException {
    if (value.startsWith("\"") && value.endsWith("\"")) {
        value = value.substring(1, value.length() - 1);
    }
    value = value.replaceAll("[ ,:-]+", " ");

    Date startDate = null;
    String[] datePatterns = DEFAULT_DATE_PATTERNS;

    if (null != browserVersion_) {
        if (browserVersion_.hasFeature(HTTP_COOKIE_START_DATE_1970)) {
            startDate = HtmlUnitBrowserCompatCookieSpec.DATE_1_1_1970;
        }

        if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_1)) {
            datePatterns = EXTENDED_DATE_PATTERNS_1;
        }

        if (browserVersion_.hasFeature(HTTP_COOKIE_EXTENDED_DATE_PATTERNS_2)) {
            final Calendar calendar = Calendar.getInstance(Locale.ROOT);
            calendar.setTimeZone(DateUtils.GMT);
            calendar.set(1969, Calendar.JANUARY, 1, 0, 0, 0);
            calendar.set(Calendar.MILLISECOND, 0);
            startDate = calendar.getTime();

            datePatterns = EXTENDED_DATE_PATTERNS_2;
        }
    }

    final Date expiry = DateUtils.parseDate(value, datePatterns, startDate);
    cookie.setExpiryDate(expiry);
}
 
Example #29
Source File: Cache.java    From htmlunit with Apache License 2.0 5 votes vote down vote up
/**
 * Parses and returns the specified date header of the specified response. This method
 * returns {@code null} if the specified header cannot be found or cannot be parsed as a date.
 *
 * @param response the response
 * @param headerName the header name
 * @return the specified date header of the specified response
 */
protected static Date parseDateHeader(final WebResponse response, final String headerName) {
    final String value = response.getResponseHeaderValue(headerName);
    if (value == null) {
        return null;
    }
    final Matcher matcher = DATE_HEADER_PATTERN.matcher(value);
    if (matcher.matches()) {
        return new Date();
    }
    return DateUtils.parseDate(value);
}
 
Example #30
Source File: FeedClientTest.java    From microservice-istio with Apache License 2.0 5 votes vote down vote up
@Test
public void requestWithLastModifiedReturns304() {
	ResponseEntity<OrderFeed> response = restTemplate.exchange(feedUrl(), HttpMethod.GET, new HttpEntity(null),
			OrderFeed.class);

	Date lastModified = DateUtils.parseDate(response.getHeaders().getFirst("Last-Modified"));

	HttpHeaders requestHeaders = new HttpHeaders();
	requestHeaders.set("If-Modified-Since", DateUtils.formatDate(lastModified));
	HttpEntity requestEntity = new HttpEntity(requestHeaders);

	response = restTemplate.exchange(feedUrl(), HttpMethod.GET, requestEntity, OrderFeed.class);

	assertEquals(HttpStatus.NOT_MODIFIED, response.getStatusCode());
}