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:eu.eubrazilcc.lvl.storage.gravatar.Gravatar.java

public URL jsonProfileUrl() {
    try {//from w ww. j  a va  2 s .co m
        final URIBuilder uriBuilder = new URIBuilder(
                (secure ? SECURE_URL_BASE : DEFAULT_URL_BASE) + emailHash(email) + ".json").addParameter("d",
                        "404");
        if (isNotBlank(profileCallback)) {
            uriBuilder.addParameter("callback", profileCallback);
        }
        return uriBuilder.build().toURL();
    } catch (Exception e) {
        throw new IllegalStateException("Failed to get Gravatar JSON profile URL", e);
    }
}

From source file:org.geosdi.geoplatform.experimental.openam.support.config.connector.OpenAMConnector.java

/**
 * @param token//from  ww  w .ja v a2s.  co  m
 * @return {@link Boolean}
 * @throws Exception
 */
@Override
public IOpenAMValidateToken validateToken(String token) throws Exception {
    Preconditions.checkArgument((token != null) && !(token.isEmpty()),
            "The Token to validate " + "must not be null or an Empty String.");
    logger.debug(
            "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@TRYING TO VALIDATE_TOKEN WITH " + "OPENAM_CONNECTOR_SETTINGS : {}\n",
            this.openAMConnectorSettings);
    ValidateTokenRequest validateTokenRequest = this.openAMRequestMediator.getRequest(VALIDATE_TOKEN);
    URIBuilder uriBuilder = this.buildURI(this.openAMConnectorSettings,
            validateTokenRequest.setExtraPathParam(token));
    validateTokenRequest.addRequestParameter(uriBuilder,
            this.requestParameterMediator.getRequest(ACTION_VALIDATE));

    logger.debug("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@OPENAM_VALIDATE_TOKEN_CONNECTOR_URI : {}\n",
            URLDecoder.decode(uriBuilder.toString(), "UTF-8"));

    HttpPost httpPost = new HttpPost(uriBuilder.build());
    httpPost.addHeader("Content-Type", "application/json");
    CloseableHttpResponse response = this.httpClient.execute(httpPost);

    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IllegalStateException(
                "OpenAMValidateToken Error Code : " + response.getStatusLine().getStatusCode());
    }

    return this.openAMReader.readValue(response.getEntity().getContent(), OpenAMValidateToken.class);
}

From source file:hudson.plugins.jira.JiraRestService.java

public List<Version> getVersions(String projectKey) {
    final URIBuilder builder = new URIBuilder(uri)
            .setPath(String.format("%s/project/%s/versions", baseApiPath, projectKey));

    List<Map<String, Object>> decoded = Collections.emptyList();
    try {//w ww . j a  v  a 2 s .c o  m
        URI uri = builder.build();
        final Content content = buildGetRequest(uri).execute().returnContent();

        decoded = objectMapper.readValue(content.asString(), new TypeReference<List<Map<String, Object>>>() {
        });
    } catch (Exception e) {
        LOGGER.log(WARNING, "jira rest client get versions error. cause: " + e.getMessage(), e);
    }

    final List<Version> versions = new ArrayList<Version>();
    for (Map<String, Object> decodedVersion : decoded) {
        final DateTime releaseDate = decodedVersion.containsKey("releaseDate")
                ? DATE_TIME_FORMATTER.parseDateTime((String) decodedVersion.get("releaseDate"))
                : null;
        final Version version = new Version(URI.create((String) decodedVersion.get("self")),
                Long.parseLong((String) decodedVersion.get("id")), (String) decodedVersion.get("name"),
                (String) decodedVersion.get("description"), (Boolean) decodedVersion.get("archived"),
                (Boolean) decodedVersion.get("released"), releaseDate);
        versions.add(version);
    }
    return versions;
}

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 {/* w w w .  j ava2s.c o m*/

        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.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Sharing item.//from  w ww .j ava 2 s .c om
 * @param owner user name
 * @param folderId folder id (optional)
 * @param itemId item id
 * @param everyone <code>true</code> to share with everyone
 * @param org <code>true</code> to share with group
 * @param groups list of groups to share with
 * @param token token
 * @return share response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public ShareResponse share(String owner, String folderId, String itemId, boolean everyone, boolean org,
        String[] groups, String token) throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(shareUri(owner, folderId, itemId));

    HttpPost req = new HttpPost(builder.build());
    HashMap<String, String> params = new HashMap<>();
    params.put("f", "json");
    params.put("everyone", Boolean.toString(everyone));
    params.put("org", Boolean.toString(org));
    params.put("groups", groups != null ? Arrays.asList(groups).stream().collect(Collectors.joining(",")) : "");
    params.put("token", token);

    req.setEntity(createEntity(params));

    return execute(req, ShareResponse.class);
}

From source file:com.rackspacecloud.blueflood.outputs.handlers.HttpRollupHandlerIntegrationTest.java

private URI getHistQueryURI() throws URISyntaxException {
    URIBuilder builder = new URIBuilder().setScheme("http").setHost("127.0.0.1").setPort(queryPort)
            .setPath("/v2.0/" + tenantId + "/views/histograms/" + metricName)
            .setParameter("from", String.valueOf(baseMillis))
            .setParameter("to", String.valueOf(baseMillis + 86400000)).setParameter("resolution", "full");
    return builder.build();
}

From source file:io.fabric8.etcd.impl.dsl.DeleteDataImpl.java

@Override
public HttpUriRequest createRequest(OperationContext context) {
    try {//from  ww w . j  a va  2 s  .com
        URIBuilder builder = new URIBuilder(context.getBaseUri()).setPath(Keys.makeKey(key))
                .addParameter("dir", String.valueOf(dir)).addParameter("recursive", String.valueOf(recursive))
                .addParameter("prevExists", String.valueOf(prevExists));

        if (prevValue != null) {
            builder = builder.addParameter("prevValue", prevValue).addParameter("prevIndex",
                    String.valueOf(prevIndex));
        }

        return new HttpDelete(builder.build());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.geoxp.oss.client.OSSClient.java

public static void genSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException {

    SSHAgentClient agent = null;//from   w  ww . jav a2s .com

    HttpClient httpclient = null;

    try {

        agent = new SSHAgentClient();

        List<SSHKey> sshkeys = agent.requestIdentities();

        //
        // If no SSH Key fingerprint was provided, try all SSH keys available in the agent
        //

        List<String> fingerprints = new ArrayList<String>();

        if (null == sshKeyFingerprint) {
            for (SSHKey key : sshkeys) {
                fingerprints.add(key.fingerprint);
            }
        } else {
            fingerprints.add(sshKeyFingerprint.toLowerCase().replaceAll("[^0-9a-f]", ""));
        }

        int idx = 0;

        for (String fingerprint : fingerprints) {
            idx++;

            //
            // Check if the signing key is available in the agent
            //

            byte[] keyblob = null;

            for (SSHKey key : sshkeys) {
                if (key.fingerprint.equals(fingerprint)) {
                    keyblob = key.blob;
                    break;
                }
            }

            //
            // Throw an exception if this condition is encountered as it can only happen if
            // there was a provided fingerprint which is not in the agent.
            //

            if (null == keyblob) {
                throw new OSSException("SSH Key " + sshKeyFingerprint + " was not found by your SSH agent.");
            }

            //
            // Build OSS Token
            //
            // <TS> <SECRET_NAME> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

            token.write(CryptoHelper.encodeNetworkString(tsdata));

            token.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8")));

            token.write(CryptoHelper.encodeNetworkString(keyblob));

            //
            // Generate signature
            //

            byte[] sigblob = agent.sign(keyblob, token.toByteArray());

            token.write(CryptoHelper.encodeNetworkString(sigblob));

            String b64token = new String(Base64.encode(token.toByteArray()), "UTF-8");

            //
            // Send request
            //

            httpclient = newHttpClient();

            URIBuilder builder = new URIBuilder(ossURL + GuiceServletModule.SERVLET_PATH_GEN_SECRET);

            builder.addParameter("token", b64token);

            URI uri = builder.build();

            String qs = uri.getRawQuery();

            HttpPost post = new HttpPost(
                    uri.getScheme() + "://" + uri.getHost() + ":" + uri.getPort() + uri.getPath());

            post.setHeader("Content-Type", "application/x-www-form-urlencoded");

            post.setEntity(new StringEntity(qs));

            HttpResponse response = httpclient.execute(post);
            post.reset();

            if (HttpServletResponse.SC_OK != response.getStatusLine().getStatusCode()) {
                // Only throw an exception if this is the last SSH key we could try
                if (idx == fingerprints.size()) {
                    throw new OSSException("None of the provided keys (" + idx
                            + ") could be used to generate secret. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            return;
        }
    } catch (OSSException osse) {
        throw osse;
    } catch (Exception e) {
        throw new OSSException(e);
    } finally {
        if (null != httpclient) {
            httpclient.getConnectionManager().shutdown();
        }
        if (null != agent) {
            agent.close();
        }
    }
}

From source file:com.seleniumtests.connectors.selenium.SeleniumRobotGridConnector.java

/**
 * Upload a file given file path/*w  w w. j  a  va  2  s. c  o m*/
 * @param filePath
 */
@Override
public void uploadFile(String filePath) {
    try (CloseableHttpClient client = HttpClients.createDefault();) {
        // zip file
        List<File> appFiles = new ArrayList<>();
        appFiles.add(new File(filePath));
        File zipFile = FileUtility.createZipArchiveFromFiles(appFiles);

        HttpHost serverHost = new HttpHost(hubUrl.getHost(), hubUrl.getPort());
        URIBuilder builder = new URIBuilder();
        builder.setPath("/grid/admin/FileServlet/");
        builder.addParameter("output", "app");
        HttpPost httpPost = new HttpPost(builder.build());
        httpPost.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.OCTET_STREAM.toString());
        FileInputStream fileInputStream = new FileInputStream(zipFile);
        InputStreamEntity entity = new InputStreamEntity(fileInputStream);
        httpPost.setEntity(entity);

        CloseableHttpResponse response = client.execute(serverHost, httpPost);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new SeleniumGridException(
                    "could not upload file: " + response.getStatusLine().getReasonPhrase());
        } else {
            // TODO call remote API
            throw new NotImplementedException("call remote Robot to really upload file");
        }

    } catch (IOException | URISyntaxException e) {
        throw new SeleniumGridException("could not upload file", e);
    }
}

From source file:ph.com.globe.connect.Location.java

/**
 * Get location request.//  w ww .  j ava 2 s  .  c  o m
 * 
 * @param  address subscriber address
 * @param  requestedAccuracy request accuracy
 * @return HttpResponse
 * @throws ApiException api exception
 * @throws HttpRequestException http request exception
 * @throws HttpResponseException http response exception
 */
public HttpResponse getLocation(String address, int requestedAccuracy)
        throws ApiException, HttpRequestException, HttpResponseException {

    // try parsing url
    try {
        // initialize url builder
        URIBuilder builder = new URIBuilder(this.LOCATION_URL);

        // set access token parameter
        builder.setParameter("access_token", this.accessToken);
        // set address parameter
        builder.setParameter("address", address);
        // set requested accuracy parameter
        builder.setParameter("requestedAccuracy", Integer.toString(requestedAccuracy));

        // build the url
        String url = builder.build().toString();

        // send request
        CloseableHttpResponse results = this.request
                // set url
                .setUrl(url)
                // send get request
                .sendGet();

        return new HttpResponse(results);
    } catch (URISyntaxException e) {
        // throw exception
        throw new ApiException(e.getMessage());
    }
}