Example usage for java.net URI getQuery

List of usage examples for java.net URI getQuery

Introduction

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

Prototype

public String getQuery() 

Source Link

Document

Returns the decoded query component of this URI.

Usage

From source file:org.eclipse.orion.server.servlets.JsonURIUnqualificationStrategy.java

private void rewrite(JSONObject json, String scheme, String hostname, int port, String contextPath) {
    String[] names = JSONObject.getNames(json);
    if (names == null)
        return;// ww  w  . j  ava 2 s  . com
    for (String name : names) {
        Object o = json.opt(name);
        if (o instanceof URI) {
            try {
                URI uri = (URI) o;
                if ("orion".equals(uri.getScheme())) {
                    uri = new URI(null, null, contextPath + uri.getPath(), uri.getQuery(), uri.getFragment());
                }
                json.put(name, unqualifyObjectProperty(name, uri, scheme, hostname, port));
            } catch (JSONException e) {
            } catch (URISyntaxException e) {
            }
        } else if (o instanceof String) {
            String string = (String) o;
            if (string.startsWith(scheme) || string.startsWith("orion:/")) {
                try {
                    URI uri = new URI(string);
                    if ("orion".equals(uri.getScheme())) {
                        uri = new URI(null, null, contextPath + uri.getPath(), uri.getQuery(),
                                uri.getFragment());
                    }
                    json.put(name, unqualifyObjectProperty(name, uri, scheme, hostname, port));
                } catch (JSONException e) {
                } catch (URISyntaxException e) {
                }
            }
        } else {
            rewrite(o, scheme, hostname, port, contextPath);
        }
    }
}

From source file:org.jets3t.service.utils.SignatureUtils.java

/**
 * Build the canonical request string for a REST/HTTP request to a storage
 * service for the AWS Request Signature version 4.
 *
 * {@link "http://docs.aws.amazon.com/AmazonS3/latest/API/sig-v4-header-based-auth.html"}
 *
 * @param uri/*from  ww w  .ja v  a  2s  .  c  o m*/
 * @param httpMethod
 * the request's HTTP method just prior to sending
 * @param headersMap
 * @param requestPayloadHexSha256Hash
 * hex-encoded SHA256 hash of request's payload. May be null or "" in
 * which case the default SHA256 hash of an empty string is used.
 * @return canonical request string according to AWS Request Signature version 4
 */
public static String awsV4BuildCanonicalRequestString(URI uri, String httpMethod,
        Map<String, String> headersMap, String requestPayloadHexSha256Hash) {
    StringBuilder canonicalStringBuf = new StringBuilder();

    // HTTP Request method: GET, POST etc
    canonicalStringBuf.append(httpMethod).append("\n");

    // Canonical URI: URI-encoded version of the absolute path
    String absolutePath = uri.getPath();
    if (absolutePath.length() == 0) {
        canonicalStringBuf.append("/");
    } else {
        canonicalStringBuf.append(SignatureUtils.awsV4EncodeURI(absolutePath, false));
    }
    canonicalStringBuf.append("\n");

    // Canonical query string
    String query = uri.getQuery();
    if (query == null || query.length() == 0) {
        canonicalStringBuf.append("\n");
    } else {
        // Parse and sort query parameters and values from query string
        SortedMap<String, String> sortedQueryParameters = new TreeMap<String, String>();
        for (String paramPair : query.split("&")) {
            String[] paramNameValue = paramPair.split("=");
            String name = paramNameValue[0];
            String value = "";
            if (paramNameValue.length > 1) {
                value = paramNameValue[1];
            }
            // Add parameters to sorting map, URI-encoded appropriately
            sortedQueryParameters.put(SignatureUtils.awsV4EncodeURI(name, true),
                    SignatureUtils.awsV4EncodeURI(value, true));
        }
        // Add query parameters to canonical string
        boolean isPriorParam = false;
        for (Map.Entry<String, String> entry : sortedQueryParameters.entrySet()) {
            if (isPriorParam) {
                canonicalStringBuf.append("&");
            }
            canonicalStringBuf.append(entry.getKey()).append("=").append(entry.getValue());
            isPriorParam = true;
        }
        canonicalStringBuf.append("\n");
    }

    // Canonical Headers
    SortedMap<String, String> sortedHeaders = new TreeMap<String, String>();
    sortedHeaders.putAll(headersMap);
    for (Map.Entry<String, String> entry : sortedHeaders.entrySet()) {
        canonicalStringBuf.append(entry.getKey()).append(":").append(entry.getValue()).append("\n");
    }
    canonicalStringBuf.append("\n");

    // Signed headers
    boolean isPriorSignedHeader = false;
    for (Map.Entry<String, String> entry : sortedHeaders.entrySet()) {
        if (isPriorSignedHeader) {
            canonicalStringBuf.append(";");
        }
        canonicalStringBuf.append(entry.getKey());
        isPriorSignedHeader = true;
    }
    canonicalStringBuf.append("\n");

    // Hashed Payload.
    canonicalStringBuf.append(requestPayloadHexSha256Hash);

    return canonicalStringBuf.toString();
}

From source file:org.kitodo.dataaccess.format.xml.Namespaces.java

/**
 * Converts a URI to a globally unique name space. The name space is formed
 * with the host name of the machine the program is running on.
 *
 * @param uri/*from   www.  j  av  a  2s  .  c o  m*/
 *            URI to create a globally unique URI for
 * @return globally unique namespace
 * @throws IOException
 *             if it fails
 */
public static String namespaceFromURI(URI uri) throws IOException {
    try {
        String host = uri.getHost();
        String path = uri.getPath();
        if (host == null) {
            host = InetAddress.getLocalHost().getCanonicalHostName();
            if ((path != null) && path.startsWith("//")) {
                int pathStart = path.indexOf('/', 2);
                String remote = path.substring(2, pathStart);
                path = path.substring(pathStart);
                host = remote.contains(".") ? remote
                        : remote.concat(host.substring(InetAddress.getLocalHost().getHostName().length()));
            }
        }
        String scheme = uri.getScheme();
        if ((scheme == null) || !scheme.toLowerCase().startsWith("http")) {
            scheme = "http";
        }
        return new URI(scheme, uri.getUserInfo(), host, uri.getPort(), path, uri.getQuery(), "")
                .toASCIIString();
    } catch (URISyntaxException e) {
        String message = e.getMessage();
        throw new IllegalArgumentException(message != null ? message : e.getClass().getName(), e);
    }
}

From source file:com.cloudera.sqoop.manager.MySQLManager.java

/**
 * MySQL allows TIMESTAMP fields to have the value '0000-00-00 00:00:00',
 * which causes errors in import. If the user has not set the
 * zeroDateTimeBehavior property already, we set it for them to coerce
 * the type to null./*from   w  w  w  .j av  a 2  s .co  m*/
 */
private void checkDateTimeBehavior(ImportJobContext context) {
    final String ZERO_BEHAVIOR_STR = "zeroDateTimeBehavior";
    final String CONVERT_TO_NULL = "=convertToNull";

    String connectStr = context.getOptions().getConnectString();
    if (connectStr.indexOf("jdbc:") != 0) {
        // This connect string doesn't have the prefix we expect.
        // We can't parse the rest of it here.
        return;
    }

    // This starts with 'jdbc:mysql://' ... let's remove the 'jdbc:'
    // prefix so that java.net.URI can parse the rest of the line.
    String uriComponent = connectStr.substring(5);
    try {
        URI uri = new URI(uriComponent);
        String query = uri.getQuery(); // get the part after a '?'

        // If they haven't set the zeroBehavior option, set it to
        // squash-null for them.
        if (null == query) {
            connectStr = connectStr + "?" + ZERO_BEHAVIOR_STR + CONVERT_TO_NULL;
            LOG.info("Setting zero DATETIME behavior to convertToNull (mysql)");
        } else if (query.length() == 0) {
            connectStr = connectStr + ZERO_BEHAVIOR_STR + CONVERT_TO_NULL;
            LOG.info("Setting zero DATETIME behavior to convertToNull (mysql)");
        } else if (query.indexOf(ZERO_BEHAVIOR_STR) == -1) {
            if (!connectStr.endsWith("&")) {
                connectStr = connectStr + "&";
            }
            connectStr = connectStr + ZERO_BEHAVIOR_STR + CONVERT_TO_NULL;
            LOG.info("Setting zero DATETIME behavior to convertToNull (mysql)");
        }

        LOG.debug("Rewriting connect string to " + connectStr);
        context.getOptions().setConnectString(connectStr);
    } catch (URISyntaxException use) {
        // Just ignore this. If we can't parse the URI, don't attempt
        // to add any extra flags to it.
        LOG.debug("mysql: Couldn't parse connect str in checkDateTimeBehavior: " + use);
    }
}

From source file:org.apache.hadoop.yarn.server.resourcemanager.webapp.RMWebAppFilter.java

private String appendOrReplaceParamter(String uri, String newQuery) {
    if (uri.contains(YarnWebParams.NEXT_REFRESH_INTERVAL + "=")) {
        return uri.replaceAll(YarnWebParams.NEXT_REFRESH_INTERVAL + "=[^&]+", newQuery);
    }// www  . j  ava 2  s .  co  m
    try {
        URI oldUri = new URI(uri);
        String appendQuery = oldUri.getQuery();
        if (appendQuery == null) {
            appendQuery = newQuery;
        } else {
            appendQuery += "&" + newQuery;
        }

        URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(), oldUri.getPath(), appendQuery,
                oldUri.getFragment());

        return newUri.toString();
    } catch (URISyntaxException e) {
        return null;
    }
}

From source file:org.aksw.resparql.IMyHandler.java

public static String getJenaFormatByQueryString(URI uri) {
    // Check if a particular format was requested via the query string
    // As this excludes some of the content types that may be used
    String query = uri.getQuery();
    MultiMap<String, String> params = URIUtil.getQueryMap(query);

    String rawFormat = getFirst(params.get("format"));
    rawFormat = rawFormat == null ? null : rawFormat.trim().toLowerCase();
    String requestFormat = formatToJenaFormat.get(rawFormat);
    if (rawFormat != null && requestFormat == null) {
        // FIXME Respect the accept header when returning an error
        //return new SimpleResponse(400, "text/plain", "Unsupported format");
        return null;
    }/*from   w w w.  jav a  2 s . co m*/

    return requestFormat;
}

From source file:net.paoding.spdy.server.tomcat.impl.RequestDecoder.java

private Request decode(SynStream synStream) throws URISyntaxException {
    Request request = new Request();
    request.setStartTime(synStream.getTimestamp());
    CoyoteAttributes.setSynStream(request, synStream);
    ///*from   w  w w  .ja va 2 s.co m*/
    String method = synStream.getHeader("method");
    String url = synStream.getHeader("url");
    String version = synStream.getHeader("version");
    if (method == null && url == null && version == null) {
        throw new IllegalArgumentException("method=" + method + "; url=" + url + "; version=" + version);
    }
    request.method().setString(method);
    URI uri = new URI(url);
    request.protocol().setString(uri.getScheme());
    request.requestURI().setString(uri.getPath());
    request.query().setString(uri.getQuery());
    request.serverName().setString(uri.getHost());
    int port = uri.getPort();
    request.setServerPort(port > 0 ? port : 80);
    // copy headers
    MimeHeaders coyoteHeaders = request.getMimeHeaders();
    Map<String, String> headers = synStream.getHeaders();
    for (Map.Entry<String, String> header : headers.entrySet()) {
        MessageBytes val = coyoteHeaders.addValue(header.getKey());
        val.setString(header.getValue());
    }
    // body
    request.setInputBuffer(new SpdyInputBuffer(synStream));
    //        System.out.println("RequestDecoder.decode: returnrequest " + request.decodedURI());
    return request;
}

From source file:org.apache.shindig.gadgets.servlet.UrlGeneratorTest.java

@Test
public void getIframeUrlTypeHtml() throws Exception {
    String xml = "<Module>" + " <ModulePrefs title='test'/>" + " <Content type='html'/>" + " <UserPref name='"
            + UP_NAME + "' datatype='string'/>" + "</Module>";
    GadgetSpec spec = new GadgetSpec(URI.create(SPEC_URL), xml);
    Gadget gadget = new Gadget(context, spec, Collections.<JsLibrary>emptyList());
    fixture.replay();//from   w w  w  .j  a v a2 s  .  c om

    URI iframeUrl = URI.create(urlGenerator.getIframeUrl(gadget));

    assertEquals(IFR_PREFIX, iframeUrl.getPath() + '?');
    StringAssert.assertContains("container=" + CONTAINER, iframeUrl.getQuery());
    StringAssert.assertContains("up_" + UP_NAME + '=' + UP_VALUE, iframeUrl.getQuery());
    StringAssert.assertContains("mid=" + MODULE_ID, iframeUrl.getQuery());
    StringAssert.assertContains("view=" + VIEW, iframeUrl.getQuery());
}

From source file:com.thoughtworks.go.util.command.UrlArgument.java

@Override
public String forDisplay() {
    try {/*w w  w .  j  a  va 2  s  .c  o  m*/
        URI uri = new URI(sanitizeUrl());
        if (uri.getUserInfo() != null) {
            uri = new URI(uri.getScheme(), clean(uri.getScheme(), uri.getUserInfo()), uri.getHost(),
                    uri.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());
        }
        return uri.toString();
    } catch (URISyntaxException e) {
        return url;
    }
}

From source file:com.joyent.manta.client.UriSigner.java

/**
 * Signs an arbitrary URL using the Manta-compatible HTTP signature
 * method.//  w ww  .  j  a va2s  .  c om
 *
 * @param uri URI with no query pointing to a downloadable resource
 * @param method HTTP request method to be used in the signature
 * @param expires epoch time in seconds when the resource will no longer
 *                be available
 * @return a signed version of the input URI
 * @throws IOException thrown when we can't sign or read char data
 */
public URI signURI(final URI uri, final String method, final long expires) throws IOException {
    Validate.notNull(method, "Method must not be null");
    Validate.notNull(uri, "URI must not be null");

    Validate.isTrue(StringUtils.isEmpty(uri.getQuery()), "Query must be null or empty. URI: %s", uri);

    final ThreadLocalSigner signer = authConfig.getSigner();

    final String charset = "UTF-8";
    final String algorithm = signer.get().getHttpHeaderAlgorithm().toUpperCase();
    final String keyId = String.format("/%s/keys/%s", authConfig.getMantaUser(),
            KeyFingerprinter.md5Fingerprint(authConfig.getKeyPair()));

    final String keyIdEncoded = URLEncoder.encode(keyId, charset);

    StringBuilder sigText = new StringBuilder();
    sigText.append(method).append(StringUtils.LF).append(uri.getHost()).append(StringUtils.LF)
            .append(uri.getRawPath()).append(StringUtils.LF).append("algorithm=").append(algorithm).append("&")
            .append("expires=").append(expires).append("&").append("keyId=").append(keyIdEncoded);

    StringBuilder request = new StringBuilder();
    final byte[] sigBytes = sigText.toString().getBytes(StandardCharsets.UTF_8);

    // first parameter isn't actually used for anything, just checked for nullness
    final byte[] signed = signer.get().sign("", authConfig.getKeyPair(), sigBytes);

    final String encoded = new String(Base64.encode(signed), charset);
    final String urlEncoded = URLEncoder.encode(encoded, charset);

    request.append(uri).append("?").append("algorithm=").append(algorithm).append("&").append("expires=")
            .append(expires).append("&").append("keyId=").append(keyIdEncoded).append("&").append("signature=")
            .append(urlEncoded);

    return URI.create(request.toString());
}