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:net.rcarz.jiraclient.RestClient.java

/**
 * Build a URI from a path and query parmeters.
 *
 * @param path Path to append to the base URI
 * @param params Map of key value pairs/*ww w  . ja  va 2s . c om*/
 *
 * @return the full URI
 *
 * @throws URISyntaxException when the path is invalid
 */
public URI buildURI(String path, Map<String, String> params) throws URISyntaxException {
    URIBuilder ub = new URIBuilder(uri);
    ub.setPath(ub.getPath() + path);

    if (params != null) {
        for (Map.Entry<String, String> ent : params.entrySet())
            ub.addParameter(ent.getKey(), ent.getValue());
    }

    return ub.build();
}

From source file:org.dspace.submit.lookup.CrossRefService.java

public List<Record> search(Context context, String title, String authors, int year, int count, String apiKey)
        throws IOException, HttpException {
    HttpGet method = null;/* w w  w  .j  a  va 2 s  .c  om*/
    try {
        HttpClient client = new DefaultHttpClient();
        client.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);

        URIBuilder uriBuilder = new URIBuilder("http://search.labs.crossref.org/dois");

        StringBuilder sb = new StringBuilder();
        if (StringUtils.isNotBlank(title)) {
            sb.append(title);
        }
        sb.append(" ");
        if (StringUtils.isNotBlank(authors)) {
            sb.append(authors);
        }
        String q = sb.toString().trim();
        uriBuilder.addParameter("q", q);

        uriBuilder.addParameter("year", year != -1 ? String.valueOf(year) : "");
        uriBuilder.addParameter("rows", count != -1 ? String.valueOf(count) : "");
        method = new HttpGet(uriBuilder.build());

        // Execute the method.
        HttpResponse response = client.execute(method);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();

        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("Http call failed:: " + statusLine);
        }

        Gson gson = new Gson();
        Type listType = new TypeToken<ArrayList<Map>>() {
        }.getType();
        List<Map> json = gson.fromJson(
                IOUtils.toString(response.getEntity().getContent(), StandardCharsets.UTF_8), listType);
        Set<String> dois = new HashSet<String>();
        for (Map r : json) {
            dois.add(SubmissionLookupUtils.normalizeDOI((String) r.get("doi")));
        }
        method.releaseConnection();

        return search(context, dois, apiKey);
    } catch (Exception e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

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

public static byte[] getSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException {

    HttpClient httpclient = null;/*from www.ja va 2 s  . c om*/

    SSHAgentClient agent = 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.");
            }

            //
            // Generate temporary RSA key pair
            //

            RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator();
            RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"),
                    CryptoHelper.getSecureRandom(), OSS.DEFAULT_RSA_STRENGTH, 64);
            rsagen.init(params);
            final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair();

            RSAPrivateKey rsapriv = new RSAPrivateKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPrivateExponent() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getExponent();
                }
            };

            RSAPublicKey rsapub = new RSAPublicKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPublic()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPublicExponent() {
                    return ((RSAKeyParameters) keypair.getPublic()).getExponent();
                }
            };

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

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

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

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8")));
            subtoken.write(CryptoHelper.encodeNetworkString(CryptoHelper.sshKeyBlobFromPublicKey(rsapub)));

            token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray()));

            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_GET_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);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");
            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 retrieve secret. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            //
            // Extract encrypted secret and sealed key
            //

            byte[] secretandsealedkey = Base64.decode(content);

            byte[] encryptedsecret = CryptoHelper.decodeNetworkString(secretandsealedkey, 0);
            byte[] sealedkey = CryptoHelper.decodeNetworkString(secretandsealedkey, 4 + encryptedsecret.length);

            //
            // Unseal key
            //

            byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey);

            //
            // Unwrap secret
            //

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

    return null;
}

From source file:org.apache.james.jmap.methods.integration.cucumber.DownloadStepdefs.java

private Request authenticatedDownloadRequest(URIBuilder uriBuilder, String blobId, String username)
        throws URISyntaxException {
    AccessToken accessToken = userStepdefs.tokenByUser.get(username);
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    if (attachmentAccessTokens.containsKey(key)) {
        uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    }/*from w  w  w  .  ja  v  a  2s  . c  om*/
    Request request = Request.Get(uriBuilder.build());
    if (accessToken != null) {
        request.addHeader("Authorization", accessToken.serialize());
    }
    return request;
}

From source file:org.openhim.mediator.engine.connectors.HTTPConnector.java

private URI buildURI(MediatorHTTPRequest req) throws URISyntaxException {
    URIBuilder builder = new URIBuilder().setScheme(req.getScheme()).setHost(req.getHost())
            .setPort(req.getPort()).setPath(req.getPath());
    if (req.getParams() != null) {
        Iterator<String> iter = req.getParams().keySet().iterator();
        while (iter.hasNext()) {
            String param = iter.next();
            builder.addParameter(param, req.getParams().get(param));
        }/*from  w w w.  j a  v  a 2s .  com*/
    }
    return builder.build();
}

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

public static List<String> getACL(String ossURL, String sshKeyFingerprint, String secretName)
        throws OSSException {

    SSHAgentClient agent = null;//from  ww  w.  ja  v  a  2 s . 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.");
            }

            //
            // Generate temporary RSA key pair
            //

            RSAKeyPairGenerator rsagen = new RSAKeyPairGenerator();
            RSAKeyGenerationParameters params = new RSAKeyGenerationParameters(new BigInteger("65537"),
                    CryptoHelper.getSecureRandom(), OSS.DEFAULT_RSA_STRENGTH, 64);
            rsagen.init(params);
            final AsymmetricCipherKeyPair keypair = rsagen.generateKeyPair();

            RSAPrivateKey rsapriv = new RSAPrivateKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPrivateExponent() {
                    return ((RSAKeyParameters) keypair.getPrivate()).getExponent();
                }
            };

            RSAPublicKey rsapub = new RSAPublicKey() {
                public BigInteger getModulus() {
                    return ((RSAKeyParameters) keypair.getPublic()).getModulus();
                }

                public String getFormat() {
                    return "PKCS#8";
                }

                public byte[] getEncoded() {
                    return null;
                }

                public String getAlgorithm() {
                    return "RSA";
                }

                public BigInteger getPublicExponent() {
                    return ((RSAKeyParameters) keypair.getPublic()).getExponent();
                }
            };

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

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

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

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8")));
            subtoken.write(CryptoHelper.encodeNetworkString(CryptoHelper.sshKeyBlobFromPublicKey(rsapub)));

            token.write(CryptoHelper.encodeNetworkString(subtoken.toByteArray()));

            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_GET_ACL);

            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);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");
            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 retrieve ACLs. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            //
            // Extract encrypted list of fingerprints and sealed key
            //

            byte[] fprandsealedkey = Base64.decode(content);

            byte[] encryptedfpr = CryptoHelper.decodeNetworkString(fprandsealedkey, 0);
            byte[] sealedkey = CryptoHelper.decodeNetworkString(fprandsealedkey, 4 + encryptedfpr.length);

            //
            // Unseal key
            //

            byte[] wrappingkey = CryptoHelper.decryptRSA(rsapriv, sealedkey);

            //
            // Unwrap fingerprints
            //

            byte[] fpr = CryptoHelper.unwrapAES(wrappingkey, encryptedfpr);

            int offset = 0;

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

            while (offset < fpr.length) {
                byte[] f = CryptoHelper.decodeNetworkString(fpr, offset);

                if (null == f) {
                    break;
                }

                offset += 4 + f.length;

                if (0 < f.length) {
                    res.add(new String(Hex.encode(f), "UTF-8").replaceAll("([0-9a-f]{2})", "$1:"));
                }
            }

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

    return null;
}

From source file:com.simple.toadiot.rtinfosdk.http.DefaultRequestHandler.java

private URIBuilder buildUri(HttpMethod method, String path, Map<String, Object> params,
        AcceptedMediaType mediaType) {//from   w ww.j a v  a2s . c  om
    URIBuilder uriBuilder = new URIBuilder();
    //      if (HttpMethod.GET == method) {
    //         path = path.concat(".").concat(mediaType.name());
    //      }
    uriBuilder.setScheme("http").setHost(AppConfig.getBaseURI()).setPath("/" + AppConfig.getVersion() + 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.geoxp.oss.client.OSSClient.java

private static void changeACL(boolean remove, String ossURL, String sshKeyFingerprint, String secretname,
        List<String> keyfpr) throws OSSException {

    SSHAgentClient agent = null;/*from ww w  .  ja va2s.  c om*/

    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++;

            //
            // Ask the SSH agent for the SSH key blob
            //

            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.");
            }

            //
            // Retrieve OSS RSA key
            //

            RSAPublicKey pubkey = getOSSRSA(ossURL);

            //
            // Build the token
            //
            // <TS> <<SECRET_NAME><FINGERPRINT1>....<FINGERPRINTN>> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

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

            ByteArrayOutputStream subtoken = new ByteArrayOutputStream();

            subtoken.write(CryptoHelper.encodeNetworkString(secretname.getBytes("UTF-8")));

            for (String fpr : keyfpr) {
                subtoken.write(CryptoHelper
                        .encodeNetworkString(fpr.toLowerCase().replaceAll("[^a-f0-9]", "").getBytes("UTF-8")));
            }

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

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

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

            //
            // Encrypt the token with a random AES256 key
            //

            byte[] aeskey = new byte[32];
            CryptoHelper.getSecureRandom().nextBytes(aeskey);

            byte[] wrappedtoken = CryptoHelper.wrapAES(aeskey, token.toByteArray());

            //
            // Encrypt the random key with OSS' RSA key
            //

            byte[] sealedaeskey = CryptoHelper.encryptRSA(pubkey, aeskey);

            //
            // Create the token
            //

            token.reset();

            token.write(CryptoHelper.encodeNetworkString(wrappedtoken));
            token.write(CryptoHelper.encodeNetworkString(sealedaeskey));

            //
            // Base64 encode the encryptedtoken
            //

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

            //
            // Send request to OSS
            //

            URIBuilder builder = new URIBuilder(ossURL + (remove ? GuiceServletModule.SERVLET_PATH_REMOVE_ACL
                    : GuiceServletModule.SERVLET_PATH_ADD_ACL));

            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));

            httpclient = newHttpClient();

            HttpResponse response = httpclient.execute(post);
            HttpEntity resEntity = response.getEntity();
            String content = EntityUtils.toString(resEntity, "UTF-8");

            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 modify ACL. 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:org.mobicents.servlet.restcomm.provisioning.number.bandwidth.BandwidthNumberProvisioningManager.java

private String buildSearchUri(PhoneNumberSearchFilters filters) throws URISyntaxException {
    Pattern filterPattern = filters.getFilterPattern();

    URIBuilder builder = new URIBuilder(this.uri);
    builder.setPath("/v1.0/accounts/" + this.accountId + "/availableNumbers");

    //Local number type search
    if (filters.getPhoneNumberTypeSearch().equals(PhoneNumberType.Local)) {
        if (!StringUtils.isEmpty(filters.getAreaCode())) {
            builder.addParameter("areaCode", filters.getAreaCode());
        }/*  w  w w.j av  a2s.com*/
        if (!StringUtils.isEmpty(filters.getInLata())) {
            builder.addParameter("lata", filters.getInLata());
        }
        if (!StringUtils.isEmpty(filters.getInPostalCode())) {
            builder.addParameter("zip", filters.getInPostalCode());
        }
        if (!StringUtils.isEmpty(filters.getInRateCenter())) {
            builder.addParameter("rateCenter", filters.getInRateCenter());
            builder.addParameter("state", filters.getInRegion());
        }
        builder.addParameter("enableTNDetail", String.valueOf(true));

    } else if (filters.getPhoneNumberTypeSearch().equals(PhoneNumberType.TollFree)) {
        //Make some assumptions for the user
        if (filterPattern == null || StringUtils.isEmpty(filterPattern.toString())) {
            builder.addParameter("tollFreeWildCardPattern", "8**");
        } else {
            if (filterPattern.toString().contains("*")) {
                builder.addParameter("tollFreeWildCardPattern", filterPattern.toString());
            } else {
                builder.addParameter("tollFreeVanity", filterPattern.toString());
            }
        }

    } else {
        logger.error("Phone Number Type: " + filters.getPhoneNumberTypeSearch().name() + " is not supported");
    }
    builder.addParameter("quantity", String.valueOf(filters.getRangeSize() == -1 ? 5 : filters.getRangeSize()));
    if (logger.isDebugEnabled()) {
        logger.debug("building uri: " + builder.build().toString());
    }
    return builder.build().toString();
}