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

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

Introduction

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

Prototype

public static String formatDate(final Date date) 

Source Link

Document

Formats the given date according to the RFC 1123 pattern.

Usage

From source file:net.staticsnow.nexus.repository.apt.internal.hosted.AptHostedFacet.java

private String buildReleaseFile(String distribution, Collection<String> architectures, String md5,
        String sha256) {/*from w ww.ja v  a2s  .com*/
    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();
}

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

/**
 * Opens a connection to the given HTTP host and requests a file. Checks
 * the last-modified header on the server if the given timestamp is
 * greater than 0./* w  ww  .  ja  va2  s  .c  o  m*/
 * @param httpHost the HTTP host to connect to
 * @param file the file to request
 * @param timestamp the timestamp of the destination file, in milliseconds
 * @param client the HTTP client to use to perform the request
 * @return the URLConnection
 * @throws IOException if the connection could not be opened
 */
private CloseableHttpResponse openConnection(HttpHost httpHost, String file, long timestamp,
        CloseableHttpClient client) throws IOException {
    //perform preemptive authentication
    HttpClientContext context = null;
    if ((username != null && password != null) || credentials != null) {
        context = HttpClientContext.create();
        AuthScheme as = authScheme;
        if (as == null) {
            as = new BasicScheme();
        }
        Credentials c;
        if (username != null && password != null) {
            if (!(as instanceof BasicScheme) && !(as instanceof DigestScheme)) {
                throw new IllegalArgumentException("If 'username' and "
                        + "'password' are set 'authScheme' must be either " + "'Basic' or 'Digest'.");
            }
            c = new UsernamePasswordCredentials(username, password);
        } else {
            c = credentials;
        }
        addAuthentication(httpHost, c, as, context);
    }

    //create request
    HttpGet get = new HttpGet(file);

    //configure timeouts
    RequestConfig config = RequestConfig.custom().setConnectTimeout(timeoutMs)
            .setConnectionRequestTimeout(timeoutMs).setSocketTimeout(timeoutMs).build();
    get.setConfig(config);

    //add authentication information for proxy
    String scheme = httpHost.getSchemeName();
    String proxyHost = System.getProperty(scheme + ".proxyHost");
    String proxyPort = System.getProperty(scheme + ".proxyPort");
    String proxyUser = System.getProperty(scheme + ".proxyUser");
    String proxyPassword = System.getProperty(scheme + ".proxyPassword");
    if (proxyHost != null && proxyPort != null && proxyUser != null && proxyPassword != null) {
        if (context == null) {
            context = HttpClientContext.create();
        }
        int nProxyPort = Integer.parseInt(proxyPort);
        HttpHost proxy = new HttpHost(proxyHost, nProxyPort, scheme);
        Credentials credentials = new UsernamePasswordCredentials(proxyUser, proxyPassword);
        addAuthentication(proxy, credentials, null, context);
    }

    //set If-Modified-Since header
    if (timestamp > 0) {
        get.setHeader("If-Modified-Since", DateUtils.formatDate(new Date(timestamp)));
    }

    //set headers
    if (headers != null) {
        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
            get.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }
    }

    //enable compression
    if (compress) {
        get.setHeader("Accept-Encoding", "gzip");
    }

    //execute request
    CloseableHttpResponse response = client.execute(httpHost, get, context);

    //handle response
    int code = response.getStatusLine().getStatusCode();
    if ((code < 200 || code > 299) && code != HttpStatus.SC_NOT_MODIFIED) {
        throw new ClientProtocolException(response.getStatusLine().getReasonPhrase());
    }

    return response;
}

From source file:org.eclipse.aether.transport.http.HttpTransporter.java

private <T extends HttpUriRequest> T resume(T request, GetTask task) {
    long resumeOffset = task.getResumeOffset();
    if (resumeOffset > 0L && task.getDataFile() != null) {
        request.setHeader(HttpHeaders.RANGE, "bytes=" + Long.toString(resumeOffset) + '-');
        request.setHeader(HttpHeaders.IF_UNMODIFIED_SINCE,
                DateUtils.formatDate(new Date(task.getDataFile().lastModified() - 60L * 1000L)));
        request.setHeader(HttpHeaders.ACCEPT_ENCODING, "identity");
    }/*w ww.j a  va 2s.co m*/
    return request;
}

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   w  w  w  .j  a v a 2  s.  c  om*/
@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:com.hypersocket.netty.HttpRequestDispatcherHandler.java

private void addStandardHeaders(HttpResponseServletWrapper servletResponse) {

    servletResponse.setHeader("Server", server.getApplicationName());

    String connection = servletResponse.getRequest().getHeader(HttpHeaders.CONNECTION);
    if (connection != null && connection.equalsIgnoreCase("close")) {
        servletResponse.setHeader("Connection", "close");
        servletResponse.setCloseOnComplete(true);
    }/*from w w w .j av  a 2 s . co  m*/

    servletResponse.setHeader("Date", DateUtils.formatDate(new Date(System.currentTimeMillis())));
}