Example usage for javax.servlet.http HttpServletRequest getRequestedSessionId

List of usage examples for javax.servlet.http HttpServletRequest getRequestedSessionId

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRequestedSessionId.

Prototype

public String getRequestedSessionId();

Source Link

Document

Returns the session ID specified by the client.

Usage

From source file:org.sakaiproject.kernel.rest.test.RestUserProviderKernelUnitT.java

@Test
public void testNewUser() throws ServletException, IOException {
    KernelManager km = new KernelManager();
    SessionManagerService sessionManagerService = km.getService(SessionManagerService.class);
    CacheManagerService cacheManagerService = km.getService(CacheManagerService.class);
    UserResolverService userResolverService = km.getService(UserResolverService.class);

    RegistryService registryService = km.getService(RegistryService.class);
    Registry<String, RestProvider> registry = registryService.getRegistry(RestProvider.REST_REGISTRY);
    RestUserProvider rup = (RestUserProvider) registry.getMap().get("user");

    HttpServletRequest request = createMock(HttpServletRequest.class);
    HttpServletResponse response = createMock(HttpServletResponse.class);
    HttpSession session = createMock(HttpSession.class);

    expect(request.getMethod()).andReturn("POST").anyTimes();

    expect(request.getParameter("firstName")).andReturn("Ian").atLeastOnce();
    expect(request.getParameter("lastName")).andReturn("Ian").atLeastOnce();
    expect(request.getParameter("email")).andReturn("ian@sakai.org").atLeastOnce();
    expect(request.getParameter("eid")).andReturn("ib236").atLeastOnce();
    expect(request.getParameter("password")).andReturn("password").atLeastOnce();
    expect(request.getParameter("userType")).andReturn("student").atLeastOnce();

    response.setContentType("text/plain");
    expectLastCall().atLeastOnce();/*from w  w w  .ja va  2  s  . com*/

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ServletOutputStream out = new ServletOutputStream() {

        @Override
        public void write(int b) throws IOException {
            baos.write(b);
        }

    };
    expect(response.getOutputStream()).andReturn(out).anyTimes();

    expect(request.getRemoteUser()).andReturn(null).anyTimes();
    expect(request.getRequestedSessionId()).andReturn("SESSIONID-123-1").anyTimes();
    expect(session.getId()).andReturn("SESSIONID-123-1").anyTimes();
    Cookie cookie = new Cookie("SAKAIID", "SESSIONID-123-1");
    expect(request.getCookies()).andReturn(new Cookie[] { cookie }).anyTimes();

    expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
    expect(request.getSession(true)).andReturn(session).anyTimes();
    expect(request.getSession(false)).andReturn(session).anyTimes();
    expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
    expect(session.getAttribute("_u")).andReturn(null).anyTimes();
    expect(session.getAttribute("_uu")).andReturn(null).anyTimes();
    expect(request.getLocale()).andReturn(new Locale("en", "US")).anyTimes();
    expect(session.getAttribute("sakai.locale.")).andReturn(null).anyTimes();
    response.addCookie((Cookie) anyObject());
    expectLastCall().anyTimes();

    replay(request, response, session);

    SakaiServletRequest sakaiServletRequest = new SakaiServletRequest(request, response, userResolverService,
            sessionManagerService);
    sessionManagerService.bindRequest(sakaiServletRequest);

    rup.dispatch(new String[] { "user", "new" }, request, response);

    String respBody = new String(baos.toByteArray(), "UTF-8");
    System.err.println("Response Was " + respBody);
    assertTrue(respBody.indexOf("uuid") > 0);
    assertTrue(respBody.indexOf("OK") > 0);

    cacheManagerService.unbind(CacheScope.REQUEST);
    verify(request, response, session);

}

From source file:org.sakaiproject.kernel.session.SessionManagerServiceImpl.java

/**
 * {@inheritDoc}/*from  ww w  .ja v a2 s .c  o  m*/
 *
 * @see org.sakaiproject.kernel.api.session.SessionManagerService#getSession(javax.servlet.http.HttpServletRequest,
 *      boolean)
 */
public HttpSession getSession(HttpServletRequest request, HttpServletResponse response, boolean create) {

    Cache<Object> requestScope = cacheManagerService.getCache(REQUEST_CACHE, CacheScope.REQUEST);
    HttpSession session = (HttpSession) requestScope.get(CURRENT_SESSION);
    if (session != null) {
        return session;
    }

    // try and get it from the cache, if there use it, otherwise create it and
    // place it in the cache.
    // try the container location first
    // PERF: sessionMap could change so this has to be done every time.
    String sessionID = request.getRequestedSessionId();
    if (sessionID != null) {
        // if its not in the map... its not the right session
        session = checkSession(sessionMap.get(sessionID));
        if (debug) {
            LOG.debug("SessionManager (standard): Got Sesssion " + sessionID + " as " + session + " from "
                    + sessionMap);
        }
    }
    // try the cookie
    // PERF: sessionMap could change so this has to be done every time.
    if (session == null) {
        sessionID = null;
        // could be its in a cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie c : cookies) {
                if (cookieName.equals(c.getName())) {
                    sessionID = c.getValue();
                    break;
                }
            }
        }
        if (sessionID != null) {
            session = checkSession(sessionMap.get(sessionID));
            if (debug) {
                LOG.debug("SessionManager (cookie): Got Sesssion " + sessionID + " as " + session + " from "
                        + sessionMap);
            }
        }
        if (session == null) {
            // not in the map of could have no session, so create one (if requested)
            // go back and create with the sever, which will set a cookie,
            // that OK, but also set my cookie.
            // PERF: sessionMap if we were here with create = true, we wont be here
            // again
            // PERF: is we were here with create = false, then we need to try again.
            session = request.getSession(create);
            if (session != null) {
                if (debug) {
                    Exception ex = new Exception("Session Created By:");
                    LOG.debug("SessionManager (created): Got Sesssion " + session.getId() + " as " + session
                            + " from " + sessionMap, ex);
                }
                Cookie c = new Cookie(cookieName, session.getId());
                c.setPath("/");
                c.setMaxAge(-1);
                response.addCookie(c);
                System.err.println("SessionManager (put): Got Sesssion " + session.getId() + " as " + session
                        + " from " + sessionMap);
                // When this is put in here, provided session is not GC'd it will remain 
                // in the sessionMap for other webapps to use.
                // The session is GC'd it will be removed from here.
                sessionMap.put(session.getId(), session);
                requestScope.put(CURRENT_SESSION, session);
            } else if (debug) {
                LOG.debug("SessionManager (failed to create) create=" + create + ": Sesssion " + sessionID
                        + " as null from " + sessionMap);
            }
        }
    }
    return session;
}

From source file:org.sakaiproject.kernel.test.AuthZServiceKernelUnitT.java

/**
 * @param request/*from  w  ww  .ja  va2 s. c  om*/
 * @param response
 * @param session
 */
private void setupRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        String userName) {
    User u = new InternalUser(userName);
    Random r = new Random();
    long sessionID = r.nextLong();
    expect(request.getRemoteUser()).andReturn(userName).anyTimes();
    expect(request.getSession()).andReturn(session).anyTimes();
    expect(request.getSession(true)).andReturn(session).anyTimes();
    expect(request.getSession(false)).andReturn(session).anyTimes();
    expect(session.getId()).andReturn(userName + "SESSIONID-123-A" + sessionID).anyTimes();
    expect(request.getRequestedSessionId()).andReturn(userName + "SESSIONID-123-A" + sessionID).anyTimes();
    Cookie cookie = new Cookie("SAKAIID", "SESSIONID-123-A" + sessionID);
    expect(request.getCookies()).andReturn(new Cookie[] { cookie }).anyTimes();

    expect(session.getAttribute("check-valid")).andReturn(null).anyTimes();
    response.addCookie((Cookie) anyObject());
    expectLastCall().anyTimes();

    expect(session.getAttribute(SessionImpl.USER)).andReturn(u).anyTimes();
    expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
    expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
}

From source file:org.sakaiproject.kernel.test.ObservationKernelUnitT.java

/**
 * @param request/*from   ww w . j a v a2  s .c o  m*/
 * @param response
 * @param session
 */
private void setupRequest(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        String userName) {
    Random r = new Random();
    long sessionID = r.nextLong();
    User u = new InternalUser(userName);
    expect(request.getRemoteUser()).andReturn(userName).anyTimes();
    expect(request.getSession()).andReturn(session).anyTimes();
    expect(request.getSession(true)).andReturn(session).anyTimes();
    expect(request.getSession(false)).andReturn(session).anyTimes();
    expect(session.getId()).andReturn(userName + "SESSIONID-123" + sessionID).anyTimes();
    expect(request.getRequestedSessionId()).andReturn(userName + "SESSIONID-123" + sessionID).anyTimes();
    Cookie cookie = new Cookie("SAKAIID", "SESSIONID-123" + sessionID);
    expect(request.getCookies()).andReturn(new Cookie[] { cookie }).anyTimes();
    expect(session.getAttribute(SessionImpl.USER)).andReturn(u).anyTimes();
    response.addCookie((Cookie) anyObject());
    expectLastCall().anyTimes();
    expect(request.getAttribute("_uuid")).andReturn(null).anyTimes();
    expect(request.getAttribute("_no_session")).andReturn(null).anyTimes();
}

From source file:org.sakaiproject.kernel.webapp.filter.SakaiRequestFilter.java

/**
 * {@inheritDoc}//from w w  w.  java2 s.  c o  m
 *
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hrequest = (HttpServletRequest) request;
    String requestedSessionID = hrequest.getRequestedSessionId();
    if (noSession) {
        request.setAttribute(SakaiServletRequest.NO_SESSION_USE, "true");
    }
    SakaiServletRequest wrequest = new SakaiServletRequest(request, response, userResolverService,
            sessionManagerService);
    SakaiServletResponse wresponse = new SakaiServletResponse(response);
    sessionManagerService.bindRequest(wrequest);
    try {
        begin();
        if (timeOn) {
            long start = System.currentTimeMillis();
            try {
                chain.doFilter(wrequest, wresponse);

            } finally {
                long end = System.currentTimeMillis();
                LOG.info("Request took " + hrequest.getMethod() + " " + hrequest.getPathInfo() + " "
                        + (end - start) + " ms");
            }
        } else {
            chain.doFilter(wrequest, wresponse);
        }
        try {
            if (jcrService.hasActiveSession()) {
                Session session = jcrService.getSession();
                session.save();
            }
        } catch (AccessDeniedException e) {
            throw new SecurityException(e.getMessage(), e);
        } catch (Exception e) {
            LOG.warn(e);
        }
        commit();
    } catch (SecurityException se) {
        se.printStackTrace();
        rollback();
        // catch any Security exceptions and send a 401
        wresponse.reset();
        wresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, se.getMessage());
    } catch (UnauthorizedException ape) {
        rollback();
        // catch any Unauthorized exceptions and send a 401
        wresponse.reset();
        wresponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, ape.getMessage());
    } catch (PermissionDeniedException pde) {
        rollback();
        // catch any permission denied exceptions, and send a 403
        wresponse.reset();
        wresponse.sendError(HttpServletResponse.SC_FORBIDDEN, pde.getMessage());
    } catch (RuntimeException e) {
        rollback();
        throw e;
    } catch (IOException e) {
        rollback();
        throw e;
    } catch (ServletException e) {
        rollback();
        throw e;
    } catch (Throwable t) {
        rollback();
        throw new ServletException(t.getMessage(), t);
    } finally {
        wresponse.commitStatus(sessionManagerService);
        cacheManagerService.unbind(CacheScope.REQUEST);
    }
    if (debug) {
        HttpSession hsession = hrequest.getSession(false);
        if (hsession != null && !hsession.getId().equals(requestedSessionID)) {
            LOG.debug("New Session Created with ID " + hsession.getId());
        }
    }

}

From source file:org.soaplab.clients.spinet.filters.RequestDumperFilter.java

/**
 * Time the processing that is performed by all subsequent filters in the
 * current filter stack, including the ultimately invoked servlet.
 *
 * @param request The servlet request we are processing
 * @param result The servlet response we are creating
 * @param chain The filter chain we are processing
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 *///from  www.  j  a va 2s  . c om
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (filterConfig == null)
        return;

    // Render the generic servlet request properties
    StringWriter sw = new StringWriter();
    PrintWriter writer = new PrintWriter(sw);
    writer.println("Request Received at " + (new Timestamp(System.currentTimeMillis())));
    writer.println(" characterEncoding=" + request.getCharacterEncoding());
    writer.println("     contentLength=" + request.getContentLength());
    writer.println("       contentType=" + request.getContentType());
    writer.println("            locale=" + request.getLocale());
    writer.print("           locales=");
    Enumeration locales = request.getLocales();
    boolean first = true;
    while (locales.hasMoreElements()) {
        Locale locale = (Locale) locales.nextElement();
        if (first)
            first = false;
        else
            writer.print(", ");
        writer.print(locale.toString());
    }
    writer.println();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = (String) names.nextElement();
        writer.print("         parameter=" + name + "=");
        String values[] = request.getParameterValues(name);
        for (int i = 0; i < values.length; i++) {
            if (i > 0)
                writer.print(", ");
            writer.print(values[i]);
        }
        writer.println();
    }
    writer.println("          protocol=" + request.getProtocol());
    writer.println("        remoteAddr=" + request.getRemoteAddr());
    writer.println("        remoteHost=" + request.getRemoteHost());
    writer.println("            scheme=" + request.getScheme());
    writer.println("        serverName=" + request.getServerName());
    writer.println("        serverPort=" + request.getServerPort());
    writer.println("          isSecure=" + request.isSecure());

    // Render the HTTP servlet request properties
    if (request instanceof HttpServletRequest) {
        writer.println("---------------------------------------------");
        HttpServletRequest hrequest = (HttpServletRequest) request;
        writer.println("       contextPath=" + hrequest.getContextPath());
        Cookie cookies[] = hrequest.getCookies();
        if (cookies == null)
            cookies = new Cookie[0];
        for (int i = 0; i < cookies.length; i++) {
            writer.println("            cookie=" + cookies[i].getName() + "=" + cookies[i].getValue());
        }
        names = hrequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = (String) names.nextElement();
            String value = hrequest.getHeader(name);
            writer.println("            header=" + name + "=" + value);
        }
        writer.println("            method=" + hrequest.getMethod());
        writer.println("          pathInfo=" + hrequest.getPathInfo());
        writer.println("       queryString=" + hrequest.getQueryString());
        writer.println("        remoteUser=" + hrequest.getRemoteUser());
        writer.println("requestedSessionId=" + hrequest.getRequestedSessionId());
        writer.println("        requestURI=" + hrequest.getRequestURI());
        writer.println("       servletPath=" + hrequest.getServletPath());
    }
    writer.println("=============================================");

    // Log the resulting string
    writer.flush();
    filterConfig.getServletContext().log(sw.getBuffer().toString());
    log.info(sw.getBuffer().toString());

    // Pass control on to the next filter
    chain.doFilter(request, response);

}

From source file:org.structr.rest.auth.SessionHelper.java

public static Principal checkSessionAuthentication(final HttpServletRequest request) throws FrameworkException {

    String requestedSessionId = request.getRequestedSessionId();
    String sessionId = null;/*from w w w .  ja va2 s.  c  o m*/

    logger.debug("0. Requested session id: " + requestedSessionId + ", request says is valid? "
            + request.isRequestedSessionIdValid());

    //HttpSession session       = request.getSession(false);
    boolean isNotTimedOut = false;

    if (requestedSessionId == null) {

        logger.debug("1b. Empty requested session id, creating a new one.");

        // No session id requested => create new session
        SessionHelper.newSession(request);

        // Store info in request that session is new => saves us a lookup later
        request.setAttribute(SESSION_IS_NEW, true);

        // we just created a totally new session, there can't
        // be a user with this session ID, so don't search.
        return null;

    } else {

        requestedSessionId = getShortSessionId(requestedSessionId);

        // Existing session id, check if we have an existing session
        if (request.getSession(false) != null) {

            logger.debug("1a. Requested session id without worker id suffix: " + requestedSessionId);

            sessionId = request.getSession(false).getId();
            logger.debug("2a. Current session id: " + sessionId);

            if (sessionId.equals(requestedSessionId)) {

                logger.debug("3a. Current session id equals requested session id");
            } else {

                logger.debug("3b. Current session id does not equal requested session id.");
            }

        } else {

            logger.debug("2b. Current session is null.");

            // Try to find session in session cache
            if (getSessionBySessionId(requestedSessionId) == null) {

                // Not found, create new
                SessionHelper.newSession(request);
                logger.debug("3a. Created new session");

                // remove session ID without session
                SessionHelper.clearSession(requestedSessionId);
                logger.debug("4. Cleared unknown session " + requestedSessionId);

                // we just created a totally new session, there can't
                // be a user with this session ID, so don't search.
                return null;

            } else {
                logger.debug("3b. Session with requested id " + requestedSessionId + " found, continuing.");

                sessionId = requestedSessionId;

            }

        }

        if (SessionHelper.isSessionTimedOut(request.getSession(false))) {

            isNotTimedOut = false;

            // invalidate session
            SessionHelper.invalidateSession(sessionId);

            // remove invalid session ID
            SessionHelper.clearSession(sessionId);

            logger.debug("4a. Cleared timed-out session " + sessionId);

            SessionHelper.newSession(request);
            // we just created a totally new session, there can't
            // be a user with this session ID, so don't search.
            return null;

        } else {

            logger.debug("4b. Session " + sessionId + " is not timed-out.");

            isNotTimedOut = true;
        }
    }

    if (isNotTimedOut) {

        final Principal user = AuthHelper.getPrincipalForSessionId(sessionId);
        //logger.debug("Valid session found: {}, last accessed {}, authenticated with user {}", new Object[]{session, session.getLastAccessedTime(), user});

        return user;

    } else {

        final Principal user = AuthHelper.getPrincipalForSessionId(sessionId);
        if (user != null) {

            //logger.info("Timed-out session: {}, last accessed {}, authenticated with user {}", new Object[]{session, (session != null ? session.getLastAccessedTime() : ""), user});
            logger.debug("Logging out user {}", new Object[] { user });
            AuthHelper.doLogout(request, user);
            try {
                request.logout();
            } catch (Throwable t) {
            }
        }

        SessionHelper.newSession(request);

        return null;
    }
}

From source file:org.structr.web.auth.HttpAuthenticator.java

@Override
public Principal doLogin(HttpServletRequest request, String emailOrUsername, String password)
        throws AuthenticationException {

    Principal user = AuthHelper.getPrincipalForPassword(Person.eMail, emailOrUsername, password);

    if (user == null) {

        // try again with name
        user = AuthHelper.getPrincipalForPassword(AbstractNode.name, emailOrUsername, password);

    }//  w  w w  . ja v a 2s  .  c om

    if (user != null) {

        final String sessionIdFromRequest = request.getRequestedSessionId();
        final App app = StructrApp.getInstance();
        final Principal principal = user;

        try {

            app.beginTx();
            principal.setProperty(Principal.sessionId, sessionIdFromRequest);
            app.commitTx();

        } catch (FrameworkException ex) {

            logger.log(Level.SEVERE, null, ex);

        } finally {

            app.finishTx();
        }

    }

    return user;

}

From source file:org.structr.web.auth.HttpAuthenticator.java

protected static Principal checkSessionAuthentication(HttpServletRequest request) {

    String sessionIdFromRequest = request.getRequestedSessionId();

    if (sessionIdFromRequest == null) {

        // create session id
        request.getSession(true);//from w w  w  . j a va  2s  .com
        return null;

    }

    Principal user = AuthHelper.getPrincipalForSessionId(sessionIdFromRequest);

    if (user != null) {

        return user;

    }

    return null;

}

From source file:org.structr.web.auth.HttpAuthenticator.java

private static String getSessionId(final HttpServletRequest request) {

    String existingSessionId = request.getRequestedSessionId();

    if (existingSessionId == null) {

        HttpSession session = request.getSession(true);

        logger.log(Level.INFO, "Created new HTTP session: {0}", session.toString());

        return session.getId();

    }/*from w  ww .j a  va2  s .c  o  m*/

    return existingSessionId;

}