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:Controller.MessageController.java

@RequestMapping(value = "/Chat")
public String goToChatPage(HttpServletRequest request) {
    try {/*from   w  w  w  .j  a  v a2 s  . c  o m*/
        HttpSession session = request.getSession();
        String conversationList = "";
        if (request.getAttribute("conversationID") != null
                || !request.getAttribute("conversationID").equals("")) {
            String conID = (String) request.getAttribute("conversationID");
            request.setAttribute("conversationID", conID);
        }
        if (session != null) {
            AccountSession account = (AccountSession) session.getAttribute("account");
            if (providerService.isProvider(account)) {
                conversationList = messageService.getListConversationbyProviderID(account.getId());
            } else if (tripperService.isUser(account)) {
                conversationList = messageService.getListConversationbyTripperID(account.getId());

            }
            request.setAttribute("conversationList", conversationList);
        }
        return "chat";
    } catch (Exception e) {
        HttpSession session = request.getSession();
        String content = "Function: MessageController - goToChatPage\n" + "***Input***\n" + "conversationID: "
                + (String) request.getAttribute("conversationID") + "\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:Controller.UserController.java

@RequestMapping(value = "/Notification")
String getNotification(HttpServletRequest request) {
    try {//from   w w w  . ja v  a2  s.  com
        HttpSession session = request.getSession(true);
        AccountSession account = (AccountSession) session.getAttribute("account");
        List<TripperNotification> providerNoti = tripperService.getTripperNotification();
        Gson gson = new Gson();
        List<TripperNotificationSetting> providerSetting = tripperService
                .getTripperNotificationSetting(account.getId());
        List<Integer> providerSettingList = new ArrayList<Integer>();
        for (int i = 0; i < providerSetting.size(); i++) {
            providerSettingList.add(providerSetting.get(i).getTripperNotificationID());
        }
        request.setAttribute("tripperSetting", gson.toJson(providerSettingList));
        request.setAttribute("tripperNotification", gson.toJson(providerNoti));
        request.setAttribute("page", "tripperNotification");
        return "tripper/notification";
    } catch (Exception e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - getNotification\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:gov.nih.nci.security.upt.actions.ProtectionGroupAction.java

public String loadParentAssociation() throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();
    UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
            .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logProtectionGroup.isDebugEnabled())
            logProtectionGroup.debug("||" + protectionGroupForm.getFormName()
                    + "|loadParentAssociation|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//  ww  w. ja  v  a 2s  .c o m

    Collection associatedProtectionGroup = (Collection) new HashSet();
    protectionGroupForm.buildDisplayForm(userProvisioningManager);
    if (protectionGroupForm.getProtectionGroupParentProtectionGroup() != null)
        associatedProtectionGroup.add(protectionGroupForm.getProtectionGroupParentProtectionGroup());

    ProtectionGroup protectionGroup = new ProtectionGroup();
    SearchCriteria searchCriteria = new ProtectionGroupSearchCriteria(protectionGroup);
    Collection totalProtectionGroups = (Collection) userProvisioningManager.getObjects(searchCriteria);

    Collection availableProtectionGroups = ObjectSetUtil.minus(totalProtectionGroups,
            associatedProtectionGroup);

    Collection protectionGroupList = (Collection) new HashSet();
    protectionGroupList.add(userProvisioningManager.getProtectionGroupById(protectionGroupForm.getPrimaryId()));
    availableProtectionGroups = ObjectSetUtil.minus(availableProtectionGroups, protectionGroupList);
    request.setAttribute(DisplayConstants.ASSIGNED_SET, associatedProtectionGroup);
    request.setAttribute(DisplayConstants.AVAILABLE_SET, availableProtectionGroups);

    if (logProtectionGroup.isDebugEnabled())
        logProtectionGroup.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + protectionGroupForm.getFormName()
                + "|loadParentAssociation|Success|Success in Loading Parent Association for "
                + protectionGroupForm.getFormName() + " object|" + "|");
    return ForwardConstants.LOAD_PARENT_ASSOCIATION_SUCCESS;

}

From source file:de.betterform.agent.web.WebUtil.java

/**
 * this method is responsible for passing all context information needed by the Adapter and Processor from
 * ServletRequest to Context. Will be called only once when the form-session is inited (GET).
 * <p/>//from  w  ww  . j a va 2 s  .com
 * <p/>
 * todo: better logging of context params
 *
 * @param request     the Servlet request to fetch params from
 * @param httpSession the Http Session context
 * @param processor   the XFormsProcessor which receives the context params
 * @param sessionkey  the key to identify the XFormsSession
 */
public static void setContextParams(HttpServletRequest request, HttpSession httpSession,
        XFormsProcessor processor, String sessionkey) throws XFormsConfigException {
    Map servletMap = new HashMap();
    servletMap.put(WebProcessor.SESSION_ID, sessionkey);
    processor.setContextParam(XFormsProcessor.SUBMISSION_RESPONSE, servletMap);

    //adding requestURI to context
    processor.setContextParam(WebProcessor.REQUEST_URI, WebUtil.getRequestURI(request));

    //adding request URL to context
    String requestURL = request.getRequestURL().toString();
    processor.setContextParam(WebProcessor.REQUEST_URL, requestURL);

    // the web app name with an '/' prepended e.g. '/betterform' by default
    String contextRoot = WebUtil.getContextRoot(request);
    processor.setContextParam(WebProcessor.CONTEXTROOT, contextRoot);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("context root of webapp: " + processor.getContextParam(WebProcessor.CONTEXTROOT));
    }

    String requestPath = "";
    URL url = null;
    String plainPath = "";
    try {
        url = new URL(requestURL);
        requestPath = url.getPath();
    } catch (MalformedURLException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    }
    if (requestPath.length() != 0) {
        //adding request path e.g. '/betterform/forms/demo/registration.xhtml'
        processor.setContextParam(WebProcessor.REQUEST_PATH, requestPath);

        //adding filename of requested doc to context
        String fileName = requestPath.substring(requestPath.lastIndexOf('/') + 1, requestPath.length());//FILENAME xforms
        processor.setContextParam(FILENAME, fileName);

        if (requestURL.contains(contextRoot)) { //case1: contextRoot is a part of the URL
            //adding plainPath which is the part between contextroot and filename e.g. '/forms' for a requestPath of '/betterform/forms/Status.xhtml'
            plainPath = requestPath.substring(contextRoot.length() + 1,
                    requestPath.length() - fileName.length());
            processor.setContextParam(PLAIN_PATH, plainPath);
        } else {//case2: contextRoot is not a part of the URL take the part previous the filename.
            String[] urlParts = requestURL.split("/");
            plainPath = urlParts[urlParts.length - 2];
        }

        //adding contextPath - requestPath without the filename
        processor.setContextParam(CONTEXT_PATH, contextRoot + "/" + plainPath);
    }

    //adding session id to context
    processor.setContextParam(HTTP_SESSION_ID, httpSession.getId());
    //adding context absolute path to context

    //EXIST-WORKAROUND: TODO triple check ...
    //TODO: triple check where this is used.
    if (request.isRequestedSessionIdValid()) {
        processor.setContextParam(EXISTDB_USER, httpSession.getAttribute(EXISTDB_USER));
    }

    //adding pathInfo to context - attention: this is only available when a servlet is requested
    String s1 = request.getPathInfo();
    if (s1 != null) {
        processor.setContextParam(WebProcessor.PATH_INFO, s1);
    }
    processor.setContextParam(WebProcessor.QUERY_STRING,
            (request.getQueryString() != null ? request.getQueryString() : ""));

    //storing the realpath for webapp

    String realPath = WebFactory.getRealPath(".", httpSession.getServletContext());
    File f = new File(realPath);
    URI fileURI = f.toURI();

    processor.setContextParam(WebProcessor.REALPATH, fileURI.toString());
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("real path of webapp: " + realPath);
    }

    //storing the TransformerService
    processor.setContextParam(TransformerService.TRANSFORMER_SERVICE,
            httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("TransformerService: "
                + httpSession.getServletContext().getAttribute(TransformerService.TRANSFORMER_SERVICE));
    }

    //[2] read any request params that are *not* betterForm params and pass them into the context map
    Enumeration params = request.getParameterNames();
    String s;
    while (params.hasMoreElements()) {
        s = (String) params.nextElement();
        //store all request-params we don't use in the context map of XFormsProcessorImpl
        String value = request.getParameter(s);
        processor.setContextParam(s, value);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("added request param '" + s + "' added to context");
            LOGGER.debug("param value'" + value);
        }
    }

}

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

public String loadProtectionGroupAssociation(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()
                    + "|loadProtectionGroupAssociation|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }/*w w  w  . ja  va2s  .  co m*/
    session.setAttribute(DisplayConstants.CREATE_WORKFLOW, "0");
    try {

        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        baseDoubleAssociationForm.setRequest(request);
        Collection temp = baseDoubleAssociationForm
                .buildProtectionGroupAssociationObject(userProvisioningManager);

        List associatedProtectionGroupRoleContexts = new ArrayList();
        Iterator iterator = temp.iterator();
        while (iterator.hasNext()) {
            associatedProtectionGroupRoleContexts.add(iterator.next());
        }
        Collections.sort(associatedProtectionGroupRoleContexts, new ProtectionGroupRoleContextComparator());

        if (associatedProtectionGroupRoleContexts.size() != 0)
            session.setAttribute(DisplayConstants.AVAILABLE_PROTECTIONGROUPROLECONTEXT_SET,
                    associatedProtectionGroupRoleContexts);
        else {
            addActionError("No Associated Protection Group or Roles found");
            if (logDoubleAssociation.isDebugEnabled())
                logDoubleAssociation.debug(session.getId() + "|"
                        + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                        + baseDoubleAssociationForm.getFormName()
                        + "|loadProtectionGroupAssociation|Failure|No Protection Group Association for the "
                        + baseDoubleAssociationForm.getFormName() + " object|" + logDoubleAssociation.toString()
                        + "|");
            return ForwardConstants.LOAD_PROTECTIONGROUPASSOCIATION_FAILURE;
        }
    } 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()
                    + "|loadProtectionGroupAssociation|Failure|Error Loading Protection Group Association for the "
                    + baseDoubleAssociationForm.getFormName() + " object|" + logDoubleAssociation.toString()
                    + "|" + cse.getMessage());
    }
    if (logDoubleAssociation.isDebugEnabled())
        logDoubleAssociation.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseDoubleAssociationForm.getFormName()
                + "|loadProtectionGroupAssociation|Success|Success in Loading Protection Group Association for "
                + baseDoubleAssociationForm.getFormName() + " object|" + logDoubleAssociation.toString() + "|");
    return ForwardConstants.LOAD_PROTECTIONGROUPASSOCIATION_SUCCESS;
}

From source file:Controller.UserController.java

@RequestMapping(value = "/ChangePassword", method = RequestMethod.POST)
public String changePassword(HttpServletRequest request) {
    try {/*from   w w w .  ja va  2s  .c o  m*/
        HttpSession session = request.getSession(true);
        String oldPassword = request.getParameter("currentPass");
        String newPassword = (String) request.getParameter("newPass");
        AccountSession account = (AccountSession) session.getAttribute("account");
        boolean result = tripperService.changeTripperPassword(account.getId(), oldPassword, newPassword);
        if (result) {
            if (request.getParameter("language") != null) {
                return "redirect:/Tripper/AccountInfo" + "?language=" + request.getParameter("language");
            } else {
                return "redirect:/Tripper/AccountInfo";
            }

        } else {
            request.setAttribute("message", "Your current password not correct!");
        }
        return "tripper/password";
    } catch (Exception e) {
        HttpSession session = request.getSession(true);
        String content = "Function: UserController - changePassword\n" + "***Input***\n" + "currentPass: "
                + request.getParameter("currentPass") + "\n" + "newPass: " + request.getParameter("newPass")
                + "\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.citrix.cpbm.portal.fragment.controllers.AbstractUsersController.java

/**
 * Method used for deleting.//from  w w w  .  j a va2 s. c o m
 * 
 * @param userParam
 * @param map
 * @return null
 * @throws NoSuchUserException
 * @throws ConnectorManagementServiceException
 */
@RequestMapping(value = "/{userParam}/delete", method = RequestMethod.GET)
@ResponseBody
public String delete(@PathVariable String userParam, ModelMap map, HttpSession session)
        throws NoSuchUserException {
    User user = userService.get(userParam);
    Tenant tenant = user.getTenant();
    if (tenant.getState().equals(State.ACTIVE)) {
        String userNameWithoutId = user.getUsername();
        userService.deleteUser(user, getCurrentUser());
        map.clear();
        String message = "delete.user";
        String messageArgs = userNameWithoutId + "," + tenant.getName();
        eventService.createEvent(new Date(), tenant, message, messageArgs, Source.PORTAL, Scope.ACCOUNT,
                Category.ACCOUNT, Severity.INFORMATION, true);
        clearActiveSessionForUser(userNameWithoutId, session.getId());
    }
    return null;
}

From source file:org.alfresco.web.site.servlet.SSOAuthenticationFilter.java

/**
 * Run the filter/* w w  w  .j a  v a2 s  .c  o m*/
 * 
 * @param sreq ServletRequest
 * @param sresp ServletResponse
 * @param chain FilterChain
 * 
 * @exception IOException
 * @exception ServletException
 */
public void doFilter(ServletRequest sreq, ServletResponse sresp, FilterChain chain)
        throws IOException, ServletException {
    NDC.remove();
    NDC.push(Thread.currentThread().getName());
    final boolean debug = logger.isDebugEnabled();

    // Wrap externally authenticated requests that provide the user in an HTTP header
    // with one that returns the correct name from getRemoteUser(). For use in our own
    // calls to this method and any chained filters.
    sreq = wrapHeaderAuthenticatedRequest(sreq);

    // Bypass the filter if we don't have an endpoint with external auth enabled
    if (this.endpoint == null) {
        if (debug)
            logger.debug("There is no endpoint with external auth enabled.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // Get the HTTP request/response/session
    HttpServletRequest req = (HttpServletRequest) sreq;
    HttpServletResponse res = (HttpServletResponse) sresp;
    HttpSession session = req.getSession();

    if (req.getServletPath() != null && req.getServletPath().startsWith(UNAUTHENTICATED_ACCESS_PROXY)) {
        if (debug)
            logger.debug("SSO is by-passed for unauthenticated access endpoint.");
        chain.doFilter(sreq, sresp);
        return;
    }

    // external invitation link should not trigger any SSO
    if (PAGE_SERVLET_PATH.equals(req.getServletPath()) && IGNORE_LINK.equals(req.getPathInfo())) {
        if (debug)
            logger.debug("SSO is by-passed for external invitation link.");
        chain.doFilter(sreq, sresp);
        return;
    }

    if (debug)
        logger.debug("Processing request " + req.getRequestURI() + " SID:" + session.getId());

    // Login page or login submission
    String pathInfo;
    if (PAGE_SERVLET_PATH.equals(req.getServletPath())
            && (LOGIN_PATH_INFORMATION.equals(pathInfo = req.getPathInfo())
                    || pathInfo == null && LOGIN_PARAMETER.equals(req.getParameter("pt")))) {
        if (debug)
            logger.debug("Login page requested, chaining ...");

        // Chain to the next filter
        chain.doFilter(sreq, sresp);
        return;
    }

    // initialize a new request context
    RequestContext context = null;
    try {
        // perform a "silent" init - i.e. no user creation or remote connections
        context = RequestContextUtil.initRequestContext(getApplicationContext(), req, true);
    } catch (Exception ex) {
        logger.error("Error calling initRequestContext", ex);
        throw new ServletException(ex);
    }

    // get the page from the model if any - it may not require authentication
    Page page = context.getPage();
    if (page != null && page.getAuthentication() == RequiredAuthentication.none) {
        if (logger.isDebugEnabled())
            logger.debug("Unauthenticated page requested - skipping auth filter...");
        chain.doFilter(sreq, sresp);
        return;
    }

    // If userHeader (X-Alfresco-Remote-User or similar) external auth - does not require a challenge/response
    if (this.userHeader != null) {
        String userId = AuthenticationUtil.getUserId(req);
        if (userId != null && req.getRemoteUser() != null) {
            if (logger.isDebugEnabled())
                logger.debug("userHeader external auth - skipping auth filter...");
            setExternalAuthSession(session);
            onSuccess(req, res, session, req.getRemoteUser());
            chain.doFilter(sreq, sresp);
            return;
        } else {
            // initial external user login requires a ping check to authenticate remote Session
            challengeOrPassThrough(chain, req, res, session);
            return;
        }
    }

    // Check if there is an authorization header with a challenge response
    String authHdr = req.getHeader(HEADER_AUTHORIZATION);

    // We are not passing on a challenge response and we have sufficient client session information
    if (authHdr == null && AuthenticationUtil.isAuthenticated(req)) {
        if (debug)
            logger.debug("Touching the repo to ensure we still have an authenticated session.");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }

    // Check the authorization header
    if (authHdr == null) {
        if (debug)
            logger.debug("New auth request from " + req.getRemoteHost() + " (" + req.getRemoteAddr() + ":"
                    + req.getRemotePort() + ")");
        challengeOrPassThrough(chain, req, res, session);
        return;
    }
    // SPNEGO / Kerberos authentication
    else if (authHdr.startsWith(AUTH_SPNEGO) && this.krbRealm != null) {
        if (debug)
            logger.debug("Processing SPNEGO / Kerberos authentication.");
        // Decode the received SPNEGO blob and validate

        final byte[] spnegoByts = Base64.decode(authHdr.substring(10).getBytes());

        // Check if the client sent an NTLMSSP blob

        if (isNTLMSSPBlob(spnegoByts, 0)) {
            if (logger.isDebugEnabled())
                logger.debug("Client sent an NTLMSSP security blob");

            // Restart the authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
            return;
        }

        //  Check the received SPNEGO token type

        int tokType = -1;

        try {
            tokType = SPNEGO.checkTokenType(spnegoByts, 0, spnegoByts.length);
        } catch (IOException ex) {
        }

        // Check for a NegTokenInit blob

        if (tokType == SPNEGO.NegTokenInit) {
            if (debug)
                logger.debug("Parsing the SPNEGO security blob to get the Kerberos ticket.");

            NegTokenInit negToken = new NegTokenInit();

            try {
                // Decode the security blob

                negToken.decode(spnegoByts, 0, spnegoByts.length);

                //  Determine the authentication mechanism the client is using and logon

                String oidStr = null;
                if (negToken.numberOfOids() > 0)
                    oidStr = negToken.getOidAt(0).toString();

                if (oidStr != null && (oidStr.equals(OID.ID_MSKERBEROS5) || oidStr.equals(OID.ID_KERBEROS5))) {
                    if (debug)
                        logger.debug("Kerberos logon.");
                    //  Kerberos logon

                    if (doKerberosLogon(negToken, req, res, session) != null) {
                        // Allow the user to access the requested page

                        chain.doFilter(req, res);
                        if (logger.isDebugEnabled())
                            logger.debug("Request processing ended");
                    } else {
                        // Send back a request for SPNEGO authentication

                        restartAuthProcess(session, req, res, AUTH_SPNEGO);
                    }
                } else {
                    //  Unsupported mechanism, e.g. NegoEx

                    if (logger.isDebugEnabled())
                        logger.debug("Unsupported SPNEGO mechanism " + oidStr);

                    // Try again!

                    restartAuthProcess(session, req, res, AUTH_SPNEGO);
                }
            } catch (IOException ex) {
                // Log the error

                if (logger.isDebugEnabled())
                    logger.debug(ex);
            }
        } else {
            //  Unknown SPNEGO token type

            if (logger.isDebugEnabled())
                logger.debug("Unknown SPNEGO token type");

            // Send back a request for SPNEGO authentication

            restartAuthProcess(session, req, res, AUTH_SPNEGO);
        }
    }
    // NTLM authentication
    else if (authHdr.startsWith(AUTH_NTLM)) {
        if (debug)
            logger.debug("Processing NTLM authentication.");
        // Decode the received NTLM blob and validate
        final byte[] authHdrByts = authHdr.substring(5).getBytes();
        final byte[] ntlmByts = Base64.decode(authHdrByts);
        int ntlmTyp = NTLMMessage.isNTLMType(ntlmByts);
        Object sessionMutex = WebUtils.getSessionMutex(session);

        if (ntlmTyp == NTLM.Type1) {
            if (debug)
                logger.debug("Process the type 1 NTLM message.");
            Type1NTLMMessage type1Msg = new Type1NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType1(type1Msg, req, res, session);
            }
        } else if (ntlmTyp == NTLM.Type3) {
            if (debug)
                logger.debug("Process the type 3 NTLM message.");
            Type3NTLMMessage type3Msg = new Type3NTLMMessage(ntlmByts);
            synchronized (sessionMutex) {
                processType3(type3Msg, req, res, session, chain);
            }
        } else {
            if (debug)
                logger.debug("NTLM not handled, redirecting to login page");

            redirectToLoginPage(req, res);
        }
    }
    // Possibly basic auth - allow through
    else {
        if (debug)
            logger.debug("Processing Basic Authentication.");
        // ACE-3257 fix, it looks like basic auth header was sent.
        // However lets check for presence of remote_user CGI variable in AJP.
        // If remote user is not null then it most likely that apache proxy with mod_auth_basic module is used
        if (AuthenticationUtil.isAuthenticated(req) || req.getRemoteUser() != null) {
            if (debug)
                logger.debug("Ensuring the session is still valid.");
            challengeOrPassThrough(chain, req, res, session);
        } else {
            if (debug)
                logger.debug("Establish a new session or bring up the login page.");
            chain.doFilter(req, res);
        }
    }
}

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

@Override
public SocialUser getSocialUserAfterVerification() throws OAuthException {

    HttpSession session = getHttpSession();
    boolean isUserVerified = false;

    int waitingTime = 0;

    while (!isUserVerified) {

        String userVerified = (String) session.getAttribute(SESSION_USER_VERIFIED);

        if (!Constant.YES.equals(userVerified)) {

            try {

                int sleepTime = 3 * Constant.MILISECS;

                waitingTime += sleepTime;

                if (waitingTime > Constant.SOCIAL_VERIFICAITON_TIMEOUT) {

                    throw new OAuthException("Social verification timeout");

                } else {
                    Thread.sleep(sleepTime);
                }/* ww w  .  j a  v  a  2 s  .  c  o m*/

            } catch (InterruptedException e) {

                isUserVerified = true;
                logger.log(Level.SEVERE, "waitUserVerification: thread sleep error", e);
            }

        } else {
            isUserVerified = true;
        }
    }

    return getSocialUser(session.getId());
}

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

@RequestMapping(value = "/wbpost")
public ModelAndView doWhiteboardPost(ModelMap model, HttpServletRequest req) {
    model.clear();//from  ww  w  . j  a va  2s. c  o m

    try {
        String jsonData = req.getParameter("data");
        JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonData);
        WBMessage message = (WBMessage) JSONObject.toBean(json, WBMessage.class);
        HttpSession session = req.getSession();
        String userName = session.getAttribute("userName").toString();

        //TODO validate message contents
        message.setFromUser(userName);

        if (message.getChatMessage() != null) {
            message.setChatMessage(getInputValidator().cleanCommentText(message.getChatMessage()));
            message.setChatMessage(getTextFormatter().formatCommentText(message.getChatMessage()));
        }

        WhiteBoard wb = getWhiteBoard(req);
        if (wb == null) {
            throw new Exception("Invalid White Board");
        }

        message.setWbKey(wb.getKey());
        message.setFromUser(userName);
        message.setCreationTime(System.currentTimeMillis());

        //trim any text geom > 100 chars
        if (message.getGeometry() != null) {
            WBGeometry geom = message.getGeometry();
            if ((geom.getText() != null) && (geom.getText().length() > 100)) {
                geom.setText(geom.getText().substring(0, 99));
            }
        }

        getPM().makePersistent(message);

        List<WBChannel> channels = getLiveChannels(KeyFactory.keyToString(wb.getKey()));
        ChannelService channelService = ChannelServiceFactory.getChannelService();
        String channelError = null;
        for (WBChannel wbChannel : channels) {

            // don't need to send drawing data back to originating user
            if ((message.getChatMessage() != null) || (!session.getId().equals(wbChannel.getSessionId()))) {
                try {
                    channelService.sendMessage(new ChannelMessage(wbChannel.getSessionId(),
                            JSONObject.fromObject(message).toString()));

                } catch (Exception e) {
                    channelError = e.getMessage();
                }
            }
        }

        //if there was at least one channelError, we'll log it to the browser console
        if (channelError != null) {
            model.put("channelError",
                    "error delivering to at least one channel: " + channelError + "(user may have left)");
        }
        model.put("status", "ok");
        model.put("message", JSONObject.fromObject(message));

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

    return doJSON(model);
}