ContextFilter implements Filter, Filter.Listener { @Override public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException { Map<String, Object> attachments = invocation.getObjectAttachments(); if (attachments != null) { Map<String, Object> newAttach = new HashMap<>(attachments.size()); for (Map.Entry<String, Object> entry : attachments.entrySet()) { String key = entry.getKey(); if (!UNLOADING_KEYS.contains(key)) { newAttach.put(key, entry.getValue()); } } attachments = newAttach; } RpcContext context = RpcContext.getContext(); context.setInvoker(invoker) .setInvocation(invocation) .setLocalAddress(invoker.getUrl().getHost(), invoker.getUrl().getPort()); String remoteApplication = (String) invocation.getAttachment(REMOTE_APPLICATION_KEY); if (StringUtils.isNotEmpty(remoteApplication)) { context.setRemoteApplicationName(remoteApplication); } else { context.setRemoteApplicationName((String) context.getAttachment(REMOTE_APPLICATION_KEY)); } long timeout = RpcUtils.getTimeout(invocation, -1); if (timeout != -1) { context.set(TIME_COUNTDOWN_KEY, TimeoutCountDown.newCountDown(timeout, TimeUnit.MILLISECONDS)); } if (attachments != null) { if (context.getObjectAttachments() != null) { context.getObjectAttachments().putAll(attachments); } else { context.setObjectAttachments(attachments); } } if (invocation instanceof RpcInvocation) { ((RpcInvocation) invocation).setInvoker(invoker); } try { context.clearAfterEachInvoke(false); return invoker.invoke(invocation); } finally { context.clearAfterEachInvoke(true); RpcContext.removeContext(true); RpcContext.removeServerContext(); } }  @Override Result invoke(Invoker<?> invoker, Invocation invocation); @Override void onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation); @Override void onError(Throwable t, Invoker<?> invoker, Invocation invocation);  }
@SuppressWarnings("unchecked") @Test public void testSetContext() { invocation = mock(Invocation.class); given(invocation.getMethodName()).willReturn("$enumlength"); given(invocation.getParameterTypes()).willReturn(new Class<?>[]{Enum.class}); given(invocation.getArguments()).willReturn(new Object[]{"hello"}); given(invocation.getObjectAttachments()).willReturn(null); invoker = mock(Invoker.class); given(invoker.isAvailable()).willReturn(true); given(invoker.getInterface()).willReturn(DemoService.class); AppResponse result = new AppResponse(); result.setValue("High"); given(invoker.invoke(invocation)).willReturn(result); URL url = URL.valueOf("test: given(invoker.getUrl()).willReturn(url); contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInvoker()); }
@Test public void testWithAttachments() { URL url = URL.valueOf("test: Invoker<DemoService> invoker = new MyInvoker<DemoService>(url); Invocation invocation = new MockInvocation(); Result result = contextFilter.invoke(invoker, invocation); assertNull(RpcContext.getContext().getInvoker()); }