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:gov.nih.nci.security.upt.actions.CommonDoubleAssociationAction.java

public String loadRoleAssociation(BaseDoubleAssociationForm baseDoubleAssociationForm) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logDoubleAssociation.isDebugEnabled())
            logDoubleAssociation.debug("||" + baseDoubleAssociationForm.getFormName()
                    + "|loadRoleAssociation|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//from w ww  .  j  a  v a2s . c  o m
    session.setAttribute(DisplayConstants.CREATE_WORKFLOW, "0");
    if (baseDoubleAssociationForm.getProtectionGroupAssociatedId() == null
            || baseDoubleAssociationForm.getProtectionGroupAssociatedId().equalsIgnoreCase("")) {
        addActionError("A record needs to be selected first");
        if (logDoubleAssociation.isDebugEnabled())
            logDoubleAssociation.debug(session.getId() + "|"
                    + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                    + baseDoubleAssociationForm.getFormName()
                    + "|loadRoleAssociation|Failure|No Protection Group Id selected for "
                    + baseDoubleAssociationForm.getFormName() + " object||");
        return ForwardConstants.LOAD_PROTECTIONGROUPASSOCIATION_SUCCESS;
    }
    try {
        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        baseDoubleAssociationForm.setRequest(request);

        baseDoubleAssociationForm.buildRoleAssociationObject(userProvisioningManager);
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (logDoubleAssociation.isDebugEnabled())
            logDoubleAssociation.debug(session.getId() + "|"
                    + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                    + baseDoubleAssociationForm.getFormName()
                    + "|loadRoleAssociation|Failure|Error Loading Role Association for the "
                    + baseDoubleAssociationForm.getFormName() + " object|"
                    + baseDoubleAssociationForm.toString() + "|" + cse.getMessage());
    }
    if (logDoubleAssociation.isDebugEnabled())
        logDoubleAssociation.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseDoubleAssociationForm.getFormName()
                + "|loadRoleAssociation|Success|Success in Loading Role Association for "
                + baseDoubleAssociationForm.getFormName() + " object|" + baseDoubleAssociationForm.toString()
                + "|");
    return ForwardConstants.LOAD_ROLEASSOCIATION_SUCCESS;
}

From source file:com.infoklinik.rsvp.server.service.OAuthLoginServiceImpl.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/*from   w ww  . j av a  2  s.com*/

        switch (req.getServletPath()) {

        case "/verifyCredential":

            HttpSession session = req.getSession();

            logger.info("Session ID : " + session.getId());
            Integer authProvider = (Integer) req.getSession().getAttribute(SESSION_AUTH_PROVIDER);
            String state = req.getParameter("state");
            String code = req.getParameter("code");
            String oauth_verifier = req.getParameter("oauth_verifier");

            Credential credential = OAuthUtil.getSvrCredential(authProvider, state, code, oauth_verifier);
            verifySocialUser(credential, req.getSession());

            session.setAttribute(SESSION_USER_VERIFIED, Constant.YES);

            logger.info("verify credential successful");

            resp.sendRedirect("oAuthLoginVerified");

            break;
        }

    } catch (Exception e) {

        logger.log(Level.SEVERE, "OAuthLoginServiceImpl Exception", e);
        throw new ServletException(e);
    }
}

From source file:Controller.UserController.java

@RequestMapping(value = "/SaveSetting", method = RequestMethod.POST)
public String saveSetting(HttpServletRequest request) {
    try {/*from  www .java 2s  .c  om*/
        int tripperID;
        try {
            tripperID = Integer.parseInt(request.getParameter("tripperID"));
        } catch (NumberFormatException e) {
            tripperID = 0;
        }
        tripperService.saveSetting(tripperID, request.getParameter("settingJson"));
        if (request.getParameter("language") != null) {
            return "redirect:/Tripper/Notification" + "?language=" + request.getParameter("language");
        } else {
            return "redirect:/Tripper/Notification";
        }

    } catch (Exception e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - saveSetting\n" + "***Input***\n" + "tripperID: "
                + request.getAttribute("tripperID") + "\n" + "settingJson: "
                + request.getAttribute("settingJson") + "\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:byps.http.HHttpServlet.java

protected HSession doCreateSession(final HttpServletRequest request) throws BException {
    // Create new JSESSIONID to support load balancing.
    // For newer clients, we do not rely on the JSESSIONID to identify the BYPS
    // session in incoming requests.
    // Otherwise two JSON connections in a browser window could not be
    // distinguished.
    // Older clients still need to reach their HSession by the JSESSIONID.
    HttpSession hsess = request.getSession(true);
    if (log.isDebugEnabled())
        log.debug("JSESSIONID=" + hsess.getId());

    // Assign a set of BYPS session objects to the app server's session.
    hsess.setAttribute(HConstants.HTTP_SESSION_BYPS_SESSIONS, new HHttpSessionObject());

    // Constrain the lifetime of the session to 10s. It is extended, if the
    // session gets authenticated.
    hsess.setMaxInactiveInterval(HConstants.MAX_INACTIVE_SECONDS_BEFORE_AUTHENTICATED);

    // Create new BYPS session
    final HTargetIdFactory targetIdFactory = getTargetIdFactory();
    final BTargetId targetId = targetIdFactory.createTargetId();
    final HSession sess = createSession(hsess, request.getRemoteUser());
    sess.setTargetId(targetId);//  w w  w  .jav  a2s .  c om
    if (log.isDebugEnabled())
        log.debug("targetId=" + targetId);

    // Add session to session map
    final BHashMap<String, HSession> sessions = HSessionListener.getAllSessions();
    final String bsessionId = targetId.toSessionId();
    sessions.put(bsessionId, sess);

    // Add BRemote for utility requests.
    addUtilityRequestsInterface(sess);
    return sess;
}

From source file:org.ovirt.engine.api.common.security.CSRFProtectionFilter.java

private void doFilterExistingSession(HttpSession session, HttpServletRequest request,
        HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
    // Check if the protection is enabled for this session, if it isn't then jump to the next filter:
    boolean enabled = (Boolean) session.getAttribute(ENABLED_ATTRIBUTE);
    if (!enabled) {
        chain.doFilter(request, response);
        return;/*from   w  ww .  ja v a 2 s . co  m*/
    }

    // Check if the request contains a session id header, if it doesn't then it must be rejected immediately:
    String sessionIdHeader = request.getHeader(SESSION_ID_HEADER);
    if (sessionIdHeader == null) {
        log.warn(
                "Request for path \"{}\" from IP address {} has been rejected because CSRF protection is enabled "
                        + "for the session but the the session id header \"{}\" hasn't been provided.",
                request.getContextPath() + request.getPathInfo(), request.getRemoteAddr(), SESSION_ID_HEADER);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Check if the actual session id matches the session id header:
    String actualSessionId = session.getId();
    if (!sessionIdHeader.equals(actualSessionId)) {
        log.warn(
                "Request for path \"{}\" from IP address {} has been rejected because CSRF protection is enabled "
                        + "for the session but the value of the session id header \"{}\" doesn't match the actual session "
                        + "id.",
                request.getContextPath() + request.getPathInfo(), request.getRemoteAddr(), SESSION_ID_HEADER);
        response.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Everything is OK, let the request go to the next filter:
    chain.doFilter(request, response);
}

From source file:com.aurel.track.attachment.AttachmentAction.java

/**
 * Deletes the selected attachments//from   w w  w  .  java  2  s . co  m
 * @return
 */
public String deleted() {
    Integer[] attachmentsToDelete = ItemDetailBL.getIntegerTokens(deletedItems);
    Date originalLastModifiedDate = null;
    Date lastModifiedDate = DateTimeUtils.getInstance().parseISODateTime(lastModified);

    for (int i = 0; i < attachmentsToDelete.length; i++) {
        if (workItemID == null) {
            HttpServletRequest request = ServletActionContext.getRequest();
            HttpSession httpSession = request.getSession();
            WorkItemContext workItemContext = ((WorkItemContext) session.get("workItemContext"));
            if (workItemContext == null) {
                String err = "No context on session!";
                LOGGER.error("No context on session");
                JSONUtility.encodeJSONFailure(err);
                return null;
            }
            List<TAttachmentBean> attachments = workItemContext.getAttachmentsList();
            if (attachments == null) {
                attachments = new ArrayList<TAttachmentBean>();
            }
            String sessionID = httpSession.getId();
            AttachBL.deleteLocalAttachment(attachments, attachmentsToDelete[i], sessionID);
            workItemContext.setAttachmentsList(attachments);
        } else {
            TWorkItemBean workItemBean = null;
            try {
                workItemBean = ItemBL.loadWorkItem(workItemID);
            } catch (ItemLoaderException e) {
                LOGGER.error("Loading the workItem failed with " + e.getMessage());
            }
            if (workItemBean != null && AccessBeans.isAllowedToChange(workItemBean, personID)) {
                if (workItemBean != null) {
                    originalLastModifiedDate = workItemBean.getLastEdit();
                }
                TAttachmentBean attachmentBean = AttachBL.loadAttachment(attachmentsToDelete[i], workItemID,
                        false);
                AttachBL.deleteAttachment(attachmentsToDelete[i], workItemID);
                //register the remove in history
                if (attachmentBean != null) {
                    HistorySaverBL.removeAttachment(workItemID, personID, locale,
                            HistorySaverBL.getAttachmentHistoryText(attachmentBean.getFileName(),
                                    attachmentBean.getDescription(), null, locale,
                                    BooleanFields.fromStringToBoolean(attachmentBean.getIsUrl())));
                }
            }
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("{");
    JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true);
    JSONUtility.appendFieldName(sb, JSONUtility.JSON_FIELDS.DATA).append(":{");
    if (originalLastModifiedDate != null && lastModifiedDate != null) {
        if (!lastModifiedDate.before(originalLastModifiedDate)) {
            TWorkItemBean workItemBean = ItemBL.loadWorkItemSystemAttributes(workItemID);
            Date lastModified = null;
            if (workItemBean != null) {
                lastModified = workItemBean.getLastEdit();
            }
            JSONUtility.appendStringValue(sb, "lastModified",
                    DateTimeUtils.getInstance().formatISODateTime(lastModified), true);
        }
    }

    sb.append("}}");
    try {
        JSONUtility.prepareServletResponseJSON(ServletActionContext.getResponse());
        PrintWriter out = ServletActionContext.getResponse().getWriter();
        out.println(sb);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        LOGGER.error(ExceptionUtils.getStackTrace(e));
    }
    return null;
}

From source file:base.util.IDSActor.java

/**
 * Demo(Session), Demo(, )./*from  w ww .ja  v  a2  s .co m*/
 * 
 * @see StdHttpSessionBasedActor#loadLoginUser(javax.servlet.http.Http
 *      ServletRequest, com.trs.idm.client.actor.SSOUser)
 */
public void loadLoginUser(HttpServletRequest request, SSOUser user) throws ActorException {
    HttpSession session = request.getSession();
    String userID = user.getUserName();
    String url = request.getRequestURI();
    System.out.println("######SSOUser loadLoginUser#URL#####" + url);
    System.out.println("######SSOUser loadLoginUser#1#####" + user.getUserName());
    //session.setAttribute("userProps", user.getProperties());

    //      sessionContext
    com.primeton.tp.core.prservice.context.SessionContext sessionContext = null;
    sessionContext = (SessionContext) session
            .getAttribute(com.primeton.tp.web.driver.webdriver.WebDriver.SESSION_CONTEXT);
    com.primeton.tp.core.prservice.context.RequestContext requestContext = (com.primeton.tp.core.prservice.context.RequestContext) request
            .getAttribute(com.primeton.tp.web.driver.webdriver.WebDriver.SESSION_CONTEXT);
    if (sessionContext == null) {
        System.out.println("######SSOUser loadLoginUser#2#####" + user.getUserName());
        sessionContext = new com.primeton.tp.core.prservice.context.SessionContext();
        sessionContext.setHttpSessionId(session.getId());
    }
    //      com.primeton.tp.core.prservice.context.SessionContext sessionContext
    // =
    // (com.primeton.tp.core.prservice.context.SessionContext)session.getAttribute("sessionContext");
    sessionContext.setUserID(userID);
    sessionContext.setUserRemoteAddr(request.getRemoteAddr());
    //sessionContext.setHttpSessionId(session.getId());
    //
    System.out.println("######SSOUser loadLoginUser#3#####" + user.getUserName());
    session.setAttribute(com.primeton.tp.web.driver.webdriver.WebDriver.SESSION_CONTEXT, sessionContext);
    //

    TalentHand handle = new TalentHand();
    try {
        System.out.println("######SSOUser loadLoginUser#4#####" + user.getUserName());
        handle.doProcess(sessionContext, session);
    } catch (PrException e) {
        log.equals(e);
        System.out.println(
                "######SSOUser loadLoginUser######" + user.getUserName() + " With ERROR: " + e.getMessage());
    }
    //session.setAttribute("sessionContext", sessionContext);

    //com.primeton.tp.core.prservice.handle.InitPermissionHandle permissionHand = new com.primeton.tp.core.prservice.handle.InitPermissionHandle();
    //try {
    //   System.out.println("######SSOUser loadLoginUser#5#####" + user.getUserName() );
    //   permissionHand.doProcess(sessionContext, requestContext);
    //} catch (Exception e1) {
    //   e1.printStackTrace();
    //}

    //com.primeton.tp.core.prservice.handle.MenuHandle menuHand = new com.primeton.tp.core.prservice.handle.MenuHandle();
    //try {
    //   System.out.println("######SSOUser loadLoginUser#5#####" + user.getUserName() );
    //   menuHand.doProcess(sessionContext, requestContext);
    //} catch (Exception e1) {
    //   e1.printStackTrace();
    //}

    //      
    com.primeton.tp.core.prservice.monitor.UserMessage userMsg = new com.primeton.tp.core.prservice.monitor.UserMessage(
            com.primeton.tp.core.prservice.monitor.CurrentUserMBean.getUserMBean(), userID,
            request.getRemoteAddr(), session.getId(), System.currentTimeMillis());
    userMsg.setRegister(true);
    com.primeton.tp.core.management.StatQueue.theOne().put(userMsg);
    System.out.println("######SSOUser loadLoginUser#4#####" + user.getUserName());
    com.primeton.tp.core.prservice.context.MenuContext menu = null;
    try {
        menu = com.primeton.tp.core.prservice.controller.Controller.getMenu(sessionContext);
        System.out.println("######SSOUser loadLoginUser#8#####" + user.getUserName());
        session.setAttribute("menuContext", menu);
    } catch (Exception e) {
        log.equals(e);
        System.out.println(
                "######SSOUser loadLoginUser######" + user.getUserName() + " With ERROR_1: " + e.getMessage());
    }
    session.setAttribute(LOGIN_FLAG, userID);
    System.out.println("######SSOUser loadLoginUser#7#####" + user.getUserName());
}

From source file:gov.nih.nci.security.upt.actions.CommonAssociationAction.java

public String setAssociation(BaseAssociationForm baseAssociationForm) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logAssociation.isDebugEnabled())
            logAssociation.debug("||" + baseAssociationForm.getFormName()
                    + "|setAssociation|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }/*www  .jav  a  2s .com*/
    try {
        session.setAttribute(DisplayConstants.CREATE_WORKFLOW, "0");
        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        baseAssociationForm.setRequest(request);
        baseAssociationForm.buildDisplayForm(userProvisioningManager);
        baseAssociationForm.setAssociationObject(userProvisioningManager);
        addActionMessage("Association Update Successful");
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (logAssociation.isDebugEnabled())
            logAssociation.debug(session.getId() + "|"
                    + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                    + baseAssociationForm.getFormName()
                    + "|setAssociation|Failure|Error in setting Association for the "
                    + baseAssociationForm.getFormName() + " object|" + "|" + cse.getMessage());
    }
    session.setAttribute(DisplayConstants.CURRENT_ACTION, DisplayConstants.SEARCH);
    session.setAttribute(DisplayConstants.CURRENT_FORM, baseAssociationForm);
    if (logAssociation.isDebugEnabled())
        logAssociation.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseAssociationForm.getFormName()
                + "|setAssociation|Success|Success in setting association for "
                + baseAssociationForm.getFormName() + " object|");
    return ForwardConstants.SET_ASSOCIATION_SUCCESS;
}

From source file:com.infoklinik.rsvp.server.service.OAuthLoginServiceImpl.java

private void saveAuthProviderToSession(int authProvider, HttpSession session) throws OAuthException {
    if (session == null) {
        throw new OAuthException(OAuthUtil.SESSION_EXPIRED_MESSAGE);
    }/*  w w w. j a v a2s  . c  o  m*/

    logger.info("Session ID : " + session.getId());
    session.setAttribute(SESSION_AUTH_PROVIDER, authProvider);
}

From source file:com.adito.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.adito.navigation.ApplicationResources")
            .getMessage("footer.info", user.getPrincipalName(),
                    SimpleDateFormat.getDateTimeInstance().format(new Date()));
    session.setAttribute(Constants.LOGON_INFO, logonInfo);
    try {/*  www  . j a v  a  2 s  .co  m*/
        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);
}