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:nl.nn.adapterframework.extensions.cmis.CmisHttpSender.java

@Override
public HttpRequestBase getMethod(URIBuilder uri, String message, ParameterValueList pvl,
        Map<String, String> headersParamsMap, IPipeLineSession session) throws SenderException {
    HttpRequestBase method = null;//w w  w  .  jav  a  2  s.  c om

    try {
        if (getMethodType().equals("GET")) {
            method = new HttpGet(uri.build());
        } else if (getMethodType().equals("POST")) {
            HttpPost httpPost = new HttpPost(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPost.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPost.setEntity(entity);
                out.close();

                method = httpPost;
            }
        } else if (getMethodType().equals("PUT")) {
            HttpPut httpPut = new HttpPut(uri.build());

            // send data
            if (pvl.getParameterValue("writer") != null) {
                Output writer = (Output) pvl.getParameterValue("writer").getValue();
                ByteArrayOutputStream out = new ByteArrayOutputStream();

                Object clientCompression = pvl.getParameterValue(SessionParameter.CLIENT_COMPRESSION);
                if ((clientCompression != null) && Boolean.parseBoolean(clientCompression.toString())) {
                    httpPut.setHeader("Content-Encoding", "gzip");
                    writer.write(new GZIPOutputStream(out, 4096));
                } else {
                    writer.write(out);
                }

                HttpEntity entity = new BufferedHttpEntity(new ByteArrayEntity(out.toByteArray()));
                httpPut.setEntity(entity);
                out.close();

                method = httpPut;
            }
        } else if (getMethodType().equals("DELETE")) {
            method = new HttpDelete(uri.build());
        } else {
            throw new MethodNotSupportedException("method [" + getMethodType() + "] not implemented");
        }
    } catch (Exception e) {
        throw new SenderException(e);
    }

    for (Map.Entry<String, String> entry : headers.entrySet()) {
        log.debug("append header [" + entry.getKey() + "] with value [" + entry.getValue() + "]");

        method.addHeader(entry.getKey(), entry.getValue());
    }

    //Cmis creates it's own contentType depending on the method and bindingType
    method.setHeader("Content-Type", getContentType());

    log.debug(getLogPrefix() + "HttpSender constructed " + getMethodType() + "-method [" + method.getURI()
            + "] query [" + method.getURI().getQuery() + "] ");
    return method;
}

From source file:nl.eveoh.mytimetable.apiclient.service.MyTimetableServiceImpl.java

/**
 * Creates a request for each MyTimetable API endpoint defined in the configuration.
 *
 * @param username Username the fetch the upcoming events for.
 * @return List of {@link HttpUriRequest} objects, which should be executed in order, until a result is acquired.
 *///w  ww  . ja  v a 2  s. c  o  m
private ArrayList<HttpUriRequest> getApiRequests(String username) {
    if (StringUtils.isBlank(username)) {
        log.error("Username cannot be empty.");
        throw new LocalizableException("Username cannot be empty.", "notLoggedIn");
    }

    if (StringUtils.isBlank(configuration.getApiKey())) {
        log.error("API key cannot be empty.");
        throw new LocalizableException("API key cannot be empty.");
    }

    // Prefix the username, for example when MyTimetable is used in a domain.
    String domainPrefix = configuration.getUsernameDomainPrefix();
    if (domainPrefix != null && !domainPrefix.isEmpty()) {
        username = domainPrefix + '\\' + username;
    }

    // build request URI
    Date currentTime = new Date();

    ArrayList<HttpUriRequest> requests = new ArrayList<HttpUriRequest>();

    for (String uri : configuration.getApiEndpointUris()) {
        String baseUrl;

        if (uri.endsWith("/")) {
            baseUrl = uri + "timetable";
        } else {
            baseUrl = uri + "/timetable";
        }

        try {
            URIBuilder uriBuilder = new URIBuilder(baseUrl);
            uriBuilder.addParameter("startDate", Long.toString(currentTime.getTime()));
            uriBuilder.addParameter("limit", Integer.toString(configuration.getNumberOfEvents()));

            URI apiUri = uriBuilder.build();

            HttpGet request = new HttpGet(apiUri);
            request.addHeader("apiToken", configuration.getApiKey());
            request.addHeader("requestedAuth", username);

            // Configure request timeouts.
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(configuration.getApiSocketTimeout())
                    .setConnectTimeout(configuration.getApiConnectTimeout()).build();

            request.setConfig(requestConfig);

            requests.add(request);
        } catch (URISyntaxException e) {
            log.error("Incorrect MyTimetable API url syntax.", e);
        }
    }

    if (requests.isEmpty()) {
        log.error("No usable MyTimetable API url.");
        throw new LocalizableException("No usable MyTimetable API url.");
    }

    return requests;
}

From source file:com.anrisoftware.simplerest.oanda.rest.OandaRestInstruments.java

private URI getRequestURI0() throws URISyntaxException {
    URIBuilder builder = new URIBuilder(propertiesProvider.getOandaInstrumentsURI());
    builder.setParameter(ACCOUNT_ID_PARAM, account.getAccount());
    if (filter.getNames().size() > 0) {
        String instruments = join(filter.getNames(), COMMA);
        builder.setParameter(INSTRUMENTS_PARAM, instruments);
    }//from  w  ww. j a  v a 2s  . c o m
    return builder.build();
}

From source file:client.Traveller.java

public void searchHotels(HotelSearch hotelSearch) {
    // Keeps current search in order to store session variables
    currentHotelSearch = hotelSearch;/*from  w ww. j a v  a2 s  . com*/

    try {
        // Builds URL for HTTP request that queries for hotels
        URIBuilder uriBuilder = new URIBuilder(hostURL + "/search/hotel");
        uriBuilder.addParameter("city", hotelSearch.getCity());
        uriBuilder.addParameter("numberOfGuests", String.valueOf(hotelSearch.getNumberOfRooms()));

        // Converts URL to string
        String urlString = uriBuilder.build().toString();

        // Sends GET request and waits for response
        String response = httpConnector.sendGet(urlString);

        // Handles server response
        ArrayList<Hotel> hotelsQueried = new ArrayList<>();
        JSONArray hotels = new JSONArray(response);
        int n = hotels.length();
        for (int i = 0; i < n; ++i) {
            final JSONObject hotel = hotels.getJSONObject(i);
            String hotelId = (hotel.getString("hotelId"));
            String hotelName = (hotel.getString("hotelName"));
            String city = (hotel.getString("city"));
            int availableRooms = (hotel.getInt("availableRooms"));
            String pricePerNight = (hotel.getString("pricePerNight"));
            Hotel h = new Hotel(hotelId, hotelName, city, availableRooms, Double.parseDouble(pricePerNight));
            hotelsQueried.add(h);
        }

        // Display search results on a new window
        hotelSearchResultsFrame = new HotelSearchResultsFrame(this, hotelsQueried);
        hotelSearchResultsFrame.setLocationRelativeTo(null);
        hotelSearchResultsFrame.setVisible(true);

    } catch (URISyntaxException ex) {
        this.displayBookingConfirmation("ERROR | Invalid search");
    }
}

From source file:net.tirasa.olingooauth2.AzureADOAuth2HttpClientFactory.java

@Override
protected void init() throws OAuth2Exception {
    final DefaultHttpClient httpClient = wrapped.create(null, null);

    // 1. access the OAuth2 grant service (with authentication)
    String code = null;// w  w  w.  j  a  v  a  2 s  . co  m
    try {
        final URIBuilder builder = new URIBuilder(oauth2GrantServiceURI).addParameter("response_type", "code")
                .addParameter("client_id", clientId).addParameter("redirect_uri", redirectURI);

        HttpResponse response = httpClient.execute(new HttpGet(builder.build()));

        final String loginPage = EntityUtils.toString(response.getEntity());

        String postURL = StringUtils.substringBefore(
                StringUtils.substringAfter(loginPage, "<form id=\"credentials\" method=\"post\" action=\""),
                "\">");
        final String ppsx = StringUtils.substringBefore(StringUtils.substringAfter(loginPage,
                "<input type=\"hidden\" id=\"PPSX\" name=\"PPSX\" value=\""), "\"/>");
        final String ppft = StringUtils.substringBefore(StringUtils.substringAfter(loginPage,
                "<input type=\"hidden\" name=\"PPFT\" id=\"i0327\" value=\""), "\"/>");

        List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
        data.add(new BasicNameValuePair("login", creds.getUserName()));
        data.add(new BasicNameValuePair("passwd", creds.getPassword()));
        data.add(new BasicNameValuePair("PPSX", ppsx));
        data.add(new BasicNameValuePair("PPFT", ppft));

        HttpPost post = new HttpPost(postURL);
        post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

        response = httpClient.execute(post);

        final String samlPage = EntityUtils.toString(response.getEntity());

        postURL = StringUtils.substringBefore(
                StringUtils.substringAfter(samlPage, "<form name=\"fmHF\" id=\"fmHF\" action=\""),
                "\" method=\"post\" target=\"_top\">");
        final String wctx = StringUtils.substringBefore(StringUtils.substringAfter(samlPage,
                "<input type=\"hidden\" name=\"wctx\" id=\"wctx\" value=\""), "\">");
        final String wresult = StringUtils.substringBefore(StringUtils.substringAfter(samlPage,
                "<input type=\"hidden\" name=\"wresult\" id=\"wresult\" value=\""), "\">");
        final String wa = StringUtils.substringBefore(
                StringUtils.substringAfter(samlPage, "<input type=\"hidden\" name=\"wa\" id=\"wa\" value=\""),
                "\">");

        data = new ArrayList<BasicNameValuePair>();
        data.add(new BasicNameValuePair("wctx", wctx));
        data.add(new BasicNameValuePair("wresult", wresult.replace("&quot;", "\"")));
        data.add(new BasicNameValuePair("wa", wa));

        post = new HttpPost(postURL);
        post.setEntity(new UrlEncodedFormEntity(data, "UTF-8"));

        response = httpClient.execute(post);

        final Header locationHeader = response.getFirstHeader("Location");
        if (response.getStatusLine().getStatusCode() != 302 || locationHeader == null) {
            throw new OAuth2Exception("Unexpected response from server");
        }

        final String[] oauth2Info = StringUtils
                .split(StringUtils.substringAfter(locationHeader.getValue(), "?"), '&');
        code = StringUtils.substringAfter(oauth2Info[0], "=");

        EntityUtils.consume(response.getEntity());
    } catch (Exception e) {
        throw new OAuth2Exception(e);
    }

    if (code == null) {
        throw new OAuth2Exception("No OAuth2 grant");
    }

    // 2. ask the OAuth2 token service
    final List<BasicNameValuePair> data = new ArrayList<BasicNameValuePair>();
    data.add(new BasicNameValuePair("grant_type", "authorization_code"));
    data.add(new BasicNameValuePair("code", code));
    data.add(new BasicNameValuePair("client_id", clientId));
    data.add(new BasicNameValuePair("redirect_uri", redirectURI));
    data.add(new BasicNameValuePair("resource", resourceURI));

    fetchAccessToken(httpClient, data);

    if (token == null) {
        throw new OAuth2Exception("No OAuth2 access token");
    }
}

From source file:com.launchkey.sdk.transport.v1.ApacheHttpClientTransport.java

/**
 * @see Transport#ping(PingRequest)//from w w w . j a va 2  s. c o  m
 */
public PingResponse ping(PingRequest request) throws LaunchKeyException {
    log.trace("Beginning ping request");
    PingResponse pingResponse;
    try {
        URIBuilder uriBuilder = new URIBuilder(getUrlForPath("/ping"));
        String dateStamp = request.getDateStamp();
        if (dateStamp != null) {
            uriBuilder.setParameter("date_stamp", dateStamp);
        }
        HttpGet ping = new HttpGet(uriBuilder.build());
        HttpResponse httpResponse = client.execute(ping);
        pingResponse = getTransportObjectFromResponse(PingResponse.class, httpResponse);
    } catch (LaunchKeyException e) {
        log.trace("Error encountered in response from LaunchKey engine", e);
        throw e;
    } catch (Exception e) {
        log.trace("Exception caught processing ping request", e);
        throw new LaunchKeyException("Exception caught processing ping request", e, 0);
    }
    log.trace("Completed ping request");
    log.trace(pingResponse);
    return pingResponse;
}

From source file:com.github.yongchristophertang.engine.web.request.HttpRequestBuilders.java

/**
 * {@inheritDoc}//  w ww. j  a  va  2  s .c om
 */
@Override
public HttpRequest buildRequest() throws Exception {
    URIBuilder builder = new URIBuilder(uriTemplate);
    builder.addParameters(parameters);
    Header[] heads = new Header[headers.size()];
    httpRequest.setHeaders(headers.toArray(heads));
    ((HttpRequestBase) httpRequest).setURI(builder.build());
    postProcessors.stream().forEach(p -> httpRequest = p.postProcessRequest(httpRequest));

    // The priorities for each content type are bytesContent > stringContent > bodyParameters
    if (bytesContent != null && bytesContent.length > 0) {
        ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(new ByteArrayEntity(bytesContent));
    } else if (stringContent != null && stringContent.length() > 0) {
        ((HttpEntityEnclosingRequestBase) httpRequest).setEntity(new StringEntity(stringContent, "UTF-8"));
    } else if (bodyParameters.size() > 0) {
        ((HttpEntityEnclosingRequestBase) httpRequest)
                .setEntity(new UrlEncodedFormEntity(bodyParameters, "UTF-8"));
    }
    return httpRequest;
}

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

public String getHealthNews(String condition, String location) {

    String result = "";

    logger.debug("Looking for {} in {}", condition, location);

    try {/* w w  w . j a  va 2  s .  c  om*/
        CloseableHttpClient httpClient = HttpClients.createDefault();

        URIBuilder builder = new URIBuilder(baseURLAlerts + "/news");
        builder.setParameter("client_id", clientId).setParameter("client_secret", clientSecret)
                .setParameter("condition", condition).setParameter("location", location);
        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 health condition news {}",
                    httpResponse.getStatusLine().getStatusCode());
        }

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

    logger.debug("found {}", result);

    return result;
}

From source file:io.uploader.drive.drive.largefile.DriveResumableUpload.java

public DriveResumableUpload(HasProxySettings proxySetting, DriveAuth auth, String uploadLocation, String title,
        HasDescription description, HasId parentId, HasMimeType mimeType, String filename, long fileSize,
        InputStreamProgressFilter.StreamProgressCallback progressCallback)
        throws IOException, URISyntaxException {

    this.auth = auth;

    this.fileSize = fileSize;
    this.useOldApi = true;
    this.proxySetting = proxySetting;
    if (org.apache.commons.lang3.StringUtils.isEmpty(uploadLocation)) {
        this.location = createResumableUpload(title, description, parentId, mimeType);
    } else {//from  w  w w . j  av  a 2  s .  c o  m
        this.location = uploadLocation;
    }
    Preconditions.checkState(StringUtils.isNotEmpty(this.location));
    URIBuilder urib = new URIBuilder(location);
    uri = urib.build();
    //logger.info("URI: " + uri.toASCIIString());
}