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

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

Introduction

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

Prototype

@Override
public void addRequestHeader(String headerName, String headerValue) 

Source Link

Document

Adds the specified request header, NOT overwriting any previous value.

Usage

From source file:com.zimbra.cs.store.triton.TritonIncomingBlob.java

@Override
protected long getRemoteSize() throws IOException {
    outStream.flush();/* www . j  a va  2 s .co  m*/
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    HeadMethod head = new HeadMethod(baseUrl + uploadUrl);
    ZimbraLog.store.info("heading %s", head.getURI());
    try {
        head.addRequestHeader(TritonHeaders.SERVER_TOKEN, serverToken.getToken());
        int statusCode = HttpClientUtil.executeMethod(client, head);
        if (statusCode == HttpStatus.SC_OK) {
            String contentLength = head.getResponseHeader(TritonHeaders.CONTENT_LENGTH).getValue();
            long remoteSize = -1;
            try {
                remoteSize = Long.valueOf(contentLength);
            } catch (NumberFormatException nfe) {
                throw new IOException("Content length can't be parsed to Long", nfe);
            }
            return remoteSize;
        } else {
            ZimbraLog.store.error("failed with code %d response: %s", statusCode,
                    head.getResponseBodyAsString());
            throw new IOException("unable to head blob " + statusCode + ":" + head.getStatusText(), null);
        }
    } finally {
        head.releaseConnection();
    }
}

From source file:edu.indiana.d2i.registryext.RegistryExtAgent.java

/**
 * check whether a resource exists/*from w w w  . ja  v  a  2  s . com*/
 * 
 * @param repoPath
 *            path in registry
 * @return
 * @throws HttpException
 * @throws IOException
 * @throws RegistryExtException
 * @throws OAuthSystemException
 * @throws OAuthProblemException
 */
public boolean isResourceExist(String repoPath)
        throws HttpException, IOException, RegistryExtException, OAuthSystemException, OAuthProblemException {
    Map<String, Object> session = ActionContext.getContext().getSession();

    int statusCode = 200;
    String accessToken = (String) session.get(Constants.SESSION_TOKEN);

    boolean exist = true;

    String requestURL = composeURL(FILEOPPREFIX, repoPath);

    if (logger.isDebugEnabled()) {
        logger.debug("Check existence request URL=" + requestURL);
    }

    HttpClient httpclient = new HttpClient();
    HeadMethod head = new HeadMethod(requestURL);
    head.addRequestHeader("Authorization", "Bearer " + accessToken);

    try {

        httpclient.executeMethod(head);

        statusCode = head.getStatusLine().getStatusCode();

        /* handle token expiration */
        if (statusCode == 401) {
            logger.info(String.format("Access token %s expired, going to refresh it", accessToken));

            refreshToken(session);

            // use refreshed access token
            accessToken = (String) session.get(Constants.SESSION_TOKEN);
            head.addRequestHeader("Authorization", "Bearer " + accessToken);

            // re-send the request
            httpclient.executeMethod(head);

            statusCode = head.getStatusLine().getStatusCode();

        }

        if (statusCode == 404)
            exist = false;
        else if (statusCode != 200) {
            throw new RegistryExtException(
                    "Failed in checking resource existence: HTTP error code : " + statusCode);
        }

    } finally {
        if (head != null)
            head.releaseConnection();
    }
    return exist;
}

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

/**
 * Verifies if a specific named bucket exists.
 *
 * @param objectID//from w  w w . j av a2s .com
 */
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  ww.j a  v  a  2 s  .co 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.structr.function.UiFunction.java

protected GraphObjectMap headFromUrl(final ActionContext ctx, final String requestUrl, final String username,
        final String password) throws IOException, FrameworkException {

    final HttpClientParams params = new HttpClientParams(HttpClientParams.getDefaultParams());
    final HttpClient client = new HttpClient(params);
    final HeadMethod headMethod = new HeadMethod(requestUrl);

    if (username != null && password != null) {

        Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        client.getState().setCredentials(AuthScope.ANY, defaultcreds);
        client.getParams().setAuthenticationPreemptive(true);

        headMethod.setDoAuthentication(true);
    }//from   ww w.  j  av a  2 s  .c om

    headMethod.addRequestHeader("Connection", "close");
    // Don't follow redirects automatically, return status code 302 etc. instead
    headMethod.setFollowRedirects(false);

    // add request headers from context
    for (final Map.Entry<String, String> header : ctx.getHeaders().entrySet()) {
        headMethod.addRequestHeader(header.getKey(), header.getValue());
    }

    client.executeMethod(headMethod);

    final GraphObjectMap response = new GraphObjectMap();
    response.setProperty(new IntProperty("status"), headMethod.getStatusCode());
    response.setProperty(new StringProperty("headers"), extractHeaders(headMethod.getResponseHeaders()));

    return response;

}

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;
        try {/*w w w. j  a  v a 2  s  .com*/
            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;
}