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:org.aotorrent.tracker.TrackerConnectionHandler.java

private Map<String, String> splitQuery(URI uri) throws UnsupportedEncodingException {
    final Map<String, String> queryPairs = new HashMap<>();
    final String rawQuery = uri.getRawQuery();
    if (rawQuery != null) {
        final String[] pairs = rawQuery.split("&");
        for (String pair : pairs) {
            final int idx = pair.indexOf("=");
            final String key = idx > 0
                    ? URLDecoder.decode(pair.substring(0, idx), Torrent.DEFAULT_TORRENT_ENCODING)
                    : pair;/*from  ww w . j a  v  a  2s .c  om*/
            final String value = idx > 0 && pair.length() > idx + 1
                    ? URLDecoder.decode(pair.substring(idx + 1), Torrent.DEFAULT_TORRENT_ENCODING)
                    : null;
            queryPairs.put(key, value);
        }
    }
    return queryPairs;
}

From source file:org.openlmis.fulfillment.service.request.RequestHelperTest.java

@Test
public void shouldCreateUriWithEncodedParameters() throws Exception {
    URI uri = RequestHelper.createUri(URL, RequestParameters.init().set("a", "b c"));
    assertThat(uri.getQuery(), is("a=b c"));
    assertThat(uri.getRawQuery(), is("a=b%20c"));
}

From source file:com.rightscale.app.dashboard.ShowServerMonitoring.java

private Map<String, String> parseQueryParams(URI uri) {
    Map<String, String> queryParams = new HashMap<String, String>();

    String query = uri.getRawQuery();
    String[] items = query.split("&");
    for (String item : items) {
        String[] pair = item.split("=");
        if (pair.length >= 2) {
            queryParams.put(pair[0], pair[1]);
        }/*from  w  ww  . ja  va  2  s .  c o  m*/
    }

    return queryParams;
}

From source file:com.chigix.bio.proxy.buffer.FixedBufferTest.java

License:asdf

@Test
public void testGoogleConnect() {
    System.out.println("BANKAI");
    Socket tmp_socket = null;//w  w w  .j  a v  a2 s.  c o m
    try {
        tmp_socket = new Socket("www.google.com", 80);
    } catch (IOException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    final Socket socket = tmp_socket;
    new Thread() {

        @Override
        public void run() {
            while (true) {
                try {
                    int read;
                    System.out.print(read = socket.getInputStream().read());
                    System.out.print("[" + (char) read + "]");
                    System.out.print(",");
                } catch (IOException ex) {
                    Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }

    }.start();
    try {
        //socket.getOutputStream().write("GET http://www.google.com/ HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\n".getBytes());
        //URI uri = new URI("/?gfe_rd=cr&ei=F07YVIjKBe_98wfq74LICw");
        URI uri = new URI("/asdfwef?");
        System.out.println(uri.getRawFragment());
        System.out.println(uri.getRawPath());
        System.out.println(uri.getRawQuery());
        System.out.println(uri.getRawSchemeSpecificPart());
        socket.getOutputStream()
                .write(("GET / HTTP/1.0\r\nHost: www.google.com\r\nConnection: close\r\n\r\n").getBytes());
        System.out.println("REQUEST SENT");
    } catch (IOException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    } catch (URISyntaxException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        Thread.sleep(50000);
    } catch (InterruptedException ex) {
        Logger.getLogger(FixedBufferTest.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:org.echocat.jomon.net.service.UriBasedServicesManager.java

@Nonnull
protected URI toUri(@Nonnull URI original, @Nonnull InetSocketAddress address) {
    final String scheme = original.getScheme();
    final int port = address.getPort();
    final String userInfo = original.getRawUserInfo();
    final String path = original.getRawPath();
    final String query = original.getRawQuery();
    final String fragment = original.getRawFragment();
    final StringBuilder sb = new StringBuilder();
    sb.append(scheme).append("://");
    if (isNotEmpty(userInfo)) {
        sb.append(userInfo).append('@');
    }/*from   www  .  ja v a 2 s.c o m*/
    sb.append(address.getHostString());
    if (canAppendPort(scheme, port)) {
        sb.append(':').append(port);
    }
    if (isNotEmpty(path)) {
        sb.append(path);
    }
    if (isNotEmpty(query)) {
        sb.append('?').append(query);
    }
    if (isNotEmpty(fragment)) {
        sb.append('#').append(fragment);
    }
    return URI.create(sb.toString());
}

From source file:org.mule.transport.http.transformers.ObjectToHttpClientMethodRequest.java

protected HttpMethod createGetMethod(MuleMessage msg, String outputEncoding) throws Exception {
    final Object src = msg.getPayload();
    // TODO It makes testing much harder if we use the endpoint on the
    // transformer since we need to create correct message types and endpoints
    // URI uri = getEndpoint().getEndpointURI().getUri();
    final URI uri = getURI(msg);
    HttpMethod httpMethod;/*  w w  w. j av a2  s  .  com*/
    String query = uri.getRawQuery();

    httpMethod = new GetMethod(uri.toString());
    String paramName = msg.getOutboundProperty(HttpConnector.HTTP_GET_BODY_PARAM_PROPERTY, null);
    if (paramName != null) {
        paramName = URLEncoder.encode(paramName, outputEncoding);

        String paramValue;
        Boolean encode = msg.getInvocationProperty(HttpConnector.HTTP_ENCODE_PARAMVALUE);
        if (encode == null) {
            encode = msg.getOutboundProperty(HttpConnector.HTTP_ENCODE_PARAMVALUE, true);
        }

        if (encode) {
            paramValue = URLEncoder.encode(src.toString(), outputEncoding);
        } else {
            paramValue = src.toString();
        }

        if (!(src instanceof NullPayload) && !StringUtils.EMPTY.equals(src)) {
            if (query == null) {
                query = paramName + "=" + paramValue;
            } else {
                query += "&" + paramName + "=" + paramValue;
            }
        }
    }

    httpMethod.setQueryString(query);
    return httpMethod;
}

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

public static void genSecret(String ossURL, String secretName, String sshKeyFingerprint) throws OSSException {

    SSHAgentClient agent = null;/*from   w  w  w.jav a 2 s  .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++;

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

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

            ByteArrayOutputStream token = new ByteArrayOutputStream();

            byte[] tsdata = nowBytes();

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

            token.write(CryptoHelper.encodeNetworkString(secretName.getBytes("UTF-8")));

            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_GEN_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);
            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 generate 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.snowplowanalytics.refererparser.Parser.java

public Referer parse(URI refererUri, String pageHost, List<String> internalDomains) {
    if (refererUri == null) {
        return null;
    }/*from w w w. j a va  2  s  .  c om*/
    return parse(refererUri.getScheme(), refererUri.getHost(), refererUri.getPath(), refererUri.getRawQuery(),
            pageHost, internalDomains);
}

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   ww  w. j a v  a  2 s. c o  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:org.meresco.triplestore.HttpHandler.java

public void handle(HttpExchange exchange) throws IOException {
    OutputStream outputStream = exchange.getResponseBody();
    URI requestURI = exchange.getRequestURI();
    String path = requestURI.getPath();
    String rawQueryString = requestURI.getRawQuery();
    Headers requestHeaders = exchange.getRequestHeaders();

    try {// ww  w . j a va2s.c om
        QueryParameters httpArguments = Utils.parseQS(rawQueryString);
        if ("/add".equals(path)) {
            String body = Utils.read(exchange.getRequestBody());
            try {
                addData(httpArguments, requestHeaders, body);
            } catch (RDFParseException e) {
                exchange.sendResponseHeaders(400, 0);
                _writeResponse(e.toString(), outputStream);
                return;
            }
        } else if ("/update".equals(path)) {
            String body = Utils.read(exchange.getRequestBody());
            try {
                updateData(httpArguments, requestHeaders, body);
            } catch (RDFParseException e) {
                exchange.sendResponseHeaders(400, 0);
                _writeResponse(e.toString(), outputStream);
                return;
            }
        } else if ("/delete".equals(path)) {
            deleteData(httpArguments);
        } else if ("/addTriple".equals(path)) {
            String body = Utils.read(exchange.getRequestBody());
            addTriple(body);
        } else if ("/removeTriple".equals(path)) {
            String body = Utils.read(exchange.getRequestBody());
            removeTriple(body);
        } else if ("/query".equals(path)) {
            String response = "";
            Headers responseHeaders = exchange.getResponseHeaders();
            try {
                long start = System.currentTimeMillis();
                String query = httpArguments.singleValue("query");
                List<String> responseTypes = getResponseTypes(requestHeaders, httpArguments);
                if (query != null) {
                    ParsedQuery p = QueryParserUtil.parseQuery(QueryLanguage.SPARQL, query, null);
                    if (p instanceof ParsedGraphQuery) {
                        response = executeGraphQuery(query, responseTypes, responseHeaders);
                    } else {
                        response = executeTupleQuery(query, responseTypes, responseHeaders);
                    }
                }
                long indexQueryTime = System.currentTimeMillis() - start;
                if (response == null || response == "") {
                    String responseBody = "Supported formats SELECT query:\n";
                    Iterator<TupleQueryResultFormat> i = TupleQueryResultFormat.values().iterator();
                    while (i.hasNext()) {
                        responseBody += "- " + i.next() + "\n";
                    }

                    responseBody += "\nSupported formats DESCRIBE query:\n";
                    Iterator<RDFFormat> j = RDFFormat.values().iterator();
                    while (j.hasNext()) {
                        responseBody += "- " + j.next() + "\n";
                    }

                    responseHeaders.set("Content-Type", "text/plain");
                    exchange.sendResponseHeaders(406, 0);
                    _writeResponse(responseBody, outputStream);
                    return;
                }
                responseHeaders.set("X-Meresco-Triplestore-QueryTime", String.valueOf(indexQueryTime));
                if (httpArguments.containsKey("outputContentType")) {
                    responseHeaders.set("Content-Type", httpArguments.singleValue("outputContentType"));
                }
                exchange.sendResponseHeaders(200, 0);
                _writeResponse(response, outputStream);
            } catch (MalformedQueryException e) {
                exchange.sendResponseHeaders(400, 0);
                _writeResponse(e.toString(), outputStream);
            }
            return;
        } else if ("/sparql".equals(path)) {
            String response = sparqlForm(httpArguments);
            Headers headers = exchange.getResponseHeaders();
            headers.set("Content-Type", "text/html");
            exchange.sendResponseHeaders(200, 0);
            _writeResponse(response, outputStream);
        } else if ("/validate".equals(path)) {
            String body = Utils.read(exchange.getRequestBody());
            exchange.sendResponseHeaders(200, 0);
            try {
                validateRDF(httpArguments, body);
                _writeResponse("Ok", outputStream);
            } catch (RDFParseException e) {
                _writeResponse("Invalid\n" + e.toString(), outputStream);
            }
        } else if ("/export".equals(path)) {
            export(httpArguments);
        } else if ("/import".equals(path)) {
            String body = Utils.read(exchange.getRequestBody());
            importTrig(body);
        } else {
            exchange.sendResponseHeaders(404, 0);
            return;
        }
        exchange.sendResponseHeaders(200, 0);
    } catch (IllegalArgumentException e) {
        exchange.sendResponseHeaders(400, 0);
        _writeResponse(e.toString(), outputStream);
    } catch (RuntimeException e) {
        e.printStackTrace();
        exchange.sendResponseHeaders(500, 0);
        String response = Utils.getStackTrace(e);
        //System.out.println(response);
        _writeResponse(response, outputStream);
        return;
    } catch (Error e) {
        e.printStackTrace();
        exchange.sendResponseHeaders(500, 0);
        _writeResponse(e.getMessage(), outputStream);
        exchange.getHttpContext().getServer().stop(0);
        ((ExecutorService) exchange.getHttpContext().getServer().getExecutor()).shutdownNow();
        return;
    } finally {
        exchange.close();
    }
}