com.networknt.utility.StringUtils Java Examples

The following examples show how to use com.networknt.utility.StringUtils. 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 File: PathParameterDeserializer.java    From light-rest-4j with 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 File: URLNormalizer.java    From light-4j with 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 File: URLNormalizer.java    From light-4j with 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 #4
Source File: OauthHelper.java    From light-4j with 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 #5
Source File: ConsulClientImpl.java    From light-4j with 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 #6
Source File: RequestValidator.java    From light-rest-4j with 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 #7
Source File: StyleParameterDeserializer.java    From light-rest-4j with 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 #8
Source File: URLNormalizer.java    From light-4j with 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 #9
Source File: TLSConfig.java    From light-4j with Apache License 2.0 5 votes vote down vote up
public static Set<String> resolveTrustedNames(String trustedNames){
	Set<String> nameSet = Arrays.stream(StringUtils.trimToEmpty(trustedNames).split(","))
			.filter(StringUtils::isNotBlank)
			.collect(Collectors.toSet());
	
	if (logger.isDebugEnabled()) {
		logger.debug("trusted names {}", nameSet);
	}
	
	return nameSet;
}
 
Example #10
Source File: TLSConfig.java    From light-4j with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Set<String> resolveTrustedNames(Map<String, Object> tlsMap, String groupKey){
	if (StringUtils.isBlank(groupKey) // blank key (null, empty, or white spaces)
			|| !Boolean.TRUE.equals(tlsMap.get(VERIFY_HOSTNAME))) {// hostname verification is not enabled
		return Collections.EMPTY_SET;
	}
	
	String[] levels = StringUtils.trimToEmpty(groupKey).split(TLSConfig.CONFIG_LEVEL_DELIMITER);
	
	if (levels.length<1) {//the groupKey has only '.'
		throw new InvalidGroupKeyException(groupKey);
	}
	
	Map<String, Object> innerMap = tlsMap;
	
	String level = null;
	
	for (int i=0; i<levels.length-1; ++i) {
		level = levels[i];
		innerMap = typeSafeGet(innerMap, level, Map.class, groupKey);
	}
	
	String leafLevel = levels[levels.length-1];
	String values = typeSafeGet(innerMap, leafLevel, String.class, groupKey);
	
	return resolveTrustedNames((String)values);
}
 
Example #11
Source File: URLNormalizer.java    From light-4j with 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 #12
Source File: URLNormalizer.java    From light-4j with 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 #13
Source File: URLNormalizer.java    From light-4j with 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 #14
Source File: URLNormalizer.java    From light-4j with 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 #15
Source File: URLNormalizer.java    From light-4j with 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 #16
Source File: StyleParameterDeserializer.java    From light-rest-4j with 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 #17
Source File: URLNormalizer.java    From light-4j with 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 #18
Source File: Mask.java    From light-4j with Apache License 2.0 5 votes vote down vote up
private static String replaceWithMask(String stringToBeMasked, char maskingChar, String regex) {
    if (stringToBeMasked.length() == 0) {
        return stringToBeMasked;
    }
    String replacementString = "";
    String padGroup;
    if (!StringUtils.isEmpty(regex)) {
        try {
            Pattern pattern = patternCache.get(regex);
            if (pattern == null) {
                pattern = Pattern.compile(regex);
                patternCache.put(regex, pattern);
            }
            Matcher matcher = pattern.matcher(stringToBeMasked);
            if (matcher.matches()) {
                String currentGroup;
                for (int i = 0; i < matcher.groupCount(); i++) {
                    currentGroup = matcher.group(i + 1);
                    padGroup = StringUtils.rightPad("", currentGroup.length(), maskingChar);
                    stringToBeMasked = StringUtils.replace(stringToBeMasked, currentGroup, padGroup, 1);
                }
                replacementString = stringToBeMasked;
            }
        } catch (Exception e) {
            replacementString = StringUtils.rightPad("", stringToBeMasked.length(), maskingChar);
        }
    } else {
        replacementString = StringUtils.rightPad("", stringToBeMasked.length(), maskingChar);
    }
    return replacementString;
}
 
Example #19
Source File: URLNormalizer.java    From light-4j with 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 #20
Source File: URLNormalizer.java    From light-4j with 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 #21
Source File: BodyHandler.java    From light-4j with 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);
}
 
Example #22
Source File: UrlDumper.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * put this.url to result
 * @param result a Map you want to put dumping info to.
 */
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
    if(StringUtils.isNotBlank(this.url)) {
        result.put(DumpConstants.URL, this.url);
    }
}
 
Example #23
Source File: StatusCodeDumper.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * put this.statusCodeResult to result
 * @param result a Map you want to put dumping info to.
 */
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
    if(StringUtils.isNotBlank(this.statusCodeResult)) {
        result.put(DumpConstants.STATUS_CODE, this.statusCodeResult);
    }
}
 
Example #24
Source File: BodyDumper.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 * put bodyContent to result
 * @param result a Map<String, Object> you want to put dumping info to.
 */
@Override
protected void putDumpInfoTo(Map<String, Object> result) {
    if(StringUtils.isNotBlank(this.bodyContent)) {
        result.put(DumpConstants.BODY, this.bodyContent);
    }
}
 
Example #25
Source File: DumpHelper.java    From light-4j with Apache License 2.0 5 votes vote down vote up
/**
 *
 * @param result a Map<String, Object> contains http request/response info which needs to be logged.
 * @param loggerFunc Consuer<T> getLoggerFuncBasedOnLevel(config.getLogLevel())
 */
private static void logResultUsingJson(Map<String, Object> result, Consumer<String> loggerFunc) {
    ObjectMapper mapper = new ObjectMapper();
    String resultJson = "";
    try {
        resultJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
    } catch (JsonProcessingException e) {
        logger.error(e.toString());
    }
    if(StringUtils.isNotBlank(resultJson)){
        loggerFunc.accept("Dump Info:\n" + resultJson);
    }
}
 
Example #26
Source File: URLNormalizer.java    From light-4j with 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 #27
Source File: HeaderParameterDeserializer.java    From light-rest-4j with 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 #28
Source File: StyleParameterDeserializer.java    From light-rest-4j with 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 #29
Source File: StyleParameterDeserializer.java    From light-rest-4j with 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 #30
Source File: HttpURL.java    From light-4j with 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;
}