Search in sources :

Example 1 with HttpSession

use of jakarta.servlet.http.HttpSession in project atmosphere by Atmosphere.

the class AsynchronousProcessor method action.

/**
 * Invoke the {@link AtmosphereHandler#onRequest} method.
 *
 * @param req the {@link AtmosphereRequest}
 * @param res the {@link AtmosphereResponse}
 * @return action the Action operation.
 */
Action action(AtmosphereRequest req, AtmosphereResponse res) throws IOException, ServletException {
    if (!Utils.properProtocol(req)) {
        logger.debug("Invalid request state.");
        res.setStatus(501);
        res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported");
        res.flushBuffer();
        return new Action();
    }
    if (Utils.webSocketEnabled(req) && !supportWebSocket()) {
        logger.warn("Websocket protocol not supported");
        res.setStatus(501);
        res.addHeader(X_ATMOSPHERE_ERROR, "Websocket protocol not supported");
        res.flushBuffer();
        return new Action();
    }
    if (config.handlers().isEmpty()) {
        logger.error("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @___Service");
        throw new AtmosphereMappingException("No AtmosphereHandler found. Make sure you define it inside WEB-INF/atmosphere.xml or annotate using @___Service");
    }
    if (res.request() == null) {
        res.request(req);
    }
    if (supportSession()) {
        // Create the session needed to support the Resume
        // operation from disparate requests.
        HttpSession s = req.getSession(config.getInitParameter(PROPERTY_SESSION_CREATE, true));
        // https://github.com/Atmosphere/atmosphere/issues/2034
        try {
            if (s != null && s.isNew()) {
                s.setAttribute(getClass().getName(), "");
                s.removeAttribute(getClass().getName());
            }
        } catch (IllegalStateException ex) {
            AtmosphereResourceImpl r = (AtmosphereResourceImpl) req.resource();
            logger.warn("Session Expired for {}. Closing the connection", req.uuid(), ex);
            if (r != null) {
                logger.trace("Ending request for {}", r.uuid());
                endRequest(r, true);
                return Action.CANCELLED;
            } else {
                logger.trace("Sending error for {}", req.uuid());
                res.setStatus(500);
                res.addHeader(X_ATMOSPHERE_ERROR, "Session expired");
                res.flushBuffer();
                return new Action();
            }
        }
    }
    req.setAttribute(FrameworkConfig.SUPPORT_SESSION, supportSession());
    int tracing = 0;
    AtmosphereHandlerWrapper handlerWrapper = map(req);
    if (config.getBroadcasterFactory() == null) {
        logger.error("Atmosphere is misconfigured and will not work. BroadcasterFactory is null");
        return Action.CANCELLED;
    }
    AtmosphereResourceImpl resource = configureWorkflow(null, handlerWrapper, req, res);
    String v = req.getHeader(HeaderConfig.X_ATMO_BINARY);
    if (v != null) {
        resource.forceBinaryWrite(Boolean.parseBoolean(v));
    }
    if (resource.transport() == AtmosphereResource.TRANSPORT.WEBSOCKET && !Utils.webSocketEnabled(req) && !Utils.isRunningTest()) {
        logger.warn("Transport not matching webSocketEnabled. Ending request for {}", resource.uuid());
        return Action.CANCELLED;
    }
    // handler interceptor lists
    LinkedList<AtmosphereInterceptor> invokedInterceptors = handlerWrapper.interceptors;
    Action a = invokeInterceptors(invokedInterceptors, resource, tracing);
    if (a.type() != Action.TYPE.CONTINUE && a.type() != Action.TYPE.SKIP_ATMOSPHEREHANDLER) {
        return a;
    }
    try {
        // Remap occured.
        if (req.getAttribute(FrameworkConfig.NEW_MAPPING) != null) {
            req.removeAttribute(FrameworkConfig.NEW_MAPPING);
            handlerWrapper = map(req);
            if (handlerWrapper == null) {
                logger.debug("Remap {}", resource.uuid());
                throw new AtmosphereMappingException("Invalid state. No AtmosphereHandler maps request for " + req.getRequestURI());
            }
            resource = configureWorkflow(resource, handlerWrapper, req, res);
            resource.setBroadcaster(handlerWrapper.broadcaster);
        }
        // Unit test mock the request and will throw NPE.
        boolean skipAtmosphereHandler = req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) != null ? (Boolean) req.getAttribute(SKIP_ATMOSPHEREHANDLER.name()) : Boolean.FALSE;
        if (!skipAtmosphereHandler) {
            try {
                logger.trace("\t Last: {}", handlerWrapper.atmosphereHandler.getClass().getName());
                handlerWrapper.atmosphereHandler.onRequest(resource);
            } catch (IOException t) {
                resource.onThrowable(t);
                throw t;
            }
        }
    } finally {
        postInterceptors(handlerWrapper != null ? handlerWrapper.interceptors : invokedInterceptors, resource);
    }
    Action action = resource.action();
    if (supportSession() && allowSessionTimeoutRemoval() && action.type().equals(Action.TYPE.SUSPEND)) {
        // Do not allow times out.
        SessionTimeoutSupport.setupTimeout(config, req.getSession(config.getInitParameter(ApplicationConfig.PROPERTY_SESSION_CREATE, true)));
    }
    logger.trace("Action for {} was {} with transport " + req.getHeader(X_ATMOSPHERE_TRANSPORT), req.resource() != null ? req.resource().uuid() : "null", action);
    return action;
}
Also used : HttpSession(jakarta.servlet.http.HttpSession) AtmosphereHandlerWrapper(org.atmosphere.cpr.AtmosphereFramework.AtmosphereHandlerWrapper) IOException(java.io.IOException)

Example 2 with HttpSession

use of jakarta.servlet.http.HttpSession in project atmosphere by Atmosphere.

the class SessionBroadcasterCache method addToCache.

@Override
public CacheMessage addToCache(String broadcasterId, String uuid, BroadcastMessage message) {
    long now = System.nanoTime();
    CacheMessage cacheMessage = put(message, now, uuid);
    if (uuid.equals(NULL))
        return cacheMessage;
    try {
        HttpSession session = config.resourcesFactory().find(uuid).session();
        if (session == null) {
            logger.error(ERROR_MESSAGE);
            return cacheMessage;
        }
        session.setAttribute(broadcasterId, String.valueOf(now));
    } catch (IllegalStateException ex) {
        logger.trace("", ex);
        logger.warn("The Session has been invalidated. Message will be lost.");
    }
    return cacheMessage;
}
Also used : HttpSession(jakarta.servlet.http.HttpSession)

Example 3 with HttpSession

use of jakarta.servlet.http.HttpSession in project atmosphere by Atmosphere.

the class SessionBroadcasterCache method retrieveFromCache.

@Override
public List<Object> retrieveFromCache(String broadcasterId, String uuid) {
    if (uuid == null) {
        throw new IllegalArgumentException("AtmosphereResource can't be null");
    }
    List<Object> result = new ArrayList<>();
    try {
        AtmosphereResource r = config.resourcesFactory().find(uuid);
        if (r == null) {
            logger.trace("Invalid UUID {}", uuid);
            return result;
        }
        HttpSession session = r.session();
        if (session == null) {
            logger.error(ERROR_MESSAGE);
            return result;
        }
        String cacheHeaderTimeStr = (String) session.getAttribute(broadcasterId);
        if (cacheHeaderTimeStr == null)
            return result;
        long cacheHeaderTime = Long.parseLong(cacheHeaderTimeStr);
        return get(cacheHeaderTime);
    } catch (IllegalStateException ex) {
        logger.trace("", ex);
        logger.warn("The Session has been invalidated. Unable to retrieve cached messages");
        return Collections.emptyList();
    }
}
Also used : AtmosphereResource(org.atmosphere.cpr.AtmosphereResource) HttpSession(jakarta.servlet.http.HttpSession) ArrayList(java.util.ArrayList)

Example 4 with HttpSession

use of jakarta.servlet.http.HttpSession in project atmosphere by Atmosphere.

the class AtmosphereRequestImpl method cloneRequest.

/**
 * Copy the HttpServletRequest content inside an AtmosphereRequest. By default the returned AtmosphereRequest
 * is not destroyable.
 *
 * @param request {@link HttpServletRequest}
 * @return an {@link AtmosphereRequest}
 */
public static final AtmosphereRequest cloneRequest(HttpServletRequest request, boolean loadInMemory, boolean copySession, boolean isDestroyable, boolean createSession) {
    Builder b;
    HttpServletRequest r;
    Cookie[] cs = request.getCookies();
    Set<Cookie> hs = Collections.synchronizedSet(new HashSet<>());
    if (cs != null) {
        Collections.addAll(hs, cs);
    }
    boolean isWrapped = false;
    if (AtmosphereRequestImpl.class.isAssignableFrom(request.getClass())) {
        b = ((AtmosphereRequestImpl) request).b;
        isWrapped = true;
    } else {
        b = new Builder();
        b.request(request);
    }
    HttpSession session = request.getSession(false);
    if (copySession) {
        session = request.getSession(createSession);
        if (session != null) {
            session = new FakeHttpSession(session);
        } else {
            session = new FakeHttpSession("", null, System.currentTimeMillis(), -1);
        }
    }
    b.servletPath(request.getServletPath()).pathInfo(request.getPathInfo()).contextPath(request.getContextPath()).requestURI(request.getRequestURI()).requestURL(request.getRequestURL().toString()).method(request.getMethod()).serverName(request.getServerName()).serverPort(request.getServerPort()).remoteAddr(request.getRemoteAddr()).remoteHost(request.getRemoteHost()).remotePort(request.getRemotePort()).destroyable(isDestroyable).cookies(hs).session(session).principal(request.getUserPrincipal()).authType(request.getAuthType()).isSSecure(request.isSecure());
    if (loadInMemory) {
        String s = (String) attributeWithoutException(request, FrameworkConfig.THROW_EXCEPTION_ON_CLONED_REQUEST);
        boolean throwException = Boolean.parseBoolean(s);
        r = new NoOpsRequest(throwException);
        if (isWrapped) {
            load(b.request, b);
        } else {
            load(request, b);
        }
        b.request(r);
    }
    return isWrapped ? (AtmosphereRequestImpl) request : b.build();
}
Also used : HttpServletRequest(jakarta.servlet.http.HttpServletRequest) Cookie(jakarta.servlet.http.Cookie) FakeHttpSession(org.atmosphere.util.FakeHttpSession) HttpSession(jakarta.servlet.http.HttpSession) FakeHttpSession(org.atmosphere.util.FakeHttpSession)

Example 5 with HttpSession

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

the class HttpSessionOAuth2AuthorizationRequestRepository method getAuthorizationRequests.

/**
 * Gets a non-null and mutable map of {@link OAuth2AuthorizationRequest#getState()} to
 * an {@link OAuth2AuthorizationRequest}
 * @param request
 * @return a non-null and mutable map of {@link OAuth2AuthorizationRequest#getState()}
 * to an {@link OAuth2AuthorizationRequest}.
 */
private Map<String, OAuth2AuthorizationRequest> getAuthorizationRequests(HttpServletRequest request) {
    HttpSession session = request.getSession(false);
    Object sessionAttributeValue = (session != null) ? session.getAttribute(this.sessionAttributeName) : null;
    if (sessionAttributeValue == null) {
        return new HashMap<>();
    } else if (sessionAttributeValue instanceof OAuth2AuthorizationRequest) {
        OAuth2AuthorizationRequest auth2AuthorizationRequest = (OAuth2AuthorizationRequest) sessionAttributeValue;
        Map<String, OAuth2AuthorizationRequest> authorizationRequests = new HashMap<>(1);
        authorizationRequests.put(auth2AuthorizationRequest.getState(), auth2AuthorizationRequest);
        return authorizationRequests;
    } else if (sessionAttributeValue instanceof Map) {
        @SuppressWarnings("unchecked") Map<String, OAuth2AuthorizationRequest> authorizationRequests = (Map<String, OAuth2AuthorizationRequest>) sessionAttributeValue;
        return authorizationRequests;
    } else {
        throw new IllegalStateException("authorizationRequests is supposed to be a Map or OAuth2AuthorizationRequest but actually is a " + sessionAttributeValue.getClass());
    }
}
Also used : HashMap(java.util.HashMap) HttpSession(jakarta.servlet.http.HttpSession) OAuth2AuthorizationRequest(org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest) Map(java.util.Map) HashMap(java.util.HashMap)

Aggregations

HttpSession (jakarta.servlet.http.HttpSession)101 Test (org.junit.jupiter.api.Test)39 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)17 MvcResult (org.springframework.test.web.servlet.MvcResult)16 HttpServletRequest (jakarta.servlet.http.HttpServletRequest)13 MockHttpServletResponse (org.springframework.mock.web.MockHttpServletResponse)12 MockHttpSession (org.springframework.mock.web.MockHttpSession)12 Map (java.util.Map)11 MockHttpServletRequest (org.springframework.web.testfixture.servlet.MockHttpServletRequest)11 MockHttpServletResponse (org.springframework.web.testfixture.servlet.MockHttpServletResponse)9 SecurityContext (org.springframework.security.core.context.SecurityContext)7 PathPatternsParameterizedTest (org.springframework.web.servlet.handler.PathPatternsParameterizedTest)7 Authentication (org.springframework.security.core.Authentication)6 Cookie (jakarta.servlet.http.Cookie)5 Request (org.apache.catalina.connector.Request)5 OAuth2AuthorizedClient (org.springframework.security.oauth2.client.OAuth2AuthorizedClient)5 SessionFixationProtectionStrategy (org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy)5 IOException (java.io.IOException)4 PrintWriter (java.io.PrintWriter)4 Response (org.apache.catalina.connector.Response)4