Search in sources :

Example 66 with ServletException

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

the class AtmosphereFramework method loadAtmosphereDotXml.

/**
 * Load AtmosphereHandler defined under META-INF/atmosphere.xml.
 *
 * @param stream The input stream we read from.
 * @param c      The classloader
 */
protected void loadAtmosphereDotXml(InputStream stream, ClassLoader c) throws IOException, ServletException {
    if (stream == null) {
        return;
    }
    logger.info("Found Atmosphere Configuration under {}", atmosphereDotXmlPath);
    AtmosphereConfigReader.getInstance().parse(config, stream);
    AtmosphereHandler handler = null;
    for (AtmosphereHandlerConfig atmoHandler : config.getAtmosphereHandlerConfig()) {
        try {
            if (!atmoHandler.getClassName().startsWith("@")) {
                if (!ReflectorServletProcessor.class.getName().equals(atmoHandler.getClassName())) {
                    handler = newClassInstance(AtmosphereHandler.class, (Class<AtmosphereHandler>) IOUtils.loadClass(this.getClass(), atmoHandler.getClassName()));
                } else {
                    handler = newClassInstance(AtmosphereHandler.class, ReflectorServletProcessor.class);
                }
                logger.info("Installed AtmosphereHandler {} mapped to context-path: {}", handler, atmoHandler.getContextRoot());
            }
            for (ApplicationConfiguration a : atmoHandler.getApplicationConfig()) {
                initParams.put(a.getParamName(), a.getParamValue());
            }
            for (FrameworkConfiguration a : atmoHandler.getFrameworkConfig()) {
                initParams.put(a.getParamName(), a.getParamValue());
            }
            for (AtmosphereHandlerProperty handlerProperty : atmoHandler.getProperties()) {
                if (handlerProperty.getValue() != null && handlerProperty.getValue().contains("jersey")) {
                    initParams.put(DISABLE_ONSTATE_EVENT, "true");
                    useStreamForFlushingComments = true;
                    broadcasterClassName = lookupDefaultBroadcasterType(JERSEY_BROADCASTER);
                    broadcasterFactory.destroy();
                    broadcasterFactory = null;
                    configureBroadcasterFactory();
                    configureBroadcaster();
                }
                if (handler != null) {
                    IntrospectionUtils.setProperty(handler, handlerProperty.getName(), handlerProperty.getValue());
                    IntrospectionUtils.addProperty(handler, handlerProperty.getName(), handlerProperty.getValue());
                }
            }
            sessionSupport(Boolean.parseBoolean(atmoHandler.getSupportSession()));
            if (handler != null) {
                String broadcasterClass = atmoHandler.getBroadcaster();
                Broadcaster b;
                /**
                 * If there is more than one AtmosphereHandler defined, their Broadcaster
                 * may clash each other with the BroadcasterFactory. In that case we will use the
                 * last one defined.
                 */
                if (broadcasterClass != null) {
                    broadcasterClassName = broadcasterClass;
                    ClassLoader cl = Thread.currentThread().getContextClassLoader();
                    Class<? extends Broadcaster> bc = (Class<? extends Broadcaster>) cl.loadClass(broadcasterClassName);
                    broadcasterFactory = newClassInstance(BroadcasterFactory.class, DefaultBroadcasterFactory.class);
                    broadcasterFactory.configure(bc, broadcasterLifeCyclePolicy, config);
                }
                b = broadcasterFactory.lookup(atmoHandler.getContextRoot(), true);
                AtmosphereHandlerWrapper wrapper = new AtmosphereHandlerWrapper(handler, b, config);
                addMapping(atmoHandler.getContextRoot(), wrapper);
                String bc = atmoHandler.getBroadcasterCache();
                if (bc != null) {
                    broadcasterCacheClassName = bc;
                }
                if (atmoHandler.getCometSupport() != null) {
                    asyncSupport = (AsyncSupport) c.loadClass(atmoHandler.getCometSupport()).getDeclaredConstructor(new Class[] { AtmosphereConfig.class }).newInstance(new Object[] { config });
                }
                if (atmoHandler.getBroadcastFilterClasses() != null) {
                    broadcasterFilters.addAll(atmoHandler.getBroadcastFilterClasses());
                }
                LinkedList<AtmosphereInterceptor> l = new LinkedList<AtmosphereInterceptor>();
                if (atmoHandler.getAtmosphereInterceptorClasses() != null) {
                    for (String a : atmoHandler.getAtmosphereInterceptorClasses()) {
                        try {
                            AtmosphereInterceptor ai = newClassInstance(AtmosphereInterceptor.class, (Class<AtmosphereInterceptor>) IOUtils.loadClass(getClass(), a));
                            l.add(ai);
                        } catch (Throwable e) {
                            logger.warn("", e);
                        }
                    }
                }
                addInterceptorToWrapper(wrapper, l);
                if (!l.isEmpty()) {
                    logger.info("Installed AtmosphereInterceptor {} mapped to AtmosphereHandler {}", l, atmoHandler.getClassName());
                }
            }
        } catch (Throwable t) {
            logger.warn("Unable to load AtmosphereHandler class: " + atmoHandler.getClassName(), t);
            throw new ServletException(t);
        }
    }
}
Also used : AndroidAtmosphereInterceptor(org.atmosphere.interceptor.AndroidAtmosphereInterceptor) PaddingAtmosphereInterceptor(org.atmosphere.interceptor.PaddingAtmosphereInterceptor) SSEAtmosphereInterceptor(org.atmosphere.interceptor.SSEAtmosphereInterceptor) JSONPAtmosphereInterceptor(org.atmosphere.interceptor.JSONPAtmosphereInterceptor) AtmosphereHandlerProperty(org.atmosphere.config.AtmosphereHandlerProperty) LinkedList(java.util.LinkedList) ServletException(jakarta.servlet.ServletException) AbstractReflectorAtmosphereHandler(org.atmosphere.handler.AbstractReflectorAtmosphereHandler) FrameworkConfiguration(org.atmosphere.config.FrameworkConfiguration) AtmosphereHandlerConfig(org.atmosphere.config.AtmosphereHandlerConfig) URLClassLoader(java.net.URLClassLoader) ReflectorServletProcessor(org.atmosphere.handler.ReflectorServletProcessor) ApplicationConfiguration(org.atmosphere.config.ApplicationConfiguration)

Example 67 with ServletException

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

the class AtmosphereFramework method init.

/**
 * Initialize the AtmosphereFramework using the {@link ServletContext}.
 *
 * @param sc the {@link ServletContext}
 */
public AtmosphereFramework init(final ServletConfig sc, boolean wrap) throws ServletException {
    if (isInit)
        return this;
    servletConfig(sc, wrap);
    readSystemProperties();
    populateBroadcasterType();
    populateObjectFactoryType();
    loadMetaService();
    onPreInit();
    try {
        ServletContextFactory.getDefault().init(sc.getServletContext());
        preventOOM();
        doInitParams(servletConfig);
        doInitParamsForWebSocket(servletConfig);
        lookupDefaultObjectFactoryType();
        if (logger.isTraceEnabled()) {
            asyncSupportListener(newClassInstance(AsyncSupportListener.class, AsyncSupportListenerAdapter.class));
        }
        configureObjectFactory();
        configureAnnotationPackages();
        configureBroadcasterFactory();
        configureMetaBroadcaster();
        configureAtmosphereResourceFactory();
        if (isSessionSupportSpecified) {
            sessionFactory();
        }
        configureScanningPackage(servletConfig, ApplicationConfig.ANNOTATION_PACKAGE);
        configureScanningPackage(servletConfig, FrameworkConfig.JERSEY2_SCANNING_PACKAGE);
        configureScanningPackage(servletConfig, FrameworkConfig.JERSEY_SCANNING_PACKAGE);
        // Force scanning of the packages defined.
        defaultPackagesToScan();
        installAnnotationProcessor(servletConfig);
        autoConfigureService(servletConfig.getServletContext());
        // Reconfigure in case an annotation changed the default.
        configureBroadcasterFactory();
        patchContainer();
        configureBroadcaster();
        loadConfiguration(servletConfig);
        initWebSocket();
        initEndpointMapper();
        initDefaultSerializer();
        autoDetectContainer();
        configureWebDotXmlAtmosphereHandler(servletConfig);
        asyncSupport.init(servletConfig);
        initAtmosphereHandler(servletConfig);
        configureAtmosphereInterceptor(servletConfig);
        analytics();
        // http://java.net/jira/browse/ATMOSPHERE-157
        if (sc.getServletContext() != null) {
            sc.getServletContext().setAttribute(BroadcasterFactory.class.getName(), broadcasterFactory);
        }
        String s = config.getInitParameter(ApplicationConfig.BROADCASTER_SHARABLE_THREAD_POOLS);
        if (s != null) {
            sharedThreadPools = Boolean.parseBoolean(s);
        }
        this.shutdownHook = new Thread(AtmosphereFramework.this::destroy);
        Runtime.getRuntime().addShutdownHook(this.shutdownHook);
        if (logger.isInfoEnabled()) {
            info();
        }
        if (initializationError != null) {
            logger.trace("ContainerInitalizer exception. May not be an issue if Atmosphere started properly ", initializationError);
        }
        universe();
    } catch (Throwable t) {
        logger.error("Failed to initialize Atmosphere Framework", t);
        if (t instanceof ServletException) {
            throw (ServletException) t;
        }
        throw new ServletException(t);
    }
    isInit = true;
    config.initComplete();
    onPostInit();
    return this;
}
Also used : ServletException(jakarta.servlet.ServletException)

Example 68 with ServletException

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

the class SimpleRestInterceptor method inspect.

@Override
public Action inspect(final AtmosphereResource r) {
    if (AtmosphereResource.TRANSPORT.WEBSOCKET != r.transport() && AtmosphereResource.TRANSPORT.SSE != r.transport() && AtmosphereResource.TRANSPORT.POLLING != r.transport()) {
        LOG.debug("Skipping for non websocket request");
        return Action.CONTINUE;
    }
    if (AtmosphereResource.TRANSPORT.POLLING == r.transport()) {
        final String saruuid = (String) r.getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
        final AtmosphereResponse suspendedResponse = suspendedResponses.get(saruuid);
        LOG.debug("Attaching a proxy writer to suspended response");
        r.getResponse().asyncIOWriter(new AtmosphereInterceptorWriter() {

            @Override
            public AsyncIOWriter write(AtmosphereResponse r, String data) throws IOException {
                suspendedResponse.write(data);
                suspendedResponse.flushBuffer();
                return this;
            }

            @Override
            public AsyncIOWriter write(AtmosphereResponse r, byte[] data) throws IOException {
                suspendedResponse.write(data);
                suspendedResponse.flushBuffer();
                return this;
            }

            @Override
            public AsyncIOWriter write(AtmosphereResponse r, byte[] data, int offset, int length) throws IOException {
                suspendedResponse.write(data, offset, length);
                suspendedResponse.flushBuffer();
                return this;
            }

            @Override
            public void close(AtmosphereResponse response) throws IOException {
            }
        });
        // REVISIT we need to keep this response's asyncwriter alive so that data can be written to the
        // suspended response, but investigate if there is a better alternative.
        r.getResponse().destroyable(false);
        return Action.CONTINUE;
    }
    r.addEventListener(new AtmosphereResourceEventListenerAdapter() {

        @Override
        public void onSuspend(AtmosphereResourceEvent event) {
            final String srid = (String) event.getResource().getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
            LOG.debug("Registrering suspended resource: {}", srid);
            suspendedResponses.put(srid, event.getResource().getResponse());
            AsyncIOWriter writer = event.getResource().getResponse().getAsyncIOWriter();
            if (writer == null) {
                writer = new AtmosphereInterceptorWriter();
                r.getResponse().asyncIOWriter(writer);
            }
            if (writer instanceof AtmosphereInterceptorWriter) {
                ((AtmosphereInterceptorWriter) writer).interceptor(interceptor);
            }
        }

        @Override
        public void onDisconnect(AtmosphereResourceEvent event) {
            super.onDisconnect(event);
            final String srid = (String) event.getResource().getRequest().getAttribute(ApplicationConfig.SUSPENDED_ATMOSPHERE_RESOURCE_UUID);
            LOG.debug("Unregistrering suspended resource: {}", srid);
            suspendedResponses.remove(srid);
        }
    });
    AtmosphereRequest request = r.getRequest();
    if (request.getAttribute(REQUEST_DISPATCHED) == null) {
        try {
            // REVISIT use a more efficient approach for the detached mode (i.e.,avoid reading the message into a string)
            // read the message entity and dispatch a service call
            String body = IOUtils.readEntirelyAsString(r).toString();
            LOG.debug("Request message: '{}'", body);
            if (body.length() == 0) {
                // TODO we might want to move this heartbeat scheduling after the handshake phase (if that is added)
                if ((AtmosphereResource.TRANSPORT.WEBSOCKET == r.transport() || AtmosphereResource.TRANSPORT.SSE == r.transport()) && request.getAttribute(HEARTBEAT_SCHEDULED) == null) {
                    r.suspend();
                    scheduleHeartbeat(r);
                    request.setAttribute(HEARTBEAT_SCHEDULED, "true");
                    return Action.SUSPEND;
                }
                return Action.CANCELLED;
            }
            AtmosphereRequest ar = createAtmosphereRequest(request, body);
            if (ar == null) {
                return Action.CANCELLED;
            }
            AtmosphereResponse response = r.getResponse();
            ar.localAttributes().put(REQUEST_DISPATCHED, "true");
            request.removeAttribute(FrameworkConfig.INJECTED_ATMOSPHERE_RESOURCE);
            response.request(ar);
            attachWriter(r);
            Action action = r.getAtmosphereConfig().framework().doCometSupport(ar, response);
            if (action.type() == Action.TYPE.SUSPEND) {
                ar.destroyable(false);
                response.destroyable(false);
            }
            return Action.CANCELLED;
        } catch (IOException | ServletException e) {
            LOG.error("Failed to process", e);
        }
    }
    return Action.CONTINUE;
}
Also used : AtmosphereResponse(org.atmosphere.cpr.AtmosphereResponse) Action(org.atmosphere.cpr.Action) AsyncIOWriter(org.atmosphere.cpr.AsyncIOWriter) IOException(java.io.IOException) ServletException(jakarta.servlet.ServletException) AtmosphereResourceEventListenerAdapter(org.atmosphere.cpr.AtmosphereResourceEventListenerAdapter) AtmosphereRequest(org.atmosphere.cpr.AtmosphereRequest) AtmosphereResourceEvent(org.atmosphere.cpr.AtmosphereResourceEvent) AtmosphereInterceptorWriter(org.atmosphere.cpr.AtmosphereInterceptorWriter)

Example 69 with ServletException

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

the class ReflectorServletProcessor method init.

@Override
public void init(AtmosphereConfig config) throws ServletException {
    this.config = config;
    try {
        loadWebApplication(config.getServletConfig());
    } catch (Exception ex) {
        throw new ServletException(ex);
    }
    filterChain.setServlet(config.getServletConfig(), servlet);
    wrapper.init(config.getServletConfig());
}
Also used : ServletException(jakarta.servlet.ServletException) ServletException(jakarta.servlet.ServletException) IOException(java.io.IOException)

Example 70 with ServletException

use of jakarta.servlet.ServletException in project spring-security by spring-projects.

the class GrantedAuthorityDefaultsJcTests method doFilterIsUserInRole.

// SEC-2926
@Test
public void doFilterIsUserInRole() throws Exception {
    SecurityContext context = SecurityContextHolder.getContext();
    this.request.getSession().setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, context);
    this.chain = new MockFilterChain() {

        @Override
        public void doFilter(ServletRequest request, ServletResponse response) throws IOException, ServletException {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            assertThat(httpRequest.isUserInRole("USER")).isTrue();
            assertThat(httpRequest.isUserInRole("INVALID")).isFalse();
            super.doFilter(request, response);
        }
    };
    this.springSecurityFilterChain.doFilter(this.request, this.response, this.chain);
    assertThat(this.chain.getRequest()).isNotNull();
}
Also used : ServletException(jakarta.servlet.ServletException) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) HttpServletRequest(jakarta.servlet.http.HttpServletRequest) ServletRequest(jakarta.servlet.ServletRequest) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) MockHttpServletResponse(org.springframework.mock.web.MockHttpServletResponse) ServletResponse(jakarta.servlet.ServletResponse) HttpServletResponse(jakarta.servlet.http.HttpServletResponse) SecurityContext(org.springframework.security.core.context.SecurityContext) IOException(java.io.IOException) MockFilterChain(org.springframework.mock.web.MockFilterChain) Test(org.junit.jupiter.api.Test)

Aggregations

ServletException (jakarta.servlet.ServletException)115 IOException (java.io.IOException)72 Test (org.junit.jupiter.api.Test)26 HttpServletResponse (jakarta.servlet.http.HttpServletResponse)17 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)16 Assertions.assertThat (org.assertj.core.api.Assertions.assertThat)15 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)15 ServletContext (jakarta.servlet.ServletContext)14 FilterChain (jakarta.servlet.FilterChain)13 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)13 BeforeEach (org.junit.jupiter.api.BeforeEach)12 BeforeMethod (org.testng.annotations.BeforeMethod)11 ServletConfig (jakarta.servlet.ServletConfig)10 Arrays (java.util.Arrays)10 Enumeration (java.util.Enumeration)10 UnavailableException (jakarta.servlet.UnavailableException)9 HttpHeaders (org.springframework.http.HttpHeaders)9 HttpMethod (org.springframework.http.HttpMethod)9 CorsConfiguration (org.springframework.web.cors.CorsConfiguration)9 ServletRequest (jakarta.servlet.ServletRequest)8