Search in sources :

Example 1 with ServletRequestListener

use of jakarta.servlet.ServletRequestListener in project atmosphere by Atmosphere.

the class ContainerInitializer method onStartup.

@Override
public void onStartup(Set<Class<?>> classes, final ServletContext c) {
    c.log("Initializing AtmosphereFramework");
    for (Map.Entry<String, ? extends ServletRegistration> reg : c.getServletRegistrations().entrySet()) {
        String disableSwitchValue = reg.getValue().getInitParameter(ApplicationConfig.DISABLE_ATMOSPHERE_INITIALIZER);
        // check if AtmosphereInitializer is disabled via web.xml see: https://github.com/Atmosphere/atmosphere/issues/1695
        if (Boolean.parseBoolean(disableSwitchValue)) {
            c.log("Container managed initialization disabled for servlet: " + reg.getValue().getName());
            continue;
        }
        if (c.getAttribute(reg.getKey()) == null && IOUtils.isAtmosphere(reg.getValue().getClassName())) {
            final AtmosphereFramework framework = AtmosphereFrameworkInitializer.newAtmosphereFramework(c, false, true);
            // Hack to make jsr356 works. Pretty ugly.
            DefaultAsyncSupportResolver resolver = new DefaultAsyncSupportResolver(framework.getAtmosphereConfig());
            List<Class<? extends AsyncSupport>> l = resolver.detectWebSocketPresent(false, true);
            // Don't use WebLogic Native WebSocket support if JSR356 is available
            int size = c.getServerInfo().toLowerCase().contains("weblogic") ? 1 : 0;
            String s = reg.getValue().getInitParameter(ApplicationConfig.PROPERTY_COMET_SUPPORT);
            boolean force = c.getServerInfo().toLowerCase().contains("glassfish") || c.getServerInfo().toLowerCase().contains("payara");
            if (s != null && s.equals(JSR356AsyncSupport.class.getName())) {
                force = true;
            } else if (s != null) {
                force = false;
            }
            if (force || l.size() == size && resolver.testClassExists(DefaultAsyncSupportResolver.JSR356_WEBSOCKET)) {
                try {
                    framework.setAsyncSupport(new JSR356AsyncSupport(framework.getAtmosphereConfig(), c));
                } catch (IllegalStateException ex) {
                    framework.initializationError(ex);
                }
            }
            try {
                c.addListener(new ServletRequestListener() {

                    @Override
                    public void requestDestroyed(ServletRequestEvent sre) {
                    }

                    @Override
                    public void requestInitialized(ServletRequestEvent sre) {
                        HttpServletRequest r = HttpServletRequest.class.cast(sre.getServletRequest());
                        AtmosphereConfig config = framework.getAtmosphereConfig();
                        if (config.isSupportSession() && Utils.webSocketEnabled(r)) {
                            r.getSession(config.getInitParameter(ApplicationConfig.PROPERTY_SESSION_CREATE, true));
                        }
                    }
                });
            } catch (Throwable t) {
                c.log("AtmosphereFramework : Unable to install WebSocket Session Creator", t);
            }
            try {
                s = c.getInitParameter(PROPERTY_SESSION_SUPPORT);
                if (s != null) {
                    boolean sessionSupport = Boolean.valueOf(s);
                    if (sessionSupport && c.getMajorVersion() > 2) {
                        c.addListener(SessionSupport.class);
                        c.log("AtmosphereFramework : Installed " + SessionSupport.class);
                    }
                }
            } catch (Throwable t) {
                c.log("AtmosphereFramework : SessionSupport error. Make sure you also define {} as a listener in web.xml, see https://github.com/Atmosphere/atmosphere/wiki/Enabling-HttpSession-Support", t);
            }
            c.setAttribute(reg.getKey(), framework);
        }
    }
}
Also used : ServletRequestListener(jakarta.servlet.ServletRequestListener) JSR356AsyncSupport(org.atmosphere.container.JSR356AsyncSupport) JSR356AsyncSupport(org.atmosphere.container.JSR356AsyncSupport) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletRequestEvent(jakarta.servlet.ServletRequestEvent) Map(java.util.Map)

Example 2 with ServletRequestListener

use of jakarta.servlet.ServletRequestListener in project tomcat by apache.

the class StandardContext method listenerStart.

/**
 * Configure the set of instantiated application event listeners
 * for this Context.
 * @return <code>true</code> if all listeners wre
 * initialized successfully, or <code>false</code> otherwise.
 */
public boolean listenerStart() {
    if (log.isDebugEnabled()) {
        log.debug("Configuring application event listeners");
    }
    // Instantiate the required listeners
    String[] listeners = findApplicationListeners();
    Object[] results = new Object[listeners.length];
    boolean ok = true;
    for (int i = 0; i < results.length; i++) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug(" Configuring event listener class '" + listeners[i] + "'");
        }
        try {
            String listener = listeners[i];
            results[i] = getInstanceManager().newInstance(listener);
        } catch (Throwable t) {
            t = ExceptionUtils.unwrapInvocationTargetException(t);
            ExceptionUtils.handleThrowable(t);
            getLogger().error(sm.getString("standardContext.applicationListener", listeners[i]), t);
            ok = false;
        }
    }
    if (!ok) {
        getLogger().error(sm.getString("standardContext.applicationSkipped"));
        return false;
    }
    // Sort listeners in two arrays
    List<Object> eventListeners = new ArrayList<>();
    List<Object> lifecycleListeners = new ArrayList<>();
    for (Object result : results) {
        if ((result instanceof ServletContextAttributeListener) || (result instanceof ServletRequestAttributeListener) || (result instanceof ServletRequestListener) || (result instanceof HttpSessionIdListener) || (result instanceof HttpSessionAttributeListener)) {
            eventListeners.add(result);
        }
        if ((result instanceof ServletContextListener) || (result instanceof HttpSessionListener)) {
            lifecycleListeners.add(result);
        }
    }
    // Listener instances may have been added directly to this Context by
    // ServletContextInitializers and other code via the pluggability APIs.
    // Put them these listeners after the ones defined in web.xml and/or
    // annotations then overwrite the list of instances with the new, full
    // list.
    eventListeners.addAll(Arrays.asList(getApplicationEventListeners()));
    setApplicationEventListeners(eventListeners.toArray());
    for (Object lifecycleListener : getApplicationLifecycleListeners()) {
        lifecycleListeners.add(lifecycleListener);
        if (lifecycleListener instanceof ServletContextListener) {
            noPluggabilityListeners.add(lifecycleListener);
        }
    }
    setApplicationLifecycleListeners(lifecycleListeners.toArray());
    if (getLogger().isDebugEnabled()) {
        getLogger().debug("Sending application start events");
    }
    // Ensure context is not null
    getServletContext();
    context.setNewServletContextListenerAllowed(false);
    Object[] instances = getApplicationLifecycleListeners();
    if (instances == null || instances.length == 0) {
        return ok;
    }
    ServletContextEvent event = new ServletContextEvent(getServletContext());
    ServletContextEvent tldEvent = null;
    if (noPluggabilityListeners.size() > 0) {
        noPluggabilityServletContext = new NoPluggabilityServletContext(getServletContext());
        tldEvent = new ServletContextEvent(noPluggabilityServletContext);
    }
    for (Object instance : instances) {
        if (!(instance instanceof ServletContextListener)) {
            continue;
        }
        ServletContextListener listener = (ServletContextListener) instance;
        try {
            fireContainerEvent("beforeContextInitialized", listener);
            if (noPluggabilityListeners.contains(listener)) {
                listener.contextInitialized(tldEvent);
            } else {
                listener.contextInitialized(event);
            }
            fireContainerEvent("afterContextInitialized", listener);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            fireContainerEvent("afterContextInitialized", listener);
            getLogger().error(sm.getString("standardContext.listenerStart", instance.getClass().getName()), t);
            ok = false;
        }
    }
    return ok;
}
Also used : ServletContextAttributeListener(jakarta.servlet.ServletContextAttributeListener) ServletRequestAttributeListener(jakarta.servlet.ServletRequestAttributeListener) HttpSessionListener(jakarta.servlet.http.HttpSessionListener) ServletContextListener(jakarta.servlet.ServletContextListener) ServletRequestListener(jakarta.servlet.ServletRequestListener) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) HttpSessionAttributeListener(jakarta.servlet.http.HttpSessionAttributeListener) HttpSessionIdListener(jakarta.servlet.http.HttpSessionIdListener) ServletContextEvent(jakarta.servlet.ServletContextEvent)

Example 3 with ServletRequestListener

use of jakarta.servlet.ServletRequestListener in project tomcat by apache.

the class TestStandardHostValve method testSRLAfterError.

@Test
public void testSRLAfterError() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    // Add the error page
    Tomcat.addServlet(ctx, "error", new ErrorServlet());
    ctx.addServletMappingDecoded("/error", "error");
    final List<String> result = new ArrayList<>();
    // Add the request listener
    ServletRequestListener servletRequestListener = new ServletRequestListener() {

        @Override
        public void requestDestroyed(ServletRequestEvent sre) {
            result.add("Visit requestDestroyed");
        }

        @Override
        public void requestInitialized(ServletRequestEvent sre) {
            result.add("Visit requestInitialized");
        }
    };
    ((StandardContext) ctx).addApplicationEventListener(servletRequestListener);
    tomcat.start();
    // Request a page that triggers an error
    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/error?errorCode=400", bc, null);
    Assert.assertEquals(400, rc);
    Assert.assertTrue(result.contains("Visit requestInitialized"));
    Assert.assertTrue(result.contains("Visit requestDestroyed"));
}
Also used : Context(org.apache.catalina.Context) Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) ServletRequestListener(jakarta.servlet.ServletRequestListener) ArrayList(java.util.ArrayList) ServletRequestEvent(jakarta.servlet.ServletRequestEvent) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Example 4 with ServletRequestListener

use of jakarta.servlet.ServletRequestListener in project tomcat by apache.

the class StandardContext method fireRequestDestroyEvent.

@Override
public boolean fireRequestDestroyEvent(ServletRequest request) {
    Object[] instances = getApplicationEventListeners();
    if ((instances != null) && (instances.length > 0)) {
        ServletRequestEvent event = new ServletRequestEvent(getServletContext(), request);
        for (int i = 0; i < instances.length; i++) {
            int j = (instances.length - 1) - i;
            if (instances[j] == null) {
                continue;
            }
            if (!(instances[j] instanceof ServletRequestListener)) {
                continue;
            }
            ServletRequestListener listener = (ServletRequestListener) instances[j];
            try {
                listener.requestDestroyed(event);
            } catch (Throwable t) {
                ExceptionUtils.handleThrowable(t);
                getLogger().error(sm.getString("standardContext.requestListener.requestInit", instances[j].getClass().getName()), t);
                request.setAttribute(RequestDispatcher.ERROR_EXCEPTION, t);
                return false;
            }
        }
    }
    return true;
}
Also used : ServletRequestListener(jakarta.servlet.ServletRequestListener) ServletRequestEvent(jakarta.servlet.ServletRequestEvent) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint)

Aggregations

ServletRequestListener (jakarta.servlet.ServletRequestListener)4 ServletRequestEvent (jakarta.servlet.ServletRequestEvent)3 ArrayList (java.util.ArrayList)2 SecurityConstraint (org.apache.tomcat.util.descriptor.web.SecurityConstraint)2 ServletContextAttributeListener (jakarta.servlet.ServletContextAttributeListener)1 ServletContextEvent (jakarta.servlet.ServletContextEvent)1 ServletContextListener (jakarta.servlet.ServletContextListener)1 ServletRequestAttributeListener (jakarta.servlet.ServletRequestAttributeListener)1 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)1 HttpSessionAttributeListener (jakarta.servlet.http.HttpSessionAttributeListener)1 HttpSessionIdListener (jakarta.servlet.http.HttpSessionIdListener)1 HttpSessionListener (jakarta.servlet.http.HttpSessionListener)1 Map (java.util.Map)1 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)1 Context (org.apache.catalina.Context)1 Tomcat (org.apache.catalina.startup.Tomcat)1 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)1 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)1 JSR356AsyncSupport (org.atmosphere.container.JSR356AsyncSupport)1 Test (org.junit.Test)1