Example usage for org.apache.http.client.methods HttpUriRequest toString

List of usage examples for org.apache.http.client.methods HttpUriRequest toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:com.twitter.hbc.core.event.ConnectionEvent.java

public ConnectionEvent(EventType eventType, HttpUriRequest request) {
    super(eventType, request.toString());
    this.request = request;
}

From source file:com.salesforce.dva.argus.service.callback.DefaultCallbackService.java

private HttpResponse sendNotification(HttpUriRequest request) {

    _logger.debug(request.toString());
    HttpClient httpClient = httpClientPool.borrowObject();
    try {/*from ww w .j ava  2s.c om*/
        return httpClient.execute(request);
    } catch (Throwable t) {
        return errorResponse("error executing request " + request.toString(), t);
    } finally {
        httpClientPool.returnObject(httpClient);
    }
}

From source file:org.metaeffekt.dcc.commons.ant.HttpRequestTask.java

public void doRequest(HttpClient httpClient, HttpUriRequest request)
        throws IOException, ClientProtocolException {
    log("Executing request: " + request.toString(), Project.MSG_DEBUG);
    if (request instanceof HttpEntityEnclosingRequestBase
            && ((HttpEntityEnclosingRequestBase) request).getEntity() != null && StringUtils.isNotBlank(body)) {
        log("With request body: " + body, Project.MSG_DEBUG);
    } else {/*from  ww  w. ja  v  a2s. c om*/
        log("Without request body.", Project.MSG_DEBUG);
    }
    HttpResponse response = httpClient.execute(request);
    StatusLine statusLine = response.getStatusLine();
    String responseBody = EntityUtils.toString(response.getEntity());
    EntityUtils.consume(response.getEntity());

    final String statusCode = String.valueOf(statusLine.getStatusCode());
    final String reasonPhrase = statusLine.getReasonPhrase();

    String message = responseBody != null && responseBody.trim().length() > 0 ? responseBody : reasonPhrase;
    if (message == null) {
        message = "failed without cause";
    }

    log("Received response (" + statusCode + "): " + message, Project.MSG_DEBUG);

    if (responseStatusCodePropertyName != null) {
        getProject().setProperty(responseStatusCodePropertyName, statusCode);
    }

    if (responseStatusReasonPropertyName != null) {
        getProject().setProperty(responseStatusReasonPropertyName, reasonPhrase);
    }

    if (responseBodyPropertyName != null) {
        getProject().setProperty(responseBodyPropertyName, responseBody);
    }

    if (failOnError) {
        if (Integer.parseInt(statusCode) >= 400) {
            throw new BuildException(String.format("Http request failed. Status code: '%s', reason: '%s'.",
                    statusCode, reasonPhrase));
        }
    }
}

From source file:eu.prestoprime.plugin.mserve.MServeTasks.java

@WfService(name = "create_mserve_service", version = "1.0.0")
public void createService(Map<String, String> sParams, Map<String, String> dParamsString,
        Map<String, File> dParamFile) throws TaskExecutionFailedException {

    // retrieve static parameters
    String tingServer = sParams.get("ting.server");
    String slaTemplate = sParams.get("ting.sla.template");// serviceFactory
    String resourceManager = sParams.get("ting.resource.manager");// cap

    // retrieve dynamic parameters
    String userID = dParamsString.get("userID");

    // create new SLA
    String uri = null;/*from w  w w.  j  ava2  s .  c  o  m*/
    try {
        URL url = new URL(tingServer + "/resourcemanager/slas?cap=" + resourceManager);
        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpPost(url.toString());

        List<NameValuePair> parameters = new ArrayList<>();
        parameters.add(new BasicNameValuePair("name", "P4-" + System.currentTimeMillis()));
        parameters.add(new BasicNameValuePair("serviceFactory", slaTemplate));
        UrlEncodedFormEntity requestEntity = new UrlEncodedFormEntity(parameters);

        ((HttpEntityEnclosingRequestBase) request).setEntity(requestEntity);

        logger.debug(request.getRequestLine().toString());
        logger.debug(request.toString());

        HttpResponse response = client.execute(request);
        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String line;
                StringBuffer sb = new StringBuffer();
                while ((line = reader.readLine()) != null)
                    sb.append(line);
                JSONObject json = new JSONObject(sb.toString());

                logger.debug(json.toString());

                uri = json.getString("uri");
            }
        } else {
            throw new TaskExecutionFailedException("Ting error...");
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    logger.debug("URI: " + uri);

    if (uri == null) {
        throw new TaskExecutionFailedException("URI null");
    }

    String mserveURL = null;
    try {
        String sla = uri.split("#")[1];

        logger.debug(sla);

        URL url = new URL(tingServer + "/slas/sla?cap=" + sla);
        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpGet(url.toString());
        HttpResponse response = client.execute(request);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
                String line;
                StringBuffer sb = new StringBuffer();
                while ((line = reader.readLine()) != null)
                    sb.append(line);
                JSONObject json = new JSONObject(sb.toString());

                logger.debug(json.toString());

                mserveURL = json.getString("browse");
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    logger.debug(mserveURL);

    if (mserveURL == null) {
        throw new TaskExecutionFailedException("mserveURL null");
    }

    String[] fields = mserveURL.split("/");
    String mserveID = fields[fields.length - 1];

    logger.debug(mserveID);

    ConfigurationManager.getUserInstance().addUserService(userID, "mserve", mserveID);
}

From source file:uk.ac.susx.tag.method51.webapp.handler.CodingInstanceHandler.java

/**
 * Re-issue the request to an instance.//from  w ww  . j  av  a2 s . co  m
 *
 * @param target
 * @param baseRequest
 * @param request
 * @param response
 * @throws IOException
 */
private void coding(final String target, Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) throws IOException {

    new DoSomethingWithTheSpecifiedJobID(request, response) {

        public void something(String jid) throws IOException {

            Integer port = project.m51(jid).getPort();

            //int port = ((Number)j.getMeta("port")).intValue();

            HttpClient httpclient = new DefaultHttpClient();

            String method = request.getMethod();

            String target = "/coding" + request.getParameter("_target");

            URIBuilder builder = new URIBuilder();

            Set<String> ignore = new HashSet<>();
            ignore.add("id");
            ignore.add("_target");

            builder.setHost("localhost").setScheme("http").setPort(port).setPath(target);

            try {

                HttpUriRequest uriRequest;

                if ("GET".equals(method)) {
                    for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
                        String key = e.getKey();
                        if (!ignore.contains(key)) {
                            builder.setParameter(e.getKey(), e.getValue()[0]);
                        }
                    }
                    URI uri = builder.build();
                    uriRequest = new HttpGet(uri);
                } else {
                    URI uri = builder.build();
                    List<NameValuePair> params = new ArrayList<>();
                    for (Map.Entry<String, String[]> e : request.getParameterMap().entrySet()) {
                        String key = e.getKey();
                        if (!ignore.contains(key)) {
                            params.add(new BasicNameValuePair(key, e.getValue()[0]));
                        }
                    }
                    uriRequest = new HttpPost(uri);
                    ((HttpPost) uriRequest).setEntity(new UrlEncodedFormEntity(params));
                }

                LOG.info("re-issuing request: {}", uriRequest.toString());

                HttpResponse r = httpclient.execute(uriRequest);

                StatusLine statusLine = r.getStatusLine();
                HttpEntity entity = r.getEntity();
                if (statusLine.getStatusCode() >= 400) {
                    try {
                        ContentType contentType = ContentType.get(entity);
                        String responseBody = EntityUtils.toString(entity, contentType.getCharset());
                        throw new RequestException(statusLine.getReasonPhrase() + responseBody,
                                statusLine.getStatusCode());
                    } catch (IOException | ParseException | NullPointerException e) {
                        EntityUtils.consume(entity);
                        throw new RequestException(statusLine.getReasonPhrase(), statusLine.getStatusCode());
                    }
                }

                response.setStatus(statusLine.getStatusCode());

                ContentType contentType = ContentType.get(entity);
                if (contentType == null) {
                    error("null content type!", response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                } else {
                    String responseBody = EntityUtils.toString(entity, contentType.getCharset());

                    response.setContentType(contentType.toString());
                    response.setCharacterEncoding(contentType.getCharset().toString());
                    response.getWriter().print(responseBody);
                }

            } catch (URISyntaxException e) {
                error(e.getMessage(), response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        }
    };
}

From source file:org.duniter.core.client.service.HttpServiceImpl.java

protected <T> T executeRequest(HttpClient httpClient, HttpUriRequest request, Class<? extends T> resultClass,
        Class<?> errorClass, int retryCount) {
    T result = null;/*from  w w  w .  ja v a 2s .  c om*/

    if (debug) {
        log.debug("Executing request : " + request.getRequestLine());
    }

    boolean retry = false;
    HttpResponse response = null;
    try {
        response = httpClient.execute(request);

        if (debug) {
            log.debug("Received response : " + response.getStatusLine());
        }

        switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_OK: {
            if (resultClass == null || resultClass.equals(HttpResponse.class)) {
                result = (T) response;
            } else {
                result = (T) parseResponse(request, response, resultClass);
                EntityUtils.consume(response.getEntity());
            }
            break;
        }
        case HttpStatus.SC_UNAUTHORIZED:
        case HttpStatus.SC_FORBIDDEN:
            throw new HttpUnauthorizeException(I18n.t("duniter4j.client.authentication"));
        case HttpStatus.SC_NOT_FOUND:
            throw new HttpNotFoundException(I18n.t("duniter4j.client.notFound", request.toString()));
        case HttpStatus.SC_BAD_REQUEST:
            try {
                Object errorResponse = parseResponse(request, response, errorClass);
                if (errorResponse instanceof Error) {
                    throw new HttpBadRequestException((Error) errorResponse);
                } else {
                    throw new HttpBadRequestException(errorResponse.toString());
                }
            } catch (IOException e) {
                throw new HttpBadRequestException(
                        I18n.t("duniter4j.client.status", response.getStatusLine().toString()));
            }

        case HttpStatus.SC_SERVICE_UNAVAILABLE:
        case Constants.HttpStatus.SC_TOO_MANY_REQUESTS:
            retry = true;
            break;
        default:
            String defaultMessage = I18n.t("duniter4j.client.status", request.toString(),
                    response.getStatusLine().toString());
            if (isContentType(response, ContentType.APPLICATION_JSON)) {
                JsonNode node = objectMapper.readTree(response.getEntity().getContent());
                if (node.hasNonNull("ucode")) {
                    throw new BmaTechnicalException(node.get("ucode").asInt(),
                            node.get("message").asText(defaultMessage));
                }
            }
            throw new TechnicalException(defaultMessage);
        }
    } catch (ConnectException e) {
        throw new HttpConnectException(I18n.t("duniter4j.client.core.connect", request.toString()), e);
    } catch (SocketTimeoutException | ConnectTimeoutException e) {
        throw new HttpTimeoutException(I18n.t("duniter4j.client.core.timeout"), e);
    } catch (TechnicalException e) {
        throw e;
    } catch (Throwable e) {
        throw new TechnicalException(e.getMessage(), e);
    } finally {
        // Close is need
        if (response instanceof CloseableHttpResponse) {
            try {
                ((CloseableHttpResponse) response).close();
            } catch (IOException e) {
                // Silent is gold
            }
        }
    }

    // HTTP requests limit exceed, retry when possible
    if (retry) {
        if (retryCount > 0) {
            log.debug(String.format("Service unavailable: waiting [%s ms] before retrying...",
                    Constants.Config.TOO_MANY_REQUEST_RETRY_TIME));
            try {
                Thread.sleep(Constants.Config.TOO_MANY_REQUEST_RETRY_TIME);
            } catch (InterruptedException e) {
                throw new TechnicalException(I18n.t("duniter4j.client.status", request.toString(),
                        response.getStatusLine().toString()));
            }
            // iterate
            return executeRequest(httpClient, request, resultClass, errorClass, retryCount - 1);
        } else {
            throw new TechnicalException(
                    I18n.t("duniter4j.client.status", request.toString(), response.getStatusLine().toString()));
        }
    }

    return result;
}

From source file:org.eclipse.om2m.binding.http.RestHttpClient.java

/**
 * Converts a protocol-independent {@link RequestPrimitive} object into a standard HTTP request and sends a standard HTTP request.
 * Converts the received standard HTTP request into {@link ResponsePrimitive} object and returns it back.
 * @param requestPrimitive - protocol independent request.
 * @return protocol independent response.
 *///from w  w w.  j  av  a2  s  .c om
public ResponsePrimitive sendRequest(RequestPrimitive requestPrimitive) {
    LOGGER.info("Sending request: " + requestPrimitive);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    ResponsePrimitive responsePrimitive = new ResponsePrimitive(requestPrimitive);
    HttpUriRequest method = null;

    // Retrieve the url
    String url = requestPrimitive.getTo();
    if (!url.startsWith(protocol + "://")) {
        if (url.startsWith("://")) {
            url = protocol + url;
        } else if (url.startsWith("//")) {
            url = protocol + ":" + url;
        } else {
            url = protocol + "://" + url;
        }
    }

    Map<String, List<String>> parameters = getParameters(requestPrimitive);
    parameters.putAll(requestPrimitive.getQueryStrings());
    if (!parameters.isEmpty()) {
        String queryString = "";
        for (String parameter : parameters.keySet()) {
            for (String value : parameters.get(parameter)) {
                queryString += "&" + parameter + "=" + value;
            }
        }
        queryString = queryString.replaceFirst("&", "?");
        LOGGER.info("Query string generated: " + queryString);
        url += queryString;
    }

    try {
        // Set the operation
        BigInteger operation = requestPrimitive.getOperation();
        if (operation != null) {
            if (operation.equals(Operation.CREATE)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.RETRIEVE)) {
                method = new HttpGet(url);
            } else if (operation.equals(Operation.UPDATE)) {
                method = new HttpPut(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPut) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            } else if (operation.equals(Operation.DELETE)) {
                method = new HttpDelete(url);
            } else if (operation.equals(Operation.NOTIFY)) {
                method = new HttpPost(url);
                if (requestPrimitive.getContent() != null) {
                    ((HttpPost) method).setEntity(new StringEntity((String) requestPrimitive.getContent()));
                }
            }
        } else {
            return null;
        }

        // Set the return content type
        method.addHeader(HttpHeaders.ACCEPT, requestPrimitive.getReturnContentType());

        // Set the request content type
        String contentTypeHeader = requestPrimitive.getRequestContentType();

        // Set the request identifier header
        if (requestPrimitive.getRequestIdentifier() != null) {
            method.addHeader(HttpHeaders.REQUEST_IDENTIFIER, requestPrimitive.getRequestIdentifier());
        }

        // Set the originator header
        if (requestPrimitive.getFrom() != null) {
            method.addHeader(HttpHeaders.ORIGINATOR, requestPrimitive.getFrom());
        }

        // Add the content type header with the resource type for create operation
        if (requestPrimitive.getResourceType() != null) {
            contentTypeHeader += ";ty=" + requestPrimitive.getResourceType().toString();
        }
        method.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeHeader);

        // Add the notification URI in the case of non-blocking request
        if (requestPrimitive.getResponseTypeInfo() != null) {
            String uris = "";
            for (String notifUri : requestPrimitive.getResponseTypeInfo().getNotificationURI()) {
                uris += "&" + notifUri;
            }
            uris = uris.replaceFirst("&", "");
            method.addHeader(HttpHeaders.RESPONSE_TYPE, uris);
        }

        if (requestPrimitive.getName() != null) {
            method.addHeader(HttpHeaders.NAME, requestPrimitive.getName());
        }

        LOGGER.info("Request to be send: " + method.toString());
        String headers = "";
        for (Header h : method.getAllHeaders()) {
            headers += h.toString() + "\n";
        }
        LOGGER.info("Headers:\n" + headers);

        HttpResponse httpResponse = httpClient.execute(method);
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        if (httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE) != null) {
            responsePrimitive.setResponseStatusCode(
                    new BigInteger(httpResponse.getFirstHeader(HttpHeaders.RESPONSE_STATUS_CODE).getValue()));
        } else {
            responsePrimitive.setResponseStatusCode(getResponseStatusCode(httpResponse, statusCode));
        }
        if (statusCode != 204) {
            if (httpResponse.getEntity() != null) {
                responsePrimitive.setContent(Util.convertStreamToString(httpResponse.getEntity().getContent()));
                if (httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE) != null) {
                    responsePrimitive
                            .setContentType(httpResponse.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                }
            }
        }
        if (statusCode == 201) {
            String contentHeader = "";
            for (Header header : httpResponse.getHeaders(HttpHeaders.CONTENT_LOCATION)) {
                contentHeader += header.getValue();
            }
            responsePrimitive.setLocation(contentHeader);
        }
        LOGGER.info("Http Client response: " + responsePrimitive);
        httpClient.close();
    } catch (HttpHostConnectException e) {
        LOGGER.info("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
        responsePrimitive.setContent("Target is not reachable: " + requestPrimitive.getTo());
        responsePrimitive.setContentType(MimeMediaType.TEXT_PLAIN);
    } catch (IOException e) {
        LOGGER.error(url + " not found", e);
        responsePrimitive.setResponseStatusCode(ResponseStatusCode.TARGET_NOT_REACHABLE);
    }
    return responsePrimitive;
}

From source file:org.opennms.core.web.HttpClientWrapper.java

/**
 * Execute the given HTTP method, returning an HTTP response.
 * /* www. j a va 2s .  c  o  m*/
 * Note that when you are done with the response, you must call {@link #closeResponse()} so that it gets cleaned up properly.
 */
public CloseableHttpResponse execute(final HttpUriRequest method) throws ClientProtocolException, IOException {
    LOG.debug("execute: " + this.toString() + "; method: " + method.toString());
    // override some headers with our versions
    final HttpRequestWrapper requestWrapper = HttpRequestWrapper.wrap(method);
    if (!isEmpty(m_userAgent)) {
        requestWrapper.setHeader(HTTP.USER_AGENT, m_userAgent);
    }
    if (!isEmpty(m_virtualHost)) {
        requestWrapper.setHeader(HTTP.TARGET_HOST, m_virtualHost);
    }

    if (m_version != null) {
        if (HttpVersion.HTTP_1_1.equals(m_version) && isEmpty(m_virtualHost)) {
            // NMS-7506, set HTTP version to 1.0 if virtual host is not set (since 1.1 requires a virtual host)
            requestWrapper.setProtocolVersion(HttpVersion.HTTP_1_0);
        } else {
            requestWrapper.setProtocolVersion(m_version);
        }
    }

    return getClient().execute(requestWrapper);
}