UserAgentMetricFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request instanceof HttpServletRequest) { HttpServletRequest httpRequest = (HttpServletRequest) request; String roadName = template.match(httpRequest.getRequestURI()).get("name"); UserAgent userAgent = UserAgent.parse(httpRequest.getHeader("User-Agent")); products.forEach(product -> { userAgent.token(product).ifPresent(token -> { String version = token.getVersion().replaceAll("\\.", "-"); Tag roadTag = Tag.of("road", roadName); Tag productTag = Tag.of("product", product); Tag versionTag = Tag.of("version", version); ImmutableList<Tag> tags = ImmutableList.of(roadTag, productTag, versionTag); registry.counter("user-agent-metric-filter", tags).increment(); }); }); } chain.doFilter(request, response); }  @Override void doFilter(ServletRequest request, ServletResponse response, FilterChain chain); @Override void init(FilterConfig config); @Override void destroy();  }
@Test public void testName() throws Exception { when(request.getRequestURI()).thenReturn("/onramp/v1/roads/road1/messages"); when(request.getHeader("User-Agent")).thenReturn("product1/1.0 product2/2.0 product3/3.0"); Set<String> products = new HashSet<>(Arrays.asList("product1", "product2", "product4")); Filter underTest = new UserAgentMetricFilter(registry, products); underTest.doFilter(request, response, chain); assertThat(counter1.count(), is(1.0)); assertThat(counter2.count(), is(1.0)); assertThat(counter3.count(), is(0.0)); assertThat(counter4.count(), is(0.0)); verify(chain).doFilter(request, response); }