Example usage for java.net URL getQuery

List of usage examples for java.net URL getQuery

Introduction

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

Prototype

public String getQuery() 

Source Link

Document

Gets the query part of this URL .

Usage

From source file:org.lockss.util.UrlUtil.java

/** Return true if <code>to</code> looks like a directory redirection
 * from <code>from</code>; <i>ie</i>, that path has had a slash appended
 * to it. *///from  w w w . ja  v a  2  s .  c  om
// XXX does this need to be insensitive to differently encoded URLs?
public static boolean isDirectoryRedirection(String from, String to) {
    if (to.length() != (from.length() + 1))
        return false;
    try {
        URL ufrom = new URL(from);
        URL uto = new URL(to);
        String toPath = uto.getPath();
        String fromPath = ufrom.getPath();
        int len = fromPath.length();
        return (toPath.length() == (len + 1) && toPath.charAt(len) == '/' && toPath.startsWith(fromPath)
                && ufrom.getHost().equalsIgnoreCase(uto.getHost())
                && ufrom.getProtocol().equalsIgnoreCase(uto.getProtocol()) && ufrom.getPort() == uto.getPort()
                && StringUtil.equalStringsIgnoreCase(ufrom.getQuery(), uto.getQuery())

        );
    } catch (MalformedURLException e) {
        return false;
    }
}

From source file:com.pearson.pdn.learningstudio.helloworld.OAuth1SignatureServlet.java

private String normalizeParams(String httpMethod, URL url, Map<String, String> oauthParams, byte[] requestBody)
        throws UnsupportedEncodingException {

    // Sort the parameters in lexicographical order, 1st by Key then by Value
    Map<String, String> kvpParams = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    kvpParams.putAll(oauthParams);/*from w w w . j  av  a2  s .  c o m*/

    // Place any query string parameters into a key value pair using equals
    // ("=") to mark
    // the key/value relationship and join each parameter with an ampersand
    // ("&")
    if (url.getQuery() != null) {
        for (String keyValue : url.getQuery().split("&")) {
            String[] p = keyValue.split("=");
            kvpParams.put(p[0], p[1]);
        }

    }

    // Include the body parameter if dealing with a POST or PUT request
    if ("POST".equals(httpMethod) || "PUT".equals(httpMethod)) {
        String body = Base64.encodeBase64String(requestBody).replaceAll("\r\n", "");
        // url encode the body 2 times now before combining other params
        body = URLEncoder.encode(body, "UTF-8");
        body = URLEncoder.encode(body, "UTF-8");
        kvpParams.put("body", body);
    }

    // separate the key and values with a "="
    // separate the kvp with a "&"
    StringBuilder combinedParams = new StringBuilder();
    String delimiter = "";
    for (String key : kvpParams.keySet()) {
        combinedParams.append(delimiter);
        combinedParams.append(key);
        combinedParams.append("=");
        combinedParams.append(kvpParams.get(key));
        delimiter = "&";
    }

    // url encode the entire string again before returning
    return URLEncoder.encode(combinedParams.toString(), "UTF-8");
}

From source file:com.cladonia.xngreditor.URLUtilities.java

/**
 * Returns a String representation without the Username and Password.
 * /*w w w .j av  a 2s .c  om*/
 * @param url the url to convert to a String...
 * 
 * @return the string representation.
 */
public static String toString(URL url) {
    if (url != null) {
        StringBuffer result = new StringBuffer(url.getProtocol());
        result.append(":");

        if (url.getHost() != null && url.getHost().length() > 0) {
            result.append("//");
            result.append(url.getHost());
        }

        if (url.getPort() > 0) {
            result.append(":");
            result.append(url.getPort());
        }

        if (url.getPath() != null) {
            result.append(url.getPath());
        }

        if (url.getQuery() != null) {
            result.append('?');
            result.append(url.getQuery());
        }

        if (url.getRef() != null) {
            result.append("#");
            result.append(url.getRef());
        }

        return result.toString();
    }

    return null;
}

From source file:wjhk.jupload2.upload.FileUploadThreadHTTP.java

/**
 * Converts the parameters in GET form to post form
 * //from  w w w  .  ja  va 2 s  .c  o  m
 * @param url the <code>URL</code> containing the query parameters
 * @return the parameters in a string in the correct form for a POST request
 * @throws JUploadIOException
 */
private final ByteArrayEncoder getFormParamsForPostRequest(final URL url) throws JUploadIOException {

    // Use a string buffer
    // We'll encode the output stream into UTF-8.
    ByteArrayEncoder bae = new ByteArrayEncoderHTTP(this.uploadPolicy, this.connectionHelper.getBoundary());

    // Get the query string
    String query = url.getQuery();

    if (null != query) {
        // Split this into parameters
        HashMap<String, String> requestParameters = new HashMap<String, String>();
        String[] paramPairs = query.split("&");
        String[] oneParamArray;

        // TODO This could be much more simple !

        // Put the parameters correctly to the Hashmap
        for (String param : paramPairs) {
            if (param.contains("=")) {
                oneParamArray = param.split("=");
                if (oneParamArray.length > 1) {
                    // There is a value for this parameter
                    try {
                        // Correction of URL double encoding bug
                        requestParameters.put(oneParamArray[0], URLDecoder.decode(oneParamArray[1], "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        throw new JUploadIOException(e.getClass().getName() + ": " + e.getMessage()
                                + " (when trying to decode " + oneParamArray[1] + ")");
                    }
                } else {
                    // There is no value for this parameter
                    requestParameters.put(oneParamArray[0], "");
                }
            }
        }

        // Now add one multipart segment for each
        Set<Map.Entry<String, String>> entrySet = requestParameters.entrySet();
        Map.Entry<String, String> entry;
        Iterator<Map.Entry<String, String>> i = entrySet.iterator();
        while (i.hasNext()) {
            entry = i.next();
            bae.appendTextProperty(entry.getKey(), entry.getValue(), -1);
        }
    }
    // Return the body content
    bae.close();

    return bae;
}

From source file:com.aliyun.api.gateway.demo.Client.java

/**
 * ?Header// w  w w .java 2  s  .c  o m
 * 
 * @param requestBuilder
 *            
 * @param headers
 *            Http
 * @param url
 *            http://host+path+query
 * @param formParam
 *            ??
 * @param signHeaderPrefixes
 *            ???Header?
 * @return Header
 * @throws MalformedURLException
 */
private void initialBasicHeader(RequestBuilder requestBuilder, Map<String, String> headers, URL url,
        Map<String, String> formParam, String[] signHeaderPrefixes) throws MalformedURLException {
    if (headers != null) {
        for (Map.Entry<String, String> e : headers.entrySet()) {
            requestBuilder.removeHeaders(e.getKey()).addHeader(e.getKey(), e.getValue());
        }
    }
    StringBuilder stringBuilder = new StringBuilder();
    if (StringUtils.isNotBlank(url.getPath())) {
        stringBuilder.append(url.getPath());
    }
    if (StringUtils.isNotBlank(url.getQuery())) {
        stringBuilder.append("?");
        stringBuilder.append(url.getQuery());
    }
    requestBuilder.addHeader(SystemHeader.X_CA_SIGNATURE,
            SignUtil.sign(requestBuilder, stringBuilder.toString(), formParam, appSecret, signHeaderPrefixes));
}

From source file:com.twinsoft.convertigo.eclipse.learnproxy.http.HttpProxyWorker.java

private HttpRequest handleRequest(Socket proxySocket) throws IOException {
    HttpRequest request = new HttpRequest();
    BufferedInputStream proxyInStream = new BufferedInputStream(proxySocket.getInputStream());
    byte b = -1;/*from  w  w  w. j a v  a 2 s  . co m*/
    ArrayList<Byte> list = new ArrayList<Byte>(200);
    ArrayList<Byte> listToSend = new ArrayList<Byte>(200);
    int readInt;
    String previousLine = null;
    int lastCRPos = 0;
    int lastSendCRPos = 0;
    boolean hasCompleted = false;
    int lineNo = 0;
    int length = 0;
    while (!isInterrupted && !hasCompleted && (readInt = proxyInStream.read()) != -1) {
        b = (byte) readInt;
        list.add(new Byte(b));
        listToSend.add(new Byte(b));
        if (b == 13) {
            // check for two line breaks without form feed
            if (list.size() > 1) {
                if (list.get(list.size() - 2).equals(new Byte((byte) 13))) {
                    hasCompleted = true;
                } else {
                    // try to analyze the previous line
                    byte[] bytes = new byte[list.size() - lastCRPos - 1];
                    for (int i = lastCRPos; i < list.size() - 1; i++) {
                        bytes[i - lastCRPos] = ((Byte) list.get(i)).byteValue();
                    }
                    // requests are always in ASCII
                    previousLine = new String(bytes, "ISO-8859-1");
                    //logger.debug("request: " + previousLine);
                    if (lineNo == 0) {
                        // we must have here s.th. like 
                        // GET http://server/xyz.html?param=value HTTP/1.0
                        String[] components = previousLine.split(" ");
                        String method = components[0];
                        String urlStr = components[1];
                        String httpVersion = components[2];

                        // now parse the URL
                        URL url = new URL(urlStr);
                        String host = url.getHost();
                        String path = url.getPath();
                        String query = url.getQuery();
                        String port = String.valueOf(url.getPort());
                        if ("-1".equals(port)) {
                            port = "80";
                        }
                        request.setPort(Integer.parseInt(port));
                        request.setHost(host);
                        request.setPath(path);
                        request.setQuery(query);
                        request.setMethod(method);
                        request.setVersion(httpVersion);

                        // now we can reconstruct this line...
                        if ((System.getProperty("http.proxyHost") == null)
                                || System.getProperty("http.proxyHost").trim().equals("")) {
                            listToSend = new ArrayList<Byte>();
                            StringBuffer buff = new StringBuffer(100);
                            buff.append(method);
                            buff.append(' ');
                            buff.append(path);
                            if (query != null) {
                                buff.append('?');
                                buff.append(query);
                            }
                            buff.append(' ');
                            buff.append(components[2].substring(0, components[2].length()));
                            String newLine = buff.toString();
                            byte[] newLineBytes = newLine.getBytes("ISO-8859-1");
                            for (int i = 0; i < newLineBytes.length; i++) {
                                listToSend.add(new Byte(newLineBytes[i]));
                            }
                            listToSend.add(new Byte((byte) 13));
                        }
                    }
                    if (previousLine.matches("^[Cc]ontent-[Ll]ength: .+")) {
                        String lengthStr = previousLine.substring(16, previousLine.length());
                        length = Integer.parseInt(lengthStr);
                        //logger.debug("length: " + length + ", " + lengthStr);
                    }
                    if (previousLine.matches("^[Pp]roxy.+")) {
                        if ((System.getProperty("http.proxyHost") == null)
                                || System.getProperty("http.proxyHost").trim().equals("")) {
                            //logger.debug("proxy!!! - " + previousLine);
                            // if not used behind another proxy erase proxy-related headers
                            for (int i = listToSend.size() - 1; i > lastSendCRPos - 2; i--) {
                                listToSend.remove(i);
                            }
                        }
                    }
                    // the CR should be ignored for printing any headerLine
                    lastCRPos = list.size() + 1;
                    lastSendCRPos = listToSend.size() + 1;
                    lineNo++;
                }
            }
        }
        if (b == 10) {
            // check for two line breaks with form feed
            if (list.get(list.size() - 2).equals(new Byte((byte) 13))
                    && list.get(list.size() - 3).equals(new Byte((byte) 10))
                    && list.get(list.size() - 4).equals(new Byte((byte) 13))) {
                //logger.debug("length: " + length);
                if (length == 0) {
                    hasCompleted = true;
                } else {
                    for (int i = 0; i < length; i++) {
                        readInt = proxyInStream.read();
                        b = (byte) readInt;
                        list.add(new Byte(b));
                        listToSend.add(new Byte(b));
                    }
                    list.add(new Byte((byte) '\n'));
                    listToSend.add(new Byte((byte) '\n'));
                    hasCompleted = true;
                }
            }
        }
    }
    // store original request
    byte[] byteArray = getByteArrayFromList(listToSend);
    request.setRequest(byteArray);
    //logger.debug("request: \nasText:\n" + new String(byteArray) + "as bytes:\n" + printByteArray(byteArray));
    return request;
}

From source file:org.apache.taverna.component.profile.ComponentProfileImpl.java

public ComponentProfileImpl(Registry registry, URL profileURL, BaseProfileLocator base)
        throws ComponentException {
    logger.info("Loading profile in " + identityHashCode(this) + " from " + profileURL);
    this.base = base;
    try {//  w w  w.ja  v  a2  s .  c  o  m
        URL url = profileURL;
        if (url.getProtocol().startsWith("http"))
            url = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), url.getRef())
                    .toURL();
        loadProfile(this, url, base);
    } catch (MalformedURLException e) {
        logger.warn("Malformed URL? " + profileURL);
    } catch (URISyntaxException e) {
        logger.warn("Malformed URL? " + profileURL);
    }
    parentRegistry = registry;
}

From source file:org.apache.wicket.portlet.WicketPortlet.java

/**
 * FIXME javadoc//  w ww  . ja  va2  s. c om
 * 
 * <p>
 * Corrects the incoming URL if the old home page style, or if it's missing
 * the filter path prefix.
 * 
 * @param requestUrl
 *            the original request URL
 * @param url
 *            the URL to fix
 * @return the corrected URL
 */
protected String fixWicketUrl(final String requestUrl, final String url) {
    if ((url != null) && (requestUrl != null) && (!ABSOLUTE_URI_PATTERN.matcher(url).matches())) {
        try {
            if (!requestUrl.startsWith("http")) {
                URL fixedUrl = new URL("http:" + url);
                String query = fixedUrl.getQuery();
                if (query != null) {
                    String wuViewParam = "_wuview=";
                    for (String queryParamValuePair : query.split("&")) {
                        if (queryParamValuePair.startsWith(wuViewParam)) {
                            return URLDecoder.decode(queryParamValuePair.replace(wuViewParam, ""), "UTF-8")
                                    + "?" + query;
                        }
                    }
                }

                return new URL(new URL("http:" + wicketFilterPath), url).toString().substring(5);
            } else {
                return new URL(new URL(wicketFilterPath), url).getPath();
            }
        } catch (Exception e) {
        }
    }
    return fixWicketUrl(url);
}

From source file:nya.miku.wishmaster.chans.dobrochan.DobroModule.java

private String sanitizeUrl(String urlStr) {
    if (urlStr == null)
        return null;
    try {/*from   w w w .  j a va 2 s  .  co m*/
        URL url = new URL(urlStr);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        return uri.toURL().toString();
    } catch (Exception e) {
        Logger.e(TAG, "sanitize url", e);
        return urlStr;
    }
}

From source file:com.ecomnext.rest.ning.NingRestRequestHolder.java

public NingRestRequestHolder(NingRestClient client, String url) {
    try {//www  .  ja v  a2s.  c  o m
        this.client = client;
        URL reference = new URL(url);

        this.url = url;

        String userInfo = reference.getUserInfo();
        if (userInfo != null) {
            this.setAuth(userInfo);
        }
        if (reference.getQuery() != null) {
            this.setQueryString(reference.getQuery());
        }
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }

}