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 List<String> getACL(String ossURL, String sshKeyFingerprint, String secretName)
        throws OSSException {

    SSHAgentClient agent = null;//from   w  ww.  j a v a  2s.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.jayway.restassured.internal.http.URIBuilder.java

/**
 * Adds all parameters within the Scanner to the list of
 * <code>parameters</code>, as encoded by <code>encoding</code>. For
 * example, a scanner containing the string <code>a=1&b=2&c=3</code> would
 * add the {@link NameValuePair NameValuePairs} a=1, b=2, and c=3 to the
 * list of parameters.//w  w w.ja v a  2  s .  c om
 * <p>
 * Note that this method has been copied from {@link URLEncodedUtils#parse(java.util.List, java.util.Scanner, String)} but it doesn't do URL decoding.
 * </p>
 */
private List<NameValuePair> parse(URI uri) {
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    final String query = uri.getRawQuery();
    if (query != null && query.length() > 0) {
        final Scanner scanner = new Scanner(query);
        scanner.useDelimiter(PARAMETER_SEPARATOR);
        while (scanner.hasNext()) {
            String name;
            String value = null;
            String token = scanner.next();
            int i = token.indexOf(NAME_VALUE_SEPARATOR);
            if (i != -1) {
                name = token.substring(0, i).trim();
                value = token.substring(i + 1).trim();
            } else {
                name = token.trim();
            }
            parameters.add(new BasicNameValuePair(name, value));
        }
    }
    return parameters;
}

From source file:es.onebox.rest.utils.service.QueryService.java

/**
 * This method generates the string to be signed based on the following rules:
 *
 *  - Add the request method + \n//from w  w  w .  ja  va  2 s.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, QueryForm queryForm)
        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), AMPERSAND);
        } 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 : ((Set<String>) ((MultiMap) queryForm.getFormParameters()).keySet())) {
            for (String valor : ((List<String>) ((MultiMap) queryForm.getFormParameters()).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:net.oneandone.sushi.fs.webdav.WebdavFilesystem.java

@Override
public WebdavNode node(URI uri, Object extra) throws NodeInstantiationException {
    if (extra != null) {
        throw new NodeInstantiationException(uri, "unexpected extra argument: " + extra);
    }//  ww w .  j  a  v  a2s .com
    if (uri.getFragment() != null) {
        throw new NodeInstantiationException(uri, "unexpected path fragment");
    }
    if (uri.isOpaque()) {
        throw new NodeInstantiationException(uri, "uri is not hierarchical");
    }
    return root(uri).node(getCheckedPath(uri), uri.getRawQuery());
}

From source file:org.apache.tajo.worker.LocalFetcher.java

private List<FileChunk> getChunksForRangeShuffle(final PullServerParams params, final Path queryBaseDir)
        throws IOException {
    final List<FileChunk> fileChunks = new ArrayList<>();

    if (state == FetcherState.FETCH_INIT) {
        final ChannelInitializer<Channel> initializer = new HttpClientChannelInitializer();
        bootstrap.handler(initializer);//www . j  a  va2 s  .  co  m
    }

    this.state = FetcherState.FETCH_META_FETCHING;
    ChannelFuture future = null;
    try {
        future = bootstrap.clone().connect(new InetSocketAddress(host, port))
                .addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE);

        // Wait until the connection attempt succeeds or fails.
        Channel channel = future.awaitUninterruptibly().channel();
        if (!future.isSuccess()) {
            endFetch(FetcherState.FETCH_FAILED);
            throw new IOException(future.cause());
        }

        for (URI eachURI : createChunkMetaRequestURIs(host, port, params)) {
            String query = eachURI.getPath()
                    + (eachURI.getRawQuery() != null ? "?" + eachURI.getRawQuery() : "");
            HttpRequest request = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, query);
            request.headers().set(HttpHeaders.Names.HOST, host);
            request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
            request.headers().set(HttpHeaders.Names.ACCEPT_ENCODING, HttpHeaders.Values.GZIP);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Status: " + getState() + ", URI:" + eachURI);
            }
            // Send the HTTP request.
            channel.writeAndFlush(request);
        }
        // Wait for the server to close the connection. throw exception if failed
        channel.closeFuture().syncUninterruptibly();

        if (!state.equals(FetcherState.FETCH_META_FINISHED)) {
            endFetch(FetcherState.FETCH_FAILED);
        } else {
            state = FetcherState.FETCH_DATA_FETCHING;
            fileLen = fileNum = 0;
            for (FileChunkMeta eachMeta : chunkMetas) {
                Path outputPath = StorageUtil.concatPath(queryBaseDir, eachMeta.getTaskId(), "output");
                if (!localDirAllocator.ifExists(outputPath.toString(), conf)) {
                    LOG.warn("Range shuffle - file not exist. " + outputPath);
                    continue;
                }
                Path path = localFileSystem
                        .makeQualified(localDirAllocator.getLocalPathToRead(outputPath.toString(), conf));
                File file = new File(URI.create(path.toUri() + "/output"));
                FileChunk chunk = new FileChunk(file, eachMeta.getStartOffset(), eachMeta.getLength());
                chunk.setEbId(tableName);
                fileChunks.add(chunk);
                fileLen += chunk.length();
                fileNum++;
            }
            endFetch(FetcherState.FETCH_DATA_FINISHED);
        }

        return fileChunks;
    } finally {
        if (future != null && future.channel().isOpen()) {
            // Close the channel to exit.
            future.channel().close().awaitUninterruptibly();
        }
    }
}

From source file:io.gravitee.gateway.http.vertx.VertxHttpClient.java

@Override
public ClientRequest request(io.gravitee.common.http.HttpMethod method, URI uri, HttpHeaders headers,
        Handler<ClientResponse> responseHandler) {
    HttpClient httpClient = httpClients.computeIfAbsent(Vertx.currentContext(), createHttpClient());

    final int port = uri.getPort() != -1 ? uri.getPort() : (HTTPS_SCHEME.equals(uri.getScheme()) ? 443 : 80);

    String relativeUri = (uri.getRawQuery() == null) ? uri.getRawPath()
            : uri.getRawPath() + '?' + uri.getRawQuery();

    HttpClientRequest clientRequest = httpClient.request(convert(method), port, uri.getHost(), relativeUri,
            clientResponse -> handleClientResponse(clientResponse, responseHandler));

    clientRequest.setTimeout(endpoint.getHttpClientOptions().getReadTimeout());

    VertxClientRequest invokerRequest = new VertxClientRequest(clientRequest);

    clientRequest.exceptionHandler(event -> {
        LOGGER.error("Server proxying failed: {}", event.getMessage());

        if (invokerRequest.connectTimeoutHandler() != null && event instanceof ConnectTimeoutException) {
            invokerRequest.connectTimeoutHandler().handle(event);
        } else {/*  ww w. j a  va2 s  .co m*/
            VertxClientResponse clientResponse = new VertxClientResponse(
                    ((event instanceof ConnectTimeoutException) || (event instanceof TimeoutException))
                            ? HttpStatusCode.GATEWAY_TIMEOUT_504
                            : HttpStatusCode.BAD_GATEWAY_502);

            clientResponse.headers().set(HttpHeaders.CONNECTION, HttpHeadersValues.CONNECTION_CLOSE);

            Buffer buffer = null;

            if (event.getMessage() != null) {
                // Create body content with error message
                buffer = Buffer.buffer(event.getMessage());
                clientResponse.headers().set(HttpHeaders.CONTENT_LENGTH, Integer.toString(buffer.length()));
            }

            responseHandler.handle(clientResponse);

            if (buffer != null) {
                clientResponse.bodyHandler().handle(buffer);
            }

            clientResponse.endHandler().handle(null);
        }
    });

    // Copy headers to final API
    copyRequestHeaders(headers, clientRequest,
            (port == 80 || port == 443) ? uri.getHost() : uri.getHost() + ':' + port);

    // Check chunk flag on the request if there are some content to push and if transfer_encoding is set
    // with chunk value
    if (hasContent(headers)) {
        String transferEncoding = headers.getFirst(HttpHeaders.TRANSFER_ENCODING);
        if (HttpHeadersValues.TRANSFER_ENCODING_CHUNKED.equalsIgnoreCase(transferEncoding)) {
            clientRequest.setChunked(true);
        }
    }

    // Send HTTP head as soon as possible
    clientRequest.sendHead();

    return invokerRequest;
}

From source file:org.apache.camel.component.http.HttpProducer.java

/**
 * Creates the HttpMethod to use to call the remote server, either its GET or POST.
 *
 * @param exchange the exchange//from w w w  . j  a  v  a2s  .  c om
 * @return the created method as either GET or POST
 * @throws CamelExchangeException is thrown if error creating RequestEntity
 */
@SuppressWarnings("deprecation")
protected HttpMethod createMethod(Exchange exchange) throws Exception {
    // creating the url to use takes 2-steps
    String url = HttpHelper.createURL(exchange, getEndpoint());
    URI uri = HttpHelper.createURI(exchange, url, getEndpoint());
    // get the url and query string from the uri
    url = uri.toASCIIString();
    String queryString = uri.getRawQuery();

    // execute any custom url rewrite
    String rewriteUrl = HttpHelper.urlRewrite(exchange, url, getEndpoint(), this);
    if (rewriteUrl != null) {
        // update url and query string from the rewritten url
        url = rewriteUrl;
        uri = new URI(url);
        // use raw query to have uri decimal encoded which http client requires
        queryString = uri.getRawQuery();
    }

    // remove query string as http client does not accept that
    if (url.indexOf('?') != -1) {
        url = url.substring(0, url.indexOf('?'));
    }

    // create http holder objects for the request
    RequestEntity requestEntity = createRequestEntity(exchange);
    HttpMethods methodToUse = HttpHelper.createMethod(exchange, getEndpoint(), requestEntity != null);
    HttpMethod method = methodToUse.createMethod(url);
    if (queryString != null) {
        // need to encode query string
        queryString = UnsafeUriCharactersEncoder.encode(queryString);
        method.setQueryString(queryString);
    }

    LOG.trace("Using URL: {} with method: {}", url, method);

    if (methodToUse.isEntityEnclosing()) {
        ((EntityEnclosingMethod) method).setRequestEntity(requestEntity);
        if (requestEntity != null && requestEntity.getContentType() == null) {
            LOG.debug("No Content-Type provided for URL: {} with exchange: {}", url, exchange);
        }
    }

    // there must be a host on the method
    if (method.getHostConfiguration().getHost() == null) {
        throw new IllegalArgumentException("Invalid uri: " + url
                + ". If you are forwarding/bridging http endpoints, then enable the bridgeEndpoint option on the endpoint: "
                + getEndpoint());
    }

    return method;
}

From source file:leap.webunit.client.THttpRequestImpl.java

protected String buildRequestUrl() {
    String url = null;//from   ww  w  .  ja  v  a2s.c  o  m

    if (Strings.isEmpty(uri)) {
        url = tclient.getBaseUrl();
    } else if (uri.indexOf("://") > 0) {
        url = uri;
    } else if (Strings.startsWith(uri, "/")) {
        url = tclient.getBaseUrl() + uri;
    } else {
        url = tclient.getBaseUrl() + "/" + uri;
    }

    if (!queryString.isEmpty()) {
        url = Urls.appendQueryString(url, queryString.build());
    }

    URI uri = URI.create(url);
    String path = uri.getPath();
    if (!"".equals(path)) {
        for (String contextPath : tclient.getContextPaths()) {
            if (path.equals(contextPath)) {
                url = uri.getScheme() + ":" + uri.getSchemeSpecificPart() + "/";
                if (null != uri.getQuery()) {
                    url = url + "?" + uri.getRawQuery();
                }
                break;
            }
        }
    }

    return url;
}

From source file:net.netheos.pcsapi.providers.hubic.Swift.java

private void configureSession(HttpRequestBase request, String format) {
    request.addHeader("X-Auth-token", authToken);
    if (format != null) {
        try {// w ww .  j  av  a 2s .  co m
            URI uri = request.getURI();
            if (uri.getRawQuery() != null) {
                request.setURI(URI.create(uri + "&format=" + URLEncoder.encode(format, "UTF-8")));
            } else {
                request.setURI(URI.create(uri + "?format=" + URLEncoder.encode(format, "UTF-8")));
            }

        } catch (UnsupportedEncodingException ex) {
            throw new UnsupportedOperationException("Error setting the request format", ex);
        }
    }
}

From source file:org.orcid.core.adapter.impl.MapperFacadeFactory.java

private String extractFullPath(String uriString) {
    URI uri = validateAndConvertToURI(uriString);
    StringBuilder pathBuilder = new StringBuilder(uri.getRawPath());
    String query = uri.getRawQuery();
    if (query != null) {
        pathBuilder.append('?');
        pathBuilder.append(query);//  ww w .j av a 2s .co m
    }
    String fragment = uri.getRawFragment();
    if (fragment != null) {
        pathBuilder.append(fragment);
    }
    return pathBuilder.toString();
}