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

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

Introduction

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

Prototype

public void setURI(final URI uri) 

Source Link

Usage

From source file:com.evolveum.midpoint.report.impl.ReportNodeUtils.java

public static InputStream executeOperation(String host, String fileName, String intraClusterHttpUrlPattern,
        String operation) throws CommunicationException, SecurityViolationException, ObjectNotFoundException,
        ConfigurationException, IOException {
    fileName = fileName.replaceAll("\\s", SPACE);
    InputStream inputStream = null;
    InputStream entityContent = null;
    LOGGER.trace("About to initiate connection with {}", host);
    try {/* ww w .  j  a v a  2s  .  com*/
        if (StringUtils.isNotEmpty(intraClusterHttpUrlPattern)) {
            LOGGER.trace("The cluster uri pattern: {} ", intraClusterHttpUrlPattern);
            URI requestUri = buildURI(intraClusterHttpUrlPattern, host, fileName);
            fileName = URLDecoder.decode(fileName, ReportTypeUtil.URLENCODING);

            LOGGER.debug("Sending request to the following uri: {} ", requestUri);
            HttpRequestBase httpRequest = buildHttpRequest(operation);
            httpRequest.setURI(requestUri);
            httpRequest.setHeader("User-Agent", ReportTypeUtil.HEADER_USERAGENT);
            HttpClient client = HttpClientBuilder.create().build();
            try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpRequest)) {
                HttpEntity entity = response.getEntity();
                Integer statusCode = response.getStatusLine().getStatusCode();

                if (statusCode == HttpStatus.SC_OK) {
                    LOGGER.debug("Response OK, the file successfully returned by the cluster peer. ");
                    if (entity != null) {
                        entityContent = entity.getContent();
                        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = entityContent.read(buffer)) > -1) {
                            arrayOutputStream.write(buffer, 0, len);
                        }
                        arrayOutputStream.flush();
                        inputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());
                    }
                } else if (statusCode == HttpStatus.SC_NO_CONTENT) {
                    if (HttpDelete.METHOD_NAME.equals(operation)) {
                        LOGGER.info("Deletion of the file {} was successful.", fileName);
                    }
                } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
                    LOGGER.error("The access to the report with the name {} is forbidden.", fileName);
                    String error = "The access to the report " + fileName + " is forbidden.";
                    throw new SecurityViolationException(error);
                } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
                    String error = "The report file " + fileName
                            + " was not found on the originating nodes filesystem.";
                    throw new ObjectNotFoundException(error);
                }
            } catch (ClientProtocolException e) {
                String error = "An exception with the communication protocol has occurred during a query to the cluster peer. "
                        + e.getLocalizedMessage();
                throw new CommunicationException(error);
            }
        } else {
            LOGGER.error(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
            throw new ConfigurationException(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
        }
    } catch (URISyntaxException e1) {
        throw new CommunicationException("Invalid uri syntax: " + e1.getLocalizedMessage());
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Unhandled exception when listing nodes");
        LoggingUtils.logUnexpectedException(LOGGER, "Unhandled exception when listing nodes", e);
    } finally {
        IOUtils.closeQuietly(entityContent);
    }

    return inputStream;
}

From source file:com.appdynamics.demo.gasp.service.RESTIntentService.java

private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
    try {/*ww w. ja  v a 2s. c o  m*/
        if (params == null) {
            request.setURI(new URI(uri.toString()));
        } else {
            Uri.Builder uriBuilder = uri.buildUpon();

            // Loop through our params and append them to the Uri.
            for (BasicNameValuePair param : paramsToList(params)) {
                uriBuilder.appendQueryParameter(param.getName(), param.getValue());
            }

            uri = uriBuilder.build();
            request.setURI(new URI(uri.toString()));
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect: " + uri.toString(), e);
    }
}

From source file:io.restassured.internal.http.HttpRequestFactory.java

/**
 * Get the HttpRequest class that represents this request type.
 *
 * @return a non-abstract class that implements {@link HttpRequest}
 *///w ww  . java2 s  .c o  m
static HttpRequestBase createHttpRequest(URI uri, String httpMethod) {
    String method = notNull(upperCase(trimToNull(httpMethod)), "Http method");
    Class<? extends HttpRequestBase> type = HTTP_METHOD_TO_HTTP_REQUEST_TYPE.get(method);
    final HttpRequestBase httpRequest;
    if (type == null) {
        httpRequest = new CustomHttpMethod(method, uri);
    } else {
        try {
            httpRequest = type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        httpRequest.setURI(uri);
    }
    return httpRequest;
}

From source file:com.cloudbees.gasp.service.RESTService.java

private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
    try {/*from  ww w . j  av  a2 s.co  m*/
        if (params == null) {
            // No params were given or they have already been
            // attached to the Uri.
            request.setURI(new URI(uri.toString()));
        } else {
            Uri.Builder uriBuilder = uri.buildUpon();

            // Loop through our params and append them to the Uri.
            for (BasicNameValuePair param : paramsToList(params)) {
                uriBuilder.appendQueryParameter(param.getName(), param.getValue());
            }

            uri = uriBuilder.build();
            request.setURI(new URI(uri.toString()));
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect: " + uri.toString(), e);
    }
}

From source file:com.cloudbees.gasp.loader.RESTLoader.java

private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
    try {/*  ww w  .  j  a  v  a 2s .  c  o  m*/
        if (params == null) {
            // No params were given or they have already been
            // attached to the Uri.
            request.setURI(new URI(uri.toString()));
        } else {
            Uri.Builder uriBuilder = uri.buildUpon();

            // Loop through our params and append them to the Uri.
            for (BasicNameValuePair param : paramsToList(params)) {
                uriBuilder.appendQueryParameter(param.getName(), param.getValue());
            }

            uri = uriBuilder.build();
            request.setURI(new URI(uri.toString()));
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect: " + uri.toString());
    }
}

From source file:com.antew.redditinpictures.library.service.RESTService.java

private static void attachUriWithQuery(HttpRequestBase request, Uri uri, Bundle params) {
    try {//w w w. j  a v a  2 s.c  o m
        if (params == null) {
            // No params were given or they have already been
            // attached to the Uri.
            request.setURI(new URI(uri.toString()));
        } else {
            Uri.Builder uriBuilder = uri.buildUpon();

            // Loop through our params and append them to the Uri.
            for (BasicNameValuePair param : paramsToList(params)) {
                uriBuilder.appendQueryParameter(param.getName(), param.getValue());
            }

            uri = uriBuilder.build();
            request.setURI(new URI(uri.toString()));
        }
    } catch (URISyntaxException e) {
        Ln.e(e, "URI syntax was incorrect: %s", uri.toString());
    }
}

From source file:com.bigdata.rockstor.console.RockStorSender.java

private static HttpRequestBase buildHttpRequest(HttpReq req)
        throws UnsupportedEncodingException, URISyntaxException {

    HttpRequestBase request = null;
    if ("GET".equals(req.getMethod())) {
        request = new HttpGet();
    } else if ("PUT".equals(req.getMethod())) {
        request = new HttpPut();
        if (req.getBody() != null && req.getBody().length() > 0)
            ((HttpPut) request).setEntity(new StringEntity(req.getBody()));
    } else if ("DELETE".equals(req.getMethod())) {
        request = new HttpDelete();
    } else if ("HEAD".equals(req.getMethod())) {
        request = new HttpHead();
    } else {//from  w ww .  j  a v  a2 s .c o  m
        throw new NullPointerException("Unknown HTTP Method : " + req.getMethod());
    }

    request.setURI(new URI(req.getUrl()));

    if (req.getHead() != null) {
        for (Map.Entry<String, String> e : req.getHead().entrySet()) {
            if ("PUT".equals(req.getMethod()) && e.getKey().equals("Content-Length"))
                continue;
            request.setHeader(e.getKey(), e.getValue());
        }
    }

    return request;
}

From source file:com.griddynamics.jagger.invoker.http.ApacheHttpInvoker.java

@Override
protected HttpRequestBase getHttpMethod(HttpRequestBase query, String endpoint) {
    try {//from w  w w  .  j a v a2s . c  om
        if (query.getURI() == null) {
            query.setURI(URI.create(endpoint));
            return query;
        } else {
            URIBuilder uriBuilder = new URIBuilder(URI.create(endpoint));
            uriBuilder.setQuery(query.getURI().getQuery());
            uriBuilder.setFragment(query.getURI().getFragment());
            uriBuilder.setUserInfo(query.getURI().getUserInfo());
            if (!query.getURI().getPath().isEmpty()) {
                uriBuilder.setPath(query.getURI().getPath());
            }
            query.setURI(uriBuilder.build());
            return query;
        }
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:pt.sapo.pai.vip.VipServlet.java

private void processRequest(HttpServletRequest request, HttpServletResponse response,
        Supplier<HttpRequestBase> supplier) throws ServletException, IOException {
    try (OutputStream out = response.getOutputStream(); CloseableHttpClient http = builder.build()) {
        Optional.ofNullable(servers[rand.nextInt(2)]).map(server -> server.split(":"))
                .map(parts -> Tuple.of(parts[0], Integer.valueOf(parts[1]))).ifPresent(server -> {
                    try {
                        HttpRequestBase method = supplier.get();
                        method.setURI(new URI(request.getScheme(), null, server._1, server._2,
                                request.getRequestURI(), request.getQueryString(), null));
                        HttpResponse rsp = http.execute(method);
                        Collections.list(request.getHeaderNames())
                                .forEach(name -> Collections.list(request.getHeaders(name))
                                        .forEach(value -> method.setHeader(name, value)));
                        response.setStatus(rsp.getStatusLine().getStatusCode());
                        response.setContentType(rsp.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
                        IOUtils.copy(rsp.getEntity().getContent(), out);
                    } catch (IOException | URISyntaxException ex) {
                        log.error(null, ex);
                    }/*from ww  w . j  a  va2  s .c  o  m*/
                });
    }
}