package geniusweb.runserver;
import java.io.IOException;
import java.util.logging.Level;
import java.util.stream.Collectors;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import geniusweb.protocol.NegoSettings;
import tudelft.utilities.logging.ReportToLogger;
import tudelft.utilities.logging.Reporter;
/**
* Contains incoming connection to run a Nego. runserver/runsession with the
* JSON {@link NegoSettings} in the request header. After the session is
* started, the new Nego ID is returned. This can be used to find back the log
* files..
*/
@SuppressWarnings("serial")
public class RunNego extends HttpServlet {
private final Reporter log;
private final static ObjectMapper jackson = new ObjectMapper();
public RunNego() {
this(new ReportToLogger("runserver"));
}
public RunNego(Reporter logger) {
super();
this.log = logger;
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response). Returns
*
* - URL with websocket address to contact the now running party.
*
- SC_NOT_FOUND (404) if attempt is made to access non-running
* party.
*
- SC_SERVICE_UNAVAILABLE (503) if there are no free slots to run
* the party.
*
- SC_EXPECTATION_FAILED (417) if something else goes wrong during
* instantiating the party (then see logs for more details)
*
*/
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String reqstring = request.getReader().lines()
.collect(Collectors.joining());
NegoSettings settings;
try {
settings = jackson.readValue(reqstring, NegoSettings.class);
} catch (IOException e) {
response.sendError(HttpServletResponse.SC_BAD_REQUEST,
e.getMessage());
System.err.println("Run request failed " + reqstring);
e.printStackTrace(); // helpful for debugging run requests
return;
}
log.log(Level.INFO, "request to run Nego: " + settings);
RunningNego session = new RunningNego(settings,
RunningNegotiationsRepo.instance(), log);
session.start();
// set content type to prevent some browsers
// trying to parse this (eg as XML)
response.setContentType("application/json");
response.getWriter().append(session.getID());
}
/**
* @see #doGet(HttpServletRequest, HttpServletResponse)
*/
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}