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:com.sslexplorer.security.DefaultLogonController.java

public void initialiseSession(HttpSession session, User user) throws UserDatabaseException {
    if (log.isInfoEnabled())
        log.info("Initialising session " + session.getId() + " with user "
                + (user == null ? "[none]" : user.getPrincipalName()));
    PropertyProfile profile = (PropertyProfile) session.getAttribute(Constants.SELECTED_PROFILE);
    session.setAttribute(Constants.USER, user);
    String logonInfo = MessageResources.getMessageResources("com.sslexplorer.navigation.ApplicationResources")
            .getMessage("footer.info", user.getPrincipalName(),
                    SimpleDateFormat.getDateTimeInstance().format(new Date()));
    session.setAttribute(Constants.LOGON_INFO, logonInfo);
    try {//w w  w  .  j a v a2  s.  com
        List profiles = ResourceUtil.filterResources(user, ProfilesFactory.getInstance()
                .getPropertyProfiles(user.getPrincipalName(), true, user.getRealm().getResourceId()), true);
        session.setAttribute(Constants.PROFILES, profiles);
        if (profiles.size() == 0) {
            throw new UserDatabaseException("You do not have permission to use any profiles.");
        }
        String startupProfile = Property.getProperty(new UserAttributeKey(user, User.USER_STARTUP_PROFILE));
        if (profiles.size() < 2) {
            profile = (PropertyProfile) profiles.get(0);
        } else if (!startupProfile.equals(ProfilesListDataSource.SELECT_ON_LOGIN)) {
            int profileId = Integer.parseInt(startupProfile);
            profile = null;
            for (Iterator i = profiles.iterator(); i.hasNext();) {
                PropertyProfile p = (PropertyProfile) i.next();
                if (profileId == p.getResourceId()) {
                    profile = p;
                    break;
                }
            }
            if (profile == null) {
                profile = ProfilesFactory.getInstance().getPropertyProfile(null, "Default",
                        UserDatabaseManager.getInstance().getDefaultUserDatabase().getRealm().getResourceId());
            }
        }
        if (profile != null) {
            if (log.isInfoEnabled())
                log.info("Switching user " + user.getPrincipalName() + " to profile "
                        + profile.getResourceName());
            session.setAttribute(Constants.SELECTED_PROFILE, profile);
        }
    } catch (Exception e) {
        throw new UserDatabaseException("Failed to initialise profiles.", e);
    }
    final String logonTicket = (String) session.getAttribute(Constants.LOGON_TICKET);
    session.setAttribute(Constants.LOGOFF_HOOK, new HttpSessionBindingListener() {
        public void valueBound(HttpSessionBindingEvent evt) {
        }

        public void valueUnbound(HttpSessionBindingEvent evt) {
            if (log.isDebugEnabled())
                log.debug("Session unbound");
            // We should should only log off completely if no other
            // session has
            // the logon ticket
            SessionInfo currentTicketSessionInfo = ((SessionInfo) logons.get(logonTicket));
            if (currentTicketSessionInfo == null
                    || evt.getSession().getId().equals(currentTicketSessionInfo.getHttpSession().getId())) {
                if (log.isDebugEnabled())
                    log.debug("Session (" + evt.getSession().getId()
                            + ") unbound is the current session for ticket " + logonTicket
                            + " so a logoff will be performed.");
                logoff(logonTicket);
            } else {
                if (log.isDebugEnabled())
                    log.debug("Session unbound is NOT the current session, ignoring.");
            }
        }
    });
    if (log.isDebugEnabled())
        log.debug("Using profile: " + (profile == null ? "DEFAULT" : profile.getResourceName()) + ")");
    session.removeAttribute(Constants.SESSION_LOCKED);

    resetSessionTimeout(user, profile, session);
}

From source file:org.apache.catalina.cluster.tcp.ReplicationValve.java

/**
 * Log the interesting request parameters, invoke the next Valve in the
 * sequence, and log the interesting response parameters.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 * @param context The valve context used to invoke the next valve
 *  in the current processing pipeline//from  w w  w .jav a 2s  . c om
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
public void invoke(Request request, Response response, ValveContext context)
        throws IOException, ServletException {
    //this happens before the request
    context.invokeNext(request, response);
    //this happens after the request
    try {
        long start = System.currentTimeMillis();
        HttpRequest hrequest = (HttpRequest) request;
        HttpServletRequest hreq = (HttpServletRequest) hrequest.getRequest();
        HttpSession session = hreq.getSession(false);

        if (!(request.getContext().getManager() instanceof ClusterManager))
            return;

        ClusterManager manager = (ClusterManager) request.getContext().getManager();
        SimpleTcpCluster cluster = (SimpleTcpCluster) getContainer().getCluster();
        if (cluster == null) {
            log.warn("No cluster configured for this request.");
            return;
        }
        //first check for session invalidations
        String[] invalidIds = manager.getInvalidatedSessions();
        if (invalidIds.length > 0) {
            for (int i = 0; i < invalidIds.length; i++) {
                try {
                    SessionMessage imsg = manager.requestCompleted(invalidIds[i]);
                    if (imsg != null)
                        cluster.send(imsg);
                } catch (Exception x) {
                    log.error("Unable to send session invalid message over cluster.", x);
                }
            }
        }

        String id = null;
        if (session != null)
            id = session.getId();
        else
            return;

        if (id == null)
            return;

        if ((request.getContext().getManager() == null)
                || (!(request.getContext().getManager() instanceof ClusterManager)))
            return;

        String uri = hrequest.getDecodedRequestURI();
        boolean filterfound = false;

        for (int i = 0; (i < reqFilters.length) && (!filterfound); i++) {
            java.util.regex.Matcher matcher = reqFilters[i].matcher(uri);
            filterfound = matcher.matches();
        } //for
        if (filterfound)
            return;

        log.debug("Invoking replication request on " + uri);

        SessionMessage msg = manager.requestCompleted(id);

        if (msg == null)
            return;

        cluster.send(msg);
        long stop = System.currentTimeMillis();
        addClusterSendTime(stop - start);

    } catch (Exception x) {
        log.error("Unable to perform replication request.", x);
    }
}

From source file:org.apache.stratos.rest.endpoint.api.StratosApiV40.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:org.terasoluna.gfw.web.token.transaction.HttpSessionTransactionTokenStore.java

/**
 * Creates a new Token key and reserve it in the HttpSession<br>
 * removes oldeset token if token size is greater than or equals {@link #transactionTokensPerTokenName} in the same
 * namespace./*  w ww . j  a  v a 2  s  .c om*/
 * @see org.terasoluna.gfw.web.token.transaction.TransactionTokenStore#createAndReserveTokenKey(java.lang.String)
 */
@Override
public String createAndReserveTokenKey(String tokenName) {
    String tokenNamePrefix = TOKEN_HOLDER_SESSION_ATTRIBUTE_PREFIX + tokenName;
    Set<String> sessionAttributeNames = new HashSet<String>();
    HttpSession session = getSession();
    Object mutex = getMutex(session);
    String tokenKey = null;
    synchronized (mutex) {
        Enumeration<String> tokenNameEnumeration = session.getAttributeNames();
        while (tokenNameEnumeration.hasMoreElements()) {
            String name = tokenNameEnumeration.nextElement();
            // fetch the sessionKeyPrefix (session key with only Token prefix and namespace name) and compare
            if (tokenNamePrefix.equals(name.split(TransactionToken.TOKEN_STRING_SEPARATOR)[0])) {
                sessionAttributeNames.add(name);
            }
        }

        for (int i = 0, max = sessionAttributeNames.size(); i < max; i++) {
            // do not use while loop to avoid infinite loop
            if (sessionAttributeNames.size() >= transactionTokensPerTokenName) {
                removeOldTokenName(sessionAttributeNames, session);
            } else {
                break;
            }
        }

        for (int i = 0; i < retryCreateTokenName; i++) {
            String str = generator.generate(session.getId());
            String name = tokenNamePrefix + TransactionToken.TOKEN_STRING_SEPARATOR + str;
            if (!sessionAttributeNames.contains(name)) {
                tokenKey = str;
                break;
            }
        }
    }
    if (tokenKey == null) {
        throw new IllegalStateException(
                "token key generation failed within retry count " + retryCreateTokenName);
    }

    return tokenKey;
}

From source file:com.dien.upload.server.UploadServlet.java

/**
 * Method executed each time the client asks the server for the progress status.
 * It uses the listener to generate the adequate response
 * /*from ww  w  .j a  va2  s . co  m*/
 * @param request
 * @param fieldname
 * @return a map of tag/values to be rendered 
 */
protected Map<String, String> getUploadStatus(HttpServletRequest request, String fieldname, Map ret) {

    perThreadRequest.set(request);

    HttpSession session = request.getSession();

    if (ret == null) {
        ret = new HashMap();
    }

    long currentBytes = 0;
    long totalBytes = 0;
    long percent = 0;
    AbstractUploadListener listener = getCurrentListener(request);
    if (listener != null) {
        if (listener.getException() != null) {
            if (listener.getException() instanceof UploadCanceledException) {
                ret.put(TAG_CANCELED, true);
                ret.put(TAG_FINISHED, TAG_CANCELED);
                logger.error("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname
                        + " canceled by the user after " + listener.getBytesRead() + " Bytes");
            } else {
                String errorMsg = getMessage("server_error", listener.getException().getMessage());
                ret.put(TAG_ERROR, errorMsg);
                ret.put(TAG_FINISHED, TAG_ERROR);
                logger.error("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname
                        + " finished with error: " + listener.getException().getMessage());
            }
        } else {
            currentBytes = listener.getBytesRead();
            totalBytes = listener.getContentLength();
            percent = totalBytes != 0 ? currentBytes * 100 / totalBytes : 0;
            // logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname + " " + currentBytes + "/" + totalBytes + " " + percent + "%");
            ret.put("percent", "" + percent);
            ret.put("currentBytes", "" + currentBytes);
            ret.put("totalBytes", "" + totalBytes);
            ret.put(UConsts.TAG_RET, "true");
            if (listener.isFinished()) {
                ret.put(TAG_FINISHED, "ok");
            }
        }
    } else if (getSessionFileItems(request) != null) {
        if (fieldname == null) {
            ret.put(TAG_FINISHED, "ok");
            logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + request.getQueryString()
                    + " finished with files: " + session.getAttribute(SESSION_FILES));
        } else {
            Vector<FileItem> sessionFiles = (Vector<FileItem>) getSessionFileItems(request);
            for (FileItem file : sessionFiles) {
                if (file.isFormField() == false && file.getFieldName().equals(fieldname)) {
                    ret.put(TAG_FINISHED, "ok");
                    ret.put(UConsts.PARAM_FILENAME, fieldname);
                    logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: " + fieldname
                            + " finished with files: " + session.getAttribute(SESSION_FILES));
                }
            }
        }
    } else {
        logger.debug("UPLOAD-SERVLET (" + session.getId() + ") getUploadStatus: no listener in session");
        ret.put("wait", "listener is null");
        ret.put(UConsts.TAG_RET, false);
        ret.put(UConsts.TAG_MSG, "listener is null");
    }
    if (ret.containsKey(TAG_FINISHED)) {
        removeCurrentListener(request);
    }

    perThreadRequest.set(null);
    return ret;
}

From source file:com.azprogrammer.qgf.controllers.HomeController.java

@RequestMapping(value = "/wbping")
public ModelAndView doWhiteboardPing(ModelMap model, HttpServletRequest req) {
    model.clear();/*from  w w  w  .  j  av a 2  s . c  o m*/
    HttpSession session = req.getSession();
    try {
        PersistenceManager pm = getPM();
        WBChannel wbc = null;
        //String query = "select from " + WBChannel.class.getName() + " where sessionId == '" + session.getId () + "' && wbKey == '" + cleanupWbId (req.getParameter ("wbId")) + "'";
        //List<WBChannel> channels = (List<WBChannel>) pm.newQuery(query).execute();

        Query query = pm.newQuery(WBChannel.class, "this.wbKey == key && this.sessionId == sessId");
        query.declareParameters("com.google.appengine.api.datastore.Key key, String sessId");

        List<WBChannel> channels = (List<WBChannel>) query
                .execute(KeyFactory.stringToKey(cleanupWbId(req.getParameter("wbId"))), session.getId());// pm.newQuery(query).execute();

        if ((channels != null) && (channels.size() > 0)) {
            wbc = channels.get(0);
            Transaction tx = pm.currentTransaction();
            tx.begin();
            wbc.setTime(System.currentTimeMillis());
            tx.commit();
            model.put("status", "ok");
        } else {
            model.put("error", "Invalid channel.");

        }
    } catch (Exception e) {
        model.put("error", e.getMessage());
    }

    return doJSON(model);
}

From source file:com.globalsight.everest.webapp.pagehandler.administration.users.UserImportHandler.java

public void invokePageHandler(WebPageDescriptor pageDescriptor, HttpServletRequest request,
        HttpServletResponse response, ServletContext context)
        throws ServletException, IOException, EnvoyServletException {
    // permission check
    HttpSession session = request.getSession(false);
    PermissionSet userPerms = (PermissionSet) session.getAttribute(WebAppConstants.PERMISSIONS);
    if (!userPerms.getPermissionFor(Permission.USERS_IMPORT)) {
        logger.error("User doesn't have the permission to visit this page.");
        response.sendRedirect("/globalsight/ControlServlet?");
        return;/*from  w  ww . j  a  v a2  s  . co m*/
    }
    String sessionId = session.getId();

    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);
    User user = (User) sessionMgr.getAttribute(WebAppConstants.USER);

    String action = request.getParameter("action");
    if (StringUtils.isNotEmpty(action)) {
        if (action.equals("startUpload")) {
            File uploadedFile = this.uploadFile(request);
            session.setAttribute("uploading_user", uploadedFile);

            int ignoreOrOverwriteFlag = 0;// ignore as default
            if ("1".equals(request.getParameter("ifUserExistedFlag"))) {
                ignoreOrOverwriteFlag = 1;//overwrite
            }
            session.setAttribute("ignoreOrOverwriteFlag", ignoreOrOverwriteFlag);
        } else if (action.equals("doImport")) {
            if (session.getAttribute("uploading_user") != null) {
                user_percentage_map.remove(sessionId);
                user_error_map.remove(sessionId);
                File uploadedFile = (File) session.getAttribute("uploading_user");
                session.removeAttribute("uploading_user");
                int flag = (Integer) session.getAttribute("ignoreOrOverwriteFlag");
                DoImport imp = new DoImport(sessionId, uploadedFile, user,
                        CompanyThreadLocal.getInstance().getValue(), flag);
                imp.start();
            } else {
                logger.error("No uploaded user info file.");
            }
        } else if (action.equals("refreshProgress")) {
            this.refreshProgress(request, response, sessionId);
            return;
        }
    }

    ResourceBundle bundle = PageHandler.getBundle(session);
    setLable(request, bundle);
    super.invokePageHandler(pageDescriptor, request, response, context);
}

From source file:Controller.UserController.java

@RequestMapping(value = "/payPaypalFail")
String payPaypalFail(HttpServletRequest request) {
    try {/*from  w  w  w .  j av a2  s . c om*/
        int packageID = Integer.parseInt(request.getParameter("packageID"));
        String selectedDate = request.getParameter("selDate");
        int numberOfChilds = Integer.parseInt(request.getParameter("numChild"));
        int numberOfAdults = Integer.parseInt(request.getParameter("numAdult"));

        request.setAttribute("message", "Payment with paypal was cancelled!");
        request.setAttribute("selectedDate", selectedDate);
        request.setAttribute("numberOfAdults", numberOfAdults);
        request.setAttribute("numberOfChilds", numberOfChilds);
        request.setAttribute("packageID", packageID);
        return "forward:/Tripper/Book";
    } catch (Exception e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - payPaypalFail\n" + "***Input***\n" + "packageID: "
                + request.getAttribute("packageID") + "\n" + "selDate: " + request.getAttribute("selDate")
                + "\n" + "numChild: " + request.getAttribute("numChild") + "\n" + "numAdult: "
                + request.getParameter("numAdult") + "\n" + "**********\n" + "****Error****\n" + e.getMessage()
                + "\n" + "**********";
        request.setAttribute("errorID", session.getId());
        request.setAttribute("errorTime", errorService.logBugWithAccount(content, session, e));
        return "forward:/Common/Error";
    }
}

From source file:com.liferay.portal.action.LogoutAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest req,
        HttpServletResponse res) throws Exception {

    try {//from ww  w .  j  a v a 2  s .  com
        HttpSession ses = req.getSession();
        try {
            // Logger.info(this, "User " +
            // PortalUtil.getUser(req).getFullName() + " (" +
            // PortalUtil.getUser(req).getUserId() +
            // ") has logged out from IP: " + req.getRemoteAddr());
            SecurityLogger.logInfo(this.getClass(), "User " + PortalUtil.getUser(req).getFullName() + " ("
                    + PortalUtil.getUser(req).getUserId() + ") has logged out from IP: " + req.getRemoteAddr());
        } catch (Exception e) {
            //Logger.info(this, "User has logged out from IP: " + req.getRemoteAddr());
            SecurityLogger.logInfo(this.getClass(), "User has logged out from IP: " + req.getRemoteAddr());
        }

        EventsProcessor.process(PropsUtil.getArray(PropsUtil.LOGOUT_EVENTS_PRE), req, res);

        ArrayList<Cookie> al = new ArrayList<Cookie>();
        Cookie[] cookies = req.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                al.add(cookie);
                cookie.setMaxAge(0);
                cookie.setPath("/");
                res.addCookie(cookie);
            }
        }

        Map sessions = PortletSessionPool.remove(ses.getId());

        if (sessions != null) {
            Iterator itr = sessions.entrySet().iterator();

            while (itr.hasNext()) {
                Map.Entry entry = (Map.Entry) itr.next();

                HttpSession portletSession = (HttpSession) entry.getValue();

                portletSession.invalidate();
            }
        }

        try {
            ses.invalidate();
        } catch (Exception e) {
        }

        EventsProcessor.process(PropsUtil.getArray(PropsUtil.LOGOUT_EVENTS_POST), req, res);

        // ActionForward af = mapping.findForward("referer");
        // return af;
        return mapping.findForward(Constants.COMMON_REFERER);
    } catch (Exception e) {
        req.setAttribute(PageContext.EXCEPTION, e);
        return mapping.findForward(Constants.COMMON_REFERER);
    }
}

From source file:it.scoppelletti.programmerpower.web.security.SsoRememberMeServices.java

/**
 * Valida l&rsquo;autenticazione persistente.
 * /*from   w w w .  j  av  a2  s.  co m*/
 * @param  cookieTokens Componenti del cookie per l&rsquo;autenticazione
 *                      persistente.
 * @param  req          Richiesta.
 * @param  resp         Risposta.
 * @return              Utente autenticato.
 */
@Override
protected UserDetails processAutoLoginCookie(String[] cookieTokens, HttpServletRequest req,
        HttpServletResponse resp) {
    boolean newTGT;
    String tgt, ticket;
    UserDetails user;
    HttpSession session;
    AuthenticationException authEx;

    if (Strings.isNullOrEmpty(myUserName)) {
        throw new PropertyNotSetException(toString(), "userName");
    }
    if (Strings.isNullOrEmpty(myPwd)) {
        throw new PropertyNotSetException(toString(), "password");
    }
    if (myCasClient == null) {
        throw new PropertyNotSetException(toString(), "casClient");
    }

    user = super.processAutoLoginCookie(cookieTokens, req, resp);

    tgt = getTicketGrantingTicket(req, resp);
    newTGT = Strings.isNullOrEmpty(tgt);

    try {
        if (newTGT) {
            tgt = myCasClient.newTicketGrantingTicket(myUserName, new SecureString(myPwd));
        }

        ticket = myCasClient.newServiceTicket(tgt);
    } catch (Exception ex) {
        authEx = new RememberMeAuthenticationException(ApplicationException.toString(ex));
        authEx.initCause(ex);
        throw authEx;
    }

    session = req.getSession(true);
    myLogger.debug("New ticket {} for session {}.", ticket, session.getId());

    if (newTGT) {
        tgt = tgt.concat(SsoRememberMeServices.TICKET_SUFFIX);
        myCasClient.addTicketGrantingTicket(req, resp, tgt);
    }

    myCasClient.addAuthenticatedSession(ticket, session);

    return user;
}