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

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

Introduction

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

Prototype

public URIBuilder(final URI uri) 

Source Link

Document

Construct an instance from the provided URI.

Usage

From source file:org.outermedia.solrfusion.adapter.solr.DefaultSolrAdapterTest.java

@Test
public void testHttpClientUriTools() throws IOException, URISyntaxException {
    String url = "http://141.39.229.20:9002/te/select?q=23";
    URIBuilder ub = new URIBuilder(url);

    Assert.assertEquals("", "[q=23]", ub.getQueryParams().toString());

    ub.setParameter("q", "*:*");

    Assert.assertEquals("", "[q=*:*]", ub.getQueryParams().toString());
}

From source file:com.highstreet.technologies.test.client.impl.TestClientBuilder.java

private JSONObject mountPointTest() {

    CloseableHttpClient httpclient = TestClientImpl.getRestConfClient(this.restConfServer);

    try {/*from www  .j  av  a2s. co m*/
        String path = "/restconf/operational/network-topology:network-topology/topology/topology-netconf/node/"
                + this.node.getNodeId();

        URI uri = new URIBuilder(TestClientImpl.getTarget(this.restConfServer).toURI()).setPath(path).build();
        HttpGet httpget = new HttpGet(uri);
        httpget.setHeader("Content-Type", "application/json");
        httpget.setHeader("Accept", "application/json");

        // Create a custom response handler
        ResponseHandler<JSONObject> responseHandler = new ResponseHandler<JSONObject>() {

            @Override
            public JSONObject handleResponse(final HttpResponse response)
                    throws ClientProtocolException, IOException {
                int status = response.getStatusLine().getStatusCode();
                String reason = response.getStatusLine().getReasonPhrase();

                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    return new JSONObject(EntityUtils.toString(entity));
                } else {
                    JSONObject error = new JSONObject();
                    error.put("status", status);
                    error.put("reason", reason);
                    return error;
                }
            }
        };
        JSONObject result = httpclient.execute(httpget, responseHandler);
        if (!result.has("status")) {
            // perform some checks
            JSONObject mountPoint = result.getJSONArray("node").getJSONObject(0);
            String connectionStatus = (String) mountPoint.get("netconf-node-topology:connection-status");
            if (!connectionStatus.equals("connected")) {
                System.out.println(
                        String.format("ERROR: Connection status is '%1s', but expected status is 'connected'.",
                                connectionStatus));
            }

            String capabilities = mountPoint.getJSONObject("netconf-node-topology:available-capabilities")
                    .getJSONArray("available-capability").toString();
            for (String capability : this.node.getExpectedNetconfCapabilities()) {
                Boolean found = capabilities.contains(capability);
                if (!found) {
                    System.out.println("WARNING: Capability not found! " + capability);
                }
            }

        } else {
            // error
            JSONObject checks = new JSONObject();
            checks.put("description", this.node.getNodeId() + " not mounted?! ");
            checks.put("expected-mountpoint", new JSONObject(this.node.toJsonString()));
            result.put("suggestion", checks);
            System.out.println(result.toString(1));
        }
        return result;

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } finally {
        try {
            httpclient.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:api.BaiduFolkMusicApi.java

private URI getRequestUri(List<NameValuePair> parameters) {

    try {//from  w  ww . j  a v  a  2 s.c  o  m

        parameters.add(new BasicNameValuePair("errordetails", "1"));
        URIBuilder uriBuilder = new URIBuilder(this.apiInvokeAddress);
        uriBuilder.addParameters(parameters);

        URI uri = uriBuilder.build();
        String uriStr = uri.toString();

        System.out.println(uriStr);

        return uri;

    } catch (URISyntaxException ex) {
        Logger.getLogger(BaiduFolkMusicApi.class.getName()).log(Level.SEVERE, null, ex);
    }

    return null;
}

From source file:org.stem.api.BaseHttpClient.java

protected URI getURI(String relativeUri) {
    try {//from  www .  jav  a 2  s .c  o m
        return new URIBuilder(root).setPath(relativeUri).build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:co.tuzza.swipehq.transport.ManagedHttpTransport.java

@Override
public <T> T doGet(String url, Map<String, String> params, Class<T> c) throws Exception {
    URIBuilder uriBuilder = new URIBuilder(url);
    uriBuilder.addParameters(parseParams(params));

    HttpUriRequest method;/*ww w.  ja  va2s .co m*/
    HttpGet httpGet = new HttpGet(uriBuilder.build());
    method = httpGet;

    HttpClient client = getHttpClient();

    HttpResponse httpResponse = client.execute(method);
    String response = new BasicResponseHandler().handleResponse(httpResponse);

    return ResponseParser.parseResponse(response, c);
}

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 {// w  w w .  j av a2 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());
}

From source file:com.grameenfoundation.ictchallenge.controllers.ConnectedAppREST.java

private JSONObject showFarmers(String instanceUrl, String accessToken) throws ServletException, IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpGet httpGet = new HttpGet();

    //add key and value
    httpGet.addHeader("Authorization", "OAuth " + accessToken);

    try {/*from   w  ww .  j a  v a  2 s.  com*/

        URIBuilder builder = new URIBuilder(instanceUrl + "/services/data/v30.0/query");
        //builder.setParameter("q", "SELECT Name, Id from Account LIMIT 100");
        builder.setParameter("q",
                "SELECT Name__c,Date_Of_Birth__c,Land_size__c,Farmer_I_D__c,Picture__c from Farmer__c LIMIT 100");

        httpGet.setURI(builder.build());

        log.log(Level.INFO, "URl to salesforce {0}", builder.build().getPath());

        CloseableHttpResponse closeableresponse = httpclient.execute(httpGet);
        System.out.println("Response Status line :" + closeableresponse.getStatusLine());

        if (closeableresponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Now lets use the standard java json classes to work with the
            // results
            try {

                // Do the needful with entity.  
                HttpEntity entity = closeableresponse.getEntity();
                InputStream rstream = entity.getContent();
                JSONObject authResponse = new JSONObject(new JSONTokener(rstream));

                log.log(Level.INFO, "Query response: {0}", authResponse.toString(2));

                log.log(Level.INFO, "{0} record(s) returned\n\n", authResponse.getInt("totalSize"));

                return authResponse;

            } catch (JSONException e) {
                e.printStackTrace();
                throw new ServletException(e);
            }
        }
    } catch (URISyntaxException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } finally {
        httpclient.close();
    }

    return null;
}

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

public Set<WorkflowID> getWorkflowList() throws Exception {
    URIBuilder uriBuilder = new URIBuilder(address);
    uriBuilder.setPath(uriBuilder.getPath() + WORKFLOW_LIST_PATH);

    HttpGet workflowListGet = new HttpGet(uriBuilder.build());
    HttpResponse getResponse = execute(workflowListGet);
    InputStream content = getResponse.getEntity().getContent();
    return parseWorkflowIdsList(content);
}

From source file:com.flipkart.aesop.serializer.batch.reader.UserInfoServiceReader.java

/**
 * Returns a number of {@link UserInfo} instances looked up from a service end-point.
 * Note : The end-point and parameters used here are very specific to this sample. Also the code is mostly for testing and production 
 * ready (no Http connection pools etc.) 
 * @see org.trpr.platform.batch.spi.spring.reader.BatchItemStreamReader#batchRead(org.springframework.batch.item.ExecutionContext)
 *//*  w w  w  .  jav  a 2  s .  co m*/
public UserInfo[] batchRead(ExecutionContext context)
        throws Exception, UnexpectedInputException, ParseException {
    if (!hasRun) {
        objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        for (int i = 0; i < PHONE_NUMBERS.length; i++) {
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet executionGet = new HttpGet(SERVICE_URL);
            URIBuilder uriBuilder = new URIBuilder(executionGet.getURI());
            uriBuilder.addParameter("primary_phone", PHONE_NUMBERS[i]);
            uriBuilder.addParameter("require", "{\"preferences\":true,\"addresses\":true}");
            ((HttpRequestBase) executionGet).setURI(uriBuilder.build());
            HttpResponse httpResponse = httpclient.execute(executionGet);
            String response = new String(EntityUtils.toByteArray(httpResponse.getEntity()));
            SearchResult searchResult = objectMapper.readValue(response, SearchResult.class);
            results[i] = searchResult.results[0]; // we take only the first result
        }
        hasRun = true;
    } else {
        if (modIndex < 0) {
            return null;
        }
        System.out.println("Modifiying response object at index : " + modIndex);
        results[modIndex].setFirst_name("Regu " + modIndex);
        results[modIndex].setLast_name("B " + modIndex);
        results[modIndex].setPrimary_email("regunathb@gmail.com" + modIndex);
        results[modIndex].setPrimary_phone("9886693892" + modIndex);
        if (results[modIndex].getPreferences() != null && results[modIndex].getPreferences().size() > 0) {
            Iterator<String> it = results[modIndex].getPreferences().keySet().iterator();
            while (it.hasNext()) {
                String key = it.next();
                UserPreferencesInfo upi = results[modIndex].getPreferences().get(key);
                Map<String, Object> values = new HashMap<String, Object>();
                values.put("communication", "email");
                values.put("address", "home");
                upi.setValue(values);
            }
        }
        modIndex -= 1;
    }
    return results;
}

From source file:com.thoughtworks.go.config.MingleConfig.java

public String urlFor(String path) throws URISyntaxException {
    URIBuilder baseUri = new URIBuilder(baseUrl);
    String originalPath = baseUri.getPath();
    if (originalPath == null) {
        originalPath = "";
    }/* w ww .j av a 2s. c o  m*/

    if (originalPath.endsWith(DELIMITER) && path.startsWith(DELIMITER)) {
        path = path.replaceFirst(DELIMITER, "");
    }

    return baseUri.setPath(originalPath + path).toString();
}