Example usage for org.apache.http.client.utils URIBuilder build

List of usage examples for org.apache.http.client.utils URIBuilder build

Introduction

In this page you can find the example usage for org.apache.http.client.utils URIBuilder build.

Prototype

public URI build() throws URISyntaxException 

Source Link

Document

Builds a URI instance.

Usage

From source file:org.doctester.testbrowser.Url.java

/**
 * Creates a URI from this Uri.//from  w  w  w  . j  av  a  2s . c  o  m
 *
 * @return The URI you can pass to any lib using Uri.
 */
public URI uri() {

    URI uri = null;

    try {

        URIBuilder uriBuilder = new URIBuilder(simpleUrlBuilder.toString());

        for (Map.Entry<String, String> queryParameter : queryParameters.entrySet()) {

            uriBuilder.addParameter(queryParameter.getKey(), queryParameter.getValue());

        }

        uri = uriBuilder.build();

    } catch (URISyntaxException e) {

        String message = "Something strange happend when creating a URI from your Url (host, query parameters, path and so on)";
        logger.error(message);

        throw new IllegalStateException(message, e);
    }

    return uri;

}

From source file:com.ibm.health.HealthData.java

public String getLocations() {
    String result = "";

    try {/*from   www.  java2  s . c  o  m*/
        CloseableHttpClient httpClient = HttpClients.createDefault();

        URIBuilder builder = new URIBuilder(baseURLAlerts + "/locations");
        builder.setParameter("client_id", clientId).setParameter("client_secret", clientSecret);
        URI uri = builder.build();

        HttpGet httpGet = new HttpGet(uri);

        httpGet.setHeader("Content-Type", "text/plain");
        HttpResponse httpResponse = httpClient.execute(httpGet);

        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            BufferedReader rd = new BufferedReader(
                    new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));

            StringBuilder everything = new StringBuilder();
            String line;
            while ((line = rd.readLine()) != null) {
                everything.append(line);
            }
            result = everything.toString();
        } else {
            logger.error("could not get locations {}", httpResponse.getStatusLine().getStatusCode());
        }

    } catch (Exception e) {
        logger.error("Locations error: {}", e.getMessage());
    }

    return result;
}

From source file:eu.hansolo.accs.RestClient.java

private JSONObject putSpecific(final URIBuilder BUILDER, final Location LOCATION) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPut put = new HttpPut(BUILDER.build());
        put.setHeader("Content-type", "application/json");
        put.setHeader("accept", "application/json");
        put.setEntity(new StringEntity(LOCATION.toJSONString()));

        return handleResponse(httpClient.execute(put));
    } catch (URISyntaxException | IOException e) {
        return new JSONObject();
    }//from  w  w w  . j  a v a 2  s.  c  o m
}

From source file:eu.hansolo.accs.RestClient.java

private JSONObject postSpecific(final URIBuilder BUILDER, final Location LOCATION) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost post = new HttpPost(BUILDER.build());
        post.setHeader("Content-type", "application/json");
        post.setHeader("accept", "application/json");
        post.setEntity(new StringEntity(LOCATION.toJSONString()));

        return handleResponse(httpClient.execute(post));
    } catch (URISyntaxException | IOException e) {
        return new JSONObject();
    }//from   w  w  w . ja v  a  2s .co  m
}

From source file:com.att.voice.AttDigitalLife.java

public String getAttribute(Map<String, String> authMap, String deviceGUID, String attribute) {
    try {/*from w w w  .  j av  a  2  s . c om*/
        URIBuilder builder = new URIBuilder();
        builder.setScheme("https").setHost(DIGITAL_LIFE_PATH)
                .setPath("/penguin/api/" + authMap.get("id") + "/devices/" + deviceGUID + "/" + attribute);

        URI uri = builder.build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Authtoken", authMap.get("Authtoken"));
        httpget.setHeader("Requesttoken", authMap.get("Requesttoken"));
        httpget.setHeader("Appkey", authMap.get("Appkey"));

        ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
            @Override
            public String handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return entity != null ? EntityUtils.toString(entity) : null;
                } else {
                    throw new ClientProtocolException("Unexpected response status: " + status);
                }
            }
        };
        String responseBody = httpclient.execute(httpget, responseHandler);

        String json = responseBody.trim();
        JSONObject content = new JSONObject(json);
        return content.getJSONObject("content").getString("value");
    } catch (URISyntaxException | IOException | JSONException ex) {
        System.err.println(ex.getMessage());
        return null;
    }
}

From source file:com.collective.celos.CelosClient.java

public void clearCache() throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + CLEAR_CACHE_PATH);
    executePost(uriBuilder.build());
}

From source file:ar.edu.ubp.das.src.chat.actions.ActualizarMensajesAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        //prepare http get
        SalaBean sala = (SalaBean) request.getSession().getAttribute("sala");
        String ultimo_mensaje = String.valueOf(request.getSession().getAttribute("ultimo_mensaje"));
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        if (ultimo_mensaje.equals("null") || ultimo_mensaje.isEmpty()) {
            ultimo_mensaje = "-1";
        }//from www  .  j  av  a2s . c o  m

        URIBuilder builder = new URIBuilder();
        builder.setScheme("http").setHost("25.136.78.82").setPort(8080)
                .setPath("/mensajes/sala/" + sala.getId());
        builder.setParameter("ultimo_mensaje", ultimo_mensaje);

        HttpGet getRequest = new HttpGet();
        getRequest.setURI(builder.build());
        getRequest.addHeader("Authorization", "BEARER " + authToken);
        getRequest.addHeader("accept", "application/json; charset=ISO-8859-1");

        CloseableHttpResponse getResponse = httpClient.execute(getRequest);
        HttpEntity responseEntity = getResponse.getEntity();
        StatusLine responseStatus = getResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }

        //parse message data from response
        Gson gson = new Gson();
        Type listType = new TypeToken<LinkedList<MensajeBean>>() {
        }.getType();
        List<MensajeBean> mensajes = gson.fromJson(restResp, listType);

        if (!mensajes.isEmpty()) {
            MensajeBean ultimo = mensajes.get(mensajes.size() - 1);
            request.getSession().removeAttribute("ultimo_mensaje");
            request.getSession().setAttribute("ultimo_mensaje", ultimo.getId_mensaje());
        }

        if (!ultimo_mensaje.equals("-1")) {
            request.setAttribute("mensajes", mensajes);
        }

        return mapping.getForwardByName("success");

    } catch (IOException | URISyntaxException | RuntimeException e) {
        String id_sala = (String) request.getSession().getAttribute("id_sala");
        request.setAttribute("message",
                "Error al intentar actualizar mensajes de Sala " + id_sala + ": " + e.getMessage());
        response.setStatus(400);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.dspace.app.sherpa.SHERPAService.java

public SHERPAResponse searchByJournalISSN(String query) {
    String endpoint = ConfigurationManager.getProperty("sherpa.romeo.url");
    String apiKey = ConfigurationManager.getProperty("sherpa.romeo.apikey");

    HttpGet method = null;/*from   w w  w.j  a  va  2 s.  c o  m*/
    SHERPAResponse sherpaResponse = null;
    int numberOfTries = 0;

    while (numberOfTries < maxNumberOfTries && sherpaResponse == null) {
        numberOfTries++;

        if (log.isDebugEnabled()) {
            log.debug(String.format(
                    "Trying to contact SHERPA/RoMEO - attempt %d of %d; timeout is %d; sleep between timeouts is %d",
                    numberOfTries, maxNumberOfTries, timeout, sleepBetweenTimeouts));
        }

        try {
            Thread.sleep(sleepBetweenTimeouts);

            URIBuilder uriBuilder = new URIBuilder(endpoint);
            uriBuilder.addParameter("issn", query);
            uriBuilder.addParameter("versions", "all");
            if (StringUtils.isNotBlank(apiKey))
                uriBuilder.addParameter("ak", apiKey);

            method = new HttpGet(uriBuilder.build());
            method.setConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout)
                    .setConnectTimeout(timeout).setSocketTimeout(timeout).build());
            // Execute the method.

            HttpResponse response = client.execute(method);
            int statusCode = response.getStatusLine().getStatusCode();

            if (statusCode != HttpStatus.SC_OK) {
                sherpaResponse = new SHERPAResponse("SHERPA/RoMEO return not OK status: " + statusCode);
            }

            HttpEntity responseBody = response.getEntity();

            if (null != responseBody)
                sherpaResponse = new SHERPAResponse(responseBody.getContent());
            else
                sherpaResponse = new SHERPAResponse("SHERPA/RoMEO returned no response");
        } catch (Exception e) {
            log.warn("Encountered exception while contacting SHERPA/RoMEO: " + e.getMessage(), e);
        } finally {
            if (method != null) {
                method.releaseConnection();
            }
        }
    }

    if (sherpaResponse == null) {
        sherpaResponse = new SHERPAResponse("Error processing the SHERPA/RoMEO answer");
    }

    return sherpaResponse;
}

From source file:org.mobicents.servlet.restcomm.http.client.HttpRequestDescriptor.java

private URI base(final URI uri) {
    try {/*  w ww  .  j  av a2 s.  c  om*/
        URIBuilder uriBuilder = new URIBuilder();
        uriBuilder.setScheme(uri.getScheme());
        uriBuilder.setHost(uri.getHost());
        uriBuilder.setPort(uri.getPort());
        uriBuilder.setPath(uri.getPath());

        if (uri.getUserInfo() != null) {
            uriBuilder.setUserInfo(uri.getUserInfo());
        }
        return uriBuilder.build();
    } catch (final URISyntaxException ignored) {
        // This should never happen since we are using a valid URI to construct ours.
        return null;
    }
}

From source file:gov.medicaid.screening.dao.impl.MarriageAndFamilyTherapyLicenseDAOBean.java

/**
 * Performs a search for all possible results.
 *
 * @param criteria The search criteria./*w  w  w .  java  2s .  c  o  m*/
 * @param identifier The value to be searched.
 * @param host The host where to perform search.
 * @param pageNumber The page number requested
 * @return the search result for licenses
 * @throws URISyntaxException When an error occurs while building the URL.
 * @throws IOException When an error occurs while parsing response.
 * @throws ParseException When an error occurs while parsing response.
 * @throws PersistenceException if any db related error is encountered
 * @throws ServiceException When an error occurs while trying to perform search.
 */
private SearchResult<License> getAllResults(String criteria, String identifier, String host, int pageNumber)
        throws URISyntaxException, ParseException, PersistenceException, IOException, ServiceException {
    HttpClient client = new DefaultHttpClient();
    URIBuilder builder = new URIBuilder(host).setPath("/search.asp");
    String hostId = builder.build().toString();

    builder.setParameter("qry", criteria).setParameter("crit", identifier).setParameter("p", "s")
            .setParameter("rsp", pageNumber + "");

    URI uri = builder.build();
    HttpGet httpget = new HttpGet(uri);

    SearchResult<License> searchResults = new SearchResult<License>();

    HttpResponse response = client.execute(httpget);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {

        HttpEntity entity = response.getEntity();
        SearchResult<License> nextResults = null;
        // licenses list
        List<License> licenseList = new ArrayList<License>();
        if (entity != null) {
            String result = EntityUtils.toString(entity);
            Document document = Jsoup.parse(result);
            Elements trs = document.select("tr[bgcolor]");
            for (Element tr : trs) {
                Elements tds = tr.children();
                licenseList.add(parseLicenseInfo(tds));
            }
            // check if there is next page
            Element next = document.select("a:containsOwn(Next)").first();
            if (next != null) {
                nextResults = getAllResults(criteria, identifier, host, pageNumber + 1);
            }
            if (nextResults != null) {
                licenseList.addAll(nextResults.getItems());
            }
        }

        searchResults.setItems(licenseList);
    }
    verifyAndAuditCall(hostId, response);

    return searchResults;
}