Example usage for org.apache.commons.httpclient.methods HeadMethod getResponseHeader

List of usage examples for org.apache.commons.httpclient.methods HeadMethod getResponseHeader

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods HeadMethod getResponseHeader.

Prototype

@Override
public Header getResponseHeader(String headerName) 

Source Link

Document

Gets the response header associated with the given name.

Usage

From source file:org.jenkins.ci.backend.war_size_tracker.Report.java

protected static Jenkins getJenkins(final String version) throws IOException {
    final HttpClient client = new HttpClient();
    final HeadMethod head = new HeadMethod(
            "http://mirrors.jenkins-ci.org/war/" + version + "/" + getJenkinsWarName(version));

    final int status = client.executeMethod(head);

    if (status < 400) {
        final Header contentLength = head.getResponseHeader("Content-Length");

        if (contentLength != null) {
            return new Jenkins(version, Long.valueOf(contentLength.getValue()));
        }/*  www.ja  va 2  s .  c  om*/
    }

    return null;
}

From source file:org.nuxeo.ecm.core.storage.sql.ScalityBinaryManager.java

/**
 * Retrieves the content-length of the remote object
 *
 * @param objectID/* ww w  . ja v a  2  s  .c o  m*/
 */
public long getContentLength(String objectID) {
    String url = PROTOCOL_PREFIX + this.bucketName + "." + this.hostBase;
    log.debug(url);
    HeadMethod headMethod = new HeadMethod(url);
    String contentMD5 = "";
    String stringToSign = StringGenerator.getStringToSign(HTTPMethod.HEAD, contentMD5, DEFAULT_CONTENT_TYPE,
            this.bucketName, objectID, new Date());
    long contentLength = 0;
    try {
        headMethod.addRequestHeader("Authorization",
                StringGenerator.getAuthorizationString(stringToSign, awsID, awsSecret));
        headMethod.addRequestHeader("x-amz-date", StringGenerator.getCurrentDateString());
        headMethod.setPath("/" + objectID);
        HttpClient client = new HttpClient();
        int returnCode = client.executeMethod(headMethod);
        // specific header
        if (returnCode == HttpStatus.SC_OK) {
            Header contentLengthHeader = headMethod.getResponseHeader("Content-Length");
            contentLength = Long.parseLong(contentLengthHeader.getValue());

        } else if (returnCode == HttpStatus.SC_NOT_FOUND) {
            log.debug("Object " + objectID + " does not exist");
        } else {
            String connectionMsg = "Scality connection problem. Object could not be verified";
            log.debug(connectionMsg);
            throw new RuntimeException(connectionMsg);
        }
        headMethod.releaseConnection();
    } catch (NumberFormatException e) {
        throw new RuntimeException(e);
    } catch (SignatureException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return contentLength;
}

From source file:org.opensaml.util.resource.HttpResource.java

/** {@inheritDoc} */
public DateTime getLastModifiedTime() throws ResourceException {
    HeadMethod headMethod = new HeadMethod(resourceUrl);

    try {//from   ww w  .ja v a2 s .  co m
        httpClient.executeMethod(headMethod);
        if (headMethod.getStatusCode() != HttpStatus.SC_OK) {
            throw new ResourceException("Unable to retrieve resource URL " + resourceUrl
                    + ", received HTTP status code " + headMethod.getStatusCode());
        }
        Header lastModifiedHeader = headMethod.getResponseHeader("Last-Modified");
        if (lastModifiedHeader != null) {
            HeaderElement[] elements = lastModifiedHeader.getElements();
            if (elements.length > 0) {
                long lastModifiedTime = DateUtil.parseDate(elements[0].getValue()).getTime();
                return new DateTime(lastModifiedTime);
            }
        }

        return new DateTime();
    } catch (IOException e) {
        throw new ResourceException("Unable to contact resource URL: " + resourceUrl, e);
    } catch (DateParseException e) {
        throw new ResourceException("Unable to parse last modified date for resource:" + resourceUrl, e);
    }
}

From source file:org.osaf.caldav4j.CalDAVCalendarCollection.java

protected String getETag(HttpClient httpClient, String path) throws CalDAV4JException {
    HeadMethod headMethod = new HeadMethod(path);

    try {//from www .  ja v  a 2s  . c o m
        httpClient.executeMethod(hostConfiguration, headMethod);
        int statusCode = headMethod.getStatusCode();

        if (statusCode == CaldavStatus.SC_NOT_FOUND) {
            throw new ResourceNotFoundException(ResourceNotFoundException.IdentifierType.PATH, path);
        }

        if (statusCode != CaldavStatus.SC_OK) {
            throw new CalDAV4JException(
                    "Unexpected Status returned from Server: " + headMethod.getStatusCode());
        }
    } catch (IOException e) {
        throw new CalDAV4JException("Problem executing get method", e);
    }

    Header h = headMethod.getResponseHeader("ETag");
    String etag = null;
    if (h != null) {
        etag = h.getValue();
    }
    return etag;
}

From source file:org.osaf.caldav4j.CalDAVCollection.java

/**
 * retrieve etags using HEAD /path/to/resource.ics
 * /*from   w w  w . ja  v a 2s.c o  m*/
 * @param httpClient
 * @param path
 * @return
 * @throws CalDAV4JException
 */
protected String getETag(HttpClient httpClient, String path) throws CalDAV4JException {
    HeadMethod headMethod = new HeadMethod(path);

    try {
        httpClient.executeMethod(hostConfiguration, headMethod);
        int statusCode = headMethod.getStatusCode();

        if (statusCode == CaldavStatus.SC_NOT_FOUND) {
            throw new ResourceNotFoundException(ResourceNotFoundException.IdentifierType.PATH, path);
        }

        if (statusCode != CaldavStatus.SC_OK) {
            throw new CalDAV4JException(
                    "Unexpected Status returned from Server: " + headMethod.getStatusCode());
        }
    } catch (IOException e) {
        String message = hostConfiguration.getHostURL() + headMethod.getPath();
        throw new CalDAV4JException("Problem executing HEAD method on: " + message, e);
    }

    Header h = headMethod.getResponseHeader(HEADER_ETAG);
    String etag = null;
    if (h != null) {
        etag = h.getValue();
    }
    return etag;
}

From source file:org.paxle.crawler.urlRedirector.impl.testers.HttpTester.java

private String getMimeType(HeadMethod head) {
    final Header contentTypeHeader = head.getResponseHeader("Content-Type");
    if (contentTypeHeader == null)
        return null;

    // separate MIME-type and charset from the content-type specification
    String contentMimeType = contentTypeHeader.getValue();

    int idx = contentMimeType.indexOf(";");
    if (idx != -1) {
        contentMimeType = contentMimeType.substring(0, idx);
    }/*w  w w  .java2s .com*/

    return contentMimeType;
}

From source file:org.springsource.ide.eclipse.commons.internal.core.net.HttpClientTransportService.java

/**
 * Verify availability of resources at the given web locations. Normally
 * this would be done using an HTTP HEAD.
 * /*from w ww .j a  va 2  s .c  o m*/
 * @param locations the locations of the resource to verify
 * @param one indicate if only one of the resources must exist
 * @param progressMonitor the monitor
 * @return true if the resource exists
 */
public long getLastModified(java.net.URI uri, IProgressMonitor progressMonitor) throws CoreException {
    WebLocation location = new WebLocation(uri.toString());
    SubMonitor monitor = SubMonitor.convert(progressMonitor);
    monitor.subTask(NLS.bind("Fetching {0}", location.getUrl()));
    try {
        HttpClient client = new HttpClient();
        org.eclipse.mylyn.commons.net.WebUtil.configureHttpClient(client, ""); //$NON-NLS-1$

        HeadMethod method = new HeadMethod(location.getUrl());
        try {
            HostConfiguration hostConfiguration = org.eclipse.mylyn.commons.net.WebUtil
                    .createHostConfiguration(client, location, monitor);
            int result = org.eclipse.mylyn.commons.net.WebUtil.execute(client, hostConfiguration, method,
                    monitor);
            if (result == HttpStatus.SC_OK) {
                Header lastModified = method.getResponseHeader("Last-Modified"); //$NON-NLS-1$
                if (lastModified != null) {
                    try {
                        return DateUtil.parseDate(lastModified.getValue()).getTime();
                    } catch (DateParseException e) {
                        // fall through
                    }
                }
                return 0;
            } else {
                throw toException(location, result);
            }
        } catch (IOException e) {
            throw toException(location, e);
        } finally {
            method.releaseConnection();
        }
    } finally {
        monitor.done();
    }
}

From source file:osl.examples.gui.downloader.DownloadManager.java

@message
public void download(String url, String localFile, Integer numOfParts) {
    String checkUrlResult = checkValidUrl(url);
    if (checkUrlResult.equals("OK")) {
        this.numOfWorkers = numOfParts;
        this.partFiles = new String[this.numOfWorkers];
        this.completePerWorker = new Integer[this.numOfWorkers];
        chunkReceived = 0;/* ww w .  j a va2  s.c  o m*/
        this.localFile = localFile;
        File tempDir = new File(System.getProperty("java.io.tmpdir"));
        HttpClient client = new HttpClient();
        HeadMethod request = new HeadMethod(url);
        try {
            if (client.executeMethod(request) != HttpStatus.SC_OK) {
                System.out.println("NOT OK!!");
            } else {
                Header contentLengthHeader = request.getResponseHeader("content-length");
                if (contentLengthHeader == null) {
                    send(app, "error", "Invalid Content Length. Unable to determine the file size.");
                    return;
                }
                long remoteFileSize = Long.parseLong(contentLengthHeader.getValue());

                System.out.println("Remote file size is " + remoteFileSize + " bytes.");

                int chunkSize = (int) (remoteFileSize / numOfWorkers);
                for (int i = 0; i < numOfWorkers - 1; i++) {
                    ActorName a = create(DLWorker.class);
                    send(a, "downloadChunk", url, i * chunkSize, chunkSize, remoteFileSize, i, tempDir, self());
                }
                ActorName a = create(DLWorker.class);
                send(a, "downloadChunk", url, (int) (numOfWorkers - 1) * chunkSize,
                        (int) remoteFileSize - (numOfWorkers - 1) * chunkSize, remoteFileSize,
                        (numOfWorkers - 1), tempDir, self());
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (RemoteCodeException e) {
            e.printStackTrace();
        }
    } else {
        send(app, "error", checkUrlResult);
    }
}

From source file:typoscript.TypoScriptPluginOptions.java

/**
 * Checks to ensure all fields are filled out and that login credentials check out
 * /* ww  w. j a v  a  2 s.  c om*/
 * @param reportOK Whether to report on success (false if this is a passive check before adding)
 * @return true if everything checks out
 */
private boolean test(boolean reportOK) {
    URL urlFull = null;
    URL urlBase = null;

    if (txtURL.getText().length() == 0) {
        JOptionPane.showMessageDialog(this, "You must specify a URL", "URL Field Blank",
                JOptionPane.ERROR_MESSAGE);
        return false;
    } else {
        try {
            String typeNum = jEdit.getProperty(TypoScriptPlugin.PROPERTY_PREFIX + "typenum");
            urlFull = new URL(txtURL.getText() + "index.php?type=" + typeNum);
            urlBase = new URL(txtURL.getText());
        } catch (MalformedURLException e) {
            JOptionPane.showMessageDialog(this,
                    "The URL you entered was not valid.\nPlease ensure it starts with http:// or https:// and contains no spaces or other characters that would normally be disallowed in a URL",
                    "Invalid URL", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!txtURL.getText().endsWith("/")) {
            JOptionPane.showMessageDialog(this,
                    "The URL you entered did not end with a '/' character. This is required.\nIf you would normally login at http://typo3.example.com/typo3/, then you need to enter http://typo3.example.com/",
                    "Invalid URL", JOptionPane.ERROR_MESSAGE);
            return false;
        }
    }
    if (txtUser.getText().length() == 0) {
        JOptionPane.showMessageDialog(this,
                "You must specify a username, even if you have some alternative authentication scheme (make one up)",
                "Username Field Blank", JOptionPane.ERROR_MESSAGE);
        return false;
    }
    if (txtPass.getPassword().length == 0) {
        JOptionPane.showMessageDialog(this, "You must specify a password", "Password Field Blank",
                JOptionPane.ERROR_MESSAGE);
        return false;
    }

    // First stage checks out. Disable the buttons and check the provided information
    disableButtons();

    this.pack(); // resize window

    try {
        HttpClient client = new HttpClient();
        HeadMethod head = new HeadMethod(urlFull.toString());
        client.executeMethod(head);

        //head.execute()
        if (head.getStatusCode() != HttpStatus.SC_OK) {
            JOptionPane.showMessageDialog(this, "Received a non-200 response code from the server: "
                    + head.getStatusCode() + "(" + head.getStatusText()
                    + ")\nPlease ensure there are no rewrite rules or redirects in the way.\nI tried URL: "
                    + urlFull.toString(), "Non-200 response", JOptionPane.ERROR_MESSAGE);
            resetButtonState();
            return false;
        }
        if (head.getResponseHeader("X-jeditvfs-present") == null) {
            JOptionPane.showMessageDialog(this,
                    "The jEdit VFS extension doesn't appear to be installed on the remote site.\nPlease install the 'jeditvfs' plugin from the TYPO3 extension repository and try again.\nIt's also possible the URL didn't point to the right place.\nYou  shoud be pointing to the root of the FRONTEND of your site.\nI tried: "
                            + urlFull.toString(),
                    "jeditvfs extension not located", JOptionPane.ERROR_MESSAGE);
            resetButtonState();
            return false;
        }
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this,
                "An I/O error occured while testing the site.\nPlease check your internet connection. Details below:\n"
                        + e.toString(),
                "IOException", JOptionPane.ERROR_MESSAGE);
        resetButtonState();
        return false;
    }

    // That worked. Now we need to construct a real T3Site object and perform an authentication check (and get the site name in the process)
    curSite = new T3Site(urlBase, urlFull, txtUser.getText(), new String(txtPass.getPassword()),
            chkClearCache.isSelected());

    try {
        curSite.setName(curSite.getWorker().getSiteTitle());
    } catch (IOException e) {
        JOptionPane.showMessageDialog(this,
                "An I/O error occured while testing the site.\nPlease check your internet connection. Details below:\n"
                        + e.toString(),
                "IOException", JOptionPane.ERROR_MESSAGE);
        resetButtonState();
        return false;
    } catch (XmlRpcException e) {
        // Probably an authentication failure.
        if (e.code == RemoteCallWorker.JEDITVFS_ERROR_AUTHFAIL) {
            JOptionPane.showMessageDialog(this,
                    "Authentication failed.\nPlease make sure you typed your username and password correctly.\nNote also that you require an admin-level backend account to use this system.\nIf you get this failure and are using an exotic authentication scheme, please contact the developer of this plugin to report a bug.\nServer said: "
                            + e.getMessage(),
                    "Backend authentication failed", JOptionPane.ERROR_MESSAGE);
        } else {
            JOptionPane.showMessageDialog(this,
                    "The server returned an unexpected response in reply to an authentication test\nServer said: "
                            + e.getMessage(),
                    "Unexpected XML-RPC exception", JOptionPane.ERROR_MESSAGE);
        }
        resetButtonState();
        return false;
    }

    if (reportOK) {
        JOptionPane.showMessageDialog(this, "All OK", "All tests passed", JOptionPane.INFORMATION_MESSAGE);
    }
    resetButtonState();
    return true;

}