package eu.openanalytics.controllers;

import java.io.IOException;
import java.security.Principal;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import eu.openanalytics.services.UserService;

@Controller
public class HeartbeatController {

	@Inject
	UserService userService;
	
	@RequestMapping("/heartbeat/**")
	void heartbeat(Principal principal, HttpServletRequest request, HttpServletResponse response) {
		String userName = (principal == null) ? request.getSession().getId() : principal.getName();
		Matcher matcher = Pattern.compile(".*/app/(.*)").matcher(request.getRequestURI());
		String appName = matcher.matches() ? matcher.group(1) : null;
		userService.heartbeatReceived(userName, appName);
		try {
			response.setStatus(200);
			response.getWriter().write("Ok");
			response.getWriter().flush();
		} catch (IOException e) {}
	}
}

@@ -492,18 +492,32 @@
  %7B%0A%0A
-%09@Inject%0A%09
+        @Inject%0A        
 User
@@ -541,11 +541,17 @@
 ce;%0A
-%09%0A%09
+%0A        
 @Req
@@ -579,17 +579,24 @@
 at/**%22)%0A
-%09
+        
 void hea
@@ -683,18 +683,32 @@
 onse) %7B%0A
-%09%09
+                
 String u
@@ -791,18 +791,32 @@
 Name();%0A
-%09%09
+                
 Matcher 
@@ -890,18 +890,32 @@
 URI());%0A
-%09%09
+                
 String a
@@ -968,18 +968,32 @@
 : null;%0A
-%09%09
+                
 userServ
@@ -1038,47 +1038,165 @@
 e);%0A
-%09%09try %7B%0A%09%09%09response.setStatus(200);%0A%09%09%09
+                try %7B%0A                        response.setStatus(200);%0A                        response.setContentType(%22text/html%22);%0A                        
 resp
@@ -1229,11 +1229,32 @@
 %22);%0A
-%09%09%09
+                        
 resp
@@ -1283,10 +1283,24 @@
 ();%0A
-%09%09
+                
 %7D ca
@@ -1326,9 +1326,16 @@
  %7B%7D%0A
-%09
+        
 %7D%0A%7D%0A

Add content-type header to heartbeat response. Fixes openanalytics/shinyproxy#15