Example usage for org.apache.http.client.utils DateUtils parseDate

List of usage examples for org.apache.http.client.utils DateUtils parseDate

Introduction

In this page you can find the example usage for org.apache.http.client.utils DateUtils parseDate.

Prototype

public static Date parseDate(final String dateValue) 

Source Link

Document

Parses a date value.

Usage

From source file:org.sonatype.nexus.repository.proxy.ProxyFacetSupport.java

/**
 * Extract Last-Modified date from response if possible, or {@code null}.
 *//*from   www  . ja  v a  2 s.c  o  m*/
@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;
}

From source file:org.ldp4j.server.frontend.ServerFrontendITest.java

/**
 * Enforce http://tools.ietf.org/html/rfc7232#section-2.2:
 * if the clock in the request is ahead of the clock of the origin
 * server (e.g., I request from Spain the update of a resource held in USA)
 * the last-modified data should be changed to that of the request and not
 * a generated date from the origin server
 *//*from  ww  w  .  j a  v a  2  s . co  m*/
@Test
@Category({ HappyPath.class })
@OperateOnDeployment(DEPLOYMENT)
public void testProperLastModified(@ArquillianResource final URL url) throws Exception {
    LOGGER.info("Started {}", testName.getMethodName());
    HELPER.base(url);
    HELPER.setLegacy(false);

    long now = System.currentTimeMillis();
    Date clientPostDate = new Date(now - 24 * 60 * 60 * 1000);
    Date clientPutDate = new Date(now + 24 * 60 * 60 * 1000);

    HttpPost post = HELPER.newRequest(MyApplication.ROOT_PERSON_CONTAINER_PATH, HttpPost.class);
    post.setEntity(new StringEntity(TEST_SUITE_BODY, ContentType.create("text/turtle", "UTF-8")));
    post.setHeader("Date", DateUtils.formatDate(clientPostDate));

    Metadata postResponse = HELPER.httpRequest(post);
    assertThat(postResponse.status, equalTo(HttpStatus.SC_CREATED));

    String path = HELPER.relativize(postResponse.location);
    HttpGet get = HELPER.newRequest(path, HttpGet.class);

    Metadata getResponse = HELPER.httpRequest(get);
    assertThat(DateUtils.parseDate(getResponse.lastModified).after(clientPostDate), equalTo(true));

    HttpPut put = HELPER.newRequest(path, HttpPut.class);
    put.setEntity(new StringEntity(getResponse.body, ContentType.create("text/turtle", "UTF-8")));
    put.setHeader(HttpHeaders.IF_MATCH, getResponse.etag);
    put.setHeader("Date", DateUtils.formatDate(clientPutDate));

    Metadata putResponse = HELPER.httpRequest(put);
    Date lastModified = DateUtils.parseDate(putResponse.lastModified);
    assertThat(lastModified.getTime(), equalTo(trunk(clientPutDate.getTime())));

    LOGGER.info("Completed {}", testName.getMethodName());
}

From source file:de.undercouch.gradle.tasks.download.DownloadAction.java

/**
 * Parse the Last-Modified header of a {@link HttpResponse}
 * @param response the {@link HttpResponse}
 * @return the last-modified value or 0 if it is unknown
 *//*from  w  w w .  j  a  v  a 2 s .  co m*/
private long parseLastModified(HttpResponse response) {
    Header header = response.getLastHeader("Last-Modified");
    if (header == null) {
        return 0;
    }
    String value = header.getValue();
    if (value == null || value.isEmpty()) {
        return 0;
    }
    Date date = DateUtils.parseDate(value);
    if (date == null) {
        return 0;
    }
    return date.getTime();
}

From source file:com.joyent.manta.util.MantaUtils.java

/**
 * Parses a HTTP Date header value./*from ww w . j  a  v a 2 s . c  o m*/
 *
 * @param date header to parse
 * @return instance of Date based on input
 */
public static Date parseHttpDate(final String date) {
    return DateUtils.parseDate(date);
}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagonFixed.java

private void fillInputData(int wait, InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String repositoryUrl = getRepository().getUrl();
    String url = repositoryUrl + (repositoryUrl.endsWith("/") ? "" : "/") + resource.getName();
    HttpGet getMethod = new HttpGet(url);
    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);/* ww  w  .ja  v a2s . c o  m*/
        Header hdr = new BasicHeader("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addHeader(hdr);
    }

    try {
        CloseableHttpResponse response = execute(getMethod);
        closeable = response;
        int statusCode = response.getStatusLine().getStatusCode();

        String reasonPhrase = ", ReasonPhrase:" + response.getStatusLine().getReasonPhrase() + ".";

        fireTransferDebug(url + " - Status code: " + statusCode + reasonPhrase);

        switch (statusCode) {
        case HttpStatus.SC_OK:
            break;

        case HttpStatus.SC_NOT_MODIFIED:
            // return, leaving last modified set to original value so getIfNewer should return unmodified
            return;
        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url + " " + reasonPhrase);

        case HttpStatus.SC_UNAUTHORIZED:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Not authorized " + reasonPhrase);

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Not authorized by proxy " + reasonPhrase);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " " + reasonPhrase);

        case SC_TOO_MANY_REQUESTS:
            fillInputData(backoff(wait, url), inputData);
            break;

        // add more entries here
        default:
            cleanupGetTransfer(resource);
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode + " " + reasonPhrase);
            fireTransferError(resource, e, TransferEvent.REQUEST_GET);
            throw e;
        }

        Header contentLengthHeader = response.getFirstHeader("Content-Length");

        if (contentLengthHeader != null) {
            try {
                long contentLength = Long.parseLong(contentLengthHeader.getValue());

                resource.setContentLength(contentLength);
            } catch (NumberFormatException e) {
                fireTransferDebug(
                        "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
            }
        }

        Header lastModifiedHeader = response.getFirstHeader("Last-Modified");
        if (lastModifiedHeader != null) {
            Date lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
            if (lastModified != null) {
                resource.setLastModified(lastModified.getTime());
                fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " ("
                        + lastModified.getTime() + ")");
            }
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            inputData.setInputStream(entity.getContent());
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (HttpException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (InterruptedException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    }

}

From source file:org.apache.maven.wagon.providers.http.AbstractHttpClientWagon.java

private void fillInputData(int wait, InputData inputData)
        throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    Resource resource = inputData.getResource();

    String repositoryUrl = getRepository().getUrl();
    String url = repositoryUrl + (repositoryUrl.endsWith("/") ? "" : "/") + resource.getName();
    HttpGet getMethod = new HttpGet(url);
    long timestamp = resource.getLastModified();
    if (timestamp > 0) {
        SimpleDateFormat fmt = new SimpleDateFormat("EEE, dd-MMM-yy HH:mm:ss zzz", Locale.US);
        fmt.setTimeZone(GMT_TIME_ZONE);/* ww w.  java2 s .c o m*/
        Header hdr = new BasicHeader("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addHeader(hdr);
    }

    try {
        CloseableHttpResponse response = execute(getMethod);
        closeable = response;
        int statusCode = response.getStatusLine().getStatusCode();

        String reasonPhrase = ", ReasonPhrase:" + response.getStatusLine().getReasonPhrase() + ".";

        fireTransferDebug(url + " - Status code: " + statusCode + reasonPhrase);

        switch (statusCode) {
        case HttpStatus.SC_OK:
            break;

        case HttpStatus.SC_NOT_MODIFIED:
            // return, leaving last modified set to original value so getIfNewer should return unmodified
            return;
        case HttpStatus.SC_FORBIDDEN:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Access denied to: " + url + " " + reasonPhrase);

        case HttpStatus.SC_UNAUTHORIZED:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Not authorized " + reasonPhrase);

        case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
            fireSessionConnectionRefused();
            throw new AuthorizationException("Not authorized by proxy " + reasonPhrase);

        case HttpStatus.SC_NOT_FOUND:
            throw new ResourceDoesNotExistException("File: " + url + " " + reasonPhrase);

        case SC_TOO_MANY_REQUESTS:
            fillInputData(backoff(wait, url), inputData);
            break;

        // add more entries here
        default: {
            cleanupGetTransfer(resource);
            TransferFailedException e = new TransferFailedException(
                    "Failed to transfer file: " + url + ". Return code is: " + statusCode + " " + reasonPhrase);
            fireTransferError(resource, e, TransferEvent.REQUEST_GET);
            throw e;
        }
        }

        Header contentLengthHeader = response.getFirstHeader("Content-Length");

        if (contentLengthHeader != null) {
            try {
                long contentLength = Long.parseLong(contentLengthHeader.getValue());

                resource.setContentLength(contentLength);
            } catch (NumberFormatException e) {
                fireTransferDebug(
                        "error parsing content length header '" + contentLengthHeader.getValue() + "' " + e);
            }
        }

        Header lastModifiedHeader = response.getFirstHeader("Last-Modified");
        if (lastModifiedHeader != null) {
            Date lastModified = DateUtils.parseDate(lastModifiedHeader.getValue());
            if (lastModified != null) {
                resource.setLastModified(lastModified.getTime());
                fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " ("
                        + lastModified.getTime() + ")");
            }
        }

        HttpEntity entity = response.getEntity();
        if (entity != null) {
            inputData.setInputStream(entity.getContent());
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (HttpException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    } catch (InterruptedException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        throw new TransferFailedException(e.getMessage(), e);
    }

}

From source file:org.apache.http.impl.client.cache.CachingExec.java

private boolean revalidationResponseIsTooOld(final HttpResponse backendResponse,
        final HttpCacheEntry cacheEntry) {
    final Header entryDateHeader = cacheEntry.getFirstHeader(HTTP.DATE_HEADER);
    final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
    if (entryDateHeader != null && responseDateHeader != null) {
        final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
        final Date respDate = DateUtils.parseDate(responseDateHeader.getValue());
        if (entryDate == null || respDate == null) {
            // either backend response or cached entry did not have a valid
            // Date header, so we can't tell if they are out of order
            // according to the origin clock; thus we can skip the
            // unconditional retry recommended in 13.2.6 of RFC 2616.
            return false;
        }//from   ww  w .  j a v a  2 s  .  com
        if (respDate.before(entryDate)) {
            return true;
        }
    }
    return false;
}

From source file:org.apache.http.impl.client.cache.CachingExec.java

private boolean alreadyHaveNewerCacheEntry(final HttpHost target, final HttpRequestWrapper request,
        final HttpResponse backendResponse) {
    HttpCacheEntry existing = null;/* w w w . j  a v  a 2s  .com*/
    try {
        existing = responseCache.getCacheEntry(target, request);
    } catch (final IOException ioe) {
        // nop
    }
    if (existing == null) {
        return false;
    }
    final Header entryDateHeader = existing.getFirstHeader(HTTP.DATE_HEADER);
    if (entryDateHeader == null) {
        return false;
    }
    final Header responseDateHeader = backendResponse.getFirstHeader(HTTP.DATE_HEADER);
    if (responseDateHeader == null) {
        return false;
    }
    final Date entryDate = DateUtils.parseDate(entryDateHeader.getValue());
    final Date responseDate = DateUtils.parseDate(responseDateHeader.getValue());
    if (entryDate == null || responseDate == null) {
        return false;
    }
    return responseDate.before(entryDate);
}