Example usage for java.net URI getRawQuery

List of usage examples for java.net URI getRawQuery

Introduction

In this page you can find the example usage for java.net URI getRawQuery.

Prototype

public String getRawQuery() 

Source Link

Document

Returns the raw query component of this URI.

Usage

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;//from   w w  w. ja  va  2s  .co 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.subgraph.vega.internal.http.requests.HttpRequestBuilder.java

private void setPathFromUri(URI uri) {
    path = uri.getRawPath();/*  w ww  . jav a  2 s .  co m*/
    if (path != null) {
        if (path.length() == 0 || path.charAt(0) != '/') {
            path = '/' + path;
        }
    } else {
        path = "";
    }
    if (uri.getRawQuery() != null) {
        path += '?' + uri.getRawQuery();
    }
    if (uri.getRawFragment() != null) {
        path += '#' + uri.getRawFragment();
    }
}

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  w  ww  . ja  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> <<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:com.subgraph.vega.ui.http.requestviewer.HttpViewLabelProvider.java

@Override
public String getColumnText(Object element, int columnIndex) {
    if (!(element instanceof IRequestLogRecord))
        return null;
    final IRequestLogRecord record = (IRequestLogRecord) element;
    URI uri;
    try {//  w w w.ja v a2  s .  c  o m
        uri = new URI(record.getRequest().getRequestLine().getUri());

    } catch (URISyntaxException e) {
        return null;
    }
    switch (columnIndex) {
    case 0:
        return Long.toString(record.getRequestId());
    case 1:
        return record.getHttpHost().toURI();
    case 2:
        return record.getRequest().getRequestLine().getMethod();
    case 3:
        if (uri.getRawQuery() != null)
            return uri.getRawPath() + "?" + uri.getRawQuery();
        else
            return uri.getRawPath();
    case 4:
        return Integer.valueOf(record.getResponse().getStatusLine().getStatusCode()).toString();
    case 5:
        return getResponseLength(record.getResponse());
    case 6:
        return Long.toString(record.getRequestMilliseconds());
    }
    return null;
}

From source file:org.orbeon.oxf.xforms.XFormsUtils.java

private static String uriToStringNoFragment(XFormsContainingDocument containingDocument, URI resolvedURI) {
    if (containingDocument.isPortletContainer() && resolvedURI.getFragment() != null) {
        // XForms page was loaded from a portlet and there is a fragment, remove it
        try {/*from   w  w  w. jav a 2 s .  c o m*/
            return new URI(resolvedURI.getScheme(), resolvedURI.getRawAuthority(), resolvedURI.getRawPath(),
                    resolvedURI.getRawQuery(), null).toString();
        } catch (URISyntaxException e) {
            throw new OXFException(e);
        }
    } else {
        return resolvedURI.toString();
    }
}

From source file:com.discovery.darchrow.net.ParamUtil.java

/**
 * url?? ?.//  ww w.  ja v a2 s.c  o  m
 * 
 * @param uri
 *            the uri
 * @param paramNameList
 *            the param name list
 * @param charsetType
 *            ?
 * @return the string
 */
public static String retentionParamList(URI uri, List<String> paramNameList, String charsetType) {
    if (null == uri) {
        return "";
    } else {
        String url = uri.toString();
        //  paramNameList null 
        if (Validator.isNullOrEmpty(paramNameList)) {
            return url;
        }
        String before = URIUtil.getBeforePath(url);
        // ***********************************************************************
        //  URI ? URI ???? URI 
        String query = uri.getRawQuery();
        // ***********************************************************************
        // url??
        if (Validator.isNullOrEmpty(query)) {
            // ??
            return url;
        } else {
            Map<String, String[]> map = new LinkedHashMap<String, String[]>();

            Map<String, String[]> originalMap = URIUtil.parseQueryToArrayMap(query, null);

            for (String paramName : paramNameList) {
                map.put(paramName, originalMap.get(paramName));
            }
            return URIUtil.getEncodedUrlByArrayMap(before, map, charsetType);
        }
    }
}

From source file:com.sina.cloudstorage.util.URIBuilder.java

private void digestURI(final URI uri) {
    this.scheme = uri.getScheme();
    this.schemeSpecificPart = uri.getSchemeSpecificPart();
    this.authority = uri.getAuthority();
    this.host = uri.getHost();
    this.port = uri.getPort();
    this.userInfo = uri.getUserInfo();
    this.path = uri.getPath();
    this.queryParams = parseQuery(uri.getRawQuery(), Consts.UTF_8);
    this.fragment = uri.getFragment();
}

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

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

    HttpClient httpclient = null;/*w  w  w .  j a  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:com.epl.ticketws.services.QueryService.java

/**
 * This method generates the string to be signed based on the following rules:
 *
 *  - Add the request method + \n/*from w ww .  java 2s .c  om*/
 *  - Add the timestamp + \n
 *  - Add the request URI
 *  - For each request parameter ordered alphabetically:
 *    - First parameter delimiter ?
 *    - Other parameters separated by &
 *    - Name of the parameter
 *    - Add = sign
 *    - value of the parameter
 *
 * For example:
 *
 *   Given a GET request with timestamp = 1316430943576 and uri = /uri_path/ejemplo with parameters,
 *     Bc = 'Prueba1'
 *     Aa = 'Prueba2'
 *     bc = 'aPrueba3'
 *     z1 = 'prueba4'
 *
 *   The String to sign is:
 *
 *     GET\n1316430943576\n/uri_path/ejemplo?amp;Aa=Prueba2&bc=aPrueba3&Bc=Prueba1&z1=prueba4
 *
 * @param uri
 * @param method
 * @param timestamp
 * @return
 * @throws SignatureException
 */
private String getStringToSign(URI uri, String method, long timestamp, Map<String, String> params)
        throws SignatureException {

    SortedMap<String, String> sortedMap = new TreeMap<String, String>();

    // Assuming GET. It actually processes URL parameters for all Method types
    if (uri.getRawQuery() != null) {

        StringTokenizer tokenizer = null;
        try {
            tokenizer = new StringTokenizer(URLDecoder.decode(uri.getRawQuery(), UTF_8), PARAMETERS_SEPARATOR);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        while (tokenizer.hasMoreElements()) {
            String token = tokenizer.nextToken();
            sortedMap.put(token.split(PARAM_NAME_VALUE_SEPARATOR)[0].toLowerCase()
                    + token.split(PARAM_NAME_VALUE_SEPARATOR)[1], token);
        }
    }

    // If POST process parameter map
    if (method.equals(HttpMethod.POST.name())) {
        for (String key : params.keySet()) {
            String valor = params.get(key);
            sortedMap.put(key.toLowerCase() + PARAM_NAME_VALUE_SEPARATOR + valor,
                    key + PARAM_NAME_VALUE_SEPARATOR + valor);
        }

    }
    // Generating String to sign
    StringBuilder stringToSign = new StringBuilder();
    stringToSign.append(method);
    stringToSign.append(HMAC_FIELD_SEPARATOR).append(timestamp);
    stringToSign.append(HMAC_FIELD_SEPARATOR).append(uri.getPath());

    boolean firstParam = true;

    for (String param : sortedMap.values()) {
        if (firstParam) {
            stringToSign.append(URI_PARAMETERS_SEPARATOR).append(param);
            firstParam = false;
        } else {
            stringToSign.append(PARAMETERS_SEPARATOR).append(param);
        }
    }

    return stringToSign.toString();
}

From source file:com.discovery.darchrow.net.ParamUtil.java

/**
 * ?.//  www .  ja  va 2s. c  om
 * 
 * @param uri
 *            the uri
 * @param paramNameList
 *            the param name list
 * @param charsetType
 *            ?
 * @return the string
 */
public static String removeParameterList(URI uri, List<String> paramNameList, String charsetType) {
    if (null == uri) {
        return "";
    }
    String url = uri.toString();
    //  paramNameList null 
    if (Validator.isNullOrEmpty(paramNameList)) {
        return url;
    }
    // ***********************************************************************
    String before = URIUtil.getBeforePath(url);
    // ***********************************************************************
    //  URI ? URI ???? URI 
    String query = uri.getRawQuery();
    // ***********************************************************************
    // url??
    if (Validator.isNullOrEmpty(query)) {
        // ??
        return url;
    } else {
        Map<String, String[]> map = URIUtil.parseQueryToArrayMap(query, null);
        for (String paramName : paramNameList) {
            map.remove(paramName);
        }
        return URIUtil.getEncodedUrlByArrayMap(before, map, charsetType);
    }
}