Java Code Examples for com.networknt.utility.StringUtils

The following examples show how to use com.networknt.utility.StringUtils. 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-rest-4j   Source File: PathParameterDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
private String getValue(String prop, String uri) {
	String key = String.format(";%s=", prop);
	
	if (StringUtils.containsIgnoreCase(uri,  key)) {
		String value = uri.substring(uri.indexOf(key) + key.length());
		int nextSemiColon = value.indexOf(Delimiters.SEMICOLON);
		int nextSlash = value.indexOf(Delimiters.SLASH);
		int end = Math.min(nextSemiColon, nextSlash);
		
		if (nextSemiColon>=0 && nextSlash>=0) {
			value = value.substring(0, end);
		}else if (nextSemiColon>=0) {
			value = value.substring(0, nextSemiColon);
		}else if (nextSlash>=0) {
			value = value.substring(0, nextSlash);
		}
		
		return value;
	}
	
	return StringUtils.EMPTY;
}
 
Example 2
Source Project: light-rest-4j   Source File: StyleParameterDeserializer.java    License: Apache License 2.0 6 votes vote down vote up
default Map<String, String> asExploadeMap(String str, String delimiter) {
	Map<String, String> valueMap = new HashMap<>();
	String[] items = str.split("\\"+delimiter);
	
	for (String item: items) {
		String[] tokens = item.split(Delimiters.EQUAL);
		
		String key=null;
		String value=null;
		
		if (tokens.length>0) {
			key = tokens[0];
		}
		
		if (tokens.length>1) {
			value = tokens[1];
		}
		
		if (StringUtils.isNotBlank(key)) {
			valueMap.put(key, StringUtils.trimToEmpty(value));
		}
	}
	
	return valueMap;
}
 
Example 3
Source Project: light-rest-4j   Source File: RequestValidator.java    License: Apache License 2.0 6 votes vote down vote up
private Object getDeserializedValue(final HttpServerExchange exchange, final String name, final ParameterType type) {
 	if (null!=type && StringUtils.isNotBlank(name)) {
switch(type){
case QUERY:
	return OpenApiHandler.getQueryParameters(exchange,true).get(name);
case PATH:
	return OpenApiHandler.getPathParameters(exchange,true).get(name);
case HEADER:
	return OpenApiHandler.getHeaderParameters(exchange,true).get(name);
case COOKIE:
	return OpenApiHandler.getCookieParameters(exchange,true).get(name);
}   		
 	}
 	
 	return null;
 }
 
Example 4
Source Project: light-4j   Source 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 5
Source Project: light-4j   Source 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 6
Source Project: light-4j   Source File: OauthHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * this method is to support sending a server which doesn't support chunked transfer encoding.
 * @param request ClientRequest
 * @param requestBody String
 */
public static void adjustNoChunkedEncoding(ClientRequest request, String requestBody) {
    String fixedLengthString = request.getRequestHeaders().getFirst(Headers.CONTENT_LENGTH);
    String transferEncodingString = request.getRequestHeaders().getLast(Headers.TRANSFER_ENCODING);
    if(transferEncodingString != null) {
        request.getRequestHeaders().remove(Headers.TRANSFER_ENCODING);
    }
    //if already specify a content-length, should use what they provided
    if(fixedLengthString != null && Long.parseLong(fixedLengthString) > 0) {
        return;
    }
    if(!StringUtils.isEmpty(requestBody)) {
        long contentLength = requestBody.getBytes(UTF_8).length;
        request.getRequestHeaders().put(Headers.CONTENT_LENGTH, contentLength);
    }

}
 
Example 7
Source Project: light-4j   Source File: ConsulClientImpl.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * send to consul, init or reconnect if necessary
 * @param method http method to use
 * @param path path to send to consul
 * @param token token to put in header
 * @param json request body to send
 * @return AtomicReference<ClientResponse> response
 */
 AtomicReference<ClientResponse> send (HttpString method, String path, String token, String json) throws InterruptedException {
	final CountDownLatch latch = new CountDownLatch(1);
	final AtomicReference<ClientResponse> reference = new AtomicReference<>();

	if (needsToCreateConnection()) {
		this.connection = createConnection();
	}

	ClientRequest request = new ClientRequest().setMethod(method).setPath(path);
	request.getRequestHeaders().put(Headers.HOST, "localhost");
	if (token != null) request.getRequestHeaders().put(HttpStringConstants.CONSUL_TOKEN, token);
	logger.trace("The request sent to consul: {} = request header: {}, request body is empty", uri.toString(), request.toString());
	if(StringUtils.isBlank(json)) {
		connection.sendRequest(request, client.createClientCallback(reference, latch));
	} else {
              request.getRequestHeaders().put(Headers.TRANSFER_ENCODING, "chunked");
		connection.sendRequest(request, client.createClientCallback(reference, latch, json));
	}

	latch.await();
	reqCounter.getAndIncrement();
	logger.trace("The response got from consul: {} = {}", uri.toString(), reference.get().toString());
	return reference;
}
 
Example 8
Source Project: light-rest-4j   Source File: StyleParameterDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
default String getFirst(Deque<String> values, String key) {
	if (null!=values) {
		return StringUtils.trimToEmpty(values.peekFirst());
	}
	
	return StringUtils.EMPTY;
}
 
Example 9
Source Project: light-rest-4j   Source File: StyleParameterDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
default Map<String, String> asMap(String str, String delimiter) {
	if (StringUtils.isBlank(str)) {
		return Collections.emptyMap();
	}
	
	Map<String, String> valueMap = new HashMap<>();
	
	if (!str.contains(delimiter)) {
		valueMap.put(str, StringUtils.EMPTY);
	}else {
		String[] items = str.split("\\"+delimiter);
		
		int len = items.length/2;
		
		int keyIndex = 0;
		int valueIndex = 0;
		
		for (int i=0; i<len; ++i) {
			keyIndex = 2*i;
			valueIndex = 2*i + 1;
			
			valueMap.put(items[keyIndex], items[valueIndex]);
		}
		
		if (valueIndex<items.length-1) {
			valueMap.put(items[items.length-1], StringUtils.EMPTY);
		}
	}
	
	return valueMap;
}
 
Example 10
Source Project: light-rest-4j   Source File: StyleParameterDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
default String trimStart(String str, String start) {
	if (StringUtils.isNotBlank(str) && StringUtils.isNotBlank(start) && str.startsWith(start)) {
		int pos = start.length();
		
		return str.substring(pos);
	}
	
	return str;
}
 
Example 11
Source Project: light-rest-4j   Source File: StyleParameterDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
default String replace(String str, String target, String replacement) {
	if (StringUtils.isNotBlank(str)) {
		return str.replace(target, replacement);
	}
	
	return str;
}
 
Example 12
Source Project: light-rest-4j   Source File: HeaderParameterDeserializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StyleParameterDeserializer getStyleDeserializer(String style) {
	if (StringUtils.isNotBlank(style) && !SIMPLE.equalsIgnoreCase(style)) {
		return null;
	}
	
	return new StyleParameterDeserializer() {

		@Override
		public Object deserialize(HttpServerExchange exchange, Parameter parameter, 
				ValueType valueType,
				boolean exploade) {
			Collection<String> values = exchange.getRequestHeaders().get(new HttpString(parameter.getName()));
			
			if (ValueType.ARRAY == valueType) {
				List<String> valueList = new ArrayList<>();
				
				values.forEach(v->valueList.addAll(asList(v, Delimiters.COMMA)));
				
				return valueList;			
			}else if (ValueType.OBJECT == valueType) {
				Map<String, String> valueMap = new HashMap<>();
				values.forEach(v->valueMap.putAll(exploade?asExploadeMap(v, Delimiters.COMMA):asMap(v, Delimiters.COMMA)));
				
				return valueMap;
			}
			
			return null;
		}
		
	};
}
 
Example 13
Source Project: light-4j   Source File: HttpURL.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the last URL path segment without the query string.
 * If there are segment to return,
 * an empty string will be returned instead.
 * @return the last URL path segment
 */
public String getLastPathSegment() {
    if (StringUtils.isBlank(path)) {
        return StringUtils.EMPTY;
    }
    String segment = path;
    segment = StringUtils.substringAfterLast(segment, "/");
    return segment;
}
 
Example 14
Source Project: light-4j   Source File: HttpURL.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns a string representation of this URL, properly encoded.
 * @return URL as a string
 */
@Override
public String toString() {
    StringBuilder b = new StringBuilder();
    if (StringUtils.isNotBlank(protocol)) {
        b.append(protocol);
        b.append("://");
    }
    if (StringUtils.isNotBlank(host)) {
        b.append(host);
    }
    if (!isPortDefault() && port != -1) {
        b.append(':');
        b.append(port);
    }
    if (StringUtils.isNotBlank(path)) {
        // If no scheme/host/port, leave the path as is
        if (b.length() > 0 && !path.startsWith("/")) {
            b.append('/');
        }
        b.append(encodePath(path));
    }
    if (queryString != null && !queryString.isEmpty()) {
        b.append(queryString.toString());
    }
    if (fragment != null) {
        b.append("#");
        b.append(encodePath(fragment));
    }

    return b.toString();
}
 
Example 15
Source Project: light-4j   Source File: HttpURL.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>URL-Encodes a URL path.  The entire string supplied is assumed
 * to be a URL path. Unsafe characters are percent-encoded using UTF-8
 * (as specified by W3C standard).
 * @param path path portion of a URL
 * @return encoded path
 * @since 1.7.0
 */
public static String encodePath(String path) {
    // Any characters that are not one of the following are
    // percent-encoded (including spaces):
    // a-z A-Z 0-9 . - _ ~ ! $ &amp; ' ( ) * + , ; = : @ / %
    if (StringUtils.isBlank(path)) {
        return path;
    }
    StringBuilder sb = new StringBuilder();
    for (char ch : path.toCharArray()) {
        // Space to plus sign
        if (ch == ' ') {
            sb.append("%20");
            // Valid: keep it as is.
        } else if (CharUtils.isAsciiAlphanumeric(ch)
                || ".-_~!$&'()*+,;=:@/%".indexOf(ch) != -1)  {
            sb.append(ch);
            // Invalid: encode it
        } else {
            byte[] bytes;
            bytes = Character.toString(ch).getBytes(StandardCharsets.UTF_8);
            for (byte b : bytes) {
                sb.append('%');
                int upper = (((int) b) >> 4) & 0xf;
                sb.append(Integer.toHexString(
                        upper).toUpperCase(Locale.US));
                int lower = ((int) b) & 0xf;
                sb.append(Integer.toHexString(
                        lower).toUpperCase(Locale.US));
            }
        }
    }
    return sb.toString();
}
 
Example 16
Source Project: light-4j   Source 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 17
Source Project: light-4j   Source 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 18
Source Project: light-4j   Source 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 19
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Create a new <code>URLNormalizer</code> instance.
 * </p><p>
 * Since 1.8.0, spaces in URLs are no longer converted to + automatically.
 * Use {@link #encodeNonURICharacters()} or {@link #encodeSpaces()}.
 * </p>
 * @param url the url to normalize
 */
public URLNormalizer(String url) {
    super();
    if (StringUtils.isBlank(url)) {
        throw new IllegalArgumentException("URL argument cannot be null.");
    }
    this.url = url.trim();
    // Check it is a valid URL.
    try {
        new URL(this.url);
    } catch (MalformedURLException e) {
        throw new RuntimeException("Invalid URL: " + url, e);
    }
}
 
Example 20
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Adds a trailing slash (/) right after the domain for URLs with no
 * path, before any fragment (#) or query string (?).</p>
 *
 * <p><b>Please Note:</b> Adding a trailing slash to URLs could
 * potentially break its semantic equivalence.</p>
 * <code>http://www.example.com &rarr;
 *       http://www.example.com/</code>
 * @return this instance
 * @since 1.12.0
 */
public URLNormalizer addDomainTrailingSlash() {
    String urlRoot = HttpURL.getRoot(url);
    String path = toURL().getPath();
    if (StringUtils.isNotBlank(path)) {
        // there is a path so do nothing
        return this;
    }
    String urlRootAndPath = urlRoot + "/";
    url = StringUtils.replaceOnce(url, urlRoot, urlRootAndPath);
    return this;
}
 
Example 21
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Removes any trailing slash (/) from a URL, before fragment
 * (#) or query string (?).</p>
 *
 * <p><b>Please Note:</b> Removing trailing slashes form URLs
 * could potentially break their semantic equivalence.</p>
 * <code>http://www.example.com/alice/ &rarr;
 *       http://www.example.com/alice</code>
 * @return this instance
 * @since 1.11.0
 */
public URLNormalizer removeTrailingSlash() {
    String urlRoot = HttpURL.getRoot(url);
    String path = toURL().getPath();
    String urlRootAndPath = urlRoot + path;

    if (path.endsWith("/")) {
        String newPath = StringUtils.removeEnd(path, "/");
        String newUrlRootAndPath = urlRoot + newPath;
        url = StringUtils.replaceOnce(
                url, urlRootAndPath, newUrlRootAndPath);
    }
    return this;
}
 
Example 22
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Converts <code>https</code> scheme to <code>http</code>.</p>
 * <code>https://www.example.com/ &rarr; http://www.example.com/</code>
 * @return this instance
 */
public URLNormalizer unsecureScheme() {
    Matcher m = PATTERN_SCHEMA.matcher(url);
    if (m.find()) {
        String schema = m.group(1);
        if ("https".equalsIgnoreCase(schema)) {
            url = m.replaceFirst(StringUtils.stripEnd(schema, "Ss") + "$2");
        }
    }
    return this;
}
 
Example 23
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Removes duplicate slashes.  Two or more adjacent slash ("/")
 * characters will be converted into one.</p>
 * <code>http://www.example.com/foo//bar.html
 *       &rarr; http://www.example.com/foo/bar.html </code>
 * @return this instance
 */
public URLNormalizer removeDuplicateSlashes() {
    String urlRoot = HttpURL.getRoot(url);
    String path = toURL().getPath();
    String urlRootAndPath = urlRoot + path;
    String newPath = path.replaceAll("/{2,}", "/");
    String newUrlRootAndPath = urlRoot + newPath;
    url = StringUtils.replaceOnce(url, urlRootAndPath, newUrlRootAndPath);
    return this;
}
 
Example 24
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Removes "www." domain name prefix.</p>
 * <code>http://www.example.com/ &rarr; http://example.com/</code>
 * @return this instance
 */
public URLNormalizer removeWWW() {
    String host = toURL().getHost();
    String newHost = StringUtils.removeStartIgnoreCase(host, "www.");
    url = StringUtils.replaceOnce(url, host, newHost);
    return this;
}
 
Example 25
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Adds "www." domain name prefix.</p>
 * <code>http://example.com/ &rarr; http://www.example.com/</code>
 * @return this instance
 */
public URLNormalizer addWWW() {
    String host = toURL().getHost();
    if (!host.toLowerCase().startsWith("www.")) {
        url = StringUtils.replaceOnce(url, host, "www." + host);
    }
    return this;
}
 
Example 26
Source Project: light-4j   Source 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 27
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>Removes trailing question mark ("?").</p>
 * <code>http://www.example.com/display? &rarr;
 *       http://www.example.com/display </code>
 * @return this instance
 */
public URLNormalizer removeTrailingQuestionMark() {
    if (url.endsWith("?") && StringUtils.countMatches(url, "?") == 1) {
        url = StringUtils.removeEnd(url, "?");
    }
    return this;
}
 
Example 28
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the normalized URL as {@link URI}.
 * @return URI
 */
public URI toURI() {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    return HttpURL.toURI(url);
}
 
Example 29
Source Project: light-4j   Source File: URLNormalizer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the normalized URL as {@link URL}.
 * @return URI
 */
public URL toURL() {
    if (StringUtils.isBlank(url)) {
        return null;
    }
    try {
        return new URL(url);
    } catch (MalformedURLException e) {
        logger.info("URL does not appear to be valid and cannot be parsed:"
                + url, e);
        return null;
    }
}
 
Example 30
Source Project: light-4j   Source File: BodyHandler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Check the header starts with application/json and parse it into map or list
 * based on the first character "{" or "[". Otherwise, check the header starts
 * with application/x-www-form-urlencoded or multipart/form-data and parse it
 * into formdata
 *
 * @param exchange HttpServerExchange
 * @throws Exception Exception
 */
@Override
public void handleRequest(final HttpServerExchange exchange) throws Exception {
    // parse the body to map or list if content type is application/json
    String contentType = exchange.getRequestHeaders().getFirst(Headers.CONTENT_TYPE);
    if (contentType != null) {
        if (exchange.isInIoThread()) {
            exchange.dispatch(this);
            return;
        }
        exchange.startBlocking();
        try {
            if (contentType.startsWith("application/json")) {
                InputStream inputStream = exchange.getInputStream();
                String unparsedRequestBody = StringUtils.inputStreamToString(inputStream, StandardCharsets.UTF_8);
                // attach the unparsed request body into exchange if the cacheRequestBody is enabled in body.yml
                if (config.isCacheRequestBody()) {
                    exchange.putAttachment(REQUEST_BODY_STRING, unparsedRequestBody);
                }
                // attach the parsed request body into exchange if the body parser is enabled
                attachJsonBody(exchange, unparsedRequestBody);
            } else if (contentType.startsWith("multipart/form-data") || contentType.startsWith("application/x-www-form-urlencoded")) {
                // attach the parsed request body into exchange if the body parser is enabled
                attachFormDataBody(exchange);
            }
        } catch (IOException e) {
            logger.error("IOException: ", e);
            setExchangeStatus(exchange, CONTENT_TYPE_MISMATCH, contentType);
            return;
        }
    }
    Handler.next(exchange, next);
}