Java Code Examples for com.alibaba.dubbo.common.utils.StringUtils#isBlank()

The following examples show how to use com.alibaba.dubbo.common.utils.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: ConditionRouter.java    From dubbox-hystrix with Apache License 2.0 6 votes vote down vote up
public ConditionRouter(URL url) {
    this.url = url;
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    this.force = url.getParameter(Constants.FORCE_KEY, false);
    try {
        String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
        if (rule == null || rule.trim().length() == 0) {
            throw new IllegalArgumentException("Illegal route rule!");
        }
        rule = rule.replace("consumer.", "").replace("provider.", "");
        int i = rule.indexOf("=>");
        String whenRule = i < 0 ? null : rule.substring(0, i).trim();
        String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim();
        Map<String, MatchPair> when = StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<String, MatchPair>() : parseRule(whenRule);
        Map<String, MatchPair> then = StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule);
        // NOTE: When条件是允许为空的,外部业务来保证类似的约束条件
        this.whenCondition = when;
        this.thenCondition = then;
    } catch (ParseException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 2
Source File: ReferenceConfigCache.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public String generateKey(ReferenceConfig<?> referenceConfig) {
    String iName = referenceConfig.getInterface();
    if(StringUtils.isBlank(iName)) {
        Class<?> clazz = referenceConfig.getInterfaceClass();
        iName = clazz.getName();
    }
    if(StringUtils.isBlank(iName)) {
        throw new IllegalArgumentException("No interface info in ReferenceConfig" + referenceConfig);
    }

    StringBuilder ret = new StringBuilder();
    if(! StringUtils.isBlank(referenceConfig.getGroup())) {
        ret.append(referenceConfig.getGroup()).append("/");
    }
    ret.append(iName);
    if(! StringUtils.isBlank(referenceConfig.getVersion())) {
        ret.append(":").append(referenceConfig.getVersion());
    }
    return ret.toString();
}
 
Example 3
Source File: ReferenceConfigCache.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public String generateKey(ReferenceConfig<?> referenceConfig) {
    String iName = referenceConfig.getInterface();
    if(StringUtils.isBlank(iName)) {
        Class<?> clazz = referenceConfig.getInterfaceClass();
        iName = clazz.getName();
    }
    if(StringUtils.isBlank(iName)) {
        throw new IllegalArgumentException("No interface info in ReferenceConfig" + referenceConfig);
    }

    StringBuilder ret = new StringBuilder();
    if(! StringUtils.isBlank(referenceConfig.getGroup())) {
        ret.append(referenceConfig.getGroup()).append("/");
    }
    ret.append(iName);
    if(! StringUtils.isBlank(referenceConfig.getVersion())) {
        ret.append(":").append(referenceConfig.getVersion());
    }
    return ret.toString();
}
 
Example 4
Source File: ConditionRouter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public ConditionRouter(URL url) {
    this.url = url;
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    this.force = url.getParameter(Constants.FORCE_KEY, false);
    try {
        String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
        if (rule == null || rule.trim().length() == 0) {
            throw new IllegalArgumentException("Illegal route rule!");
        }
        rule = rule.replace("consumer.", "").replace("provider.", "");
        int i = rule.indexOf("=>");
        String whenRule = i < 0 ? null : rule.substring(0, i).trim();
        String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim();
        Map<String, MatchPair> when = StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<String, MatchPair>() : parseRule(whenRule);
        Map<String, MatchPair> then = StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule);
        // NOTE: When条件是允许为空的,外部业务来保证类似的约束条件
        this.whenCondition = when;
        this.thenCondition = then;
    } catch (ParseException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 5
Source File: ConditionRouter.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public ConditionRouter(URL url) {
    this.url = url;
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    this.force = url.getParameter(Constants.FORCE_KEY, false);
    try {
        String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
        if (rule == null || rule.trim().length() == 0) {
            throw new IllegalArgumentException("Illegal route rule!");
        }
        rule = rule.replace("consumer.", "").replace("provider.", "");
        int i = rule.indexOf("=>");
        String whenRule = i < 0 ? null : rule.substring(0, i).trim();
        String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim();
        Map<String, MatchPair> when = StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<String, MatchPair>() : parseRule(whenRule);
        Map<String, MatchPair> then = StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule);
        // NOTE: When条件是允许为空的,外部业务来保证类似的约束条件
        this.whenCondition = when;
        this.thenCondition = then;
    } catch (ParseException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 6
Source File: ReferenceConfigCache.java    From dubbox with Apache License 2.0 6 votes vote down vote up
public String generateKey(ReferenceConfig<?> referenceConfig) {
    String iName = referenceConfig.getInterface();
    if(StringUtils.isBlank(iName)) {
        Class<?> clazz = referenceConfig.getInterfaceClass();
        iName = clazz.getName();
    }
    if(StringUtils.isBlank(iName)) {
        throw new IllegalArgumentException("No interface info in ReferenceConfig" + referenceConfig);
    }

    StringBuilder ret = new StringBuilder();
    if(! StringUtils.isBlank(referenceConfig.getGroup())) {
        ret.append(referenceConfig.getGroup()).append("/");
    }
    ret.append(iName);
    if(! StringUtils.isBlank(referenceConfig.getVersion())) {
        ret.append(":").append(referenceConfig.getVersion());
    }
    return ret.toString();
}
 
Example 7
Source File: ConditionRouter.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
public ConditionRouter(URL url) {
    this.url = url;
    this.priority = url.getParameter(Constants.PRIORITY_KEY, 0);
    this.force = url.getParameter(Constants.FORCE_KEY, false);
    try {
        String rule = url.getParameterAndDecoded(Constants.RULE_KEY);
        if (rule == null || rule.trim().length() == 0) {
            throw new IllegalArgumentException("Illegal route rule!");
        }
        rule = rule.replace("consumer.", "").replace("provider.", "");
        int i = rule.indexOf("=>");
        String whenRule = i < 0 ? null : rule.substring(0, i).trim();
        String thenRule = i < 0 ? rule.trim() : rule.substring(i + 2).trim();
        Map<String, MatchPair> when = StringUtils.isBlank(whenRule) || "true".equals(whenRule) ? new HashMap<String, MatchPair>() : parseRule(whenRule);
        Map<String, MatchPair> then = StringUtils.isBlank(thenRule) || "false".equals(thenRule) ? null : parseRule(thenRule);
        // NOTE: It should be determined on the business level whether the `When condition` can be empty or not.
        this.whenCondition = when;
        this.thenCondition = then;
    } catch (ParseException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
}
 
Example 8
Source File: ExtensionLoader.java    From dubbox-hystrix with Apache License 2.0 5 votes vote down vote up
/**
 * 编程方式添加新扩展点。
 *
 * @param name 扩展点名
 * @param clazz 扩展点类
 * @throws IllegalStateException 要添加扩展点名已经存在。
 */
public void addExtension(String name, Class<?> clazz) {
    getExtensionClasses(); // load classes

    if(!type.isAssignableFrom(clazz)) {
        throw new IllegalStateException("Input type " +
                clazz + "not implement Extension " + type);
    }
    if(clazz.isInterface()) {
        throw new IllegalStateException("Input type " +
                clazz + "can not be interface!");
    }

    if(!clazz.isAnnotationPresent(Adaptive.class)) {
        if(StringUtils.isBlank(name)) {
            throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
        }
        if(cachedClasses.get().containsKey(name)) {
            throw new IllegalStateException("Extension name " +
                    name + " already existed(Extension " + type + ")!");
        }

        cachedNames.put(clazz, name);
        cachedClasses.get().put(name, clazz);
    }
    else {
        if(cachedAdaptiveClass != null) {
            throw new IllegalStateException("Adaptive Extension already existed(Extension " + type + ")!");
        }

        cachedAdaptiveClass = clazz;
    }
}
 
Example 9
Source File: Register.java    From dubbo3 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
    protected String doExecute(Map<String,Object> context) throws Exception {
    	Map<String, String[]> params = request.getParameterMap();
        if (params == null || params.size() == 0) {
        	throw new IllegalArgumentException("The url parameters is null! Usage: " + request.getRequestURL().toString() + "?com.xxx.XxxService=http://" + request.getRemoteAddr() + "/xxxService?application=xxx&foo1=123");
        }
        Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            if (entry.getKey() != null && entry.getKey().length() > 0
                    && entry.getValue() != null && entry.getValue().length > 0
                    && entry.getValue()[0] != null && entry.getValue()[0].length() > 0) {
            	if (! currentUser.hasServicePrivilege(entry.getKey())) {
					throw new IllegalStateException("The user " + currentUser.getUsername() + " have no privilege of service " + entry.getKey());
				}
            	String serviceName = entry.getKey();
            	Map<String, String> url2query = CollectionUtils.split(Arrays.asList(entry.getValue()), "?");
            	// check whether url contain application info
            	for(Map.Entry<String, String> e : url2query.entrySet()) {
            	   Map<String, String> query = StringUtils.parseQueryString(e.getValue()); 
            	   String app = query.get("application");
            	   if(StringUtils.isBlank(app)) {
            	       throw new IllegalStateException("No application for service(" + serviceName + "): "
            	               + e.getKey() + "?" + e.getValue());
            	   }
            	}
                map.put(serviceName, url2query);
            }
        }
        if (map.size() > 0) {
//        	providerDAO.register(registryCache.getCurrentRegistry(), request.getRemoteAddr(), operatorAddress, operator, map, false, true);
        }
        return "Register " + map.size() + " services.";
    }
 
Example 10
Source File: Register.java    From dubbox with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
    protected String doExecute(Map<String,Object> context) throws Exception {
    	Map<String, String[]> params = request.getParameterMap();
        if (params == null || params.size() == 0) {
        	throw new IllegalArgumentException("The url parameters is null! Usage: " + request.getRequestURL().toString() + "?com.xxx.XxxService=http://" + request.getRemoteAddr() + "/xxxService?application=xxx&foo1=123");
        }
        Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            if (entry.getKey() != null && entry.getKey().length() > 0
                    && entry.getValue() != null && entry.getValue().length > 0
                    && entry.getValue()[0] != null && entry.getValue()[0].length() > 0) {
            	if (! currentUser.hasServicePrivilege(entry.getKey())) {
					throw new IllegalStateException("The user " + currentUser.getUsername() + " have no privilege of service " + entry.getKey());
				}
            	String serviceName = entry.getKey();
            	Map<String, String> url2query = CollectionUtils.split(Arrays.asList(entry.getValue()), "?");
            	// check whether url contain application info
            	for(Map.Entry<String, String> e : url2query.entrySet()) {
            	   Map<String, String> query = StringUtils.parseQueryString(e.getValue()); 
            	   String app = query.get("application");
            	   if(StringUtils.isBlank(app)) {
            	       throw new IllegalStateException("No application for service(" + serviceName + "): "
            	               + e.getKey() + "?" + e.getValue());
            	   }
            	}
                map.put(serviceName, url2query);
            }
        }
        if (map.size() > 0) {
//        	providerDAO.register(registryCache.getCurrentRegistry(), request.getRemoteAddr(), operatorAddress, operator, map, false, true);
        }
        return "Register " + map.size() + " services.";
    }
 
Example 11
Source File: ExtensionLoader.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 编程方式添加替换已有扩展点。
 *
 * @param name 扩展点名
 * @param clazz 扩展点类
 * @throws IllegalStateException 要添加扩展点名已经存在。
 * @deprecated 不推荐应用使用,一般只在测试时可以使用
 */
@Deprecated
public void replaceExtension(String name, Class<?> clazz) {
    getExtensionClasses(); // load classes

    if(!type.isAssignableFrom(clazz)) {
        throw new IllegalStateException("Input type " +
                clazz + "not implement Extension " + type);
    }
    if(clazz.isInterface()) {
        throw new IllegalStateException("Input type " +
                clazz + "can not be interface!");
    }

    if(!clazz.isAnnotationPresent(Adaptive.class)) {
        if(StringUtils.isBlank(name)) {
            throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
        }
        if(!cachedClasses.get().containsKey(name)) {
            throw new IllegalStateException("Extension name " +
                    name + " not existed(Extension " + type + ")!");
        }

        cachedNames.put(clazz, name);
        cachedClasses.get().put(name, clazz);
        cachedInstances.remove(name);
    }
    else {
        if(cachedAdaptiveClass == null) {
            throw new IllegalStateException("Adaptive Extension not existed(Extension " + type + ")!");
        }

        cachedAdaptiveClass = clazz;
        cachedAdaptiveInstance.set(null);
    }
}
 
Example 12
Source File: ExtensionLoader.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 编程方式添加新扩展点。
 *
 * @param name 扩展点名
 * @param clazz 扩展点类
 * @throws IllegalStateException 要添加扩展点名已经存在。
 */
public void addExtension(String name, Class<?> clazz) {
    getExtensionClasses(); // load classes

    if(!type.isAssignableFrom(clazz)) {
        throw new IllegalStateException("Input type " +
                clazz + "not implement Extension " + type);
    }
    if(clazz.isInterface()) {
        throw new IllegalStateException("Input type " +
                clazz + "can not be interface!");
    }

    if(!clazz.isAnnotationPresent(Adaptive.class)) {
        if(StringUtils.isBlank(name)) {
            throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
        }
        if(cachedClasses.get().containsKey(name)) {
            throw new IllegalStateException("Extension name " +
                    name + " already existed(Extension " + type + ")!");
        }

        cachedNames.put(clazz, name);
        cachedClasses.get().put(name, clazz);
    }
    else {
        if(cachedAdaptiveClass != null) {
            throw new IllegalStateException("Adaptive Extension already existed(Extension " + type + ")!");
        }

        cachedAdaptiveClass = clazz;
    }
}
 
Example 13
Source File: RouteRule.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static RouteRule parse(String rule) throws ParseException {
    if(StringUtils.isBlank(rule)) {
        throw new ParseException("Illegal blank route rule", 0);
    }
     
    final Matcher matcher = CONDITION_SEPERATOR.matcher(rule);
    if(!matcher.matches()) throw new ParseException("condition seperator => not found!", 0); 
    
    return parse(matcher.group(1), matcher.group(2));
}
 
Example 14
Source File: TraceIdFilter.java    From shield-dubbo-tracer with Apache License 2.0 5 votes vote down vote up
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
    RpcContext rpcContext = RpcContext.getContext();
    String traceId = "";
    if (rpcContext.isConsumerSide()) {
        if (StringUtils.isBlank(TraceIdUtil.getTraceId())) {
            // 根调用,生成TraceId
            traceId = TraceIdGenerator.createTraceId();
            LOGGER.debug("[TraceIdFilter-consumerSide] TraceId in TraceIdUtil is null,create new TraceId=" + traceId);
        } else {
            // 后续调用,从Rpc上下文取出并设置到线程上下文
            traceId = TraceIdUtil.getTraceId();
            LOGGER.debug("[TraceIdFilter-consumerSide] TraceId in TraceIdUtil exists,TraceId=" + traceId);
        }
        TraceIdUtil.setTraceId(traceId);
        RpcContext.getContext().setAttachment(TraceIdConst.TRACE_ID, TraceIdUtil.getTraceId());
        LOGGER.debug("[TraceIdFilter-consumerSide] set TraceId to TraceIdUtil and RpcContext,TraceId={}", traceId);
    }
    if (rpcContext.isProviderSide()) {
        // 服务提供方,从Rpc上下文获取traceId
        traceId = RpcContext.getContext().getAttachment(TraceIdConst.TRACE_ID);
        TraceIdUtil.setTraceId(traceId);
        LOGGER.debug("[TraceIdFilter-providerSide] get TraceId from RpcContext and set it to thr trace Context,TraceId={}", traceId);
    }
    Result result = invoker.invoke(invocation);
    return result;
}
 
Example 15
Source File: ExtensionLoader.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * 编程方式添加新扩展点。
 *
 * @param name 扩展点名
 * @param clazz 扩展点类
 * @throws IllegalStateException 要添加扩展点名已经存在。
 */
public void addExtension(String name, Class<?> clazz) {
    getExtensionClasses(); // load classes

    if(!type.isAssignableFrom(clazz)) {
        throw new IllegalStateException("Input type " +
                clazz + "not implement Extension " + type);
    }
    if(clazz.isInterface()) {
        throw new IllegalStateException("Input type " +
                clazz + "can not be interface!");
    }

    if(!clazz.isAnnotationPresent(Adaptive.class)) {
        if(StringUtils.isBlank(name)) {
            throw new IllegalStateException("Extension name is blank (Extension " + type + ")!");
        }
        if(cachedClasses.get().containsKey(name)) {
            throw new IllegalStateException("Extension name " +
                    name + " already existed(Extension " + type + ")!");
        }

        cachedNames.put(clazz, name);
        cachedClasses.get().put(name, clazz);
    }
    else {
        if(cachedAdaptiveClass != null) {
            throw new IllegalStateException("Adaptive Extension already existed(Extension " + type + ")!");
        }

        cachedAdaptiveClass = clazz;
    }
}
 
Example 16
Source File: RouteRule.java    From dubbox with Apache License 2.0 5 votes vote down vote up
public static RouteRule parse(String rule) throws ParseException {
    if(StringUtils.isBlank(rule)) {
        throw new ParseException("Illegal blank route rule", 0);
    }
     
    final Matcher matcher = CONDITION_SEPERATOR.matcher(rule);
    if(!matcher.matches()) throw new ParseException("condition seperator => not found!", 0); 
    
    return parse(matcher.group(1), matcher.group(2));
}
 
Example 17
Source File: RegisterController.java    From open-capacity-platform with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
    protected String doExecute(Map<String, Object> context) throws Exception {
        Map<String, String[]> params = request.getParameterMap();
        if (params == null || params.size() == 0) {
            throw new IllegalArgumentException("The url parameters is null! Usage: " + request.getRequestURL().toString() + "?com.xxx.XxxService=http://" + request.getRemoteAddr() + "/xxxService?application=xxx&foo1=123");
        }
        Map<String, Map<String, String>> map = new HashMap<String, Map<String, String>>();
        for (Map.Entry<String, String[]> entry : params.entrySet()) {
            if (entry.getKey() != null && entry.getKey().length() > 0
                    && entry.getValue() != null && entry.getValue().length > 0
                    && entry.getValue()[0] != null && entry.getValue()[0].length() > 0) {
                if (!currentUser.hasServicePrivilege(entry.getKey())) {
                    throw new IllegalStateException("The user " + currentUser.getUsername() + " have no privilege of service " + entry.getKey());
                }
                String serviceName = entry.getKey();
                Map<String, String> url2query = CollectionUtils.split(Arrays.asList(entry.getValue()), "?");
                // check whether url contain application info
                for (Map.Entry<String, String> e : url2query.entrySet()) {
                    Map<String, String> query = StringUtils.parseQueryString(e.getValue());
                    String app = query.get("application");
                    if (StringUtils.isBlank(app)) {
                        throw new IllegalStateException("No application for service(" + serviceName + "): "
                                + e.getKey() + "?" + e.getValue());
                    }
                }
                map.put(serviceName, url2query);
            }
        }
        if (map.size() > 0) {
//        	providerDAO.register(registryCache.getCurrentRegistry(), request.getRemoteAddr(), operatorAddress, operator, map, false, true);
        }
        return "RegisterController " + map.size() + " services.";
    }
 
Example 18
Source File: TracerUtils.java    From cicada with MIT License 5 votes vote down vote up
public static Long getAttachmentLong(final String value) {
  Long retLong = null;
  if (!StringUtils.isBlank(value)) {
    retLong = Long.valueOf(value);
  }

  return retLong;
}
 
Example 19
Source File: RouteRule.java    From dubbox with Apache License 2.0 4 votes vote down vote up
public static Map<String, MatchPair> parseRule(String rule)
        throws ParseException {
	Map<String, MatchPair> condition = new HashMap<String, RouteRule.MatchPair>();
    if(StringUtils.isBlank(rule)) {
        return condition;
    }        
    // 匹配或不匹配Key-Value对
    MatchPair pair = null;
    // 多个Value值
    Set<String> values = null;
    final Matcher matcher = ROUTE_PATTERN.matcher(rule);
    while (matcher.find()) { // 逐个匹配
        String separator = matcher.group(1);
        String content = matcher.group(2);
        // 表达式开始
        if (separator == null || separator.length() == 0) {
            pair = new MatchPair();
            condition.put(content, pair);
        }
        // KV开始
        else if ("&".equals(separator)) {
            if (condition.get(content) == null) {
                pair = new MatchPair();
                condition.put(content, pair);
            } else {
                condition.put(content, pair);
            }

        }
        // KV的Value部分开始
        else if ("=".equals(separator)) {
            if (pair == null)
                throw new ParseException("Illegal route rule \""
                        + rule + "\", The error char '" + separator
                        + "' at index " + matcher.start() + " before \""
                        + content + "\".", matcher.start());

            values = pair.matches;
            values.add(content);
        }
        // KV的Value部分开始
        else if ("!=".equals(separator)) {
            if (pair == null)
                throw new ParseException("Illegal route rule \""
                        + rule + "\", The error char '" + separator
                        + "' at index " + matcher.start() + " before \""
                        + content + "\".", matcher.start());

            values = pair.unmatches;
            values.add(content);
        }
        // KV的Value部分的多个条目
        else if (",".equals(separator)) { // 如果为逗号表示
            if (values == null || values.size() == 0)
                throw new ParseException("Illegal route rule \""
                        + rule + "\", The error char '" + separator
                        + "' at index " + matcher.start() + " before \""
                        + content + "\".", matcher.start());
            values.add(content);
        } else {
            throw new ParseException("Illegal route rule \"" + rule
                    + "\", The error char '" + separator + "' at index "
                    + matcher.start() + " before \"" + content + "\".", matcher.start());
        }
    }
    return condition;
}
 
Example 20
Source File: ConditionRouter.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
private static Map<String, MatchPair> parseRule(String rule)
        throws ParseException {
    Map<String, MatchPair> condition = new HashMap<String, MatchPair>();
    if (StringUtils.isBlank(rule)) {
        return condition;
    }
    // Key-Value pair, stores both match and mismatch conditions
    MatchPair pair = null;
    // Multiple values
    Set<String> values = null;
    final Matcher matcher = ROUTE_PATTERN.matcher(rule);
    while (matcher.find()) { // Try to match one by one
        String separator = matcher.group(1);
        String content = matcher.group(2);
        // Start part of the condition expression.
        if (separator == null || separator.length() == 0) {
            pair = new MatchPair();
            condition.put(content, pair);
        }
        // The KV part of the condition expression
        else if ("&".equals(separator)) {
            if (condition.get(content) == null) {
                pair = new MatchPair();
                condition.put(content, pair);
            } else {
                pair = condition.get(content);
            }
        }
        // The Value in the KV part.
        else if ("=".equals(separator)) {
            if (pair == null)
                throw new ParseException("Illegal route rule \""
                        + rule + "\", The error char '" + separator
                        + "' at index " + matcher.start() + " before \""
                        + content + "\".", matcher.start());

            values = pair.matches;
            values.add(content);
        }
        // The Value in the KV part.
        else if ("!=".equals(separator)) {
            if (pair == null)
                throw new ParseException("Illegal route rule \""
                        + rule + "\", The error char '" + separator
                        + "' at index " + matcher.start() + " before \""
                        + content + "\".", matcher.start());

            values = pair.mismatches;
            values.add(content);
        }
        // The Value in the KV part, if Value have more than one items.
        else if (",".equals(separator)) { // Should be seperateed by ','
            if (values == null || values.isEmpty())
                throw new ParseException("Illegal route rule \""
                        + rule + "\", The error char '" + separator
                        + "' at index " + matcher.start() + " before \""
                        + content + "\".", matcher.start());
            values.add(content);
        } else {
            throw new ParseException("Illegal route rule \"" + rule
                    + "\", The error char '" + separator + "' at index "
                    + matcher.start() + " before \"" + content + "\".", matcher.start());
        }
    }
    return condition;
}