本文实现根据路由表适配最优的号段,选择路由器。选择路由的规则:
1、号段num和网元都不能重复
2、号段num不能重复
3、选择号码适配长度最长的网元为路由目的地
RouterService.java
package com.discover.router;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
/**
* 简易路由器
* @author Administrator
*
*/
public class RouterService {
HashMap routerInfoMap = new HashMap();
/**
* 载入路由表规则:
* 1、号段num和网元都不能重复
* 2、号段num不能重复
* @param routerRule 路由规则
* @return
*/
public boolean loadRule(String routerRule) {
try {
Document doc = DocumentHelper.parseText(routerRule);
Element routertable = doc.getRootElement();
Iterator routerIterator = routertable.elementIterator("router");
while(routerIterator.hasNext())
{
Element router = (Element) routerIterator.next();
String num = router.elementTextTrim("num");
String net = router.elementTextTrim("net");
if(num.isEmpty()||net.isEmpty())
{
return false;
}
if(routerInfoMap.containsKey(num))
{
return false;
}
else {
routerInfoMap.put(num, net);
}
}
} catch (Exception e) {
return false;
}
return true;
}
/**
* 选择路由
* 1、选择号码适配长度最长的网元为路由目的地
* @param phone 电话号码
* @return
*/
public String selRouter(String phone) {
Iterator iterator = routerInfoMap.entrySet().iterator();
String num = "";
String net = "";
while (iterator.hasNext()) {
Entry entry = (Entry)iterator.next();
String key = entry.getKey();
if(phone.indexOf(key)>-1)
{
if(key.length()>num.length())
{
net = entry.getValue();
}
}
}
return net;
}
}
采用JUnit对路由模拟器进行测试
TestRouterService.java
package com.discover.test;
import junit.framework.TestCase;
import com.discover.router.RouterService;
/**
* @author Administrator
*
*/
public class TestRouterService extends TestCase {
public void testcase1() {
RouterService routerService = new RouterService();
String routerRule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"router1";
assertEquals(false, routerService.loadRule(routerRule));
}
public void testcase2() {
RouterService routerService = new RouterService();
String routerRule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"13567";
assertEquals(false, routerService.loadRule(routerRule));
}
public void testcase3() {
RouterService routerService = new RouterService();
String routerRule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"13567router1"
+"13567router2";
assertEquals(false, routerService.loadRule(routerRule));
}
public void testcase4() {
RouterService routerService = new RouterService();
String routerRule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"13562router1";
assertEquals(true, routerService.loadRule(routerRule));
assertEquals("router1", routerService.selRouter("13562779908"));
}
public void testcase5() {
RouterService routerService = new RouterService();
String routerRule = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"13562router1"
+"135627router2";
assertEquals(true, routerService.loadRule(routerRule));
assertEquals("router2", routerService.selRouter("13562779908"));
}
}
测试结果: