package org.glassfish.grizzly.servlet;
import static jakarta.servlet.DispatcherType.REQUEST;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.glassfish.grizzly.Grizzly;
import org.glassfish.grizzly.http.Note;
import org.glassfish.grizzly.http.server.AfterServiceListener;
import org.glassfish.grizzly.http.server.HttpHandler;
import org.glassfish.grizzly.http.server.Request;
import org.glassfish.grizzly.http.server.Response;
import org.glassfish.grizzly.http.server.SessionManager;
import org.glassfish.grizzly.http.server.util.ClassLoaderUtil;
import org.glassfish.grizzly.http.server.util.DispatcherHelper;
import org.glassfish.grizzly.http.server.util.Globals;
import org.glassfish.grizzly.http.server.util.HtmlHelper;
import org.glassfish.grizzly.http.server.util.MappingData;
import org.glassfish.grizzly.http.util.CharChunk;
import org.glassfish.grizzly.http.util.Header;
import org.glassfish.grizzly.http.util.HttpRequestURIDecoder;
import org.glassfish.grizzly.http.util.HttpStatus;
import jakarta.servlet.DispatcherType;
import jakarta.servlet.Servlet;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
public class ServletHandler extends HttpHandler {
private static final Logger LOGGER = Grizzly.logger(ServletHandler.class);
static final Note<HttpServletRequestImpl> SERVLET_REQUEST_NOTE = Request.createNote(HttpServletRequestImpl.class.getName());
static final Note<HttpServletResponseImpl> SERVLET_RESPONSE_NOTE = Request.createNote(HttpServletResponseImpl.class.getName());
static final ServletAfterServiceListener servletAfterServiceListener = new ServletAfterServiceListener();
protected String servletClassName;
protected Class<? extends Servlet> servletClass;
protected volatile Servlet servletInstance = null;
private String contextPath = "";
private final Object lock = new Object();
private final WebappContext servletCtx;
private final ServletConfigImpl servletConfig;
private SessionManager sessionManager = ServletSessionManager.instance();
protected final Map<String, Object> properties = new HashMap<>();
protected boolean initialize = true;
protected ClassLoader classLoader;
protected ExpectationHandler expectationHandler;
protected FilterChainFactory filterChainFactory;
private List<Runnable> onDestroyListeners;
protected ServletHandler(final ServletConfigImpl servletConfig) {
this.servletConfig = servletConfig;
servletCtx = (WebappContext) servletConfig.getServletContext();
}
@Override
public void start() {
try {
configureServletEnv();
} catch (Throwable t) {
LOGGER.log(Level.SEVERE, "start", t);
}
}
@Override
protected boolean sendAcknowledgment(Request request, Response response) throws IOException {
return expectationHandler != null || super.sendAcknowledgment(request, response);
}
@Override
public void service(Request request, Response response) throws Exception {
if (classLoader != null) {
final ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
doServletService(request, response);
} finally {
Thread.currentThread().setContextClassLoader(prevClassLoader);
}
} else {
doServletService(request, response);
}
}
protected void doServletService(final Request request, final Response response) {
try {
final String uri = request.getRequestURI();
if (contextPath.length() > 0 && !uri.startsWith(contextPath)) {
customizeErrorPage(response, "Resource Not Found", 404, null);
return;
}
final HttpServletRequestImpl servletRequest = HttpServletRequestImpl.create();
final HttpServletResponseImpl servletResponse = HttpServletResponseImpl.create();
setPathData(request, servletRequest);
servletRequest.initialize(request, servletResponse, servletCtx);
servletResponse.initialize(response, servletRequest);
request.setNote(SERVLET_REQUEST_NOTE, servletRequest);
request.setNote(SERVLET_RESPONSE_NOTE, servletResponse);
request.addAfterServiceListener(servletAfterServiceListener);
loadServlet();
setDispatcherPath(request, getCombinedPath(servletRequest));
final String serverInfo = servletCtx.getServerInfo();
if (serverInfo != null && !serverInfo.isEmpty()) {
servletResponse.addHeader(Header.Server.toString(), serverInfo);
}
if (expectationHandler != null) {
final AckActionImpl ackAction = new AckActionImpl(response);
expectationHandler.onExpectAcknowledgement(servletRequest, servletResponse, ackAction);
if (!ackAction.isAcknowledged()) {
ackAction.acknowledge();
} else if (ackAction.isFailAcknowledgement()) {
return;
}
}
FilterChainInvoker filterChain = getFilterChain(request);
if (filterChain != null) {
filterChain.invokeFilterChain(servletRequest, servletResponse);
} else {
servletInstance.service(servletRequest, servletResponse);
}
servletRequest.onAfterService();
} catch (Throwable ex) {
LOGGER.log(Level.SEVERE, "service exception:", ex);
customizeErrorPage(response, "Internal Error", 500, ex);
}
}
protected FilterChainInvoker getFilterChain(Request request) {
if (filterChainFactory != null) {
return filterChainFactory.createFilterChain(request, servletInstance, REQUEST);
}
return null;
}
private void setDispatcherPath(final Request request, final String path) {
request.setAttribute(Globals.DISPATCHER_REQUEST_PATH_ATTR, path);
}
private String getCombinedPath(final HttpServletRequest request) {
if (request.getServletPath() == null) {
return null;
}
if (request.getPathInfo() == null) {
return request.getServletPath();
}
return request.getServletPath() + request.getPathInfo();
}
protected void setPathData(final Request from, final HttpServletRequestImpl to) {
final MappingData data = from.obtainMappingData();
to.setServletPath(data.wrapperPath.toString());
to.setPathInfo(data.pathInfo.toString());
to.setContextPath(data.contextPath.toString());
}
void doServletService(final ServletRequest servletRequest, final ServletResponse servletResponse, final DispatcherType dispatcherType)
throws IOException, ServletException {
try {
loadServlet();
FilterChainImpl filterChain = filterChainFactory.createFilterChain(servletRequest, servletInstance, dispatcherType);
if (filterChain != null) {
filterChain.invokeFilterChain(servletRequest, servletResponse);
} else {
servletInstance.service(servletRequest, servletResponse);
}
} catch (ServletException se) {
LOGGER.log(Level.SEVERE, "service exception:", se);
throw se;
} catch (IOException ie) {
LOGGER.log(Level.SEVERE, "service exception:", ie);
throw ie;
}
}
public void customizeErrorPage(final Response response, final String message, final int errorCode, final Throwable t) {
if (!response.isCommitted()) {
try {
HtmlHelper.setErrorAndSendErrorPage(response.getRequest(), response, response.getErrorPageGenerator(), errorCode, message, message, t);
} catch (IOException ex) {
}
}
}
protected void loadServlet() throws ServletException {
if (servletInstance == null) {
synchronized (lock) {
if (servletInstance == null) {
Servlet newServletInstance;
if (servletClassName != null) {
newServletInstance = (Servlet) ClassLoaderUtil.load(servletClassName);
} else {
try {
newServletInstance = servletClass.newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
LOGGER.log(Level.INFO, "Loading Servlet: {0}", newServletInstance.getClass().getName());
newServletInstance.init(servletConfig);
servletInstance = newServletInstance;
}
}
}
}
protected void configureServletEnv() throws ServletException {
if (contextPath.length() > 0) {
final CharChunk cc = new CharChunk();
char[] ch = contextPath.toCharArray();
cc.setChars(ch, 0, ch.length);
HttpRequestURIDecoder.normalizeChars(cc);
contextPath = cc.toString();
}
if ("".equals(contextPath)) {
contextPath = "";
}
}
@SuppressWarnings({ "UnusedDeclaration" })
public Servlet getServletInstance() {
return servletInstance;
}
protected void setServletInstance(Servlet servletInstance) {
this.servletInstance = servletInstance;
}
protected void setServletClassName(final String servletClassName) {
this.servletClassName = servletClassName;
}
protected void setServletClass(final Class<? extends Servlet> servletClass) {
this.servletClass = servletClass;
}
protected void setSessionManager(SessionManager sessionManager) {
this.sessionManager = sessionManager;
}
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
@Override
public void destroy() {
try {
if (classLoader != null) {
ClassLoader prevClassLoader = Thread.currentThread().getContextClassLoader();
Thread.currentThread().setContextClassLoader(classLoader);
try {
super.destroy();
if (servletInstance != null) {
servletInstance.destroy();
servletInstance = null;
}
} finally {
Thread.currentThread().setContextClassLoader(prevClassLoader);
}
} else {
super.destroy();
}
} finally {
if (onDestroyListeners != null) {
for (int i = 0; i < onDestroyListeners.size(); i++) {
try {
onDestroyListeners.get(i).run();
} catch (Throwable t) {
LOGGER.log(Level.WARNING, "onDestroyListener error", t);
}
}
onDestroyListeners = null;
}
}
}
protected WebappContext getServletCtx() {
return servletCtx;
}
public ClassLoader getClassLoader() {
return classLoader;
}
public void setClassLoader(ClassLoader classLoader) {
this.classLoader = classLoader;
}
public ServletConfigImpl getServletConfig() {
return servletConfig;
}
@Override
public String getName() {
return servletConfig.getServletName();
}
public ExpectationHandler getExpectationHandler() {
return expectationHandler;
}
public void setExpectationHandler(ExpectationHandler expectationHandler) {
this.expectationHandler = expectationHandler;
}
@Override
protected void setDispatcherHelper(final DispatcherHelper dispatcherHelper) {
servletCtx.setDispatcherHelper(dispatcherHelper);
}
protected void setFilterChainFactory(final FilterChainFactory filterChainFactory) {
this.filterChainFactory = filterChainFactory;
}
@Override
protected String getSessionCookieName() {
return servletCtx.getSessionCookieConfig().getName();
}
@Override
protected SessionManager getSessionManager(Request request) {
final SessionManager sm = request.getHttpFilter().getConfiguration().getSessionManager();
return sm != null ? sm : this.sessionManager;
}
void addOnDestroyListener(final Runnable r) {
if (onDestroyListeners == null) {
onDestroyListeners = new ArrayList<>(2);
}
onDestroyListeners.add(r);
}
static final class ServletAfterServiceListener implements AfterServiceListener {
@Override
public void onAfterService(final Request request) {
final HttpServletRequestImpl servletRequest = getServletRequest(request);
final HttpServletResponseImpl servletResponse = getServletResponse(request);
if (servletRequest != null) {
servletRequest.recycle();
servletResponse.recycle();
}
}
}
static final class AckActionImpl implements ExpectationHandler.AckAction {
private boolean isAcknowledged;
private boolean isFailAcknowledgement;
private final Response response;
private AckActionImpl(final Response response) {
this.response = response;
}
@Override
public void acknowledge() throws IOException {
if (isAcknowledged) {
throw new IllegalStateException("Already acknowledged");
}
isAcknowledged = true;
response.setStatus(HttpStatus.CONINTUE_100);
response.sendAcknowledgement();
}
@Override
public void fail() throws IOException {
if (isAcknowledged) {
throw new IllegalStateException("Already acknowledged");
}
isAcknowledged = true;
isFailAcknowledgement = true;
response.setStatus(HttpStatus.EXPECTATION_FAILED_417);
response.finish();
}
public boolean isAcknowledged() {
return isAcknowledged;
}
public boolean isFailAcknowledgement() {
return isFailAcknowledgement;
}
}
static HttpServletRequestImpl getServletRequest(final Request request) {
return request.getNote(SERVLET_REQUEST_NOTE);
}
static HttpServletResponseImpl getServletResponse(final Request request) {
return request.getNote(SERVLET_RESPONSE_NOTE);
}
}