Example usage for org.apache.commons.httpclient.util DateUtil parseDate

List of usage examples for org.apache.commons.httpclient.util DateUtil parseDate

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.util DateUtil parseDate.

Prototype

public static Date parseDate(String paramString) throws DateParseException 

Source Link

Usage

From source file:org.apache.abdera.protocol.client.RequestOptions.java

/**
 * Returns the date value of the specified header
 *//*from w w w .j a va2 s  . c o m*/
public Date getDateHeader(String header) {
    String val = getHeader(header);
    try {
        return (val != null) ? DateUtil.parseDate(val) : null;
    } catch (DateParseException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.excalibur.source.factories.HTTPClientSource.java

/**
 * Method to update the last modified date of a resource after
 * executing a particular {@link HttpMethod}.
 *
 * @param method {@link HttpMethod} executed
 *//*w w  w .j a va 2 s.c  o  m*/
private void updateLastModified(final HttpMethod method) {
    final Header lastModified = method.getResponseHeader(LAST_MODIFIED);
    try {
        this.m_lastModified = lastModified == null ? 0 : DateUtil.parseDate(lastModified.getValue()).getTime();
    } catch (DateParseException e) {
        // we ignore this exception and simply set last modified to 0
        this.m_lastModified = 0;
    }
}

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

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

    StringBuilder url = new StringBuilder(getRepository().getUrl());
    if (!url.toString().endsWith("/")) {
        url.append('/');
    }/*ww w. jav a 2  s .c  o m*/
    url.append(resource.getName());

    getMethod = new GetMethod(url.toString());

    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);
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

    int statusCode;
    try {
        statusCode = execute(getMethod);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

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

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

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    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 SC_NULL: {
        TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }

    case HttpStatus.SC_FORBIDDEN:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Access denied to: " + url);

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

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

    case HttpStatus.SC_NOT_FOUND:
        throw new ResourceDoesNotExistException("File: " + url + " does not exist");

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

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

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

    Header lastModifiedHeader = getMethod.getResponseHeader("Last-Modified");

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding != null && "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

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

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

    String url = getRepository().getUrl() + "/" + resource.getName();
    getMethod = new GetMethod(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);//from w ww  .  ja v a 2s .com
        Header hdr = new Header("If-Modified-Since", fmt.format(new Date(timestamp)));
        fireTransferDebug("sending ==> " + hdr + "(" + timestamp + ")");
        getMethod.addRequestHeader(hdr);
    }

    int statusCode;
    try {
        statusCode = execute(getMethod);
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

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

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

    // TODO [BP]: according to httpclient docs, really should swallow the output on error. verify if that is
    // required
    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 SC_NULL: {
        TransferFailedException e = new TransferFailedException("Failed to transfer file: " + url);
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);
        throw e;
    }

    case HttpStatus.SC_FORBIDDEN:
        fireSessionConnectionRefused();
        throw new AuthorizationException("Access denied to: " + url);

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

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

    case HttpStatus.SC_NOT_FOUND:
        throw new ResourceDoesNotExistException("File: " + url + " does not exist");

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

    InputStream is = null;

    Header contentLengthHeader = getMethod.getResponseHeader("Content-Length");

    if (contentLengthHeader != null) {
        try {
            long contentLength = Integer.valueOf(contentLengthHeader.getValue()).intValue();

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

    Header lastModifiedHeader = getMethod.getResponseHeader("Last-Modified");

    long lastModified = 0;

    if (lastModifiedHeader != null) {
        try {
            lastModified = DateUtil.parseDate(lastModifiedHeader.getValue()).getTime();

            resource.setLastModified(lastModified);
        } catch (DateParseException e) {
            fireTransferDebug("Unable to parse last modified header");
        }

        fireTransferDebug("last-modified = " + lastModifiedHeader.getValue() + " (" + lastModified + ")");
    }

    Header contentEncoding = getMethod.getResponseHeader("Content-Encoding");
    boolean isGZipped = contentEncoding == null ? false : "gzip".equalsIgnoreCase(contentEncoding.getValue());

    try {
        is = getMethod.getResponseBodyAsStream();
        if (isGZipped) {
            is = new GZIPInputStream(is);
        }
    } catch (IOException e) {
        fireTransferError(resource, e, TransferEvent.REQUEST_GET);

        String msg = "Error occurred while retrieving from remote repository:" + getRepository() + ": "
                + e.getMessage();

        throw new TransferFailedException(msg, e);
    }

    inputData.setInputStream(is);
}

From source file:org.apache.solr.servlet.CacheHeaderTest.java

protected void checkVetoHeaders(HttpMethodBase m, boolean checkExpires) throws Exception {
    Header head = m.getResponseHeader("Cache-Control");
    assertNotNull("We got no Cache-Control header", head);
    assertTrue("We got no no-cache in the Cache-Control header", head.getValue().contains("no-cache"));
    assertTrue("We got no no-store in the Cache-Control header", head.getValue().contains("no-store"));

    head = m.getResponseHeader("Pragma");
    assertNotNull("We got no Pragma header", head);
    assertEquals("no-cache", head.getValue());

    if (checkExpires) {
        head = m.getResponseHeader("Expires");
        assertNotNull("We got no Expires header:" + m.getResponseHeaders(), head);
        Date d = DateUtil.parseDate(head.getValue());
        assertTrue("We got no Expires header far in the past",
                System.currentTimeMillis() - d.getTime() > 100000);
    }/*from   w w  w.  j  av  a  2  s.com*/
}

From source file:org.apache.solr.servlet.CacheHeaderTest.java

protected void doLastModified(String method) throws Exception {
    // We do a first request to get the last modified
    // This must result in a 200 OK response
    HttpMethodBase get = getSelectMethod(method);
    getClient().executeMethod(get);//from  w  w w  .j ava2  s.  co m
    checkResponseBody(method, get);

    assertEquals("Got no response code 200 in initial request", 200, get.getStatusCode());

    Header head = get.getResponseHeader("Last-Modified");
    assertNotNull("We got no Last-Modified header", head);

    Date lastModified = DateUtil.parseDate(head.getValue());

    // If-Modified-Since tests
    get = getSelectMethod(method);
    get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date()));

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 304 NotModified response with current date", 304, get.getStatusCode());

    get = getSelectMethod(method);
    get.addRequestHeader("If-Modified-Since", DateUtil.formatDate(new Date(lastModified.getTime() - 10000)));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 200 OK response with If-Modified-Since in the past", 200, get.getStatusCode());

    // If-Unmodified-Since tests
    get = getSelectMethod(method);
    get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date(lastModified.getTime() - 10000)));

    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 412 Precondition failed with If-Unmodified-Since in the past", 412,
            get.getStatusCode());

    get = getSelectMethod(method);
    get.addRequestHeader("If-Unmodified-Since", DateUtil.formatDate(new Date()));
    getClient().executeMethod(get);
    checkResponseBody(method, get);
    assertEquals("Expected 200 OK response with If-Unmodified-Since and current date", 200,
            get.getStatusCode());
}

From source file:org.basket3.web.S3ObjectRequest.java

/**
 * Create an <code>S3Object</code> based on the request supporting virtual
 * hosting of buckets./*ww w .j a v a  2 s. c o  m*/
 * 
 * @param req
 *            The original request.
 * @param baseHost
 *            The <code>baseHost</code> is the HTTP Host header that is
 *            "expected". This is used to help determine how the bucket name
 *            will be interpreted. This is used to implement the "Virtual
 *            Hosting of Buckets".
 * @param authenticator
 *            The authenticator to use to authenticate this request.
 * @return An object initialized from the request.
 * @throws IllegalArgumentException
 *             Invalid request.
 */
@SuppressWarnings("unchecked")
public static S3ObjectRequest create(HttpServletRequest req, String baseHost, Authenticator authenticator)
        throws IllegalArgumentException, AuthenticatorException {
    S3ObjectRequest o = new S3ObjectRequest();
    String pathInfo = req.getPathInfo();
    String contextPath = req.getContextPath();
    String requestURI = req.getRequestURI();
    String undecodedPathPart = null;
    int pathInfoLength;
    String requestURL;
    String serviceEndpoint;
    String bucket = null;
    String key = null;
    String host;
    String value;
    String timestamp;

    baseHost = baseHost.toLowerCase();

    host = req.getHeader("Host");
    if (host != null) {
        host = host.toLowerCase();
    }

    try {
        requestURL = URLDecoder.decode(req.getRequestURL().toString(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        // should never happen
        e.printStackTrace();
        IllegalArgumentException t = new IllegalArgumentException("Unsupport encoding: UTF-8");
        t.initCause(e);
        throw t;
    }

    if (!requestURL.endsWith(pathInfo)) {
        String m = "requestURL [" + requestURL + "] does not end with pathInfo [" + pathInfo + "]";
        throw new IllegalArgumentException(m);
    }

    pathInfoLength = pathInfo.length();

    serviceEndpoint = requestURL.substring(0, requestURL.length() - pathInfoLength);

    if (debug) {
        System.out.println("---------------");
        System.out.println("requestURI: " + requestURI);
        System.out.println("serviceEndpoint: " + serviceEndpoint);
        System.out.println("---------------");
    }
    Preconditions.checkNotNull(contextPath, "Context path cannot be null");

    if ((host == null) || // http 1.0 form
            (host.equals(baseHost))) { // ordinary method
        // http 1.0 form
        // bucket first part of path info
        // key second part of path info
        if (pathInfoLength > 1) {
            int index = pathInfo.indexOf('/', 1);
            if (index > -1) {
                bucket = pathInfo.substring(1, index);

                if (pathInfoLength > (index + 1)) {
                    key = pathInfo.substring(index + 1);
                    undecodedPathPart = requestURI.substring(contextPath.length() + 1 + bucket.length(),
                            requestURI.length());
                }
            } else {
                bucket = pathInfo.substring(1);
            }
        }
    } else if (host.endsWith("." + baseHost)) {
        // bucket prefix of host
        // key is path info
        bucket = host.substring(0, host.length() - 1 - baseHost.length());
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    } else {
        // bucket is host
        // key is path info
        bucket = host;
        if (pathInfoLength > 1) {
            key = pathInfo.substring(1);
            undecodedPathPart = requestURI.substring(contextPath.length(), requestURI.length());
        }
    }

    // timestamp
    timestamp = req.getHeader("Date");

    // CanonicalizedResource
    StringBuffer canonicalizedResource = new StringBuffer();

    canonicalizedResource.append('/');
    if (bucket != null) {
        canonicalizedResource.append(bucket);
    }
    if (undecodedPathPart != null) {
        canonicalizedResource.append(undecodedPathPart);
    }
    if (req.getParameter(PARAMETER_ACL) != null) {
        canonicalizedResource.append("?").append(PARAMETER_ACL);
    }

    // CanonicalizedAmzHeaders
    StringBuffer canonicalizedAmzHeaders = new StringBuffer();
    Map<String, String> headers = new TreeMap<String, String>();
    String headerName;
    String headerValue;

    Preconditions.checkNotNull(req.getHeaderNames(), "Http Request Header names cannot be null");

    for (Enumeration headerNames = req.getHeaderNames(); headerNames.hasMoreElements();) {
        headerName = ((String) headerNames.nextElement()).toLowerCase();

        if (headerName.startsWith("x-amz-")) {
            for (Enumeration headerValues = req.getHeaders(headerName); headerValues.hasMoreElements();) {
                headerValue = (String) headerValues.nextElement();
                String currentValue = headers.get(headerValue);

                if (currentValue != null) {
                    // combine header fields with the same name
                    headers.put(headerName, currentValue + "," + headerValue);
                } else {
                    headers.put(headerName, headerValue);
                }

                if (headerName.equals("x-amz-date")) {
                    timestamp = headerValue;
                }
            }
        }
    }

    for (Iterator<String> iter = headers.keySet().iterator(); iter.hasNext();) {
        headerName = iter.next();
        headerValue = headers.get(headerName);
        canonicalizedAmzHeaders.append(headerName).append(":").append(headerValue).append("\n");
    }

    StringBuffer stringToSign = new StringBuffer();

    stringToSign.append(req.getMethod()).append("\n");
    value = req.getHeader("Content-MD5");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Content-Type");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    value = req.getHeader("Date");
    if (value != null) {
        stringToSign.append(value);
    }
    stringToSign.append("\n");
    stringToSign.append(canonicalizedAmzHeaders);
    stringToSign.append(canonicalizedResource);

    if (debug) {
        System.out.println(":v:v:v:v:");
        System.out.println("undecodedPathPart: " + undecodedPathPart);
        System.out.println("canonicalizedAmzHeaders: " + canonicalizedAmzHeaders);
        System.out.println("canonicalizedResource: " + canonicalizedResource);
        System.out.println("stringToSign: " + stringToSign);
        System.out.println(":^:^:^:^:");
    }

    o.setServiceEndpoint(serviceEndpoint);
    o.setBucket(bucket);
    o.setKey(key);
    try {
        if (timestamp == null) {
            o.setTimestamp(null);
        } else {
            o.setTimestamp(DateUtil.parseDate(timestamp));
        }
    } catch (DateParseException e) {
        o.setTimestamp(null);
    }
    o.setStringToSign(stringToSign.toString());
    o.setRequestor(authenticate(req, o));

    return o;
}

From source file:org.callimachusproject.auth.DigestAuthenticationManager.java

private boolean isRecentDigest(Object target, Map<String, String[]> request,
        Map<String, String> authorization) {
    if (authorization == null)
        return false;
    String url = request.get("request-target")[0];
    String date = request.get("date")[0];
    String[] via = request.get("via");
    String realm = authorization.get("realm");
    String uri = authorization.get("uri");
    String username = authorization.get("username");
    if (username == null)
        throw new BadRequest("Missing username");
    ParsedURI parsed = new ParsedURI(url);
    String path = parsed.getPath();
    if (parsed.getQuery() != null) {
        path = path + "?" + parsed.getQuery();
    }// w ww  .jav a2 s.c  o  m
    if (realm == null || !url.equals(uri) && !path.equals(uri)) {
        logger.info("Bad authorization on {} using {}", url, authorization);
        throw new BadRequest("Bad Authorization");
    }
    if (!realm.equals(authName))
        return false;
    try {
        long now = DateUtil.parseDate(date).getTime();
        String nonce = authorization.get("nonce");
        if (nonce == null)
            return false;
        int first = nonce.indexOf(':');
        int last = nonce.lastIndexOf(':');
        if (first < 0 || last < 0)
            return false;
        if (!hash(via).equals(nonce.substring(last + 1)))
            return false;
        String revision = nonce.substring(first + 1, last);
        if (!revision.equals(getRevisionOf(target)))
            return false;
        String time = nonce.substring(0, first);
        Long ms = Long.valueOf(time, Character.MAX_RADIX);
        long age = now - ms;
        return age < MAX_NONCE_AGE;
    } catch (NumberFormatException e) {
        logger.debug(e.toString(), e);
        return false;
    } catch (DateParseException e) {
        logger.warn(e.toString(), e);
        return false;
    }
}

From source file:org.deri.pipes.utils.HttpResponseCache.java

/**
 * @param data//from  ww w .  ja va 2 s. c  om
 * @param headMethod
 */
private static void setExpires(HttpResponseData data, HttpMethodBase method) {
    long expires = System.currentTimeMillis() + MINIMUM_CACHE_TIME_MILLIS;
    Header expiresHeader = method.getResponseHeader(EXPIRES_HEADER);
    if (expiresHeader != null) {
        try {
            Date expiresDate = DateUtil.parseDate(expiresHeader.getValue());
            if (expiresDate.getTime() > expires) {
                logger.info("Setting cache time according to expiresHeader=[" + expiresHeader.getValue() + "]");
                expires = expiresDate.getTime();
            } else {
                logger.debug("Ignoring expires header [" + expiresHeader.getValue() + "]");
            }
        } catch (Exception e) {
            logger.debug("Problem parsing expires header [" + expiresHeader.getValue() + "]");
        }
    }
    data.setExpires(expires);

}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientFileSystemBrowser.java

private long getLastModifiedTimeFromHeader() throws IOException {
    Header lastModifiedHeader = headMethod.getResponseHeader("Last-Modified"); //$NON-NLS-1$
    if (lastModifiedHeader == null)
        return 0L;
    String lastModifiedString = lastModifiedHeader.getValue();
    long lastModified = 0;
    if (lastModifiedString != null) {
        try {/*  ww  w.  j  ava2s. c  o m*/
            lastModified = DateUtil.parseDate(lastModifiedString).getTime();
        } catch (Exception e) {
            throw new IOException(
                    Messages.HttpClientRetrieveFileTransfer_EXCEPITION_INVALID_LAST_MODIFIED_FROM_SERVER);
        }
    }
    return lastModified;
}