Example usage for org.apache.http.client.methods HttpRequestBase getMethod

List of usage examples for org.apache.http.client.methods HttpRequestBase getMethod

Introduction

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

Prototype

public abstract String getMethod();

Source Link

Usage

From source file:com.hdsfed.cometapi.HCPClient.java

private int HttpHCPCatchError(HttpRequestBase httpRequest, HttpResponse httpResponse, Boolean neverfail)
        throws IOException {
    Header[] capturedHeader = httpResponse.getAllHeaders();
    for (int i = 0; i < capturedHeader.length; i++) {
        Headers.put(capturedHeader[i].getName(), capturedHeader[i].getValue());
    }/*from  w w  w.  ja v  a2 s. c  o m*/
    setHeaders(Headers);

    if (2 != (int) (httpResponse.getStatusLine().getStatusCode() / 100)) {
        // Clean up after ourselves and release the HTTP connection to the connection manager.
        EntityUtils.consume(httpResponse.getEntity());
        if (Headers.containsKey("X-HCP-ErrorMessage")
                && Headers.get("X-HCP-ErrorMessage")
                        .contains("Custom Metadatasetting is not allowed on a directory")
                && httpResponse.getStatusLine().getStatusCode() == 400) {
            ScreenLog.out("Caught directory, return 200");
            return 200;
        } else {

            if (!neverfail) {
                throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                        "Unexpected status returned from " + httpRequest.getMethod() + " ("
                                + httpResponse.getStatusLine().getStatusCode() + ": "
                                + httpResponse.getStatusLine().getReasonPhrase() + ")");
            }
        }
    }
    return (int) (httpResponse.getStatusLine().getStatusCode());
}

From source file:com.seleritycorp.common.base.http.client.HttpRequest.java

private org.apache.http.HttpResponse getHttpResponse() throws HttpException {
    final HttpRequestBase request;

    switch (method) {
    case HttpGet.METHOD_NAME:
        request = new HttpGet();
        break;/*from www . j av a2s  . com*/
    case HttpPost.METHOD_NAME:
        request = new HttpPost();
        break;
    default:
        throw new HttpException("Unknown HTTP method '" + method + "'");
    }

    try {
        request.setURI(URI.create(uri));
    } catch (IllegalArgumentException e) {
        throw new HttpException("Failed to create URI '" + uri + "'", e);
    }

    if (userAgent != null) {
        request.setHeader(HTTP.USER_AGENT, userAgent);
    }

    if (readTimeoutMillis >= 0) {
        request.setConfig(RequestConfig.custom().setSocketTimeout(readTimeoutMillis)
                .setConnectTimeout(readTimeoutMillis).setConnectionRequestTimeout(readTimeoutMillis).build());
    }

    if (!data.isEmpty()) {
        if (request instanceof HttpEntityEnclosingRequestBase) {
            final HttpEntity entity;
            ContentType localContentType = contentType;
            if (localContentType == null) {
                localContentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
            }
            entity = new StringEntity(data, localContentType);
            HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request;
            entityRequest.setEntity(entity);
        } else {
            throw new HttpException(
                    "Request " + request.getMethod() + " does not allow to send data " + "with the request");
        }
    }

    final HttpClient httpClient;
    if (uri.startsWith("file://")) {
        httpClient = this.fileHttpClient;
    } else {
        httpClient = this.netHttpClient;
    }
    final org.apache.http.HttpResponse response;
    try {
        response = httpClient.execute(request);
    } catch (IOException e) {
        throw new HttpException("Failed to execute request to '" + uri + "'", e);
    }
    return response;
}

From source file:groovyx.net.http.HTTPBuilder.java

/**
 * All <code>request</code> methods delegate to this method.
 *//*from w w w. j a  va 2  s. c  om*/
protected Object doRequest(final RequestConfigDelegate delegate) throws ClientProtocolException, IOException {

    final HttpRequestBase reqMethod = delegate.getRequest();

    Object contentType = delegate.getContentType();

    if (this.autoAcceptHeader) {
        String acceptContentTypes = contentType.toString();
        if (contentType instanceof ContentType)
            acceptContentTypes = ((ContentType) contentType).getAcceptHeader();
        reqMethod.setHeader("Accept", acceptContentTypes);
    }

    reqMethod.setURI(delegate.getUri().toURI());
    if (reqMethod.getURI() == null)
        throw new IllegalStateException("Request URI cannot be null");

    log.debug(reqMethod.getMethod() + " " + reqMethod.getURI());

    // set any request headers from the delegate
    Map<?, ?> headers = delegate.getHeaders();
    for (Object key : headers.keySet()) {
        Object val = headers.get(key);
        if (key == null)
            continue;
        if (val == null)
            reqMethod.removeHeaders(key.toString());
        else
            reqMethod.setHeader(key.toString(), val.toString());
    }

    HttpResponseDecorator resp = new HttpResponseDecorator(client.execute(reqMethod, delegate.getContext()),
            delegate.getContext(), null);
    try {
        int status = resp.getStatusLine().getStatusCode();
        Closure responseClosure = delegate.findResponseHandler(status);
        log.debug("Response code: " + status + "; found handler: " + responseClosure);

        Object[] closureArgs = null;
        switch (responseClosure.getMaximumNumberOfParameters()) {
        case 1:
            closureArgs = new Object[] { resp };
            break;
        case 2: // parse the response entity if the response handler expects it:
            HttpEntity entity = resp.getEntity();
            try {
                if (entity == null || entity.getContentLength() == 0)
                    closureArgs = new Object[] { resp, null };
                else
                    closureArgs = new Object[] { resp, parseResponse(resp, contentType) };
            } catch (Exception ex) {
                Header h = entity.getContentType();
                String respContentType = h != null ? h.getValue() : null;
                log.warn("Error parsing '" + respContentType + "' response", ex);
                throw new ResponseParseException(resp, ex);
            }
            break;
        default:
            throw new IllegalArgumentException("Response closure must accept one or two parameters");
        }

        Object returnVal = responseClosure.call(closureArgs);
        log.trace("response handler result: " + returnVal);

        return returnVal;
    } finally {
        HttpEntity entity = resp.getEntity();
        if (entity != null)
            entity.consumeContent();
    }
}

From source file:com.ibm.sbt.services.client.ClientService.java

/**
 * Execute the specified the request.//from ww  w. jav a  2s  .  c om
 * 
 * @param httpClient
 * @param httpRequestBase
 * @param args
 * @return
 * @throws ClientServicesException
 */
protected HttpResponse executeRequest(HttpClient httpClient, HttpRequestBase httpRequestBase, Args args)
        throws ClientServicesException {
    try {
        return httpClient.execute(httpRequestBase);
    } catch (Exception ex) {
        if (logger.isLoggable(Level.FINE)) {
            String msg = "Exception ocurred while executing request {0} {1}";
            msg = StringUtil.format(msg, httpRequestBase.getMethod(), args);
            logger.log(Level.FINE, msg, ex);
        }

        if (ex instanceof ClientServicesException) {
            throw (ClientServicesException) ex;
        }
        String msg = "Error while executing the REST service {0}";
        String param = httpRequestBase.getURI().toString();
        throw new ClientServicesException(ex, msg, param);
    }
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method,
        @Nonnull Map<String, String> queryParams) throws CloudException, InternalException {
    fetchKeys();/* w  w  w  .ja  va2s  .  co  m*/

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    Header h = method.getFirstHeader("content-type");
    String contentType = (h == null ? null : h.getValue());

    if (contentType == null) {
        contentType = "";
    }
    StringBuilder stringToSign = new StringBuilder();

    stringToSign.append(method.getMethod().toUpperCase()).append("\n");
    stringToSign.append("\n"); // content-md5
    stringToSign.append(contentType).append("\n");
    stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");

    Header[] headers = method.getAllHeaders();
    TreeSet<String> keys = new TreeSet<String>();

    for (Header header : headers) {
        if (header.getName().startsWith(Header_Prefix_MS)) {
            keys.add(header.getName().toLowerCase());
        }
    }

    for (String key : keys) {
        Header header = method.getFirstHeader(key);

        if (header != null) {
            Header[] all = method.getHeaders(key);

            stringToSign.append(key.toLowerCase().trim()).append(":");
            if (all != null && all.length > 0) {
                for (Header current : all) {
                    String v = (current.getValue() != null ? current.getValue() : "");

                    stringToSign.append(v.trim().replaceAll("\n", " ")).append(",");
                }
            }
            stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
        } else {
            stringToSign.append(key.toLowerCase().trim()).append(":");
        }
        stringToSign.append("\n");
    }

    stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());

    keys.clear();
    for (String key : queryParams.keySet()) {
        if (key.equalsIgnoreCase("comp")) {
            key = key.toLowerCase();
            keys.add(key);
        }
    }
    if (!keys.isEmpty()) {
        stringToSign.append("?");
        for (String key : keys) {
            String value = queryParams.get(key);

            if (value == null) {
                value = "";
            }
            stringToSign.append(key).append("=").append(value).append("&");
        }
        stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("BEGIN STRING TO SIGN");
            logger.debug(stringToSign.toString());
            logger.debug("END STRING TO SIGN");
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));

        String signature = new String(
                Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));

        if (logger.isDebugEnabled()) {
            logger.debug("signature=" + signature);
        }
        return signature;
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 not supported: " + e.getMessage());
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm: " + e.getMessage());
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error("Invalid key: " + e.getMessage());
        throw new InternalException(e);
    }
}

From source file:com.algolia.search.saas.APIClient.java

private JSONObject _requestByHost(HttpRequestBase req, String host, String url, String json,
        HashMap<String, String> errors) throws AlgoliaException {
    req.reset();/*from   w w w. j a v a  2 s. c  o  m*/

    // set URL
    try {
        req.setURI(new URI("https://" + host + url));
    } catch (URISyntaxException e) {
        // never reached
        throw new IllegalStateException(e);
    }

    // set auth headers
    req.setHeader("X-Algolia-Application-Id", this.applicationID);
    if (forwardAdminAPIKey == null) {
        req.setHeader("X-Algolia-API-Key", this.apiKey);
    } else {
        req.setHeader("X-Algolia-API-Key", this.forwardAdminAPIKey);
        req.setHeader("X-Forwarded-For", this.forwardEndUserIP);
        req.setHeader("X-Forwarded-API-Key", this.forwardRateLimitAPIKey);
    }
    for (Entry<String, String> entry : headers.entrySet()) {
        req.setHeader(entry.getKey(), entry.getValue());
    }

    // set user agent
    req.setHeader("User-Agent", "Algolia for Java " + version);

    // set JSON entity
    if (json != null) {
        if (!(req instanceof HttpEntityEnclosingRequestBase)) {
            throw new IllegalArgumentException("Method " + req.getMethod() + " cannot enclose entity");
        }
        req.setHeader("Content-type", "application/json");
        try {
            StringEntity se = new StringEntity(json, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            ((HttpEntityEnclosingRequestBase) req).setEntity(se);
        } catch (UnsupportedEncodingException e) {
            throw new AlgoliaException("Invalid JSON Object: " + json); // $COVERAGE-IGNORE$
        }
    }

    RequestConfig config = RequestConfig.custom().setSocketTimeout(httpSocketTimeoutMS)
            .setConnectTimeout(httpConnectTimeoutMS).setConnectionRequestTimeout(httpConnectTimeoutMS).build();
    req.setConfig(config);

    HttpResponse response;
    try {
        response = httpClient.execute(req);
    } catch (IOException e) {
        // on error continue on the next host
        errors.put(host, String.format("%s=%s", e.getClass().getName(), e.getMessage()));
        return null;
    }
    try {
        int code = response.getStatusLine().getStatusCode();
        if (code / 100 == 4) {
            String message = "";
            try {
                message = EntityUtils.toString(response.getEntity());
            } catch (ParseException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (code == 400) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Bad request");
            } else if (code == 403) {
                throw new AlgoliaException(code,
                        message.length() > 0 ? message : "Invalid Application-ID or API-Key");
            } else if (code == 404) {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Resource does not exist");
            } else {
                throw new AlgoliaException(code, message.length() > 0 ? message : "Error");
            }
        }
        if (code / 100 != 2) {
            try {
                errors.put(host, EntityUtils.toString(response.getEntity()));
            } catch (IOException e) {
                errors.put(host, String.valueOf(code));
            }
            // KO, continue
            return null;
        }
        try {
            InputStream istream = response.getEntity().getContent();
            InputStreamReader is = new InputStreamReader(istream, "UTF-8");
            JSONTokener tokener = new JSONTokener(is);
            JSONObject res = new JSONObject(tokener);
            is.close();
            return res;
        } catch (IOException e) {
            return null;
        } catch (JSONException e) {
            throw new AlgoliaException("JSON decode error:" + e.getMessage());
        }
    } finally {
        req.releaseConnection();
    }
}

From source file:com.jivesoftware.os.routing.bird.http.client.ApacheHttpClient441BackedHttpClient.java

private HttpResponse execute(HttpRequestBase requestBase) throws IOException, OAuthMessageSignerException,
        OAuthExpectationFailedException, OAuthCommunicationException {

    applyHeadersCommonToAllRequests(requestBase);

    byte[] responseBody;
    StatusLine statusLine = null;//from   ww w.j av  a 2  s  .c o  m
    if (LOG.isInfoEnabled()) {
        LOG.startTimer(TIMER_NAME);
    }

    activeCount.incrementAndGet();
    CloseableHttpResponse response = null;
    try {
        response = client.execute(requestBase);

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        InputStream responseBodyAsStream = response.getEntity().getContent();
        if (responseBodyAsStream != null) {
            IOUtils.copy(responseBodyAsStream, outputStream);
        }

        responseBody = outputStream.toByteArray();
        statusLine = response.getStatusLine();
        return new HttpResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody);

    } finally {
        if (response != null) {
            HttpClientUtils.closeQuietly(response);
        }
        requestBase.reset();
        activeCount.decrementAndGet();
        if (LOG.isInfoEnabled()) {
            long elapsedTime = LOG.stopTimer(TIMER_NAME);
            StringBuilder httpInfo = new StringBuilder();
            if (statusLine != null) {
                httpInfo.append("Outbound ").append(statusLine.getProtocolVersion()).append(" Status ")
                        .append(statusLine.getStatusCode());
            } else {
                httpInfo.append("Exception sending request");
            }
            httpInfo.append(" in ").append(elapsedTime).append(" ms ").append(requestBase.getMethod())
                    .append(" ").append(client).append(requestBase.getURI());
            LOG.debug(httpInfo.toString());
        }
    }
}

From source file:com.hpe.application.automation.tools.pc.MockPcRestProxy.java

@Override
protected HttpResponse executeRequest(HttpRequestBase request)
        throws PcException, ClientProtocolException, IOException {
    HttpResponse response = null;/*ww  w . j a  v  a2  s . co  m*/
    String requestUrl = request.getURI().toString();
    if (requestUrl
            .equals(String.format(AUTHENTICATION_LOGIN_URL, PcTestBase.WEB_PROTOCOL, PcTestBase.PC_SERVER_NAME))
            || requestUrl.equals(String.format(AUTHENTICATION_LOGOUT_URL, PcTestBase.WEB_PROTOCOL,
                    PcTestBase.PC_SERVER_NAME))
            || requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s", RUNS_RESOURCE_NAME,
                    PcTestBase.RUN_ID, PcTestBase.STOP_MODE))) {
        response = getOkResponse();
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s", RUNS_RESOURCE_NAME)) || requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", RUNS_RESOURCE_NAME, PcTestBase.RUN_ID))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.runResponseEntity));
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s", TESTS_RESOURCE_NAME)) || requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", TESTS_RESOURCE_NAME, PcTestBase.TEST_ID))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.testResponseEntity));
    } else if (requestUrl
            .equals(String.format(getBaseURL() + "/%s/%s", RUNS_RESOURCE_NAME, PcTestBase.RUN_ID_WAIT))) {
        response = getOkResponse();
        response.setEntity(
                new StringEntity(PcTestBase.runResponseEntity.replace("*", runState.next().value())));
        if (!runState.hasNext())
            runState = initializeRunStateIterator();
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s", RUNS_RESOURCE_NAME,
            PcTestBase.RUN_ID, RESULTS_RESOURCE_NAME))) {
        response = getOkResponse();
        response.setEntity(new StringEntity(PcTestBase.runResultsEntity));
    } else if (requestUrl.equals(String.format(getBaseURL() + "/%s/%s/%s/%s/data", RUNS_RESOURCE_NAME,
            PcTestBase.RUN_ID, RESULTS_RESOURCE_NAME, PcTestBase.REPORT_ID))) {
        response = getOkResponse();
        response.setEntity(
                new FileEntity(new File(getClass().getResource(PcBuilder.pcReportArchiveName).getPath()),
                        ContentType.DEFAULT_BINARY));
    }
    if (response == null)
        throw new PcException(
                String.format("%s %s is not recognized by PC Rest Proxy", request.getMethod(), requestUrl));
    return response;
}

From source file:org.dasein.cloud.atmos.AtmosMethod.java

private @Nonnull String toSignatureString(@Nonnull HttpRequestBase method, @Nonnull String contentType,
        @Nonnull String range, @Nonnull String date, @Nonnull URI resource, @Nonnull List<Header> emcHeaders) {
    StringBuilder emcHeaderString = new StringBuilder();

    TreeSet<String> sorted = new TreeSet<String>();

    for (Header header : emcHeaders) {
        sorted.add(header.getName().toLowerCase());
    }//from   w  w  w  . j ava2  s.c  o m
    boolean first = true;
    for (String headerName : sorted) {
        for (Header header : emcHeaders) {
            if (header.getName().toLowerCase().equals(headerName)) {
                if (!first) {
                    emcHeaderString.append("\n");
                } else {
                    first = false;
                }
                String val = header.getValue();

                if (val == null) {
                    val = "";
                }
                emcHeaderString.append(headerName);
                emcHeaderString.append(":");
                StringBuilder tmp = new StringBuilder();
                for (char c : val.toCharArray()) {
                    if (Character.isWhitespace(c)) {
                        tmp.append(" ");
                    } else {
                        tmp.append(c);
                    }
                }
                val = tmp.toString();
                while (val.contains("  ")) {
                    val = val.replaceAll("  ", " ");
                }
                emcHeaderString.append(val);
            }
        }
    }
    String path = resource.getRawPath().toLowerCase();

    if (resource.getRawQuery() != null) {
        path = path + "?" + resource.getRawQuery().toLowerCase();
    }

    return (method.getMethod() + "\n" + contentType + "\n" + range + "\n" + date + "\n" + path + "\n"
            + emcHeaderString.toString());
}