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.lucterios.engine.transport.HttpTransportImpl.java

public int getFileLength(String aWebFile) throws LucteriosException {
    Logging.getInstance().writeLog("### HEADER ###", aWebFile, 2);
    int size = 0;
    String value = "";
    java.net.URL path_url = getUrl(aWebFile);
    int repeat_loop_index = 3;
    while (repeat_loop_index > 0) {
        try {// w ww  . j  av a2s .  co  m
            header = new HeadMethod(path_url.toString());
            try {
                // Execute the HEADER method
                int statusCode = m_Cnx.executeMethod(getHostCnx(), header);
                if (statusCode == HttpStatus.SC_OK) {
                    value = header.getResponseHeader("Content-Length").getValue();
                    if (value != null) {
                        size = Integer.parseInt(value);
                        repeat_loop_index = 0;
                    } else
                        repeat_loop_index--;
                } else {
                    repeat_loop_index--;
                    if ((statusCode != HttpStatus.SC_NOT_FOUND) || (repeat_loop_index <= 0))
                        throw new TransportException(header.getStatusLine().getReasonPhrase(),
                                TransportException.TYPE_HTTP, statusCode, "", "");
                }
            } finally {
                downloadFinished();
            }
        } catch (java.net.ConnectException ce) {
            repeat_loop_index--;
            throw new LucteriosException("Erreur de Header", aWebFile, value, ce);
        } catch (java.net.UnknownHostException uhe) {
            repeat_loop_index--;
            throw new LucteriosException("Erreur de Header", aWebFile, value, uhe);
        } catch (IOException ioe) {
            repeat_loop_index--;
            throw new LucteriosException("Erreur de Header", aWebFile, value, ioe);
        }
    }
    return size;
}

From source file:org.mbs3.deliciouschecker.DeliciousChecker.java

/**
 * @param args/*from   www. j  a  va2 s .c o m*/
 */
public static void main(String[] args) {
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
    System.out.println("Connecting to del.icio.us");
    Delicious connection = new Delicious(DeliciousChecker.username, DeliciousChecker.password);
    System.out.println("Getting post data for url verification");
    List allPosts = connection.getAllPosts();
    Iterator allPostsIterator = allPosts.iterator();
    System.out.println("Received " + allPosts.size() + " different posts, checking each");

    HttpClient hc = new HttpClient();
    hc.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_0);
    hc.getParams().setParameter("http.socket.timeout", new Integer(1000));
    while (allPostsIterator.hasNext()) {
        Post post = (Post) allPostsIterator.next();
        //System.out.println("Trying " + post.getHref());
        try {
            HeadMethod hm = new HeadMethod(post.getHref());
            hm.setRequestHeader("User-agent", DeliciousChecker.useragent);
            hm.getParams().setParameter("http.socket.timeout", new Integer(5000));
            int response = hc.executeMethod(hm);
            if (response != 200) {
                System.out
                        .println(post.getDescription() + "(" + post.getHref() + ") returned HTTP " + response);
                post.setTag(post.getTag() + " broken");
            }
        } catch (Exception ex) {
            System.out.println(post.getDescription() + "(" + post.getHref() + ") returned " + ex);
            post.setTag(post.getTag() + " exception");
        }

    }
}

From source file:org.melati.admin.Admin.java

private String proxy(Melati melati, ServletTemplateContext context) {
    if (melati.getSession().getAttribute("generatedByMelatiClass") == null)
        throw new AnticipatedException("Only available from within an Admin generated page");
    String method = melati.getRequest().getMethod();
    String url = melati.getRequest().getQueryString();
    HttpServletResponse response = melati.getResponse();
    HttpMethod httpMethod = null;/*  w  w  w.j  a  va  2  s  . com*/
    try {

        HttpClient client = new HttpClient();
        if (method.equals("GET"))
            httpMethod = new GetMethod(url);
        else if (method.equals("POST"))
            httpMethod = new PostMethod(url);
        else if (method.equals("PUT"))
            httpMethod = new PutMethod(url);
        else if (method.equals("HEAD"))
            httpMethod = new HeadMethod(url);
        else
            throw new RuntimeException("Unexpected method '" + method + "'");
        try {
            httpMethod.setFollowRedirects(true);
            client.executeMethod(httpMethod);
            for (Header h : httpMethod.getResponseHeaders()) {
                response.setHeader(h.getName(), h.getValue());
            }
            response.setStatus(httpMethod.getStatusCode());
            response.setHeader("Cache-Control", "no-cache");
            byte[] outputBytes = httpMethod.getResponseBody();
            if (outputBytes != null) {
                response.setBufferSize(outputBytes.length);
                response.getWriter().write(new String(outputBytes));
                response.getWriter().flush();
            }
        } catch (Exception e) {
            throw new MelatiIOException(e);
        }
    } finally {
        if (httpMethod != null)
            httpMethod.releaseConnection();
    }
    return null;
}

From source file:org.mozilla.zest.impl.ZestBasicRunner.java

private ZestResponse send(HttpClient httpclient, ZestRequest req) throws IOException {
    HttpMethod method;/*from  www.j  ava  2 s. c  o m*/
    URI uri = new URI(req.getUrl().toString(), false);

    switch (req.getMethod()) {
    case "GET":
        method = new GetMethod(uri.toString());
        // Can only redirect on GETs
        method.setFollowRedirects(req.isFollowRedirects());
        break;
    case "POST":
        method = new PostMethod(uri.toString());
        break;
    case "OPTIONS":
        method = new OptionsMethod(uri.toString());
        break;
    case "HEAD":
        method = new HeadMethod(uri.toString());
        break;
    case "PUT":
        method = new PutMethod(uri.toString());
        break;
    case "DELETE":
        method = new DeleteMethod(uri.toString());
        break;
    case "TRACE":
        method = new TraceMethod(uri.toString());
        break;
    default:
        throw new IllegalArgumentException("Method not supported: " + req.getMethod());
    }

    setHeaders(method, req.getHeaders());

    for (Cookie cookie : req.getCookies()) {
        // Replace any Zest variables in the value
        cookie.setValue(this.replaceVariablesInString(cookie.getValue(), false));
        httpclient.getState().addCookie(cookie);
    }

    if (req.getMethod().equals("POST")) {
        // The setRequestEntity call trashes any Content-Type specified, so record it and reapply it after
        Header contentType = method.getRequestHeader("Content-Type");
        RequestEntity requestEntity = new StringRequestEntity(req.getData(), null, null);

        ((PostMethod) method).setRequestEntity(requestEntity);

        if (contentType != null) {
            method.setRequestHeader(contentType);
        }
    }

    int code = 0;
    String responseHeader = null;
    String responseBody = null;
    Date start = new Date();
    try {
        this.debug(req.getMethod() + " : " + req.getUrl());
        code = httpclient.executeMethod(method);

        responseHeader = method.getStatusLine().toString() + "\r\n" + arrayToStr(method.getResponseHeaders());
        responseBody = method.getResponseBodyAsString();

    } finally {
        method.releaseConnection();
    }
    // Update the headers with the ones actually sent
    req.setHeaders(arrayToStr(method.getRequestHeaders()));

    if (method.getStatusCode() == 302 && req.isFollowRedirects() && !req.getMethod().equals("GET")) {
        // Follow the redirect 'manually' as the httpclient lib only supports them for GET requests
        method = new GetMethod(method.getResponseHeader("Location").getValue());
        // Just in case there are multiple redirects
        method.setFollowRedirects(req.isFollowRedirects());

        try {
            this.debug(req.getMethod() + " : " + req.getUrl());
            code = httpclient.executeMethod(method);

            responseHeader = method.getStatusLine().toString() + "\r\n"
                    + arrayToStr(method.getResponseHeaders());
            responseBody = method.getResponseBodyAsString();

        } finally {
            method.releaseConnection();
        }
    }

    return new ZestResponse(req.getUrl(), responseHeader, responseBody, code,
            new Date().getTime() - start.getTime());
}

From source file:org.mule.transport.http.functional.HttpMethodTestCase.java

@Test
public void testHead() throws Exception {
    HeadMethod method = new HeadMethod(getHttpEndpointAddress());
    int statusCode = client.executeMethod(method);
    assertEquals(HttpStatus.SC_OK, statusCode);
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

protected HttpMethod createHeadMethod(MuleMessage message) throws Exception {
    URI uri = getURI(message);
    return new HeadMethod(uri.toString());
}

From source file:org.mulgara.resolver.http.HttpContent.java

/**
 * Obtain the approrpriate connection method
 * //from www . ja va  2  s . com
 * @param methodType can be HEAD or GET
 * @return HttpMethodBase method
 */
private HttpMethod getConnectionMethod(int methodType) {
    if (methodType != GET && methodType != HEAD) {
        throw new IllegalArgumentException("Invalid method base supplied for connection");
    }

    HostConfiguration config = new HostConfiguration();
    config.setHost(host, port, Protocol.getProtocol(schema));
    if (connection != null) {
        connection.releaseConnection();
        connection.close();
        connection = null;
    }
    try {
        connection = connectionManager.getConnectionWithTimeout(config, 0L);
    } catch (ConnectionPoolTimeoutException te) {
        // NOOP: SimpleHttpConnectionManager does not use timeouts
    }

    String proxyHost = System.getProperty("mulgara.httpcontent.proxyHost");

    if (proxyHost != null && proxyHost.length() > 0) {
        connection.setProxyHost(proxyHost);
    }

    String proxyPort = System.getProperty("mulgara.httpcontent.proxyPort");
    if (proxyPort != null && proxyPort.length() > 0) {
        connection.setProxyPort(Integer.parseInt(proxyPort));
    }

    // default timeout to 30 seconds
    connection.getParams()
            .setConnectionTimeout(Integer.parseInt(System.getProperty("mulgara.httpcontent.timeout", "30000")));

    String proxyUserName = System.getProperty("mulgara.httpcontent.proxyUserName");
    if (proxyUserName != null) {
        state.setCredentials(
                new AuthScope(System.getProperty("mulgara.httpcontent.proxyRealmHost"), AuthScope.ANY_PORT,
                        System.getProperty("mulgara.httpcontent.proxyRealm"), AuthScope.ANY_SCHEME),
                new UsernamePasswordCredentials(proxyUserName,
                        System.getProperty("mulgara.httpcontent.proxyPassword")));
    }

    HttpMethod method = null;
    if (methodType == HEAD) {
        method = new HeadMethod(httpUri.toString());
    } else {
        method = new GetMethod(httpUri.toString());
    }

    // manually follow redirects due to the
    // strictness of http client implementation

    method.setFollowRedirects(false);

    return method;
}

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

/**
 * Verifies if a specific named bucket exists.
 *
 * @param objectID/*  w ww.j  av a  2 s.  c  o  m*/
 */
public boolean objectExists(String objectID) {
    boolean objectExists = false;
    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());
    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);
        log.debug(headMethod.getResponseBodyAsString());
        // only for logging
        if (returnCode == HttpStatus.SC_OK) {
            objectExists = true;
        } else if (returnCode == HttpStatus.SC_NOT_FOUND) {
            objectExists = false;
            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 (SignatureException e) {
        throw new RuntimeException(e);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return objectExists;
}

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

/**
 * Retrieves the content-length of the remote object
 *
 * @param objectID/* w w  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.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/** {@inheritDoc} */
public HttpResponse fetch(HttpRequest request) {
    HttpClient httpClient = new HttpClient();
    HttpMethod httpMethod;/*  w w w  .j  a  v  a  2 s.co m*/
    String methodType = request.getMethod();
    String requestUri = request.getUri().toString();

    ProxyHelper.fillProxy(httpClient, requestUri);

    // true for non-HEAD requests
    boolean requestCompressedContent = true;

    if ("POST".equals(methodType) || "PUT".equals(methodType)) {
        EntityEnclosingMethod enclosingMethod = ("POST".equals(methodType)) ? new PostMethod(requestUri)
                : new PutMethod(requestUri);

        if (request.getPostBodyLength() > 0) {
            enclosingMethod.setRequestEntity(new InputStreamRequestEntity(request.getPostBody()));
            enclosingMethod.setRequestHeader("Content-Length", String.valueOf(request.getPostBodyLength()));
        }
        httpMethod = enclosingMethod;
    } else if ("DELETE".equals(methodType)) {
        httpMethod = new DeleteMethod(requestUri);
    } else if ("HEAD".equals(methodType)) {
        httpMethod = new HeadMethod(requestUri);
    } else {
        httpMethod = new GetMethod(requestUri);
    }

    httpMethod.setFollowRedirects(false);
    httpMethod.getParams().setSoTimeout(connectionTimeoutMs);

    if (requestCompressedContent)
        httpMethod.setRequestHeader("Accept-Encoding", "gzip, deflate");

    for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
        httpMethod.setRequestHeader(entry.getKey(), StringUtils.join(entry.getValue(), ','));
    }

    try {

        int statusCode = httpClient.executeMethod(httpMethod);

        // Handle redirects manually
        if (request.getFollowRedirects() && ((statusCode == HttpStatus.SC_MOVED_TEMPORARILY)
                || (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) || (statusCode == HttpStatus.SC_SEE_OTHER)
                || (statusCode == HttpStatus.SC_TEMPORARY_REDIRECT))) {

            Header header = httpMethod.getResponseHeader("location");
            if (header != null) {
                String redirectUri = header.getValue();

                if ((redirectUri == null) || (redirectUri.equals(""))) {
                    redirectUri = "/";
                }
                httpMethod.releaseConnection();
                httpMethod = new GetMethod(redirectUri);

                statusCode = httpClient.executeMethod(httpMethod);
            }
        }

        return makeResponse(httpMethod, statusCode);

    } catch (IOException e) {
        if (e instanceof java.net.SocketTimeoutException || e instanceof java.net.SocketException) {
            return HttpResponse.timeout();
        }

        return HttpResponse.error();

    } finally {
        httpMethod.releaseConnection();
    }
}