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.ooyala.api.OoyalaApiClient.java

/**
 * Executes the request/*from   w  w w .ja v  a2 s . c  om*/
 *
 * @param method The class containing the type of request (HttpGet, HttpDelete, etc)
 * @return The response from the server as an object of class Object. Must be casted to
 * either a LinkedList<String> or an HashMap<String, Object>
 * @throws IOException
 * @throws HttpStatusCodeException
 */
@SuppressWarnings("unchecked")
private JSON executeRequest(HttpRequestBase method) throws IOException, HttpStatusCodeException {
    try {
        System.out.println(String.format("%s\t%s", method.getMethod(), method.getURI().toASCIIString()));
        String response = httpClient.execute(method, createResponseHandler());

        if (!isResponseOK()) {
            throw new HttpStatusCodeException(response, getResponseCode());
        }

        if (response.isEmpty()) {
            return null;
        }

        return JSONSerializer.toJSON(response);
    } finally {
    }
}

From source file:com.mondora.chargify.controller.ChargifyAdapter.java

Object parse(Class clazz, HttpResponse response, HttpRequestBase method) throws ChargifyException {
    if (response.getEntity() == null) {
        if (logger.isTraceEnabled())
            logger.trace("parse: entity is null " + method.getMethod() + " " + method.getURI().toString() + "\n"
                    + method);/*from   www . j a va2  s .  co  m*/
        return null;
    }
    try {
        if (logger.isTraceEnabled())
            logger.trace("parse: " + method.getMethod() + " " + method.getURI().toString() + "\n" + method);
        return parse(clazz, response.getEntity().getContent());
    } catch (IOException e) {
        if (logger.isTraceEnabled())
            logger.trace("parse: " + e.getMessage(), e);
        if (logger.isInfoEnabled())
            logger.info("parse: " + e.getMessage());
        return null;
    }
}

From source file:alien4cloud.paas.cloudify2.rest.external.RestClientExecutor.java

private <T> T executeRequest(final HttpRequestBase request,
        final TypeReference<Response<T>> responseTypeReference) throws RestClientException {
    HttpResponse httpResponse = null;/*w  ww.  j av  a  2  s . co  m*/
    IOException lastException = null;
    int numOfTrials = DEFAULT_TRIALS_NUM;
    if (HttpGet.METHOD_NAME.equals(request.getMethod())) {
        numOfTrials = GET_TRIALS_NUM;
    }
    for (int i = 0; i < numOfTrials; i++) {
        try {
            httpResponse = httpClient.execute(request);
            lastException = null;
            break;
        } catch (IOException e) {
            if (logger.isLoggable(Level.FINER)) {
                logger.finer("Execute get request to " + request.getURI() + ". try number " + (i + 1)
                        + " out of " + GET_TRIALS_NUM + ", error is " + e.getMessage());
            }
            lastException = e;
        }
    }
    if (lastException != null) {
        if (logger.isLoggable(Level.WARNING)) {
            logger.warning("Failed executing " + request.getMethod() + " request to " + request.getURI() + " : "
                    + lastException.getMessage());
        }
        throw MessagesUtils.createRestClientIOException(RestClientMessageKeys.EXECUTION_FAILURE.getName(),
                lastException, request.getURI());
    }
    String url = request.getURI().toString();
    checkForError(httpResponse, url);
    return getResponseObject(responseTypeReference, httpResponse, url);
}

From source file:org.talend.dataprep.command.GenericCommand.java

/**
 * Runs a data prep command with the following steps:
 * <ul>//from  w ww  .java2s .co  m
 * <li>Gets the HTTP command to execute (see {@link #execute(Supplier)}.</li>
 * <li>Gets the behavior to adopt based on returned HTTP code (see {@link #on(HttpStatus...)}).</li>
 * <li>If no behavior was defined for returned code, returns an error as defined in {@link #onError(Function)}</li>
 * <li>If a behavior was defined, invokes defined behavior.</li>
 * </ul>
 *
 * @return A instance of <code>T</code>.
 * @throws Exception If command execution fails.
 */
@Override
protected T run() throws Exception {
    final HttpRequestBase request = httpCall.get();

    // update request header with security token
    if (StringUtils.isNotBlank(authenticationToken)) {
        request.addHeader(AUTHORIZATION, authenticationToken);
    }

    final HttpResponse response;
    try {
        LOGGER.trace("Requesting {} {}", request.getMethod(), request.getURI());
        response = client.execute(request);
    } catch (Exception e) {
        throw onError.apply(e);
    }
    commandResponseHeaders = response.getAllHeaders();

    status = HttpStatus.valueOf(response.getStatusLine().getStatusCode());

    // do we have a behavior for this status code (even an error) ?
    // if yes use it
    BiFunction<HttpRequestBase, HttpResponse, T> function = behavior.get(status);
    if (function != null) {
        try {
            return function.apply(request, response);
        } catch (Exception e) {
            throw onError.apply(e);
        }
    }

    // handle response's HTTP status
    if (status.is4xxClientError() || status.is5xxServerError()) {
        // Http status >= 400 so apply onError behavior
        return callOnError(onError).apply(request, response);
    } else {
        // Http status is not error so apply onError behavior
        return behavior.getOrDefault(status, missingBehavior()).apply(request, response);
    }
}

From source file:org.wso2.carbon.identity.cloud.web.jaggery.clients.MutualSSLHttpClient.java

private String doHttpMethod(HttpRequestBase httpMethod, HttpHeaders headers) {
    String responseString = null;
    try {/*  w w w .j  a  va2 s.c o  m*/
        for (Map.Entry<String, String> entry : headers.getHeaderMap().entrySet()) {
            httpMethod.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse closeableHttpResponse = httpClient.execute(httpMethod);
        HttpEntity entity = closeableHttpResponse.getEntity();
        responseString = EntityUtils.toString(entity, "UTF-8");
    } catch (IOException e) {
        log.error("Error while executing the http method " + httpMethod.getMethod() + ". Endpoint : "
                + httpMethod.getURI(), e);
    }
    return responseString;
}

From source file:org.auraframework.integration.test.http.AuraFormatsHttpTest.java

private void requestAndAssertContentType(HttpRequestBase method, String url, Format format,
        boolean expectHeaders) throws Exception {

    HttpResponse response = perform(method);
    String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    // Eliminate the spaces separating the content Type specification
    contentType = AuraTextUtil.arrayToString(contentType.split(";\\s+"), ";", -1, false);
    assertEquals(/*w  w  w.  j  a  va  2  s .  c om*/
            String.format("Received wrong Content-Type header%nURL(or Action): %s%nContent:%s%nRequest type:%s",
                    url, getResponseBody(response), method.getMethod()),
            FORMAT_CONTENTTYPE.get(format), contentType);
    assertDefaultAntiClickjacking(response, expectHeaders, true);
}

From source file:org.cloudifysource.restclient.RestClientExecutor.java

private <T> T executeRequest(final HttpRequestBase request,
        final TypeReference<Response<T>> responseTypeReference) throws RestClientException {
    HttpResponse httpResponse = null;/*  www  .j a  v a  2  s. co m*/
    try {
        IOException lastException = null;
        int numOfTrials = DEFAULT_TRIALS_NUM;
        if (HttpGet.METHOD_NAME.equals(request.getMethod())) {
            numOfTrials = GET_TRIALS_NUM;
        }
        for (int i = 0; i < numOfTrials; i++) {
            try {
                httpResponse = httpClient.execute(request);
                lastException = null;
                break;
            } catch (IOException e) {
                if (logger.isLoggable(Level.FINER)) {
                    logger.finer("Execute get request to " + request.getURI() + ". try number " + (i + 1)
                            + " out of " + GET_TRIALS_NUM + ", error is " + e.getMessage());
                }
                lastException = e;
            }
        }
        if (lastException != null) {
            if (logger.isLoggable(Level.WARNING)) {
                logger.warning("Failed executing " + request.getMethod() + " request to " + request.getURI()
                        + " : " + lastException.getMessage());
            }
            throw MessagesUtils.createRestClientIOException(RestClientMessageKeys.EXECUTION_FAILURE.getName(),
                    lastException, request.getURI());
        }
        String url = request.getURI().toString();
        checkForError(httpResponse, url);
        return getResponseObject(responseTypeReference, httpResponse, url);
    } finally {
        request.abort();
    }
}

From source file:org.apache.zeppelin.notebook.repo.zeppelinhub.rest.HttpProxyClient.java

private String sendAndGetResponse(HttpRequestBase request) throws IOException {
    String data = StringUtils.EMPTY;
    try {/*ww  w .  jav a 2 s.co m*/
        HttpResponse response = client.execute(request, null).get(30, TimeUnit.SECONDS);
        int code = response.getStatusLine().getStatusCode();
        if (code == 200) {
            try (InputStream responseContent = response.getEntity().getContent()) {
                data = IOUtils.toString(responseContent, "UTF-8");
            }
        } else {
            LOG.error("ZeppelinHub {} {} returned with status {} ", request.getMethod(), request.getURI(),
                    code);
            throw new IOException("Cannot perform " + request.getMethod() + " request to ZeppelinHub");
        }
    } catch (InterruptedException | ExecutionException | TimeoutException | NullPointerException e) {
        throw new IOException(e);
    }
    return data;
}

From source file:org.auraframework.impl.AuraFormatsHttpTest.java

private void requestAndAssertContentType(HttpRequestBase method, String url, Format format) throws Exception {

    HttpResponse response = perform(method);
    String contentType = response.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue();
    // Eliminate the spaces separating the content Type specification
    contentType = AuraTextUtil.arrayToString(contentType.split(";\\s+"), ";", -1, false);
    assertEquals(/*  www . ja  v a2  s .  c o m*/
            String.format("Received wrong Content-Type header%nURL(or Action): %s%nContent:%s%nRequest type:%s",
                    url, getResponseBody(response), method.getMethod()),
            FORMAT_CONTENTTYPE.get(format), contentType);
}

From source file:org.hardisonbrewing.s3j.FileSyncer.java

private String signature(String accessKey, long expires, String resource, HttpRequestBase request)
        throws Exception {

    StringBuffer stringBuffer = new StringBuffer();

    // HTTP-VERB/*from   w w  w. j a va 2s  .c om*/
    stringBuffer.append(request.getMethod());
    stringBuffer.append("\n");

    // Content-MD5
    //        if ( !( request instanceof HttpEntityEnclosingRequestBase ) ) {
    stringBuffer.append("\n");
    //        }
    //        else {
    //            HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request;
    //            HttpEntity entity = entityRequest.getEntity();
    //            stringBuffer.append( md5( IOUtil.toByteArray( entity.getContent() ) ) );
    //            stringBuffer.append( "\n" );
    //        }

    //Content-Type
    //        if ( !( request instanceof HttpEntityEnclosingRequestBase ) ) {
    stringBuffer.append("\n");
    //        }
    //        else {
    //            HttpEntityEnclosingRequestBase entityRequest = (HttpEntityEnclosingRequestBase) request;
    //            HttpEntity entity = entityRequest.getEntity();
    //            stringBuffer.append( entity.getContentType().getValue() );
    //            stringBuffer.append( "\n" );
    //        }

    // Expires
    boolean hasAmzDateHeader = request.getLastHeader("x-amz-date") != null;
    stringBuffer.append(hasAmzDateHeader ? "" : expires);
    stringBuffer.append("\n");

    // CanonicalizedAmzHeaders
    for (Header header : request.getAllHeaders()) {
        String name = header.getName();
        if (name.startsWith("x-amz")) {
            stringBuffer.append(name);
            stringBuffer.append(":");
            stringBuffer.append(header.getValue());
            stringBuffer.append("\n");
        }
    }

    stringBuffer.append(resource); // CanonicalizedResource

    String signature = stringBuffer.toString();
    byte[] bytes = signature.getBytes("UTF-8");
    bytes = hmacSHA1(accessKey, bytes);
    signature = Base64.encodeBase64String(bytes);
    return signature;
}