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: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);//from  w  w  w . ja va 2s  .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:com.geoxp.oss.client.OSSClient.java

public static boolean init(String ossURL, byte[] secret, String sshKeyFingerprint) throws OSSException {

    SSHAgentClient agent = null;/*from   w w w  .  jav  a 2s. co m*/

    HttpClient httpclient = newHttpClient();

    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 initialization token
            //
            // <TS> <SECRET> <SSH Signing Key Blob> <SSH Signature Blob>
            //

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

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

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

            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 + GuiceServletModule.SERVLET_PATH_INIT);

            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_ACCEPTED == response.getStatusLine().getStatusCode()) {
                return false;
            } else 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 initialize this Open Secret Server. Latest error message was: "
                            + response.getStatusLine().getReasonPhrase());
                } else {
                    continue;
                }
            }

            return true;
        }

    } 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 false;
}

From source file:windows.webservices.utilidades.EjecutorJson.java

private void prepararParam() {
    if (param != null) {
        URIBuilder builder = new URIBuilder(uri);

        for (Map.Entry entry : param.entrySet()) {
            builder.addParameter(entry.getKey().toString(), entry.getValue().toString());
        }//from w w w  .ja  va 2s .  c om

        try {
            this.uri = builder.build();
        } catch (URISyntaxException ex) {
            Logger.getLogger(EjecutorJson.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:com.mollie.api.resource.BaseResource.java

/**
 * Creates a valid query string from the supplied options that can be used
 * as url parameters. The method returns null if there was an error building
 * the query string./*from  ww w . j a va 2 s  .  c o m*/
 * 
 * @param options options to build a query string from
 * @return a valid query string or null.
 */
private String buildQueryFromMap(Map<String, String> options) {
    URIBuilder ub = null;
    String queryString = null;

    try {
        ub = new URIBuilder();

        for (Map.Entry<String, String> entry : options.entrySet()) {
            ub.addParameter(entry.getKey(), entry.getValue());
        }

        queryString = ub.build().getQuery();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }

    return queryString;
}

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

public static void putSecret(String ossURL, String secretname, byte[] secret, String sshKeyFingerprint)
        throws OSSException {

    SSHAgentClient agent = null;/* w w  w.j a  va2s .c o m*/

    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> <<WRAPPED_SECRET><ENCRYPTED_WRAPPING_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(secret));

            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 + GuiceServletModule.SERVLET_PATH_PUT_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));

            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 store the 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.msopentech.odatajclient.engine.communication.request.invoke.ODataInvokeRequest.java

/**
 * {@inheritDoc }/*  w  w w .  j av  a 2  s .  c om*/
 */
@Override
public ODataInvokeResponse<T> execute() {
    final InputStream input = getPayload();

    if (!this.parameters.isEmpty()) {
        if (this.method == HttpMethod.GET) {
            final URIBuilder uriBuilder = new URIBuilder(this.uri);
            for (Map.Entry<String, ODataValue> param : parameters.entrySet()) {
                if (!param.getValue().isPrimitive()) {
                    throw new IllegalArgumentException("Only primitive values can be passed via GET");
                }

                uriBuilder.addParameter(param.getKey(), param.getValue().toString());
            }
            try {
                ((HttpRequestBase) this.request).setURI(uriBuilder.build());
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("While adding GET parameters", e);
            }
        } else if (this.method == HttpMethod.POST) {
            ((HttpPost) request).setEntity(URIUtils.buildInputStreamEntity(odataClient, input));

            setContentType(ODataPubFormat.JSON.toString());
        }
    }

    try {
        return new ODataInvokeResponseImpl(httpClient, doExecute());
    } finally {
        IOUtils.closeQuietly(input);
    }
}

From source file:org.apache.olingo.client.core.communication.request.invoke.ODataInvokeRequestImpl.java

/**
 * {@inheritDoc }//  w  ww.java  2s  .  c  o  m
 */
@Override
public ODataInvokeResponse<T> execute() {
    final InputStream input = getPayload();

    if (!this.parameters.isEmpty()) {
        if (this.method == HttpMethod.GET) {
            final URIBuilder uriBuilder = new URIBuilder(this.uri);
            for (Map.Entry<String, ODataValue> param : parameters.entrySet()) {
                if (!param.getValue().isPrimitive()) {
                    throw new IllegalArgumentException("Only primitive values can be passed via GET");
                }

                uriBuilder.addParameter(param.getKey(), param.getValue().toString());
            }
            try {
                ((HttpRequestBase) this.request).setURI(uriBuilder.build());
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("While adding GET parameters", e);
            }
        } else if (this.method == HttpMethod.POST) {
            ((HttpPost) request).setEntity(URIUtils.buildInputStreamEntity(odataClient, input));

            setContentType(ODataPubFormat.JSON.toString(odataClient.getServiceVersion()));
        }
    }

    try {
        return new ODataInvokeResponseImpl(httpClient, doExecute());
    } finally {
        IOUtils.closeQuietly(input);
    }
}

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//from  w  w w .  j av a2 s  . co m
 * @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: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;/*from  w  ww  .j  a v a  2  s  . co m*/
    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);
}