Example usage for org.apache.http.client.methods HttpHead HttpHead

List of usage examples for org.apache.http.client.methods HttpHead HttpHead

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpHead HttpHead.

Prototype

public HttpHead(final String uri) 

Source Link

Usage

From source file:illab.nabal.proxy.AbstractContext.java

/**
  * Get HTTP HEAD object./*w ww  . j  a v  a 2 s .c  o  m*/
 * 
 * @param apiUri
 * @return HttpHead
 * @throws Exception
 */
protected synchronized HttpHead getHttpHead(String apiUri) throws Exception {
    return new HttpHead(new URI(getApiHost() + apiUri));
}

From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcap2Adapter.java

public SSLCertChain getSSLCerts() throws IOException, StorageAdapterException {
    HttpHost httpHost = new HttpHost(getHost(), profile.getPort(), "getcerts");
    HttpUriRequest request = new HttpHead("/");

    // Eventually we will just return this cookie which will be passed back to the caller.
    HcapAdapterCookie cookie = new HcapAdapterCookie(request, httpHost);
    synchronized (savingCookieLock) {
        if (savedCookie != null) {
            throw new RuntimeException(
                    "This adapter already has a current connection to host -- cannot create two at once.");
        }/* w  ww . j  ava2 s .  co  m*/
        savedCookie = cookie;
    }
    try {
        executeMethod(cookie);
    } catch (SSLException e) {
        LOG.log(Level.WARNING, "Exception getting certs.  sslCerts = " + sslCerts, e);
        throw new SSLCertException(e, sslCerts);
    } finally {
        close();
    }
    LOG.finer("Returning sslCerts = " + sslCerts);

    return sslCerts;
}

From source file:org.georchestra.security.Proxy.java

private HttpRequestBase makeRequest(HttpServletRequest request, RequestType requestType, String sURL)
        throws IOException {
    HttpRequestBase targetRequest;/*from www .ja  v a2  s .  c  o  m*/
    try {
        // Split URL
        URL url = new URL(sURL);
        URI uri = buildUri(url);

        switch (requestType) {
        case GET: {
            logger.debug("New request is: " + sURL + "\nRequest is GET");

            HttpGet get = new HttpGet(uri);
            targetRequest = get;
            break;
        }
        case POST: {
            logger.debug("New request is: " + sURL + "\nRequest is POST");

            HttpPost post = new HttpPost(uri);
            HttpEntity entity;
            request.setCharacterEncoding("UTF8");
            if (isFormContentType(request)) {
                logger.debug("Post is recognized as a form post.");
                List<NameValuePair> parameters = new ArrayList<NameValuePair>();
                for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {
                    String name = (String) e.nextElement();
                    String[] v = request.getParameterValues(name);
                    for (String value : v) {
                        NameValuePair nv = new BasicNameValuePair(name, value);
                        parameters.add(nv);
                    }
                }
                String charset = request.getCharacterEncoding();
                try {
                    Charset.forName(charset);
                } catch (Throwable t) {
                    charset = null;
                }
                if (charset == null) {
                    charset = defaultCharset;
                }
                entity = new UrlEncodedFormEntity(parameters, charset);
                post.setEntity(entity);

            } else {
                logger.debug("Post is NOT recognized as a form post. (Not an error, just a comment)");
                int contentLength = request.getContentLength();
                ServletInputStream inputStream = request.getInputStream();
                entity = new InputStreamEntity(inputStream, contentLength);
            }
            post.setEntity(entity);
            targetRequest = post;
            break;
        }
        case TRACE: {
            logger.debug("New request is: " + sURL + "\nRequest is TRACE");

            HttpTrace post = new HttpTrace(uri);

            targetRequest = post;
            break;
        }
        case OPTIONS: {
            logger.debug("New request is: " + sURL + "\nRequest is OPTIONS");

            HttpOptions post = new HttpOptions(uri);

            targetRequest = post;
            break;
        }
        case HEAD: {
            logger.debug("New request is: " + sURL + "\nRequest is HEAD");

            HttpHead post = new HttpHead(uri);

            targetRequest = post;
            break;
        }
        case PUT: {
            logger.debug("New request is: " + sURL + "\nRequest is PUT");

            HttpPut put = new HttpPut(uri);

            put.setEntity(new InputStreamEntity(request.getInputStream(), request.getContentLength()));

            targetRequest = put;
            break;
        }
        case DELETE: {
            logger.debug("New request is: " + sURL + "\nRequest is DELETE");

            HttpDelete delete = new HttpDelete(uri);

            targetRequest = delete;
            break;
        }
        default: {
            String msg = requestType + " not yet supported";
            logger.error(msg);
            throw new IllegalArgumentException(msg);
        }

        }
    } catch (URISyntaxException e) {
        logger.error("ERROR creating URI from " + sURL, e);
        throw new IOException(e);
    }

    return targetRequest;
}

From source file:com.cognitivemedicine.nifi.http.PostAdvancedHTTP.java

private DestinationAccepts getDestinationAcceptance(final HttpClient client, final String uri,
        final ProcessorLog logger, final String transactionId) throws IOException {
    final HttpHead head = new HttpHead(uri);
    head.addHeader(TRANSACTION_ID_HEADER, transactionId);
    final HttpResponse response = client.execute(head);

    final int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == Status.METHOD_NOT_ALLOWED.getStatusCode()) {
        // we assume that the destination can support FlowFile v1 always.
        return new DestinationAccepts(false, false, true, false, null);
    } else if (statusCode == Status.OK.getStatusCode()) {
        boolean acceptsFlowFileV3 = false;
        boolean acceptsFlowFileV2 = false;
        boolean acceptsFlowFileV1 = true;
        boolean acceptsGzip = false;
        Integer protocolVersion = null;

        Header[] headers = response.getHeaders(ACCEPT);
        if (headers != null) {
            for (final Header header : headers) {
                for (final String accepted : header.getValue().split(",")) {
                    final String trimmed = accepted.trim();
                    if (trimmed.equals(APPLICATION_FLOW_FILE_V3)) {
                        acceptsFlowFileV3 = true;
                    } else if (trimmed.equals(APPLICATION_FLOW_FILE_V2)) {
                        acceptsFlowFileV2 = true;
                    } else {
                        // we assume that the destination accepts FlowFile V1 because legacy versions
                        // of NiFi that accepted V1 did not use an Accept header to indicate it... or
                        // any other header. So the bets thing we can do is just assume that V1 is
                        // accepted, if we're going to send as FlowFile.
                        acceptsFlowFileV1 = true;
                    }//from   ww  w .  j  ava2  s.  c  o  m
                }
            }
        }

        final Header destinationVersion = response.getFirstHeader(PROTOCOL_VERSION_HEADER);
        if (destinationVersion != null) {
            try {
                protocolVersion = Integer.valueOf(destinationVersion.getValue());
            } catch (final NumberFormatException e) {
                // nothing to do here really.... it's an invalid value, so treat the same as if not specified
            }
        }

        if (acceptsFlowFileV3) {
            logger.debug("Connection to URI " + uri + " will be using Content Type " + APPLICATION_FLOW_FILE_V3
                    + " if sending data as FlowFile");
        } else if (acceptsFlowFileV2) {
            logger.debug("Connection to URI " + uri + " will be using Content Type " + APPLICATION_FLOW_FILE_V2
                    + " if sending data as FlowFile");
        } else if (acceptsFlowFileV1) {
            logger.debug("Connection to URI " + uri + " will be using Content Type " + APPLICATION_FLOW_FILE_V1
                    + " if sending data as FlowFile");
        }

        headers = response.getHeaders(ACCEPT_ENCODING);
        if (headers != null) {
            for (final Header header : headers) {
                for (final String accepted : header.getValue().split(",")) {
                    if (accepted.equalsIgnoreCase("gzip")) {
                        acceptsGzip = true;
                    }
                }
            }
        }

        if (acceptsGzip) {
            logger.debug("Connection to URI " + uri + " indicates that inline GZIP compression is supported");
        } else {
            logger.debug(
                    "Connection to URI " + uri + " indicates that it does NOT support inline GZIP compression");
        }

        return new DestinationAccepts(acceptsFlowFileV3, acceptsFlowFileV2, acceptsFlowFileV1, acceptsGzip,
                protocolVersion);
    } else {
        logger.warn(
                "Unable to communicate with destination; when attempting to perform an HTTP HEAD, got unexpected response code of "
                        + statusCode + ": " + response.getStatusLine().getReasonPhrase());
        return new DestinationAccepts(false, false, false, false, null);
    }
}

From source file:com.github.caldav4j.CalDAVCollection.java

/**
 * Uses the HTTP HEAD Method to check if the connection is possible.
 * @param httpClient HTTPClient to make the request
 * @return StatusCode//www  .java  2s .co  m
 * @throws CalDAV4JException when Status is not {@link CalDAVStatus#SC_OK}
 */
public int testConnection(HttpClient httpClient) throws CalDAV4JException {
    HttpHead method = new HttpHead(getCalendarCollectionRoot());

    HttpResponse response = null;
    try {
        response = httpClient.execute(getDefaultHttpHost(method.getURI()), method);
    } catch (Exception e) {
        throw new CalDAV4JException(e.getMessage(), new Throwable(e.getCause()));
    }

    switch (response.getStatusLine().getStatusCode()) {
    case CalDAVStatus.SC_OK:
        break;
    default:
        throw new BadStatusException(response.getStatusLine().getStatusCode(), method.getMethod(),
                getCalendarCollectionRoot());
    }
    return response.getStatusLine().getStatusCode();
}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * //w  ww.  j av  a 2  s  . co  m
 * 
 * @return FilesAccountInfo
 * @throws IOException
 *              IO
 * @throws HttpException
 *              Http
 * @throws FilesExcepiton
 *              
 * @throws FilesAuthorizationException
 *              
 */
public FilesAccountInfo getAccountInfo()
        throws IOException, HttpException, FilesAuthorizationException, FilesException {
    if (this.isLoggedin()) {
        HttpHead method = null;

        try {
            method = new HttpHead(storageURL);
            method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
            method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
            FilesResponse response = new FilesResponse(client.execute(method));
            if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                method.removeHeaders(FilesConstants.X_AUTH_TOKEN);
                if (login()) {
                    method.abort();
                    method = new HttpHead(storageURL);
                    method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                    method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                    response = new FilesResponse(client.execute(method));
                } else {
                    throw new FilesAuthorizationException("Re-login failed", response.getResponseHeaders(),
                            response.getStatusLine());
                }
            }

            if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                int nContainers = response.getAccountContainerCount();
                long totalSize = response.getAccountBytesUsed();
                return new FilesAccountInfo(totalSize, nContainers);
            } else {
                throw new FilesException("Unexpected return from server", response.getResponseHeaders(),
                        response.getStatusLine());
            }
        } finally {
            if (method != null)
                method.abort();
        }
    } else {
        throw new FilesAuthorizationException("You must be logged in", null, null);
    }
}

From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java

/**
 * /*from   w  ww .  j  ava 2  s  .  c o m*/
 * 
 * @param container
 *             
 * @return ContainerInfo
 * @throws IOException
 *              IO
 * @throws HttpException
 *              Http
 * @throws FilesExcepiton
 *              
 * @throws FilesAuthorizationException
 *              
 */
public FilesContainerInfo getContainerInfo(String container) throws IOException, HttpException, FilesException {
    if (this.isLoggedin()) {
        if (isValidContainerName(container)) {

            HttpHead method = null;
            try {
                method = new HttpHead(storageURL + "/" + sanitizeForURI(container));
                method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                FilesResponse response = new FilesResponse(client.execute(method));

                if (response.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                    method.removeHeaders(FilesConstants.X_AUTH_TOKEN);
                    if (login()) {
                        method = new HttpHead(storageURL + "/" + sanitizeForURI(container));
                        method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut);
                        method.setHeader(FilesConstants.X_AUTH_TOKEN, authToken);
                        response = new FilesResponse(client.execute(method));
                    } else {
                        throw new FilesAuthorizationException("Re-login failed", response.getResponseHeaders(),
                                response.getStatusLine());
                    }
                }

                if (response.getStatusCode() == HttpStatus.SC_NO_CONTENT) {
                    int objCount = response.getContainerObjectCount();
                    long objSize = response.getContainerBytesUsed();
                    return new FilesContainerInfo(container, objCount, objSize);
                } else if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                    throw new FilesNotFoundException("Container not found: " + container,
                            response.getResponseHeaders(), response.getStatusLine());
                } else {
                    throw new FilesException("Unexpected result from server", response.getResponseHeaders(),
                            response.getStatusLine());
                }
            } finally {
                if (method != null)
                    method.abort();
            }
        } else {
            throw new FilesInvalidNameException(container);
        }
    } else
        throw new FilesAuthorizationException("You must be logged in", null, null);
}

From source file:com.rockagen.commons.http.HttpConn.java

/**
 * Get Http method instance by {@link com.rockagen.commons.http.RequestMethod}
 *
 * @param method {@link RequestMethod}/*w w w  .  j av a 2  s .c om*/
 * @param uri  the uri
 * @return {@link HttpRequestBase}
 */
private static HttpRequestBase getHttpMethod(RequestMethod method, String uri) {
    HttpRequestBase hm;
    if (method != null) {
        switch (method) {
        case POST:
            hm = new HttpPost(uri);
            break;
        case GET:
            hm = new HttpGet(uri);
            break;
        case PUT:
            hm = new HttpPut(uri);
            break;
        case DELETE:
            hm = new HttpDelete(uri);
            break;
        case HEAD:
            hm = new HttpHead(uri);
            break;
        case OPTIONS:
            hm = new HttpOptions(uri);
            break;
        case TRACE:
            hm = new HttpTrace(uri);
            break;
        case PATCH:
            hm = new HttpPatch(uri);
            break;
        default:
            hm = new HttpGet(uri);
            break;
        }
    } else
        hm = new HttpGet(uri);
    return hm;
}