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

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

Introduction

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

Prototype

public HeadMethod(String paramString) 

Source Link

Usage

From source file:org.switchyard.component.test.mixins.http.HTTPMixIn.java

/**
 * Send the specified request payload to the specified HTTP endpoint using the method specified.
 * @param endpointURL The HTTP endpoint URL.
 * @param request The request payload.//from www .j ava  2  s.  co  m
 * @param method The request method.
 * @return The HttpMethod object.
 */
public HttpMethod sendStringAndGetMethod(String endpointURL, String request, String method) {
    if (_dumpMessages) {
        _logger.info("Sending a " + method + " request to [" + endpointURL + "]");
        _logger.info("Request body:[" + request + "]");
    }
    HttpMethod httpMethod = null;
    try {
        if (method.equals(HTTP_PUT)) {
            httpMethod = new PutMethod(endpointURL);
            ((PutMethod) httpMethod).setRequestEntity(new StringRequestEntity(request, _contentType, "UTF-8"));
        } else if (method.equals(HTTP_POST)) {
            httpMethod = new PostMethod(endpointURL);
            ((PostMethod) httpMethod).setRequestEntity(new StringRequestEntity(request, _contentType, "UTF-8"));
        } else if (method.equals(HTTP_DELETE)) {
            httpMethod = new DeleteMethod(endpointURL);
        } else if (method.equals(HTTP_OPTIONS)) {
            httpMethod = new OptionsMethod(endpointURL);
        } else if (method.equals(HTTP_HEAD)) {
            httpMethod = new HeadMethod(endpointURL);
        } else {
            httpMethod = new GetMethod(endpointURL);
        }
        execute(httpMethod);
    } catch (UnsupportedEncodingException e) {
        _logger.error("Unable to set request entity", e);
    }
    return httpMethod;
}

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 .  ja v  a2  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:phex.download.PushRequestSleeper.java

private boolean requestViaPushProxies() {
    assert pushProxyAddresses != null && pushProxyAddresses.length > 0;

    // format: /gnet/push-proxy?guid=<ServentIdAsABase16UrlEncodedString>
    String requestPart = "/gnet/push-proxy?guid=" + clientGUID.toHexString();

    ((SimpleStatisticProvider) statsService
            .getStatisticProvider(StatisticsManager.PUSH_DLDPUSHPROXY_ATTEMPTS_PROVIDER)).increment(1);

    for (int i = 0; i < pushProxyAddresses.length; i++) {
        String urlStr = "http://" + pushProxyAddresses[i].getFullHostName() + requestPart;
        NLogger.debug(PushRequestSleeper.class, "PUSH via push proxy: " + urlStr);

        HttpClient httpClient = HttpClientFactory.createHttpClient();
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(1, false));

        httpClient.getParams().setSoTimeout(10000);
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        HeadMethod method = null;/*from   w w w.  java2 s  . c o m*/
        try {
            method = new HeadMethod(urlStr);
            method.addRequestHeader(GnutellaHeaderNames.X_NODE, serventAddress.getFullHostName());
            method.addRequestHeader("Cache-Control", "no-cache");
            method.addRequestHeader(HTTPHeaderNames.CONNECTION, "close");

            int responseCode = httpClient.executeMethod(method);

            NLogger.debug(PushRequestSleeper.class,
                    "PUSH via push proxy response code: " + responseCode + " (" + urlStr + ')');

            // if 202
            if (responseCode == HttpURLConnection.HTTP_ACCEPTED) {
                ((SimpleStatisticProvider) statsService
                        .getStatisticProvider(StatisticsManager.PUSH_DLDPUSHPROXY_SUCESS_PROVIDER))
                                .increment(1);
                return true;
            }
        } catch (IOException exp) {
            NLogger.warn(PushRequestSleeper.class, exp);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }
    return false;
}

From source file:typoscript.TypoScriptPluginOptions.java

/**
 * Checks to ensure all fields are filled out and that login credentials check out
 * /*from   w w w  .  j  av a 2 s.c o  m*/
 * @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;

}

From source file:uk.co.firstzero.webdav.Push.java

public boolean fileExists(String url) throws IOException {
    return Common.executeMethod(httpClient, new HeadMethod(url), true);
}