包含通配符的equals
1场景描述
网站要实现自动化测试,但是界面上有图形验证码,所以没法自动化.
如何解决呢?
我专门为测试同事写了一个接口,用于返回图形验证码明文,比如
我返回的就是PFXa
但是这个接口不能暴露在线上,否则,你懂的....
所以我增加了一个白名单,白名单中是允许访问的ip.目前白名单只有内网ip,所以就算接口暴露在线上,别人也没法访问.
但是白名单中会有通配符,比如192.168.1.* ,因为电脑关机之后ip可能会变化
private static String[] whiteList = new String[]{"127.0.0.1", "11.1.213.200", "11.1.251.166", "11.11.62.*"};
在具体业务之前,会先校验ip是否在白名单中
if (StringUtil.isContains2(whiteList, ip) == -1) {
map.put(KEY_RESULT, false);
map.put(KEY_PARAM, "ip not in white list:" + ip);
return JSONExtension.getJsonP(map, callback);
}
2,使用正则表达式
isContains2 方法
功能:判断当前访问的ip是否在白名单中,不在,则直接报错
实现如下
public static int isContains2(String[] strArray, String j) {
int index = Constant.NEGATIVE_ONE;
if (isNullOrEmpty(strArray)) {
return index;
}
int length2 = strArray.length;
for (int ii = 0; ii < length2; ii++) {
String i = strArray[ii];
if (i == j || (equalsWildcard(j, i))) {
index = ii;
break;
}
}
return index;
}
equalsWildcard方法如下:
/***
*
* @param source
* @param regex : 含有通配符,通配符只有一个:*.<br>
* *表示任何字符,不限个数
* @return
*/
public static boolean equalsWildcard(String source,String regex){
regex=regex.replace(".", "\\.");
regex=regex.replace("*", "(.*)");//加上小括号,方便查看
// System.out.println(regex);
Pattern p = Pattern.compile("^"+regex+"$", Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(source);
return m.find();
}
对方法equalsWildcard()的单元测试
@Test
public void test_equal(){
String source="ab.d.c";
// System.out.println(regex);
org.junit.Assert.assertFalse(RegexUtil.equalsWildcard(source, ".b.d.c"));
org.junit.Assert.assertFalse(RegexUtil.equalsWildcard(source, "a..d.c"));
org.junit.Assert.assertFalse(RegexUtil.equalsWildcard(source, "a.*.d.c"));
org.junit.Assert.assertFalse(RegexUtil.equalsWildcard(source, "abad.c"));
org.junit.Assert.assertFalse(RegexUtil.equalsWildcard(source, "a*ad.c"));
org.junit.Assert.assertFalse(RegexUtil.equalsWildcard(source, "ab.d.."));
org.junit.Assert.assertTrue(RegexUtil.equalsWildcard(source, "ab.d.c"));
org.junit.Assert.assertTrue(RegexUtil.equalsWildcard(source, source));
org.junit.Assert.assertTrue(RegexUtil.equalsWildcard(source, "a*.d.c"));
org.junit.Assert.assertTrue(RegexUtil.equalsWildcard(source, "ab.*.c"));
org.junit.Assert.assertTrue(RegexUtil.equalsWildcard(source, "ab*.c"));
org.junit.Assert.assertTrue(RegexUtil.equalsWildcard(source, "ab*.d*c"));
}
equalsWildcard说明:
有两个参数:
第一个参数:要比较的字符串,没有通配符,不是正则表达式.比如访问的ip;
第二个参数:包含通配符,目前只有一个通配符:* ,匹配若干个字符