Java Code Examples for com.networknt.utility.StringUtils#isBlank()
The following examples show how to use
com.networknt.utility.StringUtils#isBlank() .
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: URLNormalizer.java From light-4j with Apache License 2.0 | 6 votes |
/** * <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 * → 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 2
Source File: ConsulClientImpl.java From light-4j with Apache License 2.0 | 6 votes |
/** * 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 3
Source File: StyleParameterDeserializer.java From light-rest-4j with Apache License 2.0 | 5 votes |
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 4
Source File: HttpURL.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 5
Source File: HttpURL.java From light-4j with Apache License 2.0 | 5 votes |
/** * <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 . - _ ~ ! $ & ' ( ) * + , ; = : @ / % 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 6
Source File: QueryString.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 7
Source File: QueryString.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 8
Source File: URLNormalizer.java From light-4j with Apache License 2.0 | 5 votes |
/** * <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 9
Source File: URLNormalizer.java From light-4j with Apache License 2.0 | 5 votes |
/** * Returns the normalized URL as {@link URI}. * @return URI */ public URI toURI() { if (StringUtils.isBlank(url)) { return null; } return HttpURL.toURI(url); }
Example 10
Source File: URLNormalizer.java From light-4j with Apache License 2.0 | 5 votes |
/** * 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 11
Source File: TLSConfig.java From light-4j with Apache License 2.0 | 5 votes |
@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 12
Source File: PathParameterDeserializer.java From light-rest-4j with Apache License 2.0 | 4 votes |
@Override public Object deserialize(HttpServerExchange exchange, Parameter parameter, ValueType valueType, boolean exploade) { Collection<String> values = exchange.getPathParameters().get(parameter.getName()); String delimiter = exploade?Delimiters.SEMICOLON:Delimiters.COMMA; String start = String.format("%s%s=", Delimiters.SEMICOLON, parameter.getName()); if (ValueType.PRIMITIVE == valueType) { StringBuilder builder = new StringBuilder(); values.forEach(v->builder.append(trimStart(v, start))); return builder.toString(); }else if (ValueType.ARRAY == valueType) { List<String> valueList = new ArrayList<>(); if (!exploade) { values.forEach(v->valueList.addAll(asList(trimStart(v, start), delimiter))); }else { String prefix = String.format("%s=", parameter.getName()); values.forEach(v->valueList.addAll(asList(replace(trimStart(v, Delimiters.SEMICOLON), prefix,StringUtils.EMPTY), delimiter))); } if (StringUtils.isBlank(valueList.get(valueList.size()-1))) { // this is a undertow-specific trick. // undertow parses matrix style path parameters and removes path parameters from request path // as a result, a space is added by com.networknt.handler.Handler.start() valueList.remove(valueList.size()-1); } return valueList; }else if (ValueType.OBJECT == valueType) { Map<String, String> valueMap = new HashMap<>(); if (!exploade) { values.forEach(v->valueMap.putAll(asMap(v, delimiter))); }else { Schema schema = parameter.getSchema(); String requestURI = exchange.getRequestURI(); schema.getProperties().keySet().forEach(k->valueMap.put(k, getValue(k, requestURI))); } return valueMap; } return null; }
Example 13
Source File: ConsulClientImpl.java From light-4j with Apache License 2.0 | 4 votes |
/** * to lookup health services based on serviceName, * if lastConsulIndex == 0, will get result right away. * if lastConsulIndex != 0, will establish a long query with consul with {@link #wait} seconds. * @param serviceName service name * @param tag tag that is used for filtering * @param lastConsulIndex last consul index * @param token consul token for security * @return null if serviceName is blank */ @Override public ConsulResponse<List<ConsulService>> lookupHealthService(String serviceName, String tag, long lastConsulIndex, String token) { ConsulResponse<List<ConsulService>> newResponse = null; if(StringUtils.isBlank(serviceName)) { return null; } ConsulConnection connection = getConnection(serviceName + Thread.currentThread().getId()); String path = "/v1/health/service/" + serviceName + "?passing&wait="+wait+"&index=" + lastConsulIndex; if(tag != null) { path = path + "&tag=" + tag; } logger.trace("path = {}", path); try { AtomicReference<ClientResponse> reference = connection.send(Methods.GET, path, token, null); int statusCode = reference.get().getResponseCode(); if(statusCode >= UNUSUAL_STATUS_CODE){ throw new Exception("Failed to unregister on Consul: " + statusCode); } else { String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY); List<Map<String, Object>> services = Config.getInstance().getMapper().readValue(body, new TypeReference<List<Map<String, Object>>>(){}); List<ConsulService> ConsulServcies = new ArrayList<>( services.size()); for (Map<String, Object> service : services) { ConsulService newService = convertToConsulService((Map<String,Object>)service.get("Service")); ConsulServcies.add(newService); } if (!ConsulServcies.isEmpty()) { newResponse = new ConsulResponse<>(); newResponse.setValue(ConsulServcies); newResponse.setConsulIndex(Long.parseLong(reference.get().getResponseHeaders().getFirst("X-Consul-Index"))); newResponse.setConsulLastContact(Long.parseLong(reference.get().getResponseHeaders().getFirst("X-Consul-Lastcontact"))); newResponse.setConsulKnownLeader(Boolean.parseBoolean(reference.get().getResponseHeaders().getFirst("X-Consul-Knownleader"))); } } } catch (Exception e) { logger.error("Exception:", e); } return newResponse; }
Example 14
Source File: HttpURL.java From light-4j with Apache License 2.0 | 3 votes |
/** * <p>Gets the root of a URL. That is the left part of a URL up to and * including the host name. A <code>null</code> or empty string returns * a <code>null</code> document root. * This method is a short form of:<br> * <code>new HttpURL("http://example.com/path").getRoot();</code> * </p> * @param url a URL string * @return left part of a URL up to (and including the host name * @since 1.8.0 */ public static String getRoot(String url) { if (StringUtils.isBlank(url)) { return null; } return RegExUtils.replacePattern(url, "(.*?://.*?)([/?#].*)", "$1"); }
Example 15
Source File: HttpURL.java From light-4j with Apache License 2.0 | 3 votes |
/** * <p>URL-Encodes the query string portion of a URL. The entire * string supplied is assumed to be a query string. * @param queryString URL query string * @return encoded path * @since 1.8.0 */ public static String encodeQueryString(String queryString) { if (StringUtils.isBlank(queryString)) { return queryString; } return new QueryString(queryString).toString(); }