下面列出了org.springframework.util.StringUtils#split ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public QueryParameter queryParameter(String key) {
String query = this.result.getUrl().getRawQuery();
if (query == null) {
return null;
}
List<String> values = new ArrayList<>();
String[] strings = StringUtils.split(query, "&");
if (strings == null) {
return null;
}
for (String name : strings) {
if (name.equals(key)) {
values.add("");
}
else if (name.startsWith(key + "=")) {
values.add(name.substring(name.indexOf("=") + 1));
}
}
if (values.isEmpty()) {
return null;
}
return new QueryParameter(key, values);
}
@Nullable
/* for testing */ static LinkedCaseInsensitiveMap<String> splitIntoCaseInsensitiveMap(
String[] pairs) {
if (ObjectUtils.isEmpty(pairs)) {
return null;
}
LinkedCaseInsensitiveMap<String> result = new LinkedCaseInsensitiveMap<>();
for (String element : pairs) {
String[] splittedElement = StringUtils.split(element, "=");
if (splittedElement == null) {
continue;
}
result.put(splittedElement[0].trim(), splittedElement[1].trim());
}
return result;
}
public static String decodeSecretId(String authHeader) {
if (authHeader == null || authHeader.length() < HEADER_AUTH_PREFIX.length()) {
throw new IllegalArgumentException("Unrecognized Authorization header.");
}
String base64Final = authHeader.substring(HEADER_AUTH_PREFIX.length());
String usernameN64 = null;
try {
usernameN64 = new String(Base64.decodeBase64(base64Final.getBytes("UTF-8")));
}
catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Unrecognized Authorization header.");
}
String[] array = StringUtils.split(usernameN64, ":");
if (array == null || array.length != 2) {
throw new IllegalArgumentException("Unrecognized Authorization header.");
}
return array[0];
}
private static GrantedAuthority parseAuthority(String token, String defaultTenant) {
String[] arr = StringUtils.split(token, "@");
String name;
String tenant;
if(arr == null) {
name = token;
tenant = defaultTenant;
} else {
name = arr[0];
tenant = arr[1];
}
return Authorities.fromName(name, tenant);
}
/**
* Extract keys for looking up a {@link TextEncryptor} from the input text in the form
* of a prefix of zero or many <code>{name:value}</code> pairs. The name and profiles
* properties are always added to the keys (replacing any provided in the inputs).
* @param name application name
* @param profiles list of profiles
* @param text text to cipher
* @return encryptor keys
*/
public Map<String, String> getEncryptorKeys(String name, String profiles,
String text) {
Map<String, String> keys = new LinkedHashMap<String, String>();
text = removeEnvironmentPrefix(text);
keys.put(NAME, name);
keys.put(PROFILES, profiles);
if (text.contains(ESCAPE)) {
text = text.substring(0, text.indexOf(ESCAPE));
}
String[] tokens = StringUtils.split(text, "}");
while (tokens != null) {
String token = tokens[0].trim();
if (token.startsWith("{")) {
String key = "";
String value = "";
if (token.contains(":") && !token.endsWith(":")) {
key = token.substring(1, token.indexOf(":"));
value = token.substring(token.indexOf(":") + 1);
}
else {
key = token.substring(1);
}
keys.put(key, value);
}
text = tokens[1];
tokens = StringUtils.split(text, "}");
}
return keys;
}
private void authType(MockHttpServletRequest request) {
String authorization = header("Authorization");
String[] authSplit = StringUtils.split(authorization, ": ");
if (authSplit != null) {
request.setAuthType(authSplit[0]);
}
}
private List<RedisNode> createSentinels(SofaDashboardRedisProperties.Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<>();
for (String node : sentinel.getNodes()) {
try {
String[] parts = StringUtils.split(node, ":");
Assert.state(parts.length == 2, "Must be defined as 'host:port'");
nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
} catch (RuntimeException ex) {
throw new IllegalStateException("Invalid redis sentinel " + "property '" + node
+ "'", ex);
}
}
return nodes;
}
public long[] getHeartbeat() {
String rawValue = getFirstNativeHeader(STOMP_HEARTBEAT_HEADER);
String[] rawValues = StringUtils.split(rawValue, ",");
if (rawValues == null) {
return Arrays.copyOf(DEFAULT_HEARTBEAT, 2);
}
return new long[] {Long.valueOf(rawValues[0]), Long.valueOf(rawValues[1])};
}
/**
* Get the heartbeat header.
*/
@Nullable
public long[] getHeartbeat() {
String rawValue = getFirst(HEARTBEAT);
String[] rawValues = StringUtils.split(rawValue, ",");
if (rawValues == null) {
return null;
}
return new long[] {Long.valueOf(rawValues[0]), Long.valueOf(rawValues[1])};
}
private void authType(MockHttpServletRequest request) {
String authorization = header("Authorization");
String[] authSplit = StringUtils.split(authorization, ": ");
if (authSplit != null) {
request.setAuthType(authSplit[0]);
}
}
private void refresh() {
// 格式 |app1=100|app2=200|app3=300| 表示这3个app的限流是100,200,300
String str = configuration.getString(RATELIMIT_CONFIGS, "");
Map<String, RateLimiterWrapper> map = new ConcurrentHashMap<>();
Map<String, Integer> appLimitMap = new HashMap<>();
for (String item : SPLITTER.split(str)) {
String[] ss = StringUtils.split(item, "=");
if (ss.length != 2) {
LOGGER.warn("invalid config {}", item);
} else {
RateLimiterWrapper w = new RateLimiterWrapper();
int limit = Integer.parseInt(ss[1]);
// <0 的值认为是不限速
if (limit < 0) {
w.unlimited = true;
} else {
w.rateLimiter = RateLimiter.create(limit);
}
appLimitMap.put(ss[0], limit);
map.put(ss[0], w);
}
}
this.defaultRatePerSeconds = configuration.getInt(RATELIMIT_DEFAULT, DEFAULT_RATE_LIMIT);
// 这里直接重建一个map 不再原来的基础上改, 无需实时反映, 因此这个变量不是volatile
this.map = map;
this.appLimitMap = appLimitMap;
}
/**
* 从配置文件中读取参数 将其内容注入到map中
*
* @return: void
* @author: fruiqi
* @date: 19-6-14 下午2:35
*/
public void setKeyAndExpires(String expires) {
keyAndExpires = new ConcurrentHashMap();
String[] split = StringUtils.split(expires, ",");
for (String keyAndValue : split) {
String[] values = StringUtils.split(keyAndValue, ":");
keyAndExpires.put(values[0].trim(), Long.parseLong(values[1].trim()));
}
}
private Map<String, String> parseParams(String queryString) {
Map<String, String> params = new HashMap<String, String>();
String[] parts = StringUtils.delimitedListToStringArray(queryString, "&");
for (String part : parts) {
String[] nameAndValue = StringUtils.split(part, "=");
params.put(StringUtils.trimAllWhitespace(nameAndValue[0]),
StringUtils.trimAllWhitespace(nameAndValue[1]));
}
return params;
}
private List<RedisNode> createSentinels(String sentinelNodes) {
List<RedisNode> sentinels = new ArrayList<RedisNode>();
for (String node : StringUtils.commaDelimitedListToStringArray(sentinelNodes)) {
try {
String[] parts = StringUtils.split(node, ":");
Assert.state(parts.length == 2, "Must be defined as 'host:port'");
sentinels.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
}
catch (RuntimeException ex) {
throw new IllegalStateException("Invalid redis sentinel "
+ "property '" + node + "'", ex);
}
}
return sentinels;
}
@Bean
public JedisPool getPool(){
JedisPoolConfig config = new JedisPoolConfig();
//pool中最大连接数(若赋值为-1,则表示不限制)
//如果pool已分配完所有jedis实例,则此时池状态为exhausted(耗尽)
config.setMaxTotal(this.maxTotal);
//pool允许最大空闲的连接数
config.setMaxIdle(this.maxIdle);
//pool确保最少空闲的连接数
config.setMinIdle(this.minIdle);
//pool用尽后,调用者是否要等待(默认值为true,只有true时下面的maxWaitMillis才会生效)
config.setBlockWhenExhausted(true);
//pool连接用尽后,调用者的最大等待时间,超过等待时间则直接抛出JedisConnectionException(单位为毫秒,默认值为-1,标识永不超时)
config.setMaxWaitMillis(this.maxWaitMillis);
//借用连接从pool时是否检查连接可用性(默认值为false),业务量很大时建议设为false(多一次ping的开销)
config.setTestOnBorrow(false);
//归还连接给pool时是否检查连接可用性(默认值为false),业务量很大时建议设为false(多一次ping的开销)
config.setTestOnReturn(false);
//List<JedisShardInfo> nodes = new ArrayList<>();
//for(String node : this.getNodes()){
// try{
// String[] parts = StringUtils.split(node, ":");
// Assert.state(parts.length==2, "redis node shoule be defined as 'host:port', not '" + Arrays.toString(parts) + "'");
// nodes.add(new JedisShardInfo(parts[0], Integer.parseInt(parts[1]), this.connectionTimeout));
// }catch(RuntimeException e){
// throw new IllegalStateException("Invalid redis cluster nodes property '" + node + "'", e);
// }
//}
//return new ShardedJedisPool(config, nodes);
//这是传URI(带上密码)的方式
//URI uri = URI.create("redis://redis:[email protected]:6379");
//JedisPool pool = new JedisPool(config, uri, this.connectionTimeout);
//这是普通host和port的方式
String[] parts = StringUtils.split(this.nodes.get(0), ":");
JedisPool pool = new JedisPool(config, parts[0], Integer.parseInt(parts[1]), this.connectionTimeout, this.password);
//预热
for(int i=0; i<this.minIdle; i++){
Jedis jedis = pool.getResource();
jedis.ping();
jedis.close();
}
return pool;
}
public String getProperty(String property) {
if (property.contains(".")) {
return StringUtils.split(property, ".")[1];
}
return property;
}
static String[] unpack(String strs) {
return StringUtils.split(strs, ",");
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Path expression = null;
if (fieldName.contains(".")) {
System.out.println(root);
String[] names = StringUtils.split(fieldName, ".");
expression = root.get(names[0]);
for (int i = 1; i < names.length; i++) {
expression = expression.get(names[i]);
}
} else {
expression = root.get(fieldName);
}
switch (operator) {
case EQ:
return builder.equal(expression, value);
case NE:
return builder.notEqual(expression, value);
case LIKE:
return builder.like((Expression<String>) expression, "%" + value + "%");
case RLIKE:
return builder.like((Expression<String>) expression, value + "%");
case LLIKE:
return builder.like((Expression<String>) expression, value + "%");
case LT:
return builder.lessThan(expression, (Comparable) value);
case GT:
return builder.greaterThan(expression, (Comparable) value);
case LTE:
return builder.lessThanOrEqualTo(expression, (Comparable) value);
case GTE:
return builder.greaterThanOrEqualTo(expression, (Comparable) value);
case ISNULL:
return builder.isNull(expression);
case NOTNULL:
return builder.isNotNull(expression);
case IN:
return builder.in(expression);
default:
return null;
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public Predicate toPredicate(Root<?> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Path expression = null;
if (fieldName.contains(".")) {
System.out.println(root);
String[] names = StringUtils.split(fieldName, ".");
expression = root.get(names[0]);
for (int i = 1; i < names.length; i++) {
expression = expression.get(names[i]);
}
} else {
expression = root.get(fieldName);
}
switch (operator) {
case EQ:
return builder.equal(expression, value);
case NE:
return builder.notEqual(expression, value);
case LIKE:
return builder.like((Expression<String>) expression, "%" + value + "%");
case RLIKE:
return builder.like((Expression<String>) expression, value + "%");
case LLIKE:
return builder.like((Expression<String>) expression, value + "%");
case LT:
return builder.lessThan(expression, (Comparable) value);
case GT:
return builder.greaterThan(expression, (Comparable) value);
case LTE:
return builder.lessThanOrEqualTo(expression, (Comparable) value);
case GTE:
return builder.greaterThanOrEqualTo(expression, (Comparable) value);
case ISNULL:
return builder.isNull(expression);
case NOTNULL:
return builder.isNotNull(expression);
default:
return null;
}
}
/**
* Approximates Eureka zones from a host name. This method approximates the zone to be
* everything after the first "." in the host name.
* @param host The host name to extract the host name from
* @return The approximate zone
*/
public static String extractApproximateZone(String host) {
String[] split = StringUtils.split(host, ".");
return split == null ? host : split[1];
}