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:com.sworddance.util.UriFactoryImpl.java

/**
 * suitable for namespacing/*from   ww  w.java 2  s. com*/
 * @return the uri with relative schema ( ex. //facebook.com/path/to/stuff?query )
 */
public static URI createNamespaceUri(Object uriStr) {
    URI temp = createUriWithOptions(uriStr, true, true);
    try {
        URI namesUri = new URI(null, temp.getUserInfo(), temp.getHost(), -1, temp.getPath(), temp.getQuery(),
                temp.getFragment());
        return namesUri;
    } catch (URISyntaxException e) {
        return null;
    }
}

From source file:org.openanzo.servlet.EncryptedTokenAuthenticator.java

/**
 * Adds the give parameters to a URI string in the URI's query portion. It will add the '?' if needed, and will simply add the arguments if the URI already
 * has a query portion. It will also allow URIs with fragment portions (ex. '#foo') and place the query fragment and parameters in the appropriate place. It
 * will also escape any special URI characters in the parameter names or values.
 * /*from   www . jav  a 2s .  c o  m*/
 * This method assumes that the query string is in x-www-form-urlencoded format.
 * 
 * @param uri
 *            the URI string to modify
 * @param parameters
 *            the map with the key/value parameters to add to the query portion of the URI
 * @return a String URI with the parameters added to the given URI.
 * @throws URISyntaxException
 */
public static String addQueryParametersToURI(String uri, MultiMap<String> parameters)
        throws URISyntaxException {
    URI inUri = new URI(uri);

    String paramStr = UrlEncoded.encode(parameters, null, false);
    String newQuery = inUri.getQuery() == null ? paramStr : inUri.getQuery() + "&" + paramStr;
    StringBuilder outUri = new StringBuilder();
    if (inUri.getScheme() != null) {
        outUri.append(inUri.getScheme());
        outUri.append(':');
    }
    if (inUri.getRawAuthority() != null) {
        outUri.append("//");
        outUri.append(inUri.getRawAuthority());
    }
    if (inUri.getRawPath() != null) {
        outUri.append(inUri.getRawPath());
    }
    if (StringUtils.isNotEmpty(newQuery)) {
        outUri.append('?');
        outUri.append(newQuery);
    }
    if (inUri.getRawFragment() != null) {
        outUri.append("#");
        outUri.append(inUri.getRawFragment());
    }
    return outUri.toString();
}

From source file:tv.phantombot.httpserver.HTTPServerCommon.java

public static void handle(HttpExchange exchange, String serverPassword, String serverWebAuth)
        throws IOException {
    Boolean hasPassword = false;/*from  ww w .j  av  a2  s  . c  o m*/
    Boolean doRefresh = false;
    Boolean doMarquee = false;
    String myPassword = "";
    String myHdrUser = "";
    String myHdrMessage = "";
    String[] uriQueryList = null;
    int marqueeWidth = 420;
    int msgLength = 40;

    // Get the path and query string from the URI
    URI uriData = exchange.getRequestURI();
    String uriPath = uriData.getPath();
    String uriQuery = uriData.getQuery();

    if (uriQuery != null) {
        uriQueryList = uriQuery.split("&");
    }

    // Get the headers
    Headers headers = exchange.getRequestHeaders();

    // Get the Request Method (GET/PUT)
    String requestMethod = exchange.getRequestMethod();

    // Get any data from the body, although, we just discard it, this is required
    InputStream inputStream = exchange.getRequestBody();
    while (inputStream.read() != -1) {
        inputStream.skip(0x10000);
    }
    inputStream.close();

    if (headers.containsKey("password")) {
        myPassword = headers.getFirst("password");
        if (myPassword.equals(serverPassword) || myPassword.equals("oauth:" + serverPassword)) {
            hasPassword = true;
        }
    }
    if (headers.containsKey("webauth")) {
        myPassword = headers.getFirst("webauth");
        if (myPassword.equals(serverWebAuth)) {
            hasPassword = true;
        }
    }
    if (headers.containsKey("user")) {
        myHdrUser = headers.getFirst("user");
    }
    if (headers.containsKey("message")) {
        myHdrMessage = headers.getFirst("message");
        byte[] myHdrMessageBytes = myHdrMessage.getBytes(StandardCharsets.ISO_8859_1);
        myHdrMessage = new String(myHdrMessageBytes, StandardCharsets.UTF_8);
    }

    // Check the uriQueryList for the webauth
    if (uriQuery != null) {
        for (String query : uriQueryList) {
            if (query.startsWith("webauth=")) {
                String[] webAuthData = query.split("=");
                myPassword = webAuthData[1];
                if (myPassword.equals(serverWebAuth)) {
                    hasPassword = true;
                }
            } else if (query.startsWith("refresh")) {
                doRefresh = true;
            } else if (query.startsWith("marquee")) {
                doMarquee = true;
            } else if (query.startsWith("width")) {
                String[] splitData = query.split("=");
                try {
                    marqueeWidth = Integer.parseInt(splitData[1]);
                } catch (NumberFormatException ex) {
                    marqueeWidth = 420;
                }
            } else if (query.startsWith("cutoff")) {
                String[] splitData = query.split("=");
                try {
                    msgLength = Integer.parseInt(splitData[1]);
                } catch (NumberFormatException ex) {
                    msgLength = 40;
                }
            }
        }
    }

    if (requestMethod.equals("GET")) {
        if (uriPath.contains("..")) {
            sendHTMLError(403, "Invalid URL", exchange);
        } else if (uriPath.startsWith("/inistore")) {
            handleIniStore(uriPath, exchange, hasPassword);
        } else if (uriPath.startsWith("/dbquery")) {
            handleDBQuery(uriPath, uriQueryList, exchange, hasPassword);
        } else if (uriPath.startsWith("/addons") && !doRefresh && !doMarquee) {
            handleFile(uriPath, exchange, hasPassword, true);
        } else if (uriPath.startsWith("/addons") && doMarquee) {
            handleRefresh(uriPath, exchange, true, hasPassword, true, marqueeWidth, msgLength);
        } else if (uriPath.startsWith("/addons") && doRefresh) {
            handleRefresh(uriPath, exchange, false, hasPassword, true, 0, 0);
        } else if (uriPath.startsWith("/logs")) {
            handleFile(uriPath, exchange, hasPassword, true);
        } else if (uriPath.equals("/playlist")) {
            handleFile("/web/playlist/index.html", exchange, hasPassword, false);
        } else if (uriPath.equals("/")) {
            handleFile("/web/index.html", exchange, hasPassword, false);
        } else if (uriPath.equals("/alerts")) {
            handleFile("/web/alerts/index.html", exchange, hasPassword, false);
        } else if (uriPath.startsWith("/config/audio-hooks")) {
            handleFile(uriPath, exchange, hasPassword, false);
        } else if (uriPath.startsWith("/config/gif-alerts")) {
            handleFile(uriPath, exchange, hasPassword, false);
        } else if (uriPath.startsWith("/get-lang")) {
            handleLangFiles("", exchange, hasPassword, true);
        } else if (uriPath.startsWith("/lang")) {
            handleLangFiles(headers.getFirst("lang-path"), exchange, hasPassword, true);
        } else if (uriPath.startsWith("/games")) {
            handleGamesList(exchange, hasPassword, true);
        } else {
            handleFile("/web" + uriPath, exchange, hasPassword, false);
        }
    }

    if (requestMethod.equals("PUT")) {
        if (myHdrUser.isEmpty() && headers.containsKey("lang-path")) {
            handlePutRequestLang(headers.getFirst("lang-path"), headers.getFirst("lang-data"), exchange,
                    hasPassword);
        } else {
            handlePutRequest(myHdrUser, myHdrMessage, exchange, hasPassword);
        }
    }
}

From source file:com.sworddance.util.UriFactoryImpl.java

/**
 * TODO need to figure out what parts of WebLocationImpl belong here.
 * @param uri//from w ww  .  j  av a  2  s  .c om
 * @return uri
 */
public static URI getNormalizedUri(URI uri) {
    try {
        String path = uri.getPath();

        // see WebLocationImpl ( this implementation here may not be correct )
        return new URI(uri.getScheme(), uri.getHost(), path == null ? PATH_SEPARATOR : PATH_SEPARATOR + path,
                uri.getQuery());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.rssowl.core.util.URIUtils.java

/**
 * Try to get the File Name of the given URI.
 *
 * @param uri The URI to parse the File from.
 * @param extension the file extension or <code>null</code> if unknown.
 * @return String The File Name or the URI in external Form.
 *//*from   w  ww . j  a  v a2s. c om*/
public static String getFile(URI uri, String extension) {

    /* Fallback if Extension not set */
    if (!StringUtils.isSet(extension))
        return getFile(uri);

    /* Prefix Extension if necessary */
    if (!extension.startsWith(".")) //$NON-NLS-1$
        extension = "." + extension; //$NON-NLS-1$

    /* Obtain Filename Candidates from Query and Path */
    String fileQuerySegment = getFileSegmentFromQuery(uri.getQuery(), extension);
    String lastPathSegment = getLastSegmentFromPath(uri.getPath());

    /* Favour Query over Path if Extension part of it */
    if (StringUtils.isSet(fileQuerySegment) && fileQuerySegment.contains(extension))
        return urlDecode(fileQuerySegment);

    /* Use Path if Extension part of it */
    if (StringUtils.isSet(lastPathSegment) && lastPathSegment.contains(extension))
        return urlDecode(lastPathSegment);

    /* Favour Path over Query otherwise */
    if (StringUtils.isSet(lastPathSegment))
        return urlDecode(lastPathSegment);

    /* Use Query as Fallback */
    if (StringUtils.isSet(fileQuerySegment))
        return urlDecode(fileQuerySegment);

    return uri.toASCIIString();
}

From source file:org.jenkinsci.plugins.github_branch_source.GitHubConfiguration.java

/**
 * Fix an apiUri.// w w  w.  j  a  va2s. c  om
 *
 * @param apiUri the api URI.
 * @return the normalized api URI.
 */
@CheckForNull
public static String normalizeApiUri(@CheckForNull String apiUri) {
    if (apiUri == null) {
        return null;
    }
    try {
        URI uri = new URI(apiUri).normalize();
        String scheme = uri.getScheme();
        if ("http".equals(scheme) || "https".equals(scheme)) {
            // we only expect http / https, but also these are the only ones where we know the authority
            // is server based, i.e. [userinfo@]server[:port]
            // DNS names must be US-ASCII and are case insensitive, so we force all to lowercase

            String host = uri.getHost() == null ? null : uri.getHost().toLowerCase(Locale.ENGLISH);
            int port = uri.getPort();
            if ("http".equals(scheme) && port == 80) {
                port = -1;
            } else if ("https".equals(scheme) && port == 443) {
                port = -1;
            }
            apiUri = new URI(scheme, uri.getUserInfo(), host, port, uri.getPath(), uri.getQuery(),
                    uri.getFragment()).toASCIIString();
        }
    } catch (URISyntaxException e) {
        // ignore, this was a best effort tidy-up
    }
    return apiUri.replaceAll("/$", "");
}

From source file:org.accelio.jxio.tests.benchmarks.jxioConnection.UserServerCallbacks.java

public long getBytes(URI uri) {
    String query = uri.getQuery();
    return Long.parseLong(query.split("size=")[1].split("&")[0]);
}

From source file:Main.java

/**
 * Removes dot segments according to RFC 3986, section 5.2.4
 *
 * @param uri the original URI/*from  w w w  .  j ava 2s  .  c  o m*/
 * @return the URI without dot segments
 */
private static URI removeDotSegments(URI uri) {
    String path = uri.getPath();
    if ((path == null) || (path.indexOf("/.") == -1)) {
        // No dot segments to remove
        return uri;
    }
    String[] inputSegments = path.split("/");
    Stack<String> outputSegments = new Stack<String>();
    for (int i = 0; i < inputSegments.length; i++) {
        if ((inputSegments[i].length() == 0) || (".".equals(inputSegments[i]))) {
            // Do nothing
        } else if ("..".equals(inputSegments[i])) {
            if (!outputSegments.isEmpty()) {
                outputSegments.pop();
            }
        } else {
            outputSegments.push(inputSegments[i]);
        }
    }
    StringBuilder outputBuffer = new StringBuilder();
    for (String outputSegment : outputSegments) {
        outputBuffer.append('/').append(outputSegment);
    }
    try {
        return new URI(uri.getScheme(), uri.getAuthority(), outputBuffer.toString(), uri.getQuery(),
                uri.getFragment());
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException(e);
    }
}

From source file:org.rssowl.core.util.URIUtils.java

/**
 * A helper to convert custom schemes (like feed://) to the HTTP counterpart.
 *
 * @param uri the uri to get as HTTP/HTTPS {@link URI}.
 * @return the converted {@link URI} if necessary.
 *//* w  w w. j av a  2s .c o m*/
public static URI toHTTP(URI uri) {
    if (uri == null)
        return uri;

    String scheme = uri.getScheme();
    if (HTTP_SCHEME.equals(scheme) || HTTPS_SCHEME.equals(scheme))
        return uri;

    String newScheme = HTTP_SCHEME;
    if (SyncUtils.READER_HTTPS_SCHEME.equals(scheme))
        newScheme = HTTPS_SCHEME;

    try {
        return new URI(newScheme, uri.getUserInfo(), uri.getHost(), uri.getPort(), uri.getPath(),
                uri.getQuery(), uri.getFragment());
    } catch (URISyntaxException e) {
        return uri;
    }
}

From source file:org.apache.oozie.action.hadoop.SparkMain.java

/**
 * Spark compares URIs based on scheme, host and port. Here we convert URIs
 * into the default format so that Spark won't think those belong to
 * different file system. This will avoid an extra copy of files which
 * already exists on same hdfs.//ww  w. j a v  a 2s .c o  m
 *
 * @param fs
 * @param fileUri
 * @return fixed uri
 * @throws URISyntaxException
 */
private static URI getFixedUri(FileSystem fs, URI fileUri) throws URISyntaxException {
    if (fs.getUri().getScheme().equals(fileUri.getScheme())
            && (fs.getUri().getHost().equals(fileUri.getHost()) || fileUri.getHost() == null)
            && (fs.getUri().getPort() == -1 || fileUri.getPort() == -1
                    || fs.getUri().getPort() == fileUri.getPort())) {
        return new URI(fs.getUri().getScheme(), fileUri.getUserInfo(), fs.getUri().getHost(),
                fs.getUri().getPort(), fileUri.getPath(), fileUri.getQuery(), fileUri.getFragment());
    }
    return fileUri;
}