Java Code Examples for com.networknt.utility.StringUtils#substringBefore()

The following examples show how to use com.networknt.utility.StringUtils#substringBefore() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: light-4j   File: URLNormalizer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>Removes empty parameters.</p>
 * <code>http://www.example.com/display?a=b&amp;a=&amp;c=d&amp;e=&amp;f=g
 * &rarr; http://www.example.com/display?a=b&amp;c=d&amp;f=g</code>
 * @return this instance
 */
public URLNormalizer removeEmptyParameters() {
    // Does it have query parameters?
    if (!url.contains("?")) {
        return this;
    }
    // It does, so proceed
    List<String> keyValues = new ArrayList<>();
    String queryString = StringUtils.substringAfter(url, "?");
    String[] params = StringUtils.split(queryString, '&');
    for (String param : params) {
        if (param.contains("=")
                && StringUtils.isNotBlank(
                StringUtils.substringAfter(param, "="))
                && StringUtils.isNotBlank(
                StringUtils.substringBefore(param, "="))) {
            keyValues.add(param);
        }
    }
    String cleanQueryString = StringUtils.join(keyValues, '&');
    if (StringUtils.isNotBlank(cleanQueryString)) {
        url = StringUtils.substringBefore(
                url, "?") + "?" + cleanQueryString;
    }
    return this;
}
 
Example 2
Source Project: light-4j   File: URLNormalizer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * <p>Removes a URL-based session id.  It removes PHP (PHPSESSID),
 * ASP (ASPSESSIONID), and Java EE (jsessionid) session ids.</p>
 * <code>http://www.example.com/servlet;jsessionid=1E6FEC0D14D044541DD84D2D013D29ED?a=b
 * &rarr; http://www.example.com/servlet?a=b</code>
 * <p><b>Please Note:</b> Removing session IDs from URLs is often
 * a good way to have the URL return an error once invoked.</p>
 * @return this instance
 */
public URLNormalizer removeSessionIds() {
    if (StringUtils.containsIgnoreCase(url, ";jsessionid=")) {
        url = url.replaceFirst(
                "(;jsessionid=([A-F0-9]+)((\\.\\w+)*))", "");
    } else {
        String u = StringUtils.substringBefore(url, "?");
        String q = StringUtils.substringAfter(url, "?");
        if (StringUtils.containsIgnoreCase(url, "PHPSESSID=")) {
            q = q.replaceFirst("(&|^)(PHPSESSID=[0-9a-zA-Z]*)", "");
        } else if (StringUtils.containsIgnoreCase(url, "ASPSESSIONID")) {
            q = q.replaceFirst(
                    "(&|^)(ASPSESSIONID[a-zA-Z]{8}=[a-zA-Z]*)", "");
        }
        if (!StringUtils.isBlank(q)) {
            u += "?" + StringUtils.removeStart(q, "&");
        }
        url = u;
    }
    return this;
}
 
Example 3
Source Project: light-4j   File: HttpURL.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts a relative URL to an absolute one, based on the supplied
 * base URL. The base URL is assumed to be a valid URL. Behavior
 * is unexpected when base URL is invalid.
 * @param baseURL URL to the reference is relative to
 * @param relativeURL the relative URL portion to transform to absolute
 * @return absolute URL
 * @since 1.8.0
 */
public static String toAbsolute(String baseURL, String relativeURL) {
    String relURL = relativeURL;
    // Relative to protocol
    if (relURL.startsWith("//")) {
        return StringUtils.substringBefore(baseURL, "//") + "//"
                + StringUtils.substringAfter(relURL, "//");
    }
    // Relative to domain name
    if (relURL.startsWith("/")) {
        return getRoot(baseURL) + relURL;
    }
    // Relative to full full page URL minus ? or #
    if (relURL.startsWith("?") || relURL.startsWith("#")) {
        // this is a relative url and should have the full page base
        return baseURL.replaceFirst("(.*?)([\\?\\#])(.*)", "$1") + relURL;
    }

    // Relative to last directory/segment
    if (!relURL.contains("://")) {
        String base = baseURL.replaceFirst("(.*?)([\\?\\#])(.*)", "$1");
        if (StringUtils.countMatches(base, '/') > 2) {
            base = base.replaceFirst("(.*/)(.*)", "$1");
        }
        if (base.endsWith("/")) {
            // This is a URL relative to the last URL segment
            relURL = base + relURL;
        } else {
            relURL = base + "/" + relURL;
        }
    }

    // Not detected as relative, so return as is
    return relURL;
}
 
Example 4
Source Project: light-4j   File: QueryString.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * It is possible to only supply a query string as opposed to an
 * entire URL.
 * Key and values making up a query string are assumed to be URL-encoded.
 * Will throw a {@link RuntimeException} if the supplied encoding is
 * unsupported or invalid.
 * @param urlWithQueryString a URL from which to extract a query string.
 * @param encoding character encoding
 */
public QueryString(String urlWithQueryString, String encoding) {
    if (StringUtils.isBlank(encoding)) {
        this.encoding = StandardCharsets.UTF_8.toString();
    } else {
        this.encoding = encoding;
    }
    String paramString = urlWithQueryString;
    if (paramString.contains("?")) {
        paramString = StringUtils.substringBefore(paramString, "#");
        paramString = paramString.replaceAll("(.*?)(\\?)(.*)", "$3");
    }
    String[] paramParts = paramString.split("\\&");
    for (int i = 0; i < paramParts.length; i++) {
        String paramPart = paramParts[i];
        if (StringUtils.isBlank(paramPart)) {
            continue;
        }
        String key;
        String value;
        if (paramPart.contains("=")) {
            key = StringUtils.substringBefore(paramPart, "=");
            value = StringUtils.substringAfter(paramPart, "=");
        } else {
            key = paramPart;
            value = StringUtils.EMPTY;
        }
        try {
            addString(URLDecoder.decode(key, this.encoding),
                    URLDecoder.decode(value, this.encoding));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(
                    "Cannot URL-decode query string (key="
                            + key + "; value=" + value + ").", e);
        }
    }
}
 
Example 5
Source Project: light-4j   File: QueryString.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Apply this url QueryString on the given URL. If a query string already
 * exists, it is replaced by this one.
 * @param url the URL to apply this query string.
 * @return url with query string added
 */
public String applyOnURL(String url) {
    if (StringUtils.isBlank(url)) {
        return url;
    }
    return StringUtils.substringBefore(url, "?") + toString();
}
 
Example 6
Source Project: light-4j   File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Sorts query parameters.</p>
 * <code>http://www.example.com/?z=bb&amp;y=cc&amp;z=aa &rarr;
 *       http://www.example.com/?y=cc&amp;z=bb&amp;z=aa</code>
 * @return this instance
 */
public URLNormalizer sortQueryParameters() {
    // Does it have query parameters?
    if (!url.contains("?")) {
        return this;
    }
    // It does, so proceed
    List<String> keyValues = new ArrayList<>();
    String queryString = StringUtils.substringAfter(url, "?");

    // extract and remove any fragments
    String fragment = StringUtils.substringAfter(queryString, "#");
    if (StringUtils.isNotBlank(fragment)) {
        fragment = "#" + fragment;
    }
    queryString = StringUtils.substringBefore(queryString, "#");

    String[] params = StringUtils.split(queryString, '&');
    for (String param : params) {
        keyValues.add(param);
    }
    // sort it so that query string are in order
    Collections.sort(keyValues);

    String sortedQueryString = StringUtils.join(keyValues, '&');
    if (StringUtils.isNotBlank(sortedQueryString)) {
        url = StringUtils.substringBefore(
                url, "?") + "?" + sortedQueryString + fragment;
    }

    return this;
}
 
Example 7
Source Project: light-4j   File: URLNormalizer.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * <p>
 * Encodes space characters into plus signs (+) if they are part of the
 * query string. Spaces part of the URL path are percent-encoded to %20.
 * </p>
 * <p>
 * To encode all non-ASCII characters (including spaces), use
 * {@link #encodeNonURICharacters()} instead.
 * </p>
 * <code>http://www.example.com/a b c &rarr;
 *       http://www.example.com/a+b+c</code>
 * @return this instance
 * @since 1.8.0
 */
public URLNormalizer encodeSpaces() {
    String path = StringUtils.substringBefore(url, "?");
    path = StringUtils.replace(path, " ", "%20", -1);
    String qs = StringUtils.substringAfter(url, "?");
    if (StringUtils.isNotBlank(qs)) {
        qs = StringUtils.replace(qs, " ", "+", -1);
        url = path + "?" + qs;
    } else {
        url = path;
    }
    return this;
}