Example usage for javax.servlet.http HttpServletResponse addCookie

List of usage examples for javax.servlet.http HttpServletResponse addCookie

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse addCookie.

Prototype

public void addCookie(Cookie cookie);

Source Link

Document

Adds the specified cookie to the response.

Usage

From source file:com.konakart.actions.BaseAction.java

/**
 * Utility method to get the CustomerUuid from the browser cookie and create the cookie if it
 * doesn't exist.//from  ww w .  j a va2  s. c  o m
 * 
 * @param request
 * @return Returns the CustomerUuid
 */
private String getCustomerUuidFromBrowserCookie(HttpServletRequest request, HttpServletResponse response) {
    /*
     * Try to find the cookie we are looking for
     */
    Cookie[] cookies = request.getCookies();
    String uuid = null;
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            String cookieName = cookie.getName();
            if (cookieName.equals(CUSTOMER_UUID)) {
                /*
                 * If we find the cookie we get the value and update the max age.
                 */
                uuid = cookie.getValue();
                cookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
                cookie.setPath("/");
                response.addCookie(cookie);
            }
        }
    }

    /*
     * If the browser cookie doesn't exist then we have to create it and store a newly created
     * UUID string
     */
    if (uuid == null) {
        UUID uuidObject = UUID.randomUUID();
        uuid = uuidObject.toString();
        /*
         * Create a browser cookie with the UUID
         */
        Cookie uuidCookie = new Cookie(CUSTOMER_UUID, uuid);
        uuidCookie.setMaxAge(COOKIE_MAX_AGE_IN_SECS);
        uuidCookie.setPath("/");
        response.addCookie(uuidCookie);
    }

    return uuid;
}

From source file:com.zimbra.cs.service.ExternalUserProvServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String param = req.getParameter("p");
    if (param == null) {
        throw new ServletException("request missing param");
    }/* ww  w .ja  v a2s  .c  o  m*/
    Map<Object, Object> tokenMap = validatePrelimToken(param);
    Map<String, String> reqHeaders = new HashMap<String, String>();
    String ownerId = (String) tokenMap.get("aid");
    String folderId = (String) tokenMap.get("fid");
    String extUserEmail = (String) tokenMap.get("email");

    Provisioning prov = Provisioning.getInstance();
    Account grantee;
    try {
        Account owner = prov.getAccountById(ownerId);
        Domain domain = prov.getDomain(owner);
        grantee = prov.getAccountByName(mapExtEmailToAcctName(extUserEmail, domain));
        if (grantee == null) {
            // external virtual account not created yet
            if (prov.isOctopus() && DebugConfig.skipVirtualAccountRegistrationPage) {
                // provision using 'null' password and display name
                // UI will ask the user to set these post provisioning
                provisionVirtualAccountAndRedirect(req, resp, null, null, ownerId, extUserEmail);
            } else {
                resp.addCookie(new Cookie("ZM_PRELIM_AUTH_TOKEN", param));
                req.setAttribute("extuseremail", extUserEmail);
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("extuseremail", extUserEmail);
                    reqHeaders.put("ZM_PRELIM_AUTH_TOKEN", param);
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(EXT_USER_PROV_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    ServletContext context = getServletContext().getContext("/zimbra");
                    if (context != null) {
                        RequestDispatcher dispatcher = context.getRequestDispatcher(PUBLIC_EXTUSERPROV_JSP);
                        dispatcher.forward(req, resp);
                    } else {
                        logger.warn("Could not access servlet context url /zimbra");
                        throw ServiceException.TEMPORARILY_UNAVAILABLE();
                    }
                }
            }
        } else {
            // create a new mountpoint in the external user's mailbox if not already created

            String[] sharedItems = owner.getSharedItem();
            int sharedFolderId = Integer.valueOf(folderId);
            String sharedFolderPath = null;
            MailItem.Type sharedFolderView = null;
            for (String sharedItem : sharedItems) {
                ShareInfoData sid = AclPushSerializer.deserialize(sharedItem);
                if (sid.getItemId() == sharedFolderId && extUserEmail.equalsIgnoreCase(sid.getGranteeId())) {
                    sharedFolderPath = sid.getPath();
                    sharedFolderView = sid.getFolderDefaultViewCode();
                    break;
                }
            }
            if (sharedFolderPath == null) {
                throw new ServletException("share not found");
            }
            String mountpointName = getMountpointName(owner, grantee, sharedFolderPath);

            ZMailbox.Options options = new ZMailbox.Options();
            options.setNoSession(true);
            options.setAuthToken(AuthProvider.getAuthToken(grantee).toZAuthToken());
            options.setUri(AccountUtil.getSoapUri(grantee));
            ZMailbox zMailbox = new ZMailbox(options);
            ZMountpoint zMtpt = null;
            try {
                zMtpt = zMailbox.createMountpoint(String.valueOf(getMptParentFolderId(sharedFolderView, prov)),
                        mountpointName, ZFolder.View.fromString(sharedFolderView.toString()),
                        ZFolder.Color.DEFAULTCOLOR, null, ZMailbox.OwnerBy.BY_ID, ownerId,
                        ZMailbox.SharedItemBy.BY_ID, folderId, false);
            } catch (ServiceException e) {
                logger.debug("Error in attempting to create mountpoint. Probably it already exists.", e);
            }
            if (zMtpt != null) {
                if (sharedFolderView == MailItem.Type.APPOINTMENT) {
                    // make sure that the mountpoint is checked in the UI by default
                    FolderActionSelector actionSelector = new FolderActionSelector(zMtpt.getId(), "check");
                    FolderActionRequest actionRequest = new FolderActionRequest(actionSelector);
                    try {
                        zMailbox.invokeJaxb(actionRequest);
                    } catch (ServiceException e) {
                        logger.warn("Error in invoking check action on calendar mountpoint", e);
                    }
                }
                HashSet<MailItem.Type> types = new HashSet<MailItem.Type>();
                types.add(sharedFolderView);
                enableAppFeatures(grantee, types);
            }

            // check if the external user is already logged-in
            String zAuthTokenCookie = null;
            javax.servlet.http.Cookie cookies[] = req.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equals("ZM_AUTH_TOKEN")) {
                        zAuthTokenCookie = cookie.getValue();
                        break;
                    }
                }
            }
            AuthToken zAuthToken = null;
            if (zAuthTokenCookie != null) {
                try {
                    zAuthToken = AuthProvider.getAuthToken(zAuthTokenCookie);
                } catch (AuthTokenException ignored) {
                    // auth token is not valid
                }
            }
            if (zAuthToken != null && !zAuthToken.isExpired() && zAuthToken.isRegistered()
                    && grantee.getId().equals(zAuthToken.getAccountId())) {
                // external virtual account already logged-in
                resp.sendRedirect("/");
            } else if (prov.isOctopus() && !grantee.isVirtualAccountInitialPasswordSet()
                    && DebugConfig.skipVirtualAccountRegistrationPage) {
                // seems like the virtual user did not set his password during his last visit, after an account was
                // provisioned for him
                setCookieAndRedirect(req, resp, grantee);
            } else {
                req.setAttribute("virtualacctdomain", domain.getName());
                if (WebClientServiceUtil.isServerInSplitMode()) {
                    reqHeaders.put("virtualacctdomain", domain.getName());
                    String htmlresp = WebClientServiceUtil
                            .sendServiceRequestToOneRandomUiNode(PUBLIC_LOGIN_ON_UI_NODE, reqHeaders);
                    resp.getWriter().print(htmlresp);
                } else {
                    RequestDispatcher dispatcher = getServletContext().getContext("/zimbra")
                            .getRequestDispatcher(PUBLIC_LOGIN_JSP);
                    dispatcher.forward(req, resp);
                }
            }
        }
    } catch (ServiceException e) {
        throw new ServletException(e);
    }
}

From source file:com.openvcx.webcall.ConferenceCreateServlet.java

/**
 * <p>Lookup a client conference number stored in a cookie. If no phone number is provided by the client a random SIP URI phone number is automatically generated.</p>
 * <p>A conference definition template file is used to create the conference definition for the phone number.</p>
 * <p>The auto-assigned phone number is then stored in a cookie and returned to the client.</p>
 * @param out standard output Output writer
 * @param request The HTTP request object
 * @param response The HTTP response object
 *///from  w  w w  .ja v  a2s. c o  m
private boolean doCreateNumber(PrintWriter out, HttpServletRequest request, HttpServletResponse response)
        throws IOException {
    String strOutputNumber = null;

    Cookie[] arrCookies = request.getCookies();
    if (null != arrCookies) {
        for (Cookie cookie : arrCookies) {
            //logger.debug("cookie name: " + cookie.getName() + ", path: " + cookie.getPath() + ", domain: " + cookie.getDomain() + ", maxAge: " + cookie.getMaxAge() + ", value: " + cookie.getValue());
            if (COOKIE_NUMBER_KEY.equals(cookie.getName())) {
                if (null != (strOutputNumber = cookie.getValue()) && strOutputNumber.length() == 0) {
                    strOutputNumber = null;
                }
                logger.debug("Using cookie stored conference output number: '" + strOutputNumber + "'.");
                break;
            }
        }
    }

    strOutputNumber = createConferenceDefinition(strOutputNumber);

    if (null != strOutputNumber) {

        int cookieAgeDays = 7;
        Cookie cookie = new Cookie(COOKIE_NUMBER_KEY, strOutputNumber);
        cookie.setMaxAge(cookieAgeDays * SECONDS_IN_DAY);
        cookie.setPath("/" + getUriDirSegment(request.getRequestURI(), 0) + "/");
        logger.debug("Setting cookie " + COOKIE_NUMBER_KEY + "=" + strOutputNumber);
        response.addCookie(cookie);
        out.println("number=" + strOutputNumber);
    }

    return true;
}

From source file:com.adito.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }/*from w  w w .j  a v a  2 s .  c  om*/
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("adito.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}

From source file:com.hypersocket.server.HypersocketServerImpl.java

public HypersocketSession setupHttpSession(List<String> cookies, boolean secure,
        HttpServletResponse servletResponse) {

    HypersocketSession session = null;//w w w . java2 s  . com

    for (String header : cookies) {

        StringTokenizer t = new StringTokenizer(header, ";");

        while (t.hasMoreTokens()) {
            String cookie = t.nextToken();
            int idx = cookie.indexOf('=');
            if (idx == -1)
                continue;
            String name = cookie.substring(0, idx).trim();
            if (name.equals(sessionCookieName)) {
                String value = cookie.substring(idx + 1);
                session = HypersocketSessionFactory.getInstance().getSession(value,
                        servletConfig.getServletContext());
                // Check that the session exists in case we have any old
                // cookies
                if (session != null) {
                    break;
                }
            }
        }
    }
    if (session == null) {
        session = HypersocketSessionFactory.getInstance().createSession(servletConfig.getServletContext());
    }

    Cookie cookie = new Cookie(sessionCookieName, session.getId());
    cookie.setMaxAge(60 * 15);
    cookie.setPath("/");
    cookie.setSecure(secure);
    servletResponse.addCookie(cookie);

    return session;
}

From source file:neu.edu.lab08.HomeController.java

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String submitForm(Model model, @Validated User user, BindingResult result, HttpServletRequest request,
        HttpServletResponse response) {
    model.addAttribute("user", user);
    String returnVal = "menu";
    String remember = request.getParameter("remember");
    if (result.hasErrors()) {

        return "home";
    } else {//from w  ww. j  a v a2s  .  c om
        try {
            User u = userDao.queryUserByNameAndPassword(user.getUsername(), user.getPassword());
            //            ArrayList<Message> messageList = messageDao.listMessagesByUsername(u.getUsername());
            //            ArrayList<Contacts> contactsList = contactsDao.listContactsByUsername(u.getUsername());
            //            int messageSize = messageList.size();
            //            int contactsSize = contactsList.size();
            if (u != null) {
                if (remember != null) {
                    Cookie usernameCookie = new Cookie("usernameCookie", u.getUsername());
                    Cookie passwordCookie = new Cookie("passwordCookie", u.getPassword());
                    usernameCookie.setMaxAge(604000);
                    passwordCookie.setMaxAge(604000);
                    response.addCookie(usernameCookie);
                    response.addCookie(passwordCookie);
                }

                if (u.getRole().equals("admin")) {
                    model.addAttribute("user", u);
                    HttpSession session = request.getSession();
                    session.setAttribute("username", u.getUsername());
                    //                        HttpSession useridsession = request.getSession();
                    //                        useridsession.setAttribute("userid", u.getId());
                    return "createUser";
                } else if (u.getRole().equals("CDC")) {
                    HttpSession session = request.getSession();
                    session.setAttribute("username", u.getUsername());
                    //                        HttpSession useridsession = request.getSession();
                    //                        useridsession.setAttribute("userid", u.getId());
                    model.addAttribute("user", u);
                    ArrayList<Vaccine> vaccineList = vaccineDao.listVaccineByUsername(u.getUsername());
                    ArrayList<Request> requestList = requestDao.listRequest();
                    model.addAttribute("producedvaccineList", vaccineList);
                    model.addAttribute("requestList", requestList);
                    return "cdcMenu";
                } else if (u.getRole().equals("Hospital")) {
                    HttpSession session = request.getSession();
                    session.setAttribute("username", u.getUsername());
                    //                        HttpSession useridsession = request.getSession();
                    //                        useridsession.setAttribute("userid", u.getId());
                    model.addAttribute("user", u);
                    ArrayList<Vaccine> vaccineList = vaccineDao.listVaccine();
                    ArrayList<InsuredPatient> insuredPatientList = patientDao
                            .listInsuredPatientByUsername(u.getUsername());
                    ArrayList<UninsuredPatient> uninsuredPatientList = patientDao
                            .listUninsuredPatientByUsername(u.getUsername());
                    ArrayList<Inventory> inventoryList = inventoryDao.listInventoryByUser(u.getUsername());
                    model.addAttribute("insuredPatientList", insuredPatientList);
                    model.addAttribute("uninsuredPatientList", uninsuredPatientList);
                    model.addAttribute("vaccineList", vaccineList);
                    model.addAttribute("inventoryList", inventoryList);
                    HttpSession inventorysession = request.getSession();
                    inventorysession.setAttribute("inventoryList", inventoryList);
                    ArrayList<UsedVaccine> usedvaccineList = vaccineDao
                            .listUsedVaccineByUsername(u.getUsername());
                    model.addAttribute("usedvaccineList", usedvaccineList);
                    return "hospitalMenu";
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    return "home";

}

From source file:com.sslexplorer.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }/*from  w w  w.j  a  va2  s.  c  o m*/
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("sslexplorer.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}

From source file:com.google.youtube.captions.AuthSubLogin.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    try {//from w w  w  .j a v  a  2s .  com
        String authSubToken = AuthSubUtil.getTokenFromReply(req.getQueryString());
        if (authSubToken == null) {
            throw new IllegalStateException("Could not parse token from AuthSub response.");
        } else {
            authSubToken = URLDecoder.decode(authSubToken, "UTF-8");
        }

        authSubToken = AuthSubUtil.exchangeForSessionToken(authSubToken, null);

        YouTubeService service = new YouTubeService(SystemProperty.applicationId.get(), Util.DEVELOPER_KEY);
        service.setAuthSubToken(authSubToken);

        UserProfileEntry profileEntry = service.getEntry(new URL(PROFILE_URL), UserProfileEntry.class);
        String username = profileEntry.getUsername();

        String authSubCookie = Util.getCookie(req, Util.AUTH_SUB_COOKIE);
        JSONObject cookieAsJSON = new JSONObject();
        if (!Util.isEmptyOrNull(authSubCookie)) {
            try {
                cookieAsJSON = new JSONObject(authSubCookie);
            } catch (JSONException e) {
                LOG.log(Level.WARNING, "Unable to parse JSON from the existing cookie: " + authSubCookie, e);
            }
        }

        try {
            cookieAsJSON.put(username, authSubToken);
        } catch (JSONException e) {
            LOG.log(Level.WARNING,
                    String.format("Unable to add account '%s' and AuthSub token '%s'" + " to the JSON object.",
                            username, authSubToken),
                    e);
        }

        Cookie cookie = new Cookie(Util.AUTH_SUB_COOKIE, cookieAsJSON.toString());
        cookie.setMaxAge(Util.COOKIE_LIFETIME);
        resp.addCookie(cookie);

        cookie = new Cookie(Util.CURRENT_AUTHSUB_TOKEN, authSubToken);
        cookie.setMaxAge(Util.COOKIE_LIFETIME);
        resp.addCookie(cookie);

        cookie = new Cookie(Util.CURRENT_USERNAME, username);
        cookie.setMaxAge(Util.COOKIE_LIFETIME);
        resp.addCookie(cookie);
    } catch (IllegalStateException e) {
        LOG.log(Level.WARNING, "", e);
    } catch (AuthenticationException e) {
        LOG.log(Level.WARNING, "", e);
    } catch (GeneralSecurityException e) {
        LOG.log(Level.WARNING, "", e);
    } catch (ServiceException e) {
        LOG.log(Level.WARNING, "", e);
    }

    resp.sendRedirect("/");
}

From source file:com.medallia.spider.SpiderServlet.java

private RequestHandler makeRequest(HttpServletRequest req, final HttpServletResponse response) {
    final Map<String, String> m = Empty.hashMap();
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            addCookie(m, c);//ww w  .j  a  v a 2  s.  c o  m
        }
    }
    return new RequestHandler() {
        @Implement
        public String getCookieValue(String name) {
            return m.get(name);
        }

        @Implement
        public void setCookieValue(String name, String value) {
            storeCookie(makeCookie(name, value));
        }

        @Implement
        public void setPersistentCookieValue(String name, String value, int expiry) {
            if (expiry <= 0)
                throw new IllegalArgumentException("expiry must be a positive number: " + expiry);

            Cookie c = makeCookie(name, value);
            c.setMaxAge(expiry);
            storeCookie(c);
        }

        @Implement
        public void removeCookieValue(String name) {
            Cookie c = makeCookie(name, null);
            c.setMaxAge(0);
            storeCookie(c);
        }

        private void storeCookie(Cookie c) {
            response.addCookie(c);
            addCookie(m, c);
        }

        private Cookie makeCookie(String name, String value) {
            return new Cookie(name, value);
        }
    };
}

From source file:com.liferay.portal.servlet.MainServlet.java

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    if (!PortalInstances.matches()) {
        String html = ContentUtil.get("messages/en_US/init.html");

        res.getOutputStream().print(html);

        return;// ww  w.  j ava 2s  . com
    }

    if (ShutdownUtil.isShutdown()) {
        String html = ContentUtil.get("messages/en_US/shutdown.html");

        res.getOutputStream().print(html);

        return;
    }
    req.setAttribute("dotcache", "no");
    // Shared session

    HttpSession ses = req.getSession();

    if (!GetterUtil.getBoolean(PropsUtil.get(PropsUtil.TCK_URL))) {
        String sharedSessionId = CookieUtil.get(req.getCookies(), CookieKeys.SHARED_SESSION_ID);

        _log.debug("Shared session id is " + sharedSessionId);

        if (sharedSessionId == null) {
            sharedSessionId = PwdGenerator.getPassword(PwdGenerator.KEY1 + PwdGenerator.KEY2, 12);

            Cookie sharedSessionIdCookie = new Cookie(CookieKeys.SHARED_SESSION_ID, sharedSessionId);
            sharedSessionIdCookie.setPath("/");
            sharedSessionIdCookie.setMaxAge(86400);

            res.addCookie(sharedSessionIdCookie);

            _log.debug("Shared session id is " + sharedSessionId);
        }

        // if (ses.getAttribute(WebKeys.SHARED_SESSION_ID) == null) {
        ses.setAttribute(WebKeys.SHARED_SESSION_ID, sharedSessionId);
        // }

        HttpSession portalSes = (HttpSession) SharedSessionPool.get(sharedSessionId);

        if ((portalSes == null) || (ses != portalSes)) {
            if (portalSes == null) {
                _log.debug("No session exists in pool");
            } else {
                _log.debug("Session " + portalSes.getId() + " in pool is old");
            }

            _log.debug("Inserting current session " + ses.getId() + " in pool");

            SharedSessionPool.put(sharedSessionId, ses);
        }
    }

    // Test CAS auto login

    /*
     * ses.setAttribute(
     * com.liferay.portal.auth.CASAutoLogin.CAS_FILTER_USER,
     * "liferay.com.1");
     */

    // CTX

    ServletContext ctx = getServletContext();
    ServletContext portalCtx = ctx.getContext(PropsUtil.get(PropsUtil.PORTAL_CTX));
    if (portalCtx == null) {
        portalCtx = ctx;
    }

    req.setAttribute(WebKeys.CTX, portalCtx);

    // CTX_PATH variable

    String ctxPath = (String) ctx.getAttribute(WebKeys.CTX_PATH);

    if (portalCtx.getAttribute(WebKeys.CTX_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    if (ses.getAttribute(WebKeys.CTX_PATH) == null) {
        ses.setAttribute(WebKeys.CTX_PATH, ctxPath);
    }

    req.setAttribute(WebKeys.CTX_PATH, ctxPath);

    // CAPTCHA_PATH variable

    String captchaPath = (String) ctx.getAttribute(WebKeys.CAPTCHA_PATH);

    if (portalCtx.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        portalCtx.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    if (ses.getAttribute(WebKeys.CAPTCHA_PATH) == null) {
        ses.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);
    }

    req.setAttribute(WebKeys.CAPTCHA_PATH, captchaPath);

    // IMAGE_PATH variable

    String imagePath = (String) ctx.getAttribute(WebKeys.IMAGE_PATH);

    if (portalCtx.getAttribute(WebKeys.IMAGE_PATH) == null) {
        portalCtx.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    if (ses.getAttribute(WebKeys.IMAGE_PATH) == null) {
        ses.setAttribute(WebKeys.IMAGE_PATH, imagePath);
    }

    req.setAttribute(WebKeys.IMAGE_PATH, imagePath);

    // WebKeys.COMPANY_ID variable

    String companyId = (String) ctx.getAttribute(WebKeys.COMPANY_ID);

    if (portalCtx.getAttribute(WebKeys.COMPANY_ID) == null) {
        portalCtx.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    if (ses.getAttribute(WebKeys.COMPANY_ID) == null) {
        ses.setAttribute(WebKeys.COMPANY_ID, companyId);
    }

    req.setAttribute(WebKeys.COMPANY_ID, companyId);

    // Portlet Request Processor

    PortletRequestProcessor portletReqProcessor = (PortletRequestProcessor) portalCtx
            .getAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR);

    if (portletReqProcessor == null) {
        portletReqProcessor = new PortletRequestProcessor(this, getModuleConfig(req));

        portalCtx.setAttribute(WebKeys.PORTLET_STRUTS_PROCESSOR, portletReqProcessor);
    }

    // Tiles definitions factory

    if (portalCtx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY) == null) {
        portalCtx.setAttribute(TilesUtilImpl.DEFINITIONS_FACTORY,
                ctx.getAttribute(TilesUtilImpl.DEFINITIONS_FACTORY));
    }

    // Set character encoding

    String strutsCharEncoding = PropsUtil.get(PropsUtil.STRUTS_CHAR_ENCODING);

    req.setCharacterEncoding(strutsCharEncoding);

    /*
     * if (!BrowserSniffer.is_wml(req)) { res.setContentType(
     * Constants.TEXT_HTML + "; charset=" + strutsCharEncoding); }
     */

    // Determine content type

    String contentType = req.getHeader("Content-Type");

    if ((contentType != null) && (contentType.startsWith("multipart/form-data"))) {

        req = new UploadServletRequest(req);
    } else if (ParamUtil.get(req, WebKeys.ENCRYPT, false)) {
        try {
            Company company = CompanyLocalManagerUtil.getCompany(companyId);

            req = new EncryptedServletRequest(req, company.getKeyObj());
        } catch (Exception e) {
        }
    }

    // Current URL

    String completeURL = Http.getCompleteURL(req);
    if (completeURL.indexOf("j_security_check") != -1) {
        completeURL = ctxPath;
    } else {
        completeURL = completeURL.substring(completeURL.indexOf("://") + 3, completeURL.length());

        completeURL = completeURL.substring(completeURL.indexOf("/"), completeURL.length());
    }

    req.setAttribute(WebKeys.CURRENT_URL, completeURL);

    // Chat server

    // Login

    String userId = PortalUtil.getUserId(req);

    if ((userId != null)) {
        PrincipalThreadLocal.setName(userId);
    }

    if (userId == null) {
        try {
            User user = UserManagerUtil.getDefaultUser(companyId);
            if (ses.getAttribute(Globals.LOCALE_KEY) == null)
                ses.setAttribute(Globals.LOCALE_KEY, user.getLocale());

        } catch (Exception e) {
            Logger.error(this, e.getMessage(), e);
        }
    }

    // Process pre service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_PRE), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);

        req.setAttribute(PageContext.EXCEPTION, e);

        StrutsUtil.forward(PropsUtil.get(PropsUtil.SERVLET_SERVICE_EVENTS_PRE_ERROR_PAGE), portalCtx, req, res);
    }

    // Struts service

    callParentService(req, res);

    // Process post service events

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.SERVLET_SERVICE_EVENTS_POST), req, res);
    } catch (Exception e) {
        Logger.error(this, e.getMessage(), e);
    }

    // Clear the principal associated with this thread

    PrincipalThreadLocal.setName(null);
}