]> git.argeo.org Git - lgpl/argeo-commons.git/blob - org.argeo.cms.ee/src/org/argeo/cms/servlet/httpserver/HttpContextServlet.java
Add content type to package servlet
[lgpl/argeo-commons.git] / org.argeo.cms.ee / src / org / argeo / cms / servlet / httpserver / HttpContextServlet.java
1 package org.argeo.cms.servlet.httpserver;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletException;
6 import javax.servlet.http.HttpServlet;
7 import javax.servlet.http.HttpServletRequest;
8 import javax.servlet.http.HttpServletResponse;
9
10 import org.argeo.cms.auth.RemoteAuthSession;
11 import org.argeo.cms.servlet.ServletHttpSession;
12
13 import com.sun.net.httpserver.Authenticator;
14 import com.sun.net.httpserver.HttpContext;
15 import com.sun.net.httpserver.HttpHandler;
16 import com.sun.net.httpserver.HttpPrincipal;
17
18 /**
19 * An {@link HttpServlet} which integrates an {@link HttpContext} and its
20 * {@link Authenticator} in a servlet container.
21 */
22 public class HttpContextServlet extends HttpServlet {
23 private static final long serialVersionUID = 2321612280413662738L;
24
25 private final HttpContext httpContext;
26
27 public HttpContextServlet(HttpContext httpContext) {
28 this.httpContext = httpContext;
29 }
30
31 @Override
32 protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
33 try (ServletHttpExchange httpExchange = new ServletHttpExchange(httpContext, req, resp)) {
34 ServletHttpSession httpSession = new ServletHttpSession(req.getSession());
35 httpExchange.setAttribute(RemoteAuthSession.class.getName(), httpSession);
36 Authenticator authenticator = httpContext.getAuthenticator();
37 if (authenticator != null) {
38 Authenticator.Result authenticationResult = authenticator.authenticate(httpExchange);
39 if (authenticationResult instanceof Authenticator.Success) {
40 HttpPrincipal httpPrincipal = ((Authenticator.Success) authenticationResult).getPrincipal();
41 httpExchange.setPrincipal(httpPrincipal);
42 } else if (authenticationResult instanceof Authenticator.Retry) {
43 httpExchange.sendResponseHeaders((((Authenticator.Retry) authenticationResult).getResponseCode()),
44 -1);
45 resp.flushBuffer();
46 return;
47 } else if (authenticationResult instanceof Authenticator.Failure) {
48 httpExchange.sendResponseHeaders(((Authenticator.Failure) authenticationResult).getResponseCode(),
49 -1);
50 resp.flushBuffer();
51 return;
52 } else {
53 throw new UnsupportedOperationException(
54 "Authentication result " + authenticationResult.getClass().getName() + " is not supported");
55 }
56 }
57
58 HttpHandler httpHandler = httpContext.getHandler();
59 httpHandler.handle(httpExchange);
60 }
61 }
62 }