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

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

Introduction

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

Prototype

public URIBuilder addParameter(final String param, final String value) 

Source Link

Document

Adds parameter to URI query.

Usage

From source file:de.ii.xtraplatform.ogc.csw.client.CSWAdapter.java

private HttpResponse requestGET(CSWOperation operation) throws ParserConfigurationException {
    URI url = findUrl(operation.getOperation(), CSW.METHOD.GET);

    HttpClient httpClient = url.getScheme().equals("https") ? this.untrustedSslHttpClient : this.httpClient;

    URIBuilder uri = new URIBuilder(url);

    Map<String, String> params = operation.toKvp(nsStore, version);

    for (Map.Entry<String, String> param : params.entrySet()) {
        uri.addParameter(param.getKey(), param.getValue());
    }/*from www.  j  ava 2  s . c  o m*/
    //LOGGER.debug(FrameworkMessages.GET_REQUEST_OPERATION_URL, operation.toString(), uri.toString());

    boolean retried = false;
    HttpGet httpGet;
    HttpResponse response;

    try {

        // replace the + with %20
        String uristring = uri.build().toString();
        uristring = uristring.replaceAll("\\+", "%20");
        httpGet = new HttpGet(uristring);

        // TODO: temporary basic auth hack
        if (useBasicAuth) {
            String basic_auth = new String(Base64.encodeBase64((user + ":" + password).getBytes()));
            httpGet.addHeader("Authorization", "Basic " + basic_auth);
        }

        response = httpClient.execute(httpGet, new BasicHttpContext());

        // check http status
        checkResponseStatus(response.getStatusLine().getStatusCode(), uri);

    } catch (SocketTimeoutException ex) {
        if (ignoreTimeouts) {
            //LOGGER.warn(FrameworkMessages.GET_REQUEST_TIMED_OUT_AFTER_MS_URL_REQUEST, HttpConnectionParams.getConnectionTimeout(httpClient.getParams()), uri.toString());
        }
        response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "");
        response.setEntity(new StringEntity("", ContentType.TEXT_XML));
    } catch (IOException ex) {
        try {
            if (!isDefaultUrl(uri.build(), CSW.METHOD.GET)) {

                //LOGGER.info(FrameworkMessages.REMOVING_URL, uri.toString());
                this.urls.remove(operation.getOperation().toString());

                //LOGGER.info(FrameworkMessages.RETRY_WITH_DEFAULT_URL, this.urls.get("default"));
                return requestGET(operation);
            }
        } catch (URISyntaxException ex0) {
        }
        //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString());
        throw new ReadError("Failed requesting URL: '{}'", uri);
    } catch (URISyntaxException ex) {
        //LOGGER.error(FrameworkMessages.FAILED_REQUESTING_URL, uri.toString());
        throw new ReadError("Failed requesting URL: '{}'", uri);
    }
    //LOGGER.debug(FrameworkMessages.WFS_REQUEST_SUBMITTED);
    return response;
}

From source file:com.xively.client.http.DefaultRequestHandler.java

private URIBuilder buildUri(HttpMethod requestMethod, String appPath, Map<String, Object> params,
        AcceptedMediaType mediaType) {//  w  w w  .  j  a va  2s.  c  om
    URIBuilder uriBuilder = new URIBuilder();
    String path = appPath;
    if (HttpMethod.GET == requestMethod) {
        path = appPath.concat(".").concat(mediaType.name());
    }
    uriBuilder.setScheme("http").setHost(baseURI).setPath(path);
    if (params != null && !params.isEmpty()) {
        for (Entry<String, Object> param : params.entrySet()) {
            uriBuilder.addParameter(param.getKey(), StringUtil.toString(param.getValue()));
        }
    }
    return uriBuilder;
}

From source file:com.mirth.connect.plugins.httpauth.oauth2.OAuth2Authenticator.java

@Override
public AuthenticationResult authenticate(RequestInfo request) throws Exception {
    OAuth2HttpAuthProperties properties = getReplacedProperties(request);

    CloseableHttpClient client = null;/*from   w  ww  .j  ava 2s  .  c o m*/
    CloseableHttpResponse response = null;

    try {
        // Create and configure the client and context 
        RegistryBuilder<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                .<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory());
        ConnectorPluginProperties pluginProperties = null;
        if (CollectionUtils.isNotEmpty(properties.getConnectorPluginProperties())) {
            pluginProperties = properties.getConnectorPluginProperties().iterator().next();
        }
        provider.getHttpConfiguration().configureSocketFactoryRegistry(pluginProperties, socketFactoryRegistry);
        BasicHttpClientConnectionManager httpClientConnectionManager = new BasicHttpClientConnectionManager(
                socketFactoryRegistry.build());
        httpClientConnectionManager.setSocketConfig(SocketConfig.custom().setSoTimeout(SOCKET_TIMEOUT).build());
        HttpClientBuilder clientBuilder = HttpClients.custom()
                .setConnectionManager(httpClientConnectionManager);
        HttpUtil.configureClientBuilder(clientBuilder);
        client = clientBuilder.build();

        HttpClientContext context = HttpClientContext.create();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(SOCKET_TIMEOUT)
                .setSocketTimeout(SOCKET_TIMEOUT).setStaleConnectionCheckEnabled(true).build();
        context.setRequestConfig(requestConfig);

        URIBuilder uriBuilder = new URIBuilder(properties.getVerificationURL());

        // Add query parameters
        if (properties.getTokenLocation() == TokenLocation.QUERY) {
            List<String> paramList = request.getQueryParameters().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(paramList)) {
                for (String value : paramList) {
                    uriBuilder.addParameter(properties.getLocationKey(), value);
                }
            }
        }

        // Build the final URI and create a GET request
        HttpGet httpGet = new HttpGet(uriBuilder.build());

        // Add headers
        if (properties.getTokenLocation() == TokenLocation.HEADER) {
            List<String> headerList = request.getHeaders().get(properties.getLocationKey());
            if (CollectionUtils.isNotEmpty(headerList)) {
                for (String value : headerList) {
                    httpGet.addHeader(properties.getLocationKey(), value);
                }
            }
        }

        // Execute the request
        response = client.execute(httpGet, context);

        // Determine authentication from the status code 
        if (response.getStatusLine().getStatusCode() < 400) {
            return AuthenticationResult.Success();
        } else {
            return AuthenticationResult.Failure();
        }
    } finally {
        HttpClientUtils.closeQuietly(response);
        HttpClientUtils.closeQuietly(client);
    }
}

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

/**
 * Performs a search for all possible results.
 * /*from  w  w  w.  j  a  v  a  2s  . c om*/
 * @param criteria
 *            The search criteria.
 * @param searchType
 *            the type of search to execute.
 * @return the search result for licenses
 * 
 * @throws URISyntaxException
 *             if an error occurs while building the URL.
 * @throws ClientProtocolException
 *             if client does not support protocol used.
 * @throws IOException
 *             if an error occurs while parsing response.
 * @throws ParseException
 *             if an error occurs while parsing response.
 * @throws ServiceException
 *             for any other problems encountered
 */
private SearchResult<License> getAllResults(ChiropracticLicenseSearchCriteria criteria, String searchType)
        throws URISyntaxException, ClientProtocolException, IOException, ParseException, ServiceException {
    DefaultHttpClient client = new DefaultHttpClient();
    client.setRedirectStrategy(new LaxRedirectStrategy());

    URIBuilder uriBuilder = new URIBuilder(getSearchURL());
    uriBuilder.addParameter("strName", Util.defaultString(criteria.getLastName()));
    uriBuilder.addParameter("strSoundex", Util.defaultString(criteria.getLastName()));
    uriBuilder.addParameter("strCity", Util.defaultString(criteria.getCity()));
    uriBuilder.addParameter("strZIP", Util.defaultString(criteria.getZipCode()));
    uriBuilder.addParameter(searchType, TYPES.get(searchType));

    HttpGet search = new HttpGet(uriBuilder.build());
    HttpResponse response = client.execute(search);
    verifyAndAuditCall(getSearchURL(), response);

    Document page = Jsoup.parse(EntityUtils.toString(response.getEntity()));
    List<License> allLicenses = new ArrayList<License>();

    Elements rows = page.select("tr:gt(0)");
    for (Element row : rows) {
        String href = row.select("a").first().attr("href"); // detail link
        String licenseType = row.select("td:eq(2)").text();

        HttpGet getDetails = new HttpGet(Util.replaceLastURLPart(uriBuilder.build().toString(), href));
        response = client.execute(getDetails);
        verifyAndAuditCall(getSearchURL(), response);

        page = Jsoup.parse(EntityUtils.toString(response.getEntity()));
        allLicenses.add(parseLicense(page, licenseType));
    }

    SearchResult<License> searchResult = new SearchResult<License>();
    searchResult.setItems(allLicenses);
    return searchResult;
}

From source file:de.ii.xtraplatform.ogc.csw.client.CSWAdapter.java

public String getRequestUrl(CSWOperation operation) {
    try {/* w w  w  .j  av  a2s  .  c om*/
        URIBuilder uri = new URIBuilder(findUrl(operation.getOperation(), CSW.METHOD.GET));

        Map<String, String> params = operation.toKvp(nsStore, version);

        for (Map.Entry<String, String> param : params.entrySet()) {
            uri.addParameter(param.getKey(), param.getValue());
        }

        return uri.build().toString();
    } catch (URISyntaxException | ParserConfigurationException e) {
        return "";
    }
}

From source file:org.obiba.magma.datasource.mongodb.MongoDBDatasourceFactory.java

public URI getUri() {
    try {/*from   w w  w.  j  av a 2 s  .c  o  m*/
        URIBuilder uriBuilder = new URIBuilder(url);
        if (!Strings.isNullOrEmpty(username)) {
            if (Strings.isNullOrEmpty(password)) {
                uriBuilder.setUserInfo(username);
            } else {
                uriBuilder.setUserInfo(username, password);
            }
        }
        Properties prop = readOptions();
        for (Map.Entry<Object, Object> entry : prop.entrySet()) {
            uriBuilder.addParameter(entry.getKey().toString(), entry.getValue().toString());
        }
        return uriBuilder.build();
    } catch (URISyntaxException e) {
        throw new RuntimeException("Cannot create MongoDB URI", e);
    }
}

From source file:com.dawg6.d3api.server.D3IO.java

public Account getAccount(Token token) throws Exception {
    CloseableHttpClient client = HttpClientBuilder.create().build();

    URIBuilder builder = new URIBuilder(ACCOUNT_API_URL);
    builder.addParameter("access_token", token.access_token);

    //      log.info("Request = " + builder.toString());
    HttpGet request = new HttpGet(builder.toString());

    HttpResponse response = client.execute(request);

    if (response.getStatusLine().getStatusCode() != 200) {
        log.log(Level.SEVERE, "HTTP Server Response: " + response.getStatusLine().getStatusCode());
        throw new RuntimeException("HTTP Server Response: " + response.getStatusLine().getStatusCode());
    }//from w ww  . j av  a2s.c om

    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }

    client.close();

    ObjectMapper mapper = new ObjectMapper();
    mapper = mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Account account = mapper.readValue(result.toString(), Account.class);

    if ((account != null) && (account.error != null))
        throw new RuntimeException(token.error_description);

    return account;
}

From source file:com.kolich.aws.services.s3.impl.KolichS3Client.java

@Override
public Either<HttpFailure, ObjectListing> listObjects(final String bucketName, final String marker,
        final String... path) {
    return new AwsS3HttpClosure<ObjectListing>(client_, SC_OK, bucketName) {
        @Override// w ww  .  j a va2  s. com
        public void validate() throws Exception {
            checkNotNull(bucketName, "Bucket name cannot be null.");
            checkState(isValidBucketName(bucketName),
                    "Invalid bucket name, " + "did not match expected bucket name pattern.");
        }

        @Override
        public void prepare(final AwsHttpRequest request) throws Exception {
            final URIBuilder builder = new URIBuilder(request.getURI());
            if (marker != null) {
                builder.addParameter(S3_PARAM_MARKER, marker);
            }
            // Add the prefix string to the request if we have one.
            if (path != null && path.length > 0) {
                builder.addParameter(S3_PARAM_PREFIX, varargsToPathString(path));
            }
            request.setURI(builder.build());
        }

        @Override
        public ObjectListing success(final HttpSuccess success) throws Exception {
            return new Unmarshallers.ListObjectsUnmarshaller().unmarshall(success.getContent());
        }
    }.get();
}

From source file:nl.salp.warcraft4j.battlenet.api.BattlenetHttpApi.java

/**
 * Create the request URI to call./*  w w w  .  j a v a2 s .  c o  m*/
 *
 * @param region The Battle.NET API region to call.
 * @param locale The locale to receive the responses in.
 * @param method The method to create the URI for.
 * @param <T>    The return type of the method.
 *
 * @return The URI to call for execution.
 *
 * @throws IOException When the URI could not be created.
 */
protected <T> URI createUri(BattlenetRegion region, BattlenetLocale locale, BattlenetApiRequest<T> method)
        throws IOException {
    URIBuilder builder = new URIBuilder().setScheme(BATTLENETAPI_SCHEME).setPath(method.getRequestUri())
            .addParameter(PARAMETER_API_KEY, getConfig().getBnetApiKey());
    if (region == null) {
        builder.setHost(format(BATTLENETAPI_SERVER_MASK, getRegion().getApiUri()));
    } else {
        builder.setHost(format(BATTLENETAPI_SERVER_MASK, region.getApiUri()));
    }
    if (locale == null) {
        builder.addParameter(PARAMETER_LOCALE, getLocale().getLocale());
    } else {
        builder.addParameter(PARAMETER_LOCALE, locale.getLocale());
    }

    for (Map.Entry<String, String> param : method.getRequestParameters().entrySet()) {
        builder.addParameter(param.getKey(), param.getValue());
    }

    try {
        return builder.build();
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

From source file:org.metaservice.manager.blazegraph.FastRangeCountRequestBuilder.java

public MutationResult execute() throws ManagerException {
    try {/*from   w w w.  j av a 2 s  .  c  o m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(MutationResult.class);

        URIBuilder uriBuilder = new URIBuilder(path);
        if (subject != null) {
            uriBuilder.setParameter("s", format(subject));
        }
        if (object != null) {
            uriBuilder.setParameter("o", format(object));
        }
        if (predicate != null) {
            uriBuilder.setParameter("p", format(predicate));
        }
        if (context != null) {
            uriBuilder.setParameter("c", format(context));
        }
        uriBuilder.addParameter("ESTCARD", null);
        URI uri = uriBuilder.build();
        LOGGER.debug("QUERY = " + uri.toString());
        String s = Request.Get(uri).connectTimeout(1000).socketTimeout(10000)
                .setHeader("Accept", "application/xml").execute().returnContent().asString();
        LOGGER.debug("RESULT = " + s);
        return (MutationResult) jaxbContext.createUnmarshaller().unmarshal(new StringReader(s));
    } catch (JAXBException | URISyntaxException | IOException e) {
        throw new ManagerException(e);
    }

}