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:net.packet.Request.java

/**
 * Returns the composed endpoint URI./*from   w  w  w  .ja  va  2 s  .co  m*/
 * 
 * @return {@link URI}
 * @throws URISyntaxException when URI is incorrect
 */
public URI buildUri() throws URISyntaxException {
    URIBuilder ub = new URIBuilder();
    ub.setScheme(Constants.URI_SCHEME);
    ub.setHost(Constants.HOSTNAME);

    String path = (null == pathParams) ? endpoint.getPath() : String.format(endpoint.getPath(), pathParams);
    ub.setPath(path);

    if (null != queryParams) {
        for (Map.Entry<String, String> entry : queryParams.entrySet()) {
            ub.setParameter(entry.getKey(), entry.getValue());
        }
    }

    return ub.build();
}

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

@When("^\"([^\"]*)\" downloads \"([^\"]*)\" with wrong blobId$")
public void getDownloadWithWrongBlobId(String username, String attachmentId) throws Throwable {
    String blobId = blobIdByAttachmentId.get(attachmentId);

    URIBuilder uriBuilder = mainStepdefs.baseUri()
            .setPath("/download/badbadbadbadbadbadbadbadbadbadbadbadbadb");
    trustForBlobId(blobId, username);//w  w w. j  a  v a2 s.  c  om
    AttachmentAccessTokenKey key = new AttachmentAccessTokenKey(username, blobId);
    uriBuilder.addParameter("access_token", attachmentAccessTokens.get(key).serialize());
    response = Request.Get(uriBuilder.build()).execute().returnResponse();
}

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

public String getRequestUrl(CSWOperation operation) {
    try {//from w w  w  . j  a va  2 s.c o m
        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:eu.esdihumboldt.hale.io.gml.reader.internal.wfs.WfsBackedGmlInstanceCollection.java

private int requestHits(URI requestUri) throws WFSException {
    URIBuilder builder = new URIBuilder(requestUri);
    builder.addParameter("RESULTTYPE", "hits");

    InputStream in;//  w w w. j a v a  2 s.c om
    try {
        in = builder.build().toURL().openStream();
    } catch (IOException | URISyntaxException e) {
        throw new WFSException(MessageFormat.format("Unable to execute WFS request: {0}", e.getMessage()), e);
    }

    return FeatureCollectionHelper.getNumberOfFeatures(in);
}

From source file:org.gbif.registry.metasync.protocols.tapir.TapirMetadataSynchroniser.java

/**
 * Build the TAPIR search request URL that will return the number of records count. It has scientific name range
 * AAA-zzz, offset 0, limit 1, and count equal to true.
 *
 * @param endpoint            Endpoint/*  w ww. j  a v a2  s  .  c  om*/
 * @param outputModelTemplate output model template to use in request
 *
 * @return TAPIR search request URL
 */
public URI buildSearchRequestUrl(Endpoint endpoint, String outputModelTemplate) {
    try {
        URIBuilder uriBuilder = new URIBuilder(endpoint.getUrl());
        for (Map.Entry<String, String> paramEntry : buildTapirSearchRequestParameters(outputModelTemplate)
                .entrySet()) {
            uriBuilder.addParameter(paramEntry.getKey(), paramEntry.getValue());
        }
        return uriBuilder.build();
    } catch (URISyntaxException e) {
        // It's coming from a valid URL so it shouldn't ever throw this, so we swallow this
        return null;
    }
}

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 ww  w.  ja  v a 2s.com

    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: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// w  w w .  ja  v a  2  s .  c o  m
 *
 * @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:com.esri.geoevent.transport.websocket.WebsocketInboundTransport.java

private URI getURI(String uriString) throws URISyntaxException {
    // check the port - default to 80 for unsecure and 443 for secure connections
    URIBuilder uriBuilder = new URIBuilder(uriString);
    if (uriBuilder.getPort() == -1 || uriBuilder.getPort() == 0) {
        if (StringUtils.isNotEmpty(uriBuilder.getScheme())) {
            if (uriBuilder.getScheme().equalsIgnoreCase("wss")) {
                uriBuilder.setPort(DEFAULT_SECURE_PORT);
            } else if (uriBuilder.getScheme().equalsIgnoreCase("ws")) {
                uriBuilder.setPort(DEFAULT_UNSECURE_PORT);
            }/*from   ww w.ja  va  2s  . c o m*/
        }
    }
    return uriBuilder.build();
}

From source file:com.esri.geoportal.commons.agp.client.AgpClient.java

/**
 * Deletes item.//w w  w.  j  ava 2  s .  co m
 * @param owner owner
 * @param folderId folder id
 * @param itemId item id
 * @param token token
 * @return delete response
 * @throws URISyntaxException if invalid URL
 * @throws IOException if operation fails
 */
public DeleteResponse delete(String owner, String folderId, String itemId, String token)
        throws URISyntaxException, IOException {
    URIBuilder builder = new URIBuilder(deleteUri(owner, folderId, itemId));

    builder.setParameter("f", "json");
    builder.setParameter("token", token);

    HttpPost req = new HttpPost(builder.build());

    return execute(req, DeleteResponse.class);
}

From source file:com.revo.deployr.client.core.impl.RClientImpl.java

public InputStream download(URIBuilder builder) throws RClientException {

    try {/*from  w w w.j av  a  2s.  c o  m*/
        log.debug("download: uri builder=" + builder);
        String uriPath = builder.build().toString();
        HttpGet request = new HttpGet(uriPath);
        HttpResponse response = httpClient.execute(request);
        return response.getEntity().getContent();

    } catch (Exception ex) {
        String exMsg = builder + " download failed, " + ex.getMessage();
        throw new RClientException(exMsg, ex);
    }

}