Example usage for javax.servlet.http HttpSession getId

List of usage examples for javax.servlet.http HttpSession getId

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getId.

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:org.shareok.data.webserv.UserSessionInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    try {/*from   w  ww.  j  a  v a  2s.  co m*/
        String contextPath = request.getServletPath();
        if (contextPath.contains("/")) {
            contextPath = contextPath.split("/")[1];
        }
        if (null != contextPath && !"".equals(contextPath)
                && ShareokdataManager.requiredUserAuthentication(contextPath)) {
            SessionRepository<Session> repo = (SessionRepository<Session>) request
                    .getAttribute(SessionRepository.class.getName());

            if (contextPath.equals("register")) {
                if (!configService.getRegistrationConfig()) {
                    throw new NoNewUserRegistrationException("The registraion of new users has been closed!");
                }
                String email = (String) request.getParameter("email");
                String password = pwAuthenService.hash((String) request.getParameter("password"));
                String userName = (String) request.getParameter("nickname");
                if (null == email || "".equals(email)) {
                    throw new UserRegisterInfoNotFoundException(
                            "Valid email register information is required!");
                }
                if (null == password || "".equals(password)) {
                    throw new UserRegisterInfoNotFoundException("Valid password is required for registration!");
                }
                /*****************
                 * Some password validation logic here:
                 */
                HttpSession httpSession = (HttpSession) request.getSession();
                ExpiringSession session = (ExpiringSession) repo.getSession(httpSession.getId());
                if (null == session) {
                    session = (ExpiringSession) repo.createSession();
                }
                String sessionId = session.getId();
                RedisUser user = redisUserService.findUserByUserEmail(email);
                if (null != user) {
                    throw new RegisterUserInfoExistedException("User Email has already Existed!");
                } else {
                    user = redisUserService.getNewUser();
                    user.setEmail(email);
                    user.setPassword(password);
                    if (null == userName || userName.equals("")) {
                        userName = email;
                    }
                    user.setUserName(userName);
                    user.setSessionKey(sessionId);
                    redisUserService.addUser(user);
                }

                setSessionUserInfo(session, httpSession, user);
                repo.save(session);
            } else if (contextPath.equals("userLogin")) {
                String email = (String) request.getParameter("email");
                String password = (String) request.getParameter("password");
                if (null == email || "".equals(email)) {
                    throw new UserRegisterInfoNotFoundException(
                            "Valid email information is required for logging in!");
                }
                if (null == password || "".equals(password)) {
                    throw new UserRegisterInfoNotFoundException("Valid password is required for logging in!");
                }
                /*****************
                 * Some password validation logic here:
                 */
                HttpSession httpSession = (HttpSession) request.getSession();
                ExpiringSession session = (ExpiringSession) repo.getSession(httpSession.getId());
                if (null == session || session.isExpired()) {
                    session = (ExpiringSession) repo.createSession();
                }
                String sessionId = session.getId();
                RedisUser user = redisUserService.findUserByUserEmail(email);

                if (null == user || !pwAuthenService.authenticate(password, user.getPassword())) {
                    throw new UserRegisterInfoNotFoundException("User information cannot be found!");
                }

                user.setSessionKey(sessionId);
                redisUserService.updateUser(user);

                setSessionUserInfo(session, httpSession, user);
                httpSession.setAttribute("email", email);
                repo.save(session);
            } else if (contextPath.equals("logout")) {
                HttpSession session = (HttpSession) request.getSession(false);
                if (null != session) {
                    ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId());
                    if (null != exSession) {
                        String email = (String) session.getAttribute("email");
                        if (null != email) {
                            redisUserService.invalidateUserSessionIdByEmail(email);
                        }
                        exSession.isExpired();
                        repo.delete(exSession.getId());
                    }
                    session.invalidate();
                }
            }
            // *** The following situation applies to authentication logic based on session information ***
            else {
                boolean sessionValidated = false;
                HttpSession session = (HttpSession) request.getSession(false);
                if (null != session) {
                    ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId());
                    if (null != exSession && !exSession.isExpired()) {
                        String email = (String) session.getAttribute("email");
                        if (null != email) {
                            RedisUser userPersisted = redisUserService.findAuthenticatedUser(email,
                                    session.getId());
                            if (null != userPersisted) {
                                sessionValidated = true;
                            }
                        }
                    }
                }

                if (!sessionValidated) {
                    if (null != session) {
                        repo.delete(session.getId());
                        session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), null);
                        session.invalidate();
                    }
                    request.logout();
                    //request.getRequestDispatcher("/WEB-INF/jsp/logout.jsp").forward(request, response);
                    HttpServletResponse httpReponse = (HttpServletResponse) response;
                    httpReponse.sendRedirect("/webserv/login");
                }
            }
        } else {
            ;
        }
    } catch (IOException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (ServletException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (UserRegisterInfoNotFoundException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (RegisterUserInfoExistedException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (NoNewUserRegistrationException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/closedRegistration.jsp").forward(request, response);
    }

    return true;
}

From source file:at.gv.egiz.pdfas.web.helper.PdfAsHelper.java

public static void logAccess(HttpServletRequest request) {
    HttpSession session = request.getSession();
    logger.info("Access to " + request.getServletPath() + " in Session: " + session.getId());
}

From source file:com.vportal.portal.servlet.PortalSessionListener.java

public void sessionDestroyed(HttpSessionEvent event) {
    /*if (PropsValues.SESSION_DISABLED) {
    return;/*from   ww  w  . ja va2  s  . c o  m*/
    }*/
    //hoan
    if (GetterUtil.getBoolean(PropsUtil.get("SESSION_DISABLED"))) {
        return;
    }
    //hoan

    HttpSession ses = event.getSession();

    MethodKey method = new MethodKey("com.liferay.portal.kernel.util.Validator.PortalSessionContext", "remove",
            String.class);
    Object[] args = new Object[] { ses.getId() };
    try {
        PortalClassInvoker.invoke(false, method, args);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    //PortalSessionContext.remove(ses.getId());

    try {
        Long userIdObj = (Long) ses.getAttribute(WebKeys.USER_ID);

        if (userIdObj == null) {
            _log.warn("User id is not in the session");
        } else {
            long userId = userIdObj.longValue();

            if (CompanyThreadLocal.getCompanyId() == 0) {
                setCompanyId(userId);
            }

            //MailSessionLock.cleanUp(ses);
            MethodKey methodSignOut = new MethodKey("com.liferay.portal.liveusers.LiveUsers", "signOut",
                    long.class, String.class, String.class);
            Object[] argsSignOut = new Object[] { CompanyThreadLocal.getCompanyId(), userId, ses.getId() };
            PortalClassInvoker.invoke(false, methodSignOut, argsSignOut);
            //LiveUsers.signOut(CompanyThreadLocal.getCompanyId(), userId, ses.getId());
        }

    } catch (IllegalStateException ise) {
        _log.warn("Please upgrade to a servlet 2.4 compliant container");
    } catch (Exception e) {
        _log.error(e, e);
    }
    //ses.removeAttribute(WebKeys.PORTLET_SESSION_TRACKER);
    //ses.removeAttribute(WebKeys.REVERSE_AJAX);

    //MessagingUtil.closeXMPPConnection(ses);

    // Process session destroyed events

    try {
        /*EventsProcessor.process(
        PropsKeys.SERVLET_SESSION_DESTROY_EVENTS,
        PropsValues.SERVLET_SESSION_DESTROY_EVENTS, ses);*/
        //hoan
        MethodKey methodProcess = new MethodKey("com.liferay.portal.events.EventsProcessorUtil", "process",
                String.class, String.class, HttpSession.class);
        Object[] argsProcess = new Object[] { PropsKeys.SERVLET_SESSION_DESTROY_EVENTS,
                PropsUtil.getArray(PropsKeys.SERVLET_SESSION_DESTROY_EVENTS), ses };
        PortalClassInvoker.invoke(false, methodProcess, argsProcess);

        /*EventsProcessorUtil.process(
              PropsKeys.SERVLET_SESSION_DESTROY_EVENTS,
              PropsValues.SERVLET_SESSION_DESTROY_EVENTS, ses);*/
        //hoan

    } catch (ActionException ae) {
        _log.error(ae, ae);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:org.apache.stratos.rest.endpoint.api.AuthenticationApi.java

@GET
@Path("/cookie")
@Produces("application/json")
@Consumes("application/json")
@AuthorizationAction("/permission/protected/manage/monitor/tenants")
public Response getCookie() {
    HttpSession httpSession = httpServletRequest.getSession(true);//create session if not found
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    httpSession.setAttribute("userName", carbonContext.getUsername());
    httpSession.setAttribute("tenantDomain", carbonContext.getTenantDomain());
    httpSession.setAttribute("tenantId", carbonContext.getTenantId());

    String sessionId = httpSession.getId();
    return Response.ok().header("WWW-Authenticate", "Basic").type(MediaType.APPLICATION_JSON)
            .entity(Utils.buildAuthenticationSuccessMessage(sessionId)).build();
}

From source file:com.adito.boot.Util.java

/**
 * Dump all session attributes to {@link System#err}.
 * /*from w  w  w .  ja v a2 s. co  m*/
 * @param session session to get attributes from
 */
public static void dumpSessionAttributes(HttpSession session) {
    System.err.println("Session attributes for " + session.getId());
    for (Enumeration e = session.getAttributeNames(); e.hasMoreElements();) {
        String n = (String) e.nextElement();
        System.err.println("   " + n + " = " + session.getAttribute(n));
    }
}

From source file:dk.itst.oiosaml.sp.service.SPFilter.java

/**
 * Check whether the user is authenticated i.e. having session with a valid
 * assertion. If the user is not authenticated an &lt;AuthnRequest&gt; is sent to
 * the Login Site./*from w ww .  j  a  v  a 2  s  . c o m*/
 * 
 * @param request
 *            The servletRequest
 * @param response
 *            The servletResponse
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (log.isDebugEnabled())
        log.debug("OIOSAML-J SP Filter invoked");

    if (!(request instanceof HttpServletRequest)) {
        throw new RuntimeException("Not supported operation...");
    }
    HttpServletRequest servletRequest = ((HttpServletRequest) request);
    Audit.init(servletRequest);

    if (!isFilterInitialized()) {
        try {
            Configuration conf = SAMLConfiguration.getSystemConfiguration();
            setRuntimeConfiguration(conf);
        } catch (IllegalStateException e) {
            request.getRequestDispatcher("/saml/configure").forward(request, response);
            return;
        }
    }
    if (conf.getBoolean(Constants.PROP_DEVEL_MODE, false)) {
        log.warn("Running in debug mode, skipping regular filter");
        develMode.doFilter(servletRequest, (HttpServletResponse) response, chain, conf);
        return;
    }

    if (cleanerRunning.compareAndSet(false, true)) {
        SessionCleaner.startCleaner(sessionHandlerFactory.getHandler(),
                ((HttpServletRequest) request).getSession().getMaxInactiveInterval(), 30);
    }

    SessionHandler sessionHandler = sessionHandlerFactory.getHandler();

    if (servletRequest.getServletPath().equals(conf.getProperty(Constants.PROP_SAML_SERVLET))) {
        log.debug("Request to SAML servlet, access granted");
        chain.doFilter(new SAMLHttpServletRequest(servletRequest, hostname, null), response);
        return;
    }

    final HttpSession session = servletRequest.getSession();
    if (log.isDebugEnabled())
        log.debug("sessionId....:" + session.getId());

    // Is the user logged in?
    if (sessionHandler.isLoggedIn(session.getId())
            && session.getAttribute(Constants.SESSION_USER_ASSERTION) != null) {
        int actualAssuranceLevel = sessionHandler.getAssertion(session.getId()).getAssuranceLevel();
        int assuranceLevel = conf.getInt(Constants.PROP_ASSURANCE_LEVEL);
        if (actualAssuranceLevel < assuranceLevel) {
            sessionHandler.logOut(session);
            log.warn("Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
            throw new RuntimeException(
                    "Assurance level too low: " + actualAssuranceLevel + ", required: " + assuranceLevel);
        }
        UserAssertion ua = (UserAssertion) session.getAttribute(Constants.SESSION_USER_ASSERTION);
        if (log.isDebugEnabled())
            log.debug("Everything is ok... Assertion: " + ua);

        Audit.log(Operation.ACCESS, servletRequest.getRequestURI());

        try {
            UserAssertionHolder.set(ua);
            HttpServletRequestWrapper requestWrap = new SAMLHttpServletRequest(servletRequest, ua, hostname);
            chain.doFilter(requestWrap, response);
            return;
        } finally {
            UserAssertionHolder.set(null);
        }
    } else {
        session.removeAttribute(Constants.SESSION_USER_ASSERTION);
        UserAssertionHolder.set(null);

        String relayState = sessionHandler.saveRequest(Request.fromHttpRequest(servletRequest));

        String protocol = conf.getString(Constants.PROP_PROTOCOL, "saml20");
        String loginUrl = conf.getString(Constants.PROP_SAML_SERVLET, "/saml");

        String protocolUrl = conf.getString(Constants.PROP_PROTOCOL + "." + protocol);
        if (protocolUrl == null) {
            throw new RuntimeException(
                    "No protocol url configured for " + Constants.PROP_PROTOCOL + "." + protocol);
        }
        loginUrl += protocolUrl;
        if (log.isDebugEnabled())
            log.debug("Redirecting to " + protocol + " login handler at " + loginUrl);

        RequestDispatcher dispatch = servletRequest.getRequestDispatcher(loginUrl);
        dispatch.forward(new SAMLHttpServletRequest(servletRequest, hostname, relayState), response);
    }
}

From source file:com.rockagen.gnext.service.spring.security.extension.BasicConcurrentSessionControlStrategy.java

/**
 * /* w ww.jav  a 2  s . com*/
 * @see org.springframework.security.web.authentication.session.SessionFixationProtectionStrategy#onSessionChange(java.lang.String, javax.servlet.http.HttpSession, org.springframework.security.core.Authentication)
 */
@Override
protected void onSessionChange(String originalSessionId, HttpSession newSession, Authentication auth) {
    // Update the session registry
    BasicPrincipal basicPrincipal = new BasicPrincipal(auth);
    sessionRegistry.removeSessionInformation(originalSessionId);
    sessionRegistry.registerNewSession(newSession.getId(), basicPrincipal);
}

From source file:gov.nih.nci.rembrandt.web.taglib.HCPlotReport.java

public int doStartTag() {
    try {/*from   w ww  .  j av a 2 s  . co m*/
        JspWriter out = pageContext.getOut();
        ServletRequest request = pageContext.getRequest();
        HttpSession session = pageContext.getSession();
        StringBuffer xhtml = new StringBuffer();
        if (taskId != null) {

            hcaFinding = (HCAFinding) businessTierCache.getSessionFinding(session.getId(), taskId);
            List<String> clusterByIds = new ArrayList();
            //ok, what did we cluster by?...can only be 1
            if (hcaFinding != null) {
                HierarchicalClusteringQueryDTO hcQueryDTO = (HierarchicalClusteringQueryDTO) hcaFinding
                        .getQueryDTO();
                ArrayPlatformType arrayPlatform = hcQueryDTO.getArrayPlatformDE() != null
                        ? hcQueryDTO.getArrayPlatformDE().getValueObjectAsArrayPlatformType()
                        : ArrayPlatformType.AFFY_OLIGO_PLATFORM;
                if (hcaFinding.getClusteredReporterIDs() != null
                        && hcaFinding.getClusteredReporterIDs().size() > 0) {
                    clusterByIds = (List) hcaFinding.getClusteredReporterIDs();
                    xhtml.append(quickReporterReport(clusterByIds, arrayPlatform));
                } else if (hcaFinding.getClusteredSampleIDs() != null
                        && hcaFinding.getClusteredSampleIDs().size() > 0) {
                    clusterByIds = (List) hcaFinding.getClusteredSampleIDs();
                    xhtml.append(quickSampleReport(clusterByIds));
                }
            }

            out.println(xhtml.toString());
        } else {
            out.println("No Report Available.");
        }
    } catch (Exception ex) {
        throw new Error("All is not well in the world.");
    }
    // Must return SKIP_BODY because we are not supporting a body for this tag.
    return SKIP_BODY;
}

From source file:com.feilong.servlet.http.RequestLogBuilder.java

/**
 * ?./*from  w w w .  j a  v a 2s . c  o  m*/
 * 
 * <p>
 * ?log, Cannot create a session after the response has been committed <br>
 * 
 * </p>
 * 
 * <p>
 * I have learnt that maybe my 8K buffer gets full in some cases (as you said, my contect is dynamic and sometimes could be large). <br>
 * 
 * In that case, I have understanded that a full buffer triggers a commit, and when that happens the JSP error page can not do its job
 * and then "java.lang.IllegalStateException: Cannot create a session after the response has been committed" happens. <br>
 * 
 * OK, but is there any other possible reason for the early commit? <br>
 * My session is created early enough, and in fact the JSP page creates it if necessary, by default.
 * </p>
 *
 * @return the session id,,  {@link java.lang.Throwable#getMessage()}
 * @since 1.4.1
 */
private String getSessionId() {
    try {
        HttpSession session = request.getSession(false);
        return null == session ? EMPTY : session.getId();
    } catch (IllegalStateException e) {//Cannot create a session after the response has been committed 
        String msg = Slf4jUtil.format("uri:[{}],paramMap:{}", request.getRequestURI(),
                request.getParameterMap());
        LOGGER.error(msg, e);
        return e.getMessage();
    }
}