Thursday, 11 October 2012

Java as a Service - Monitoring the Java Web Service API

One key aspect of managing your public REST web service API is understanding your client usage.

There are several options for doing this, including configuring your IP sprayer to do quota management, or facading your services with a 3rd party service management product like Layer 7 or SOA Software, but you might also consider the very simple Java web service based solution using the open source JAMon library.

The sample code below illustrates a simple per-IP address monitoring solution that you might customise to be per-account or whatever else is available in the HTTP request header.




Firstly, a servlet filter:

public class MonitorFilter extends HttpServlet implements Filter {

@Override
public void init(FilterConfig filterConfig) {
}

@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {

Monitor monitor = MonitorFactory.start(request.getRemoteAddr());

try {
filterChain.doFilter(request, response);
} finally {
monitor.stop();
}
}

@Override
public void destroy() {
}
}


Having gathered the data, a simple Spring framework based REST service to show how to get at the data:


@Component
@Controller("monitorController")
public class MonitorController {

/**
 * Return all monitor results
 */
@RequestMapping(value = "/monitor", method = { RequestMethod.GET })
@ResponseBody
public String findAll() {

return MonitorFactory.getReport();

}

/**
 * Return the monitor results for the given key
 */
@RequestMapping(value = "/monitor/{key}", method = { RequestMethod.GET })
@ResponseBody
public String findByKey(@PathVariable String key) {

return MonitorFactory.getMonitor(key, "ms.").toString();

}

/**
 * Return all monitor results
 */
@RequestMapping(value = "/monitor/keys", method = { RequestMethod.GET })
@ResponseBody
public ArrayList findKeys() {

ArrayList keys = new ArrayList();

Iterator iter = MonitorFactory.getFactory().iterator();

while (iter.hasNext()) {
Monitor monitor = (Monitor) iter.next();
keys.add(monitor.getLabel());
}

return keys;
}

}


(Aside: see here for more on building REST services using Spring)

Some sample raw output:

http://localhost:8080/sample/monitor


Service-oriented architecture (SOA) management, REST API monitoring
Share: