ScriptRouter extends AbstractRouter { @Override @SuppressWarnings("unchecked") public <T> List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation) throws RpcException { try { List<Invoker<T>> invokersCopy = new ArrayList<Invoker<T>>(invokers); Compilable compilable = (Compilable) engine; Bindings bindings = engine.createBindings(); bindings.put("invokers", invokersCopy); bindings.put("invocation", invocation); bindings.put("context", RpcContext.getContext()); CompiledScript function = compilable.compile(rule); Object obj = function.eval(bindings); if (obj instanceof Invoker[]) { invokersCopy = Arrays.asList((Invoker<T>[]) obj); } else if (obj instanceof Object[]) { invokersCopy = new ArrayList<Invoker<T>>(); for (Object inv : (Object[]) obj) { invokersCopy.add((Invoker<T>) inv); } } else { invokersCopy = (List<Invoker<T>>) obj; } return invokersCopy; } catch (ScriptException e) { logger.error("route error , rule has been ignored. rule: " + rule + ", method:" + invocation.getMethodName() + ", url: " + RpcContext.getContext().getUrl(), e); return invokers; } } ScriptRouter(URL url); @Override @SuppressWarnings("unchecked") List<Invoker<T>> route(List<Invoker<T>> invokers, URL url, Invocation invocation);  }
@Test public void testRoute_ReturnAll() { Router router = new ScriptRouterFactory().getRouter(getRouteUrl("function route(op1,op2){return op1} route(invokers)")); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); invokers.add(new MockInvoker<String>()); List<Invoker<String>> fileredInvokers = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation()); Assert.assertEquals(invokers, fileredInvokers); }
@Test public void testRoute_PickInvokers() { String rule = "var result = new java.util.ArrayList(invokers.size());" + "for (i=0;i<invokers.size(); i++){ " + "if (invokers.get(i).isAvailable()) {" + "result.add(invokers.get(i)) ;" + "}" + "} ; " + "return result;"; String script = "function route(invokers,invocation,context){" + rule + "} route(invokers,invocation,context)"; Router router = new ScriptRouterFactory().getRouter(getRouteUrl(script)); List<Invoker<String>> invokers = new ArrayList<Invoker<String>>(); Invoker<String> invoker1 = new MockInvoker<String>(false); Invoker<String> invoker2 = new MockInvoker<String>(true); Invoker<String> invoker3 = new MockInvoker<String>(true); invokers.add(invoker1); invokers.add(invoker2); invokers.add(invoker3); List<Invoker<String>> fileredInvokers = router.route(invokers, invokers.get(0).getUrl(), new RpcInvocation()); Assert.assertEquals(2, fileredInvokers.size()); Assert.assertEquals(invoker2, fileredInvokers.get(0)); Assert.assertEquals(invoker3, fileredInvokers.get(1)); }