package eu.hinsch.spring.boot.actuator.useragent;

import net.sf.uadetector.ReadableUserAgent;
import net.sf.uadetector.service.UADetectorServiceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Created by lh on 31/05/15.
 */
@Component
public class UserAgentMetricFilter implements Filter {

    private final CounterService counterService;

    @Autowired
    public UserAgentMetricFilter(CounterService counterService) {
        this.counterService = counterService;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;

            ReadableUserAgent userAgent = UADetectorServiceFactory.getResourceModuleParser().parse(httpServletRequest.getHeader("User-Agent"));
            String key = userAgent.getName() + "." + userAgent.getVersionNumber().getMajor();
            counterService.increment(key);
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}

@@ -1158,19 +1158,20 @@
  String 
-key
+name
  = userA
@@ -1184,16 +1184,55 @@
 etName()
+;%0A            String key = escape(name)
  + %22.%22 +
@@ -1325,32 +1325,133 @@
        %7D%0A    %7D%0A%0A
+    private String escape(String name) %7B%0A        return name.replace(%22 %22, %22-%22).toLowerCase();%0A    %7D%0A%0A
     @Override%0A  

handle spaces in ua name