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.w20e.socrates.servlet.WebsurveyServlet.java

/**
 * Initialize the runner for a given questionnaire. The runner, if 
 * successfully created, is stored in the 'runnerCtx' attribute
 * of the session. /*from  w w w . j  a  v a  2  s  .  c  o m*/
 * 
 * @param req HTTP request
 * @param res HTTP response
 * @param session HTTP session
 * @param options any specific creation options
 */
private boolean initializeRunner(HttpServletRequest req, HttpServletResponse res, HttpSession session,
        Map<String, String> options) {

    String id = req.getParameter("id");

    LOGGER.finest("Parameter id is " + id);

    URI qUri = QuestionnaireURIFactory.getInstance().determineURI(this.rootDir, id);

    /**
     * Get global config.
     */
    Configuration cfg = null;

    try {
        cfg = ConfigurationResource.getInstance().getConfiguration(qUri.toURL());
    } catch (Exception e1) {
        return false;
    }

    LOGGER.fine("Using config URI " + qUri.toString());

    try {
        RunnerContextImpl ctx = this.runnerFactory.createContext(qUri, options);

        // Check whether the instance has a variable locale set. If so, this becomes the default.
        //
        Locale locale = null;

        try {
            locale = LocaleUtility.getLocale(ctx.getInstance().getNode("locale").getValue().toString(), true);
            LOGGER.fine("Using default locale set in model instance: " + locale);
        } catch (Exception e) {
            locale = LocaleUtility.DEFAULT_LOCALE;
            LOGGER.warning(
                    "Not using default locale set in model instance due to errors, fall back: " + locale);
        }

        LOGGER.fine("Using default locale " + locale);

        // Now see if we need to take the locale from the request
        // parameters or the user agent headers.
        locale = ServletHelper.getLocale(req, locale);

        LOGGER.fine("Using locale " + locale);

        ctx.setLocale(locale);
        ctx.setQuestionnaireId(qUri);

        /*
         * We may need to reread an existing data set. We do this if the
         * request didn't explicitly forbid it, and we do have either an
         * existing session or a stored instance file.
         */
        if ("true".equals(cfg.getString("enablelongsessions", "true"))) {

            LOGGER.info("Has long session? " + this.sessionMgr.hasLongSession(req, id));

            if (this.sessionMgr.hasLongSession(req, id) && !"true".equals(options.get("disable_reload"))) {

                Instance inst = this.sessionMgr.salvageInstance(id, req, ctx);

                if (inst != null) {
                    ctx.setInstance(inst);
                    LOGGER.fine("Setting state to " + (String) inst.getMetaData().get("stateId"));
                    ctx.getStateManager().setStateById((String) inst.getMetaData().get("stateId"));
                } else {
                    LOGGER.warning("Unable to restore instance");
                }
            }
        } else if (req.getParameter("regkey") != null) {
            Instance inst = this.sessionMgr.salvageInstanceFromRegkey(req.getParameter("regkey"), req, ctx);

            if (inst != null) {
                ctx.setInstance(inst);
                LOGGER.fine("Setting state to " + (String) inst.getMetaData().get("stateId"));
                ctx.getStateManager().setStateById((String) inst.getMetaData().get("stateId"));
            } else {
                LOGGER.warning("Unable to restore instance");
            }
        }

        Map<String, Object> meta = ctx.getInstance().getMetaData();

        meta.put("qId", id);
        meta.put("qLocale", locale);

        ServletHelper.setMetaData(req, meta);

        // Store runner context in session
        //
        session.setAttribute("runnerCtx", new WebsurveyContext(ctx, id, locale));

        // Output filename. If unset, default to overwritable file.
        //
        if (!meta.containsKey("filename") || meta.get("filename") == null) {

            meta.put("filename",
                    id + (ctx.getModel().getMetaData().containsKey("Version")
                            ? "-" + ctx.getModel().getMetaData().get("Version")
                            : "") + "_" + locale + "_"
                            + WebsurveyServlet.FORMATTER.format(Calendar.getInstance().getTime()) + "_"
                            + meta.get("key"));
        }

        if ("true".equals(cfg.getString("enablelongsessions", "true"))) {

            // Finally, add cookie that holds info on user data, if we
            // don't
            // already have it, and set output
            // file name.
            //
            if (!this.sessionMgr.hasLongSession(req, id)) {
                this.sessionMgr.createLongLivedSession(id,
                        meta.get("filename").toString() + "||" + session.getId(), res);
            }
        }
    } catch (UnsupportedMediumException e) {

        this.sessionMgr.invalidateSession(req);
        LOGGER.log(Level.SEVERE, "Error in creating runner context", e);
        return false;
    }

    return true;
}

From source file:de.innovationgate.wgpublisher.webtml.utils.TMLContext.java

private Object getSessionMetaData(String name) {

    if (!getEnvironment().isPageContextAvailable()) {
        this.setLastError(
                "Cannot retrieve session metadata because this script does not run inside a WebTML page");
        return null;
    }/*from   ww w .  j a va2 s. c o  m*/

    HttpSession session = gethttpsession();
    if (name.equals("start")) {
        return new Date(session.getCreationTime());
    } else if (name.equals("lastaccess")) {
        return new Date(session.getLastAccessedTime());
    } else if (name.equals("id")) {
        return session.getId();
    } else if (name.equals("language")) {
        return getpreferredlanguage();
    } else {
        return null;
    }
}

From source file:com.glaf.base.modules.sys.springmvc.MxLoginController.java

/**
 * //from   w  ww .  j  a v a2s  . com
 * 
 * @param request
 * @param modelMap
 * @return
 */
@RequestMapping("/doLogin")
public ModelAndView doLogin(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
    RequestUtils.setRequestParameterToAttribute(request);
    HttpSession session = request.getSession(false);
    if (session == null) {
        return new ModelAndView("/modules/login", modelMap);
    }

    if (StringUtils.isNotEmpty(request.getParameter("systemName"))) {
        Environment.setCurrentSystemName(request.getParameter("systemName"));
    } else {
        Environment.setCurrentSystemName(Environment.DEFAULT_SYSTEM_NAME);
    }

    ViewMessages messages = new ViewMessages();
    // ??
    String account = ParamUtil.getParameter(request, "x");
    String password = ParamUtil.getParameter(request, "y");

    String rand = (String) session.getAttribute("x_y");
    if (rand != null) {
        password = StringTools.replace(password, rand, "");
    }
    String rand2 = (String) session.getAttribute("x_z");
    if (rand2 != null) {
        password = StringTools.replace(password, rand2, "");
    }
    String pwd = password;
    try {
        pwd = DigestUtil.digestString(password, "MD5");
    } catch (Exception ex) {
    }

    logger.debug(account + " start login........................");

    // 
    SysUser bean = authorizeService.authorize(account, pwd);
    if (bean == null) {
        // ?
        messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage("authorize.login_failure"));
        MessageUtils.addMessages(request, messages);
        return new ModelAndView("/modules/login", modelMap);
    }

    String ipAddr = RequestUtils.getIPAddress(request);
    SystemProperty p = SystemConfig.getProperty("login_limit");

    if (!(StringUtils.equals(ipAddr, "localhost") || StringUtils.equals(ipAddr, "127.0.0.1")
            || StringUtils.equals(account, "root") || StringUtils.equals(account, "admin"))) {

        SystemProperty pt = SystemConfig.getProperty("login_time_check");
        int timeoutSeconds = 300;

        if (pt != null && pt.getValue() != null && StringUtils.isNumeric(pt.getValue())) {
            timeoutSeconds = Integer.parseInt(pt.getValue());
        }
        if (timeoutSeconds < 300) {
            timeoutSeconds = 300;
        }
        if (timeoutSeconds > 3600) {
            timeoutSeconds = 3600;
        }

        /**
         * ???
         */
        if (p != null && StringUtils.equals(p.getValue(), "true")) {
            logger.debug("#################3#########################");
            String loginIP = null;
            UserOnline userOnline = userOnlineService.getUserOnline(account);
            logger.debug("userOnline:" + userOnline);
            boolean timeout = false;
            if (userOnline != null) {
                loginIP = userOnline.getLoginIP();
                if (userOnline.getCheckDateMs() != null
                        && System.currentTimeMillis() - userOnline.getCheckDateMs() > timeoutSeconds * 1000) {
                    timeout = true;// ?
                }
                if (userOnline.getLoginDate() != null && System.currentTimeMillis()
                        - userOnline.getLoginDate().getTime() > timeoutSeconds * 1000) {
                    timeout = true;// ?
                }
            }
            logger.info("timeout:" + timeout);
            logger.info("login IP:" + loginIP);
            if (!timeout) {// ????
                if (loginIP != null && !(StringUtils.equals(ipAddr, loginIP))) {// 
                    messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage("authorize.login_failure2"));
                    MessageUtils.addMessages(request, messages);
                    logger.debug("?");
                    return new ModelAndView("/modules/login", modelMap);
                }
            }
        }
    }

    Properties props = CallbackProperties.getProperties();
    if (props != null && props.keys().hasMoreElements()) {
        Enumeration<?> e = props.keys();
        while (e.hasMoreElements()) {
            String className = (String) e.nextElement();
            try {
                Object obj = ClassUtils.instantiateObject(className);
                if (obj instanceof LoginCallback) {
                    LoginCallback callback = (LoginCallback) obj;
                    callback.afterLogin(bean.getAccount(), request, response);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                logger.error(ex);
            }
        }
    }

    if (bean.getLoginCount() != null) {
        bean.setLoginCount(bean.getLoginCount() + 1);
    } else {
        bean.setLoginCount(1);
    }

    // ?
    bean.setLastLoginDate(new Date());
    sysUserService.updateUser(bean);

    ContextUtil.put(bean.getAccount(), bean);// ??

    RequestUtils.setLoginUser(request, response, "default", bean.getAccount());
    if (p != null && StringUtils.equals(p.getValue(), "true")) {
        try {
            UserOnline online = new UserOnline();
            online.setActorId(bean.getActorId());
            online.setName(bean.getName());
            online.setCheckDate(new Date());
            online.setLoginDate(new Date());
            online.setLoginIP(ipAddr);
            online.setSessionId(session.getId());
            userOnlineService.login(online);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex);
        }
    }

    if (bean.getAccountType() == 1) {// 
        return new ModelAndView("/modules/sp_main", modelMap);
    } else if (bean.getAccountType() == 2) {// 
        return new ModelAndView("/modules/wx_main", modelMap);
    } else {
        return new ModelAndView("/modules/main", modelMap);
    }

}

From source file:com.glaf.base.modules.sys.springmvc.LoginController.java

/**
 * //from  w w  w.j  a  v a2 s  . c  o  m
 * 
 * @param request
 * @param modelMap
 * @return
 */
@RequestMapping(params = "method=login")
public ModelAndView login(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
    RequestUtils.setRequestParameterToAttribute(request);
    HttpSession session = request.getSession(false);
    if (session == null) {
        return new ModelAndView("/modules/login", modelMap);
    }

    if (StringUtils.isNotEmpty(request.getParameter("systemName"))) {
        Environment.setCurrentSystemName(request.getParameter("systemName"));
    } else {
        Environment.setCurrentSystemName(Environment.DEFAULT_SYSTEM_NAME);
    }

    ViewMessages messages = new ViewMessages();
    // ??
    String account = ParamUtil.getParameter(request, "x");
    String password = ParamUtil.getParameter(request, "y");

    String rand = (String) session.getAttribute("x_y");
    if (rand != null) {
        password = StringTools.replace(password, rand, "");
    }

    String rand2 = (String) session.getAttribute("x_z");
    if (rand2 != null) {
        password = StringTools.replace(password, rand2, "");
    }
    String pwd = password;
    try {
        pwd = DigestUtil.digestString(password, "MD5");
    } catch (Exception ex) {
    }

    logger.debug(account + " start login........................");

    // 
    SysUser bean = authorizeService.authorize(account, pwd);
    if (bean == null) {
        // ?
        messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage("authorize.login_failure"));
        MessageUtils.addMessages(request, messages);
        return new ModelAndView("/modules/login", modelMap);
    }
    String ipAddr = RequestUtils.getIPAddress(request);
    SystemProperty p = SystemConfig.getProperty("login_limit");
    if (!(StringUtils.equals(ipAddr, "localhost") || StringUtils.equals(ipAddr, "127.0.0.1")
            || StringUtils.equals(account, "root") || StringUtils.equals(account, "admin"))) {

        SystemProperty pt = SystemConfig.getProperty("login_time_check");
        int timeoutSeconds = 300;

        if (pt != null && pt.getValue() != null && StringUtils.isNumeric(pt.getValue())) {
            timeoutSeconds = Integer.parseInt(pt.getValue());
        }
        if (timeoutSeconds < 300) {
            timeoutSeconds = 300;
        }
        if (timeoutSeconds > 3600) {
            timeoutSeconds = 3600;
        }

        /**
         * ???
         */
        if (p != null && StringUtils.equals(p.getValue(), "true")) {
            logger.debug("#################3#########################");
            String loginIP = null;
            UserOnline userOnline = userOnlineService.getUserOnline(account);
            logger.debug("userOnline:" + userOnline);
            boolean timeout = false;
            if (userOnline != null) {
                loginIP = userOnline.getLoginIP();
                if (userOnline.getCheckDateMs() != null
                        && System.currentTimeMillis() - userOnline.getCheckDateMs() > timeoutSeconds * 1000) {
                    timeout = true;// ?
                }
                if (userOnline.getLoginDate() != null && System.currentTimeMillis()
                        - userOnline.getLoginDate().getTime() > timeoutSeconds * 1000) {
                    timeout = true;// ?
                }
            }
            logger.info("login IP:" + loginIP);
            if (!timeout) {// ????
                if (loginIP != null && !(StringUtils.equals(ipAddr, loginIP))) {// 
                    messages.add(ViewMessages.GLOBAL_MESSAGE, new ViewMessage("authorize.login_failure2"));
                    MessageUtils.addMessages(request, messages);
                    logger.debug("?");
                    return new ModelAndView("/modules/login", modelMap);
                }
            }
        }
    }

    Properties props = CallbackProperties.getProperties();
    if (props != null && props.keys().hasMoreElements()) {
        Enumeration<?> e = props.keys();
        while (e.hasMoreElements()) {
            String className = (String) e.nextElement();
            if (className.indexOf("parameter") >= 0) {
                continue;
            }
            try {
                Object obj = ClassUtils.instantiateObject(className);
                if (obj instanceof LoginCallback) {
                    LoginCallback callback = (LoginCallback) obj;
                    callback.afterLogin(bean.getAccount(), request, response);
                }
            } catch (Exception ex) {
                ex.printStackTrace();
                logger.error(ex);
            }
        }
    }

    if (bean.getLoginCount() != null) {
        bean.setLoginCount(bean.getLoginCount() + 1);
    } else {
        bean.setLoginCount(1);
    }
    // ?
    bean.setLastLoginDate(new Date());
    sysUserService.updateUser(bean);

    // String menus = sysApplicationService.getMenu(3, bean);
    // bean.setMenus(menus);
    // request.setAttribute(SysConstants.MENU, menus);

    ContextUtil.put(bean.getAccount(), bean);// ??

    RequestUtils.setLoginUser(request, response, "default", bean.getAccount());
    if (p != null && StringUtils.equals(p.getValue(), "true")) {
        try {
            UserOnline online = new UserOnline();
            online.setActorId(bean.getActorId());
            online.setName(bean.getName());
            online.setCheckDate(new Date());
            online.setLoginDate(new Date());
            online.setLoginIP(ipAddr);
            online.setSessionId(session.getId());
            userOnlineService.login(online);
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(ex);
        }
    }

    if (bean.getAccountType() == 1) {// 
        return new ModelAndView("/modules/sp_main", modelMap);
    } else if (bean.getAccountType() == 2) {// 
        return new ModelAndView("/modules/wx_main", modelMap);
    } else {
        return new ModelAndView("/modules/main", modelMap);
    }

}

From source file:at.gv.egovernment.moa.id.proxy.servlet.ProxyServlet.java

/**
 * Login to online application at first call of servlet for a user session.<br/>
 * <ul>//from w  w w . j  a  v a  2s  .c om
 * <li>Acquires authentication data from the MOA-ID Auth component.</li>
 * <li>Reads configuration data for the online application.</li>
 * <li>Resolves login parameters.</li>
 * <li>Sets up an SSLSocketFactory in case of a secure connection to the online application.</li>
 * <li>For a stateless online application, stores data in the HttpSession.</li>
 * <li>Tunnels the request to the online application.</li>
 * </ul> 
 * @param req
 * @param resp
 * @throws ConfigurationException when wrong configuration is encountered
 * @throws ProxyException when wrong configuration is encountered
 * @throws BuildException while building the request for MOA-ID Auth
 * @throws ServiceException while invoking MOA-ID Auth
 * @throws ParseException while parsing the response from MOA-ID Auth
 */
private void login(HttpServletRequest req, HttpServletResponse resp) throws ConfigurationException,
        ProxyException, BuildException, ServiceException, ParseException, AuthenticationException {

    HttpSession session = req.getSession();
    String samlArtifact = "";
    Map loginHeaders = null;
    Map loginParameters = null;
    String publicURLPrefix = "";
    String realURLPrefix = "";
    SSLSocketFactory ssf = null;
    String urlRequested = req.getRequestURL().toString();
    OAConfiguration oaConf = null;
    String loginType = "";
    String binding = "";

    if (session.getAttribute(ATT_BROWSERREQU) == null) {

        // read configuration data
        ProxyConfigurationProvider proxyConf = ProxyConfigurationProvider.getInstance();
        OAProxyParameter oaParam = proxyConf.getOnlineApplicationParameter(urlRequested);
        if (oaParam == null) {
            throw new ProxyException("proxy.02", new Object[] { urlRequested });
        }

        samlArtifact = req.getParameter(PARAM_SAMLARTIFACT);
        Logger.debug("moa-id-proxy login " + PARAM_SAMLARTIFACT + ": " + samlArtifact);
        // String target = req.getParameter(PARAM_TARGET); parameter given but not processed
        // boolean targetprovided = req.getParameter(PARAM_TARGET) != null;

        // get authentication data from the MOA-ID Auth component
        SAML1AuthenticationData authData;
        try {
            authData = new GetAuthenticationDataInvoker().getAuthenticationData(samlArtifact);

        } catch (ServiceException ex) {
            throw new ProxyException("proxy.14", new Object[] { ex.getMessage() }, ex);

        } catch (ProxyException ex) {
            throw new ProxyException("proxy.14", new Object[] { ex.getMessage() }, ex);

        } catch (MOAIDException ex) {
            String errorURL = oaParam.getErrorRedirctURL();
            if (MiscUtil.isNotEmpty(errorURL)) {
                generateErrorAndRedirct(resp, errorURL, ex.getMessage());
                return;

            } else {
                Logger.info("No ErrorRedirectURL defined. The error is shown on MOA-ID Proxy errorpage.");
                throw new ProxyException("proxy.14", new Object[] { ex.getMessage() }, ex);
            }
        }
        session.setAttribute(ATT_AUTHDATAFETCHED, "true");

        publicURLPrefix = oaParam.getPublicURLPrefix();
        Logger.debug("OA: " + publicURLPrefix);
        oaConf = oaParam.getOaConfiguration();
        ConnectionParameter oaConnParam = oaParam.getConnectionParameter();
        realURLPrefix = oaConnParam.getUrl();

        // resolve login parameters to be forwarded to online application 
        LoginParameterResolver lpr = LoginParameterResolverFactory.getLoginParameterResolver(publicURLPrefix);
        String clientIPAddress = req.getRemoteAddr();
        boolean businessService = oaParam.getBusinessService();
        try {
            if (oaConf.getAuthType().equals(OAConfiguration.PARAM_AUTH)) {
                loginParameters = lpr.getAuthenticationParameters(oaConf, authData, clientIPAddress,
                        businessService, publicURLPrefix);
            } else {
                loginHeaders = lpr.getAuthenticationHeaders(oaConf, authData, clientIPAddress, businessService,
                        publicURLPrefix);
                for (Iterator iter = loginHeaders.keySet().iterator(); iter.hasNext();) {
                    //extract user-defined bindingValue
                    String headerKey = (String) iter.next();
                    String headerKeyValue = (String) loginHeaders.get(headerKey);
                    if (headerKey.equalsIgnoreCase("binding")) {
                        binding = (String) loginHeaders.get(headerKey);
                    }
                    for (int i = 1; i <= 3; i++) {
                        if (headerKey.equalsIgnoreCase("param" + i)) {
                            int sep = headerKeyValue.indexOf("=");
                            if (sep > -1) {
                                if (sep > 0) {
                                    String value = "";
                                    if (headerKeyValue.length() > sep + 1)
                                        value = headerKeyValue.substring(sep + 1);
                                    if (loginParameters == null)
                                        loginParameters = new HashMap();
                                    loginParameters.put(headerKeyValue.substring(0, sep), value);
                                }
                            } else {
                                loginParameters.put(headerKey, "");
                            }
                        }
                    }
                }
                loginHeaders.remove("binding");
                loginHeaders.remove("param1");
                loginHeaders.remove("param2");
                loginHeaders.remove("param3");
            }
        } catch (LoginParameterResolverException ex) {
            String errorURL = oaParam.getErrorRedirctURL();
            if (MiscUtil.isNotEmpty(errorURL)) {
                generateErrorAndRedirct(resp, errorURL, MOAIDMessageProvider.getInstance()
                        .getMessage("proxy.13", new Object[] { publicURLPrefix }));
                return;

            } else
                throw new ProxyException("proxy.13", new Object[] { publicURLPrefix });

        } catch (NotAllowedException e) {
            String errorURL = oaParam.getErrorRedirctURL();
            if (MiscUtil.isNotEmpty(errorURL)) {
                generateErrorAndRedirct(resp, errorURL,
                        MOAIDMessageProvider.getInstance().getMessage("proxy.15", new Object[] {}));
                return;

            } else
                throw new ProxyException("proxy.15", new Object[] {});
        }

        // setup SSLSocketFactory for communication with the online application
        if (oaConnParam.isHTTPSURL()) {
            try {
                ssf = SSLUtils.getSSLSocketFactory(proxyConf, oaConnParam);
            } catch (Throwable ex) {
                throw new ProxyException("proxy.05", new Object[] { oaConnParam.getUrl(), ex.toString() }, ex);
            }
        }

        // for stateless online application, store data in HttpSession
        loginType = oaConf.getLoginType();
        if ("".equalsIgnoreCase(binding)) {
            binding = oaConf.getBinding();
            if ("".equalsIgnoreCase(binding))
                binding = "full";
        }
        Logger.debug("Login type: " + loginType);
        if (loginType.equals(OAConfiguration.LOGINTYPE_STATELESS)) {
            int sessionTimeOut = oaParam.getSessionTimeOut();
            if (sessionTimeOut == 0)
                sessionTimeOut = 60 * 60; // default 1 h

            session.setMaxInactiveInterval(sessionTimeOut);
            session.setAttribute(ATT_PUBLIC_URLPREFIX, publicURLPrefix);
            session.setAttribute(ATT_REAL_URLPREFIX, realURLPrefix);
            session.setAttribute(ATT_SSL_SOCKET_FACTORY, ssf);
            session.setAttribute(ATT_LOGIN_HEADERS, loginHeaders);
            session.setAttribute(ATT_LOGIN_PARAMETERS, loginParameters);
            session.setAttribute(ATT_SAML_ARTIFACT, samlArtifact);
            session.setAttribute(ATT_OA_CONF, oaConf);
            session.setAttribute(ATT_OA_LOGINTYPE, loginType);
            session.setAttribute(ATT_OA_USER_BINDING, binding);
            session.removeAttribute(ATT_BROWSERREQU);
            session.removeAttribute(ATT_OA_AUTHORIZATION_HEADER);
            session.removeAttribute(ATT_OA_LOGINTRY);
            Logger.debug("moa-id-proxy: HTTPSession " + session.getId() + " angelegt");
        }

    } else {
        loginHeaders = (Map) session.getAttribute(ATT_LOGIN_HEADERS);
        publicURLPrefix = (String) session.getAttribute(ATT_PUBLIC_URLPREFIX);
        realURLPrefix = (String) session.getAttribute(ATT_REAL_URLPREFIX);
        ssf = (SSLSocketFactory) session.getAttribute(ATT_SSL_SOCKET_FACTORY);
        loginHeaders = (Map) session.getAttribute(ATT_LOGIN_HEADERS);
        loginParameters = (Map) session.getAttribute(ATT_LOGIN_PARAMETERS);
        samlArtifact = (String) session.getAttribute(ATT_SAML_ARTIFACT);
        oaConf = (OAConfiguration) session.getAttribute(ATT_OA_CONF);
        loginType = (String) session.getAttribute(ATT_OA_LOGINTYPE);
        binding = (String) session.getAttribute(ATT_OA_USER_BINDING);
        session.removeAttribute(ATT_BROWSERREQU);
        Logger.debug("moa-id-proxy: HTTPSession " + session.getId() + " aufgenommen");
    }

    try {
        int respcode = 0;

        // tunnel request to the online application
        respcode = tunnelRequest(req, resp, loginHeaders, loginParameters, publicURLPrefix, realURLPrefix, ssf,
                binding);
        if (respcode == 401) {
            if (OAConfiguration.BINDUNG_FULL.equals(binding)
                    && oaConf.getLoginType().equals(OAConfiguration.LOGINTYPE_STATELESS)) {
                throw new ProxyException("proxy.12", new Object[] { realURLPrefix });
            }
        }
    } catch (ProxyException ex) {
        throw new ProxyException("proxy.12", new Object[] { realURLPrefix });
    } catch (Throwable ex) {
        throw new ProxyException("proxy.04", new Object[] { urlRequested, ex.toString() }, ex);
    }
}

From source file:de.innovationgate.wgpublisher.WGACore.java

public boolean logout(String domain, javax.servlet.http.HttpSession session,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, boolean fireEvent)
        throws WGException {

    // Remove the sessionLogin for this domain
    Map<Object, DBLoginInfo> sessionLogins = getSessionLogins(session);
    DBLoginInfo oldLoginInfo = null;//w  ww .j  a  va 2 s. c o  m
    if (domain != null) {
        oldLoginInfo = sessionLogins.remove(domain);
    } else {
        sessionLogins.clear();
        session.removeAttribute("$defaultlogin");
    }

    // Remove profiles of self-personalized dbs, fire events
    WGA wga = WGA.get(httpServletRequest, httpServletResponse, this);
    for (WGDatabase db : getDatabasesForDomain(domain)) {
        int persMode = Integer.parseInt((String) readPublisherOptionOrDefault(db, WGACore.DBATTRIB_PERSMODE));
        if (persMode == Constants.PERSMODE_LOGIN) {
            session.removeAttribute(
                    PersonalisationManager.SESSION_PROFILENAME_INDIVIDUALDB + db.getDbReference());
        }
        if (fireEvent && oldLoginInfo != null && !WGDatabase.ANONYMOUS_USER.equals(oldLoginInfo.getUserName())
                && db.hasFeature(WGDatabase.FEATURE_FULLCONTENTFEATURES)) {
            wga.app(db).createEvent("auth=logout").param("userName", oldLoginInfo.getUserName())
                    .param("sessionId", session.getId()).param("authType", oldLoginInfo.getAuthenticationType())
                    .fireOnSession();
        }
    }

    return true;
}

From source file:org.openmrs.module.personalhr.web.controller.PhrUserFormController.java

/**
 * @should work for an example/*from   w  ww  . jav a2s  .  co m*/
 */
@RequestMapping(value = "/phr/user.form", method = RequestMethod.POST)
public String handleSubmission(final WebRequest request, final HttpSession httpSession, final ModelMap model,
        @RequestParam(required = false, value = "action") final String action,
        @RequestParam(required = false, value = "userFormPassword") String password,
        @RequestParam(required = false, value = "secretQuestion") final String secretQuestion,
        @RequestParam(required = false, value = "secretAnswer") final String secretAnswer,
        @RequestParam(required = false, value = "confirm") String confirm,
        @RequestParam(required = false, value = "forcePassword") final Boolean forcePassword,
        @RequestParam(required = false, value = "roleStrings") final String[] roles,
        @RequestParam(required = false, value = "createNewPerson") final String createNewPerson,
        @RequestParam(required = false, value = "sharingToken") String sharingToken,
        @ModelAttribute("user") final User user, final BindingResult errors) {

    if (sharingToken == null) {
        sharingToken = (String) model.get("sharingToken");
    }

    log.debug("Entering PhrUserFormController:handleSubmission..." + sharingToken);
    //add temporary privileges
    boolean isTemporary = false;
    boolean isAdministrator = false;
    if (!Context.isAuthenticated()) {
        Context.authenticate("temporary", "Temporary8");
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        Context.addProxyPrivilege("PHR Restricted Patient Access");
        isTemporary = true;
        log.debug("Added proxy privileges!");
    } else {
        if (PhrService.PhrBasicRole.PHR_ADMINISTRATOR.getValue()
                .equals(PersonalhrUtil.getService().getPhrRole(Context.getAuthenticatedUser()))) {
            isAdministrator = true;
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
        }
    }

    try {
        final UserService us = Context.getUserService();
        final MessageSourceService mss = Context.getMessageSourceService();

        if (mss.getMessage("User.assumeIdentity").equals(action)) {
            Context.becomeUser(user.getSystemId());
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.assumeIdentity.success");
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, user.getPersonName());
            return "redirect:/phr/index.htm";

        } else if (mss.getMessage("User.delete").equals(action)) {
            try {
                Context.getUserService().purgeUser(user);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.delete.success");
                return "redirect:/phr/user.list";
            } catch (final Exception ex) {
                httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "User.delete.failure");
                log.error("Failed to delete user", ex);
                return "redirect:/phr/user.form?userId=" + request.getParameter("userId");
            }

        } else if (mss.getMessage("User.retire").equals(action)) {
            final String retireReason = request.getParameter("retireReason");
            if (!(StringUtils.hasText(retireReason))) {
                errors.rejectValue("retireReason", "User.disableReason.empty");
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            } else {
                us.retireUser(user, retireReason);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.retiredMessage");
            }

        } else if (mss.getMessage("User.unRetire").equals(action)) {
            us.unretireUser(user);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.unRetiredMessage");
        } else {
            // check if username is already in the database
            if (us.hasDuplicateUsername(user)) {
                errors.rejectValue("username", "error.username.taken");
            }

            // check if password and password confirm are identical
            if ((password == null) || password.equals("XXXXXXXXXXXXXXX")) {
                password = "";
            }
            if ((confirm == null) || confirm.equals("XXXXXXXXXXXXXXX")) {
                confirm = "";
            }

            if (!password.equals(confirm)) {
                errors.reject("error.password.match");
            }

            if ((password.length() == 0) && isNewUser(user)) {
                errors.reject("error.password.weak");
            }

            //check password strength
            if (password.length() > 0) {
                try {
                    OpenmrsUtil.validatePassword(user.getUsername(), password, user.getSystemId());
                } catch (final PasswordException e) {
                    errors.reject(e.getMessage());
                }
            }

            final Set<Role> newRoles = new HashSet<Role>();
            if (roles != null) {
                for (final String r : roles) {
                    // Make sure that if we already have a detached instance of this role in the
                    // user's roles, that we don't fetch a second copy of that same role from
                    // the database, or else hibernate will throw a NonUniqueObjectException.
                    Role role = null;
                    if (user.getRoles() != null) {
                        for (final Role test : user.getRoles()) {
                            if (test.getRole().equals(r)) {
                                role = test;
                            }
                        }
                    }
                    if (role == null) {
                        role = us.getRole(r);
                        user.addRole(role);
                    }
                    newRoles.add(role);
                }
            } else {
                final Role role = us.getRole("PHR Restricted User");
                newRoles.add(role);
                user.addRole(role);
                log.debug("Added PHR Restricted User role only: " + role);
            }

            if (user.getRoles() == null) {
                newRoles.clear();
            } else {
                user.getRoles().retainAll(newRoles);
            }

            final String[] keys = request.getParameterValues("property");
            final String[] values = request.getParameterValues("value");

            if ((keys != null) && (values != null)) {
                for (int x = 0; x < keys.length; x++) {
                    final String key = keys[x];
                    final String val = values[x];
                    user.setUserProperty(key, val);
                }
            }

            new UserProperties(user.getUserProperties()).setSupposedToChangePassword(forcePassword);

            final UserValidator uv = new UserValidator();
            uv.validate(user, errors);

            if (errors.hasErrors()) {
                log.debug("errors validating user: " + errors.getErrorCount() + errors.toString());
                return showForm(user.getUserId(), createNewPerson, sharingToken, user, model, httpSession);
            }

            String emailEntered = request.getParameter("9");

            if (isNewUser(user) && !isAdministrator) {
                log.debug("Saving new user " + user.getUsername() + ", sharingToken=" + sharingToken);
                final PhrSharingToken token = Context.getService(PhrSharingTokenService.class)
                        .getSharingToken(sharingToken);

                //check token existence and name matching
                if (token == null || token.getExpireDate().before(new Date())) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register without a valid sharing token");
                    log.error("Failed to register without a valid sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register without a valid sharing token; user_name="
                                    + user.getName());

                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }
                    return "redirect:/phr/index.htm?noredirect=true";
                } else if ((token != null) && (token.getRelatedPerson() != null)) {
                    httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                            "Failed to register with a used sharing token");
                    log.error("Failed to register with a used sharing token");
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "error=Failed to register with a used sharing token; user_name=" + user.getName()
                                    + "; sharingToken=" + token);
                    if (isTemporary) {
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
                        Context.removeProxyPrivilege("PHR Restricted Patient Access");
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
                        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
                        Context.logout();
                        log.debug("Removed proxy privileges!");
                    }

                    return "redirect:/phr/index.htm?noredirect=true";
                } else if (emailEntered != null
                        && token.getRelatedPersonEmail().equalsIgnoreCase(emailEntered)) {
                    // look for person attributes (including email entered) in the request and save to user
                    for (final PersonAttributeType type : Context.getPersonService()
                            .getPersonAttributeTypes(PERSON_TYPE.PATIENT, ATTR_VIEW_TYPE.VIEWING)) {
                        final String paramName = type.getPersonAttributeTypeId().toString();
                        final String value = request.getParameter(paramName);

                        this.log.debug("paramName=" + paramName);

                        // if there is an error displaying the attribute, the value will be null
                        if (value != null) {
                            final PersonAttribute attribute = new PersonAttribute(type, value);
                            try {
                                final Object hydratedObject = attribute.getHydratedObject();
                                if ((hydratedObject == null) || "".equals(hydratedObject.toString())) {
                                    // if null is returned, the value should be blanked out
                                    attribute.setValue("");
                                } else if (hydratedObject instanceof Attributable) {
                                    attribute.setValue(((Attributable) hydratedObject).serialize());
                                } else if (!hydratedObject.getClass().getName().equals(type.getFormat())) {
                                    // if the classes doesn't match the format, the hydration failed somehow
                                    // TODO change the PersonAttribute.getHydratedObject() to not swallow all errors?
                                    throw new APIException();
                                }
                            } catch (final APIException e) {
                                errors.rejectValue("attributeMap[" + type.getName() + "]",
                                        "Invalid value for " + type.getName() + ": '" + value + "'");
                                this.log.warn("Got an invalid value: " + value
                                        + " while setting personAttributeType id #" + paramName, e);

                                // setting the value to empty so that the user can reset the value to something else
                                attribute.setValue("");

                            }
                            user.getPerson().addAttribute(attribute);
                        }
                    }

                    //create a new user by self registration
                    us.saveUser(user, password);

                    //update sharing token
                    token.setRelatedPerson(user.getPerson());
                    token.setChangedBy(user);
                    final Date date = new Date();
                    token.setDateChanged(date);
                    token.setActivateDate(date);
                    Context.getService(PhrSharingTokenService.class).savePhrSharingToken(token);
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "personalhr.user.signed.up");
                    log.debug("New self-registered user created: " + user.getUsername());
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), user,
                            httpSession.getId(), null, "info=New self-registered user created; user_name="
                                    + user.getName() + "; sharingToken=" + token);

                    //save email to messaging service
                    Integer addressId = saveEmail(user.getPerson(), emailEntered);

                    //set default messaging alert address
                    boolean shouldAlert = true;
                    PersonalhrUtil.setMessagingAlertSettings(user.getPerson(), shouldAlert, addressId);

                    //send email notification

                    // TODO get the deployUrl from the request object; also bad to inject /openmrs/ ...
                    final String deployUrl = Context.getRuntimeProperties().getProperty("deployment.url");//"https://65.111.248.164:8443/"; //"172.30.201.24";

                    final String url = deployUrl + "/openmrs/phr/index.htm";
                    final String passwordOption = Context.getAdministrationService()
                            .getGlobalProperty("personalhr.show.password");

                    String notification = NOTIFICATION_TEMPLATE;
                    notification = notification.replaceAll("OPENMRS_PHR_RELATED_PERSON",
                            user.getPerson().getGivenName());
                    notification = notification.replaceAll("OPENMRS_USERNAME", user.getUsername());
                    notification = notification.replaceAll("OPENMRS_PASSWORD",
                            showPassword(password, passwordOption));
                    notification = notification.replaceAll("OPENMRS_URL", url);

                    PersonalhrUtil.sendEmail(emailEntered, notification);
                } else {
                    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                            "Failed to create new user due to email mismatch: " + emailEntered);
                    log.debug("Failed to create new user due to email mismatch: "
                            + token.getRelatedPersonEmail() + " vs " + emailEntered);
                    PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_SIGN_UP, new Date(), null,
                            httpSession.getId(), null,
                            "info=Failed to create new user due to email mismatch: "
                                    + token.getRelatedPersonEmail() + "vs " + emailEntered + "; sharingToken="
                                    + token);
                }
            } else if (isNewUser(user) && isAdministrator) {
                //create a new user by PHR Administrator
                us.saveUser(user, password);
            } else {
                //modify an exiting user
                us.saveUser(user, null);

                if (!password.equals("") && Context.hasPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS)) {
                    if (log.isDebugEnabled()) {
                        log.debug("calling changePassword for user " + user + " by user "
                                + Context.getAuthenticatedUser());
                    }
                    us.changePassword(user, password);
                }
                log.debug("Existing user " + user.getUsername() + " changed by user "
                        + Context.getAuthenticatedUser().getUsername());
                PersonalhrUtil.getService().logEvent(PhrLogEvent.USER_UPDATE, new Date(),
                        Context.getAuthenticatedUser(), httpSession.getId(), null,
                        "info=Existing user updated; user_name=" + user.getName());
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }

            if (StringUtils.hasLength(secretQuestion) && StringUtils.hasLength(secretAnswer)) {
                us.changeQuestionAnswer(user, secretQuestion, secretAnswer);
                httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.saved");
            }
        }
    } finally {
        //remove temporary privileges
        if (isTemporary) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_VIEW_USERS);
            Context.removeProxyPrivilege("PHR Restricted Patient Access");
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            Context.logout();
            log.debug("Removed proxy privileges for self registration!");
        } else if (isAdministrator) {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_ADD_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_DELETE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_PURGE_USERS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_PERSONS);
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_EDIT_USER_PASSWORDS);
            log.debug("Removed proxy privileges for PHR Administrator!");
        }
    }
    return "redirect:/phr/index.htm?noredirect=true";
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object postPortfolioZip(MimeType mimeType, MimeType mimeType2, HttpServletRequest httpServletRequest,
        int userId, int groupId, String modelId, int substid) throws IOException {
    if (!credential.isAdmin(userId) && !credential.isCreator(userId))
        throw new RestWebApplicationException(Status.FORBIDDEN, "No admin right");

    boolean isMultipart = ServletFileUpload.isMultipartContent(httpServletRequest);
    // Create a factory for disk-based file items
    DiskFileItemFactory factory = new DiskFileItemFactory();

    // Configure a repository (to ensure a secure temp location is used)
    ServletContext servletContext = httpServletRequest.getSession().getServletContext();
    File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
    factory.setRepository(repository);/*from w  w  w  .  j  a v a 2 s  . co m*/

    // Create a new file upload handler
    ServletFileUpload upload = new ServletFileUpload(factory);

    DataInputStream inZip = null;
    // Parse the request
    try {
        List<FileItem> items = upload.parseRequest(httpServletRequest);
        // Process the uploaded items
        Iterator<FileItem> iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = iter.next();
            if (!item.isFormField()) {
                inZip = new DataInputStream(item.getInputStream());
                break;
            }
        }
    } catch (FileUploadException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String foldersfiles = null;
    String filename;
    String[] xmlFiles;
    String[] allFiles;
    //      int formDataLength = httpServletRequest.getContentLength();
    byte[] buff = new byte[0x100000]; // 1MB buffer

    // Recuperation de l'heure  laquelle le zip est cr
    //Calendar cal = Calendar.getInstance();
    //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss_S");
    //String now = sdf.format(cal.getTime());

    this.genererPortfolioUuidPreliminaire();

    javax.servlet.http.HttpSession session = httpServletRequest.getSession(true);
    String ppath = session.getServletContext().getRealPath("/");
    String outsideDir = ppath.substring(0, ppath.lastIndexOf(File.separator)) + "_files" + File.separator;
    File outsideDirectoryFile = new File(outsideDir);
    System.out.println(outsideDir);
    // if the directory does not exist, create it
    if (!outsideDirectoryFile.exists()) {
        outsideDirectoryFile.mkdir();
    }

    //Creation du zip
    filename = outsideDir + "xml_" + this.portfolioUuidPreliminaire + ".zip";
    FileOutputStream outZip = new FileOutputStream(filename);

    int len;

    while ((len = inZip.read(buff)) != -1) {
        outZip.write(buff, 0, len);
    }

    inZip.close();
    outZip.close();

    //-- unzip --
    foldersfiles = unzip(filename, outsideDir + this.portfolioUuidPreliminaire + File.separator);
    //TODO Attention si plusieurs XML dans le fichier
    xmlFiles = findFiles(outsideDir + this.portfolioUuidPreliminaire + File.separator, "xml");
    allFiles = findFiles(outsideDir + this.portfolioUuidPreliminaire + File.separator, null);

    ////// Lecture du fichier de portfolio
    StringBuffer outTrace = new StringBuffer();
    //// Importation du portfolio
    //--- Read xml fileL ----
    ///// Pour associer l'ancien uuid -> nouveau, pour les fichiers
    HashMap<String, String> resolve = new HashMap<String, String>();
    String portfolioUuid = "erreur";
    boolean hasLoaded = false;
    try {
        for (int i = 0; i < xmlFiles.length; i++) {
            String xmlFilepath = xmlFiles[i];
            String xmlFilename = xmlFilepath.substring(xmlFilepath.lastIndexOf(File.separator));
            if (xmlFilename.contains("_"))
                continue; // Case when we add an xml in the portfolio

            BufferedReader br = new BufferedReader(new FileReader(new File(xmlFilepath)));
            String line;
            StringBuilder sb = new StringBuilder();

            while ((line = br.readLine()) != null) {
                sb.append(line.trim());
            }
            String xml = "?";
            xml = sb.toString();

            portfolioUuid = UUID.randomUUID().toString();

            if (xml.contains("<portfolio")) // Le porfolio (peux mieux faire)
            {
                Document doc = DomUtils.xmlString2Document(xml, outTrace);

                Node rootNode = (doc.getElementsByTagName("portfolio")).item(0);
                if (rootNode == null)
                    throw new Exception("Root Node (portfolio) not found !");
                else {
                    rootNode = (doc.getElementsByTagName("asmRoot")).item(0);

                    String uuid = UUID.randomUUID().toString();

                    insertMysqlPortfolio(portfolioUuid, uuid, 0, userId);

                    writeNode(rootNode, portfolioUuid, null, userId, 0, uuid, null, 0, 0, false, resolve);
                }
                updateMysqlPortfolioActive(portfolioUuid, true);

                /// Finalement on cre un rle designer
                int groupid = postCreateRole(portfolioUuid, "designer", userId);

                /// Ajoute la personne dans ce groupe
                putUserGroup(Integer.toString(groupid), Integer.toString(userId));

                hasLoaded = true;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    if (hasLoaded)
        for (int i = 0; i < allFiles.length; i++) {
            String fullPath = allFiles[i];
            String tmpFileName = allFiles[i].substring(allFiles[i].lastIndexOf(File.separator) + 1);

            int index = tmpFileName.indexOf("_");
            if (index == -1)
                index = tmpFileName.indexOf(".");
            int last = tmpFileName.lastIndexOf(File.separator);
            if (last == -1)
                last = 0;
            String uuid = tmpFileName.substring(last, index);

            //         tmpFileName = allFiles[i].substring(allFiles[i].lastIndexOf(File.separator)+1);
            String lang;
            try {
                //            int tmpPos = tmpFileName.indexOf("_");
                lang = tmpFileName.substring(index + 1, index + 3);

                if ("un".equals(lang)) // Hack sort of fixing previous implementation
                    lang = "en";
            } catch (Exception ex) {
                lang = "";
            }

            InputStream is = new FileInputStream(allFiles[i]);
            byte b[] = new byte[is.available()];
            is.read(b);
            String extension;
            try {
                extension = tmpFileName.substring(tmpFileName.lastIndexOf(".") + 1);
            } catch (Exception ex) {
                extension = null;
            }

            // trop long
            //String tmpMimeType = FileUtils.getMimeType("file://"+allFiles[i]);
            String tmpMimeType = FileUtils.getMimeTypeFromExtension(extension);

            // Attention on initialise la ligne file
            // avec l'UUID d'origine de l'asmContext parent
            // Il sera mis  jour avec l'UUID asmContext final dans writeNode
            try {
                UUID tmpUuid = UUID.fromString(uuid); /// base uuid
                String resolved = resolve.get(uuid); /// New uuid
                String sessionval = session.getId();
                String user = (String) session.getAttribute("user");
                //            String test = outsideDir+File.separator+this.portfolioUuidPreliminaire+File.separator+tmpFileName;
                //            File file = new File(outsideDir+File.separator+this.portfolioUuidPreliminaire+File.separator+tmpFileName);
                File file = new File(fullPath);

                // server backend
                // fileserver
                String backend = session.getServletContext().getInitParameter("backendserver");

                if (resolved != null) {
                    /// Have to send it in FORM, compatibility with regular file posting
                    PostForm.sendFile(sessionval, backend, user, resolved, lang, file);

                    /// No need to fetch resulting ID, since we provided it
                    /*
                    InputStream objReturn = connect.getInputStream();
                    StringWriter idResponse = new StringWriter();
                    IOUtils.copy(objReturn, idResponse);
                    fileid = idResponse.toString();
                    //*/
                }

                /*
                if(tmpUuid.toString().equals(uuid))
                   this.putFile(uuid,lang,tmpFileName,outsideDir,tmpMimeType,extension,b.length,b,userId);
                //*/
            } catch (Exception ex) {
                // Le nom du fichier ne commence pas par un UUID,
                // ce n'est donc pas une ressource
                ex.printStackTrace();
            }
        }

    File zipfile = new File(filename);
    zipfile.delete();
    File zipdir = new File(outsideDir + this.portfolioUuidPreliminaire + File.separator);
    zipdir.delete();

    return portfolioUuid;
}

From source file:com.liferay.portal.events.ServicePreAction.java

public ThemeDisplay initThemeDisplay(HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    HttpSession session = request.getSession();

    // Company//from  ww  w  . j a v  a 2 s  .c  om

    Company company = PortalUtil.getCompany(request);

    long companyId = company.getCompanyId();

    // CDN host

    String cdnHost = PortalUtil.getCDNHost(request);

    String dynamicResourcesCDNHost = StringPool.BLANK;

    boolean cdnDynamicResourceEnabled = PortalUtil.isCDNDynamicResourcesEnabled(request);

    if (cdnDynamicResourceEnabled) {
        dynamicResourcesCDNHost = cdnHost;
    }

    // Portal URL

    String portalURL = PortalUtil.getPortalURL(request);

    // Paths

    String contextPath = PortalUtil.getPathContext();
    String friendlyURLPrivateGroupPath = PortalUtil.getPathFriendlyURLPrivateGroup();
    String friendlyURLPrivateUserPath = PortalUtil.getPathFriendlyURLPrivateUser();
    String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic();
    String imagePath = dynamicResourcesCDNHost.concat(PortalUtil.getPathImage());
    String mainPath = PortalUtil.getPathMain();

    String i18nPath = (String) request.getAttribute(WebKeys.I18N_PATH);

    if (Validator.isNotNull(i18nPath)) {
        if (Validator.isNotNull(contextPath)) {
            String i18nContextPath = contextPath.concat(i18nPath);

            friendlyURLPrivateGroupPath = StringUtil.replaceFirst(friendlyURLPrivateGroupPath, contextPath,
                    i18nContextPath);
            friendlyURLPrivateUserPath = StringUtil.replaceFirst(friendlyURLPrivateUserPath, contextPath,
                    i18nContextPath);
            friendlyURLPublicPath = StringUtil.replaceFirst(friendlyURLPublicPath, contextPath,
                    i18nContextPath);
            mainPath = StringUtil.replaceFirst(mainPath, contextPath, i18nContextPath);
        } else {
            friendlyURLPrivateGroupPath = i18nPath.concat(friendlyURLPrivateGroupPath);
            friendlyURLPrivateUserPath = i18nPath.concat(friendlyURLPrivateUserPath);
            friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath);
            mainPath = i18nPath.concat(mainPath);
        }
    }

    // Company logo

    StringBundler sb = new StringBundler(5);

    sb.append(imagePath);
    sb.append("/company_logo?img_id=");
    sb.append(company.getLogoId());
    sb.append("&t=");
    sb.append(WebServerServletTokenUtil.getToken(company.getLogoId()));

    String companyLogo = sb.toString();

    int companyLogoHeight = 0;
    int companyLogoWidth = 0;

    Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId());

    if (companyLogoImage != null) {
        companyLogoHeight = companyLogoImage.getHeight();
        companyLogoWidth = companyLogoImage.getWidth();
    }

    String realCompanyLogo = companyLogo;
    int realCompanyLogoHeight = companyLogoHeight;
    int realCompanyLogoWidth = companyLogoWidth;

    // User

    User user = null;

    try {
        user = PortalUtil.getUser(request);
    } catch (NoSuchUserException nsue) {
        if (_log.isWarnEnabled()) {
            _log.warn(nsue.getMessage());
        }

        long userId = PortalUtil.getUserId(request);

        if (userId > 0) {
            session.invalidate();
        }

        return null;
    }

    boolean signedIn = false;

    if (user == null) {
        user = company.getDefaultUser();
    } else if (!user.isDefaultUser()) {
        signedIn = true;
    }

    if (PropsValues.BROWSER_CACHE_DISABLED || (PropsValues.BROWSER_CACHE_SIGNED_IN_DISABLED && signedIn)) {

        response.setDateHeader(HttpHeaders.EXPIRES, 0);
        response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);
        response.setHeader(HttpHeaders.PRAGMA, HttpHeaders.PRAGMA_NO_CACHE_VALUE);
    }

    User realUser = user;

    Long realUserId = (Long) session.getAttribute(WebKeys.USER_ID);

    if (realUserId != null) {
        if (user.getUserId() != realUserId.longValue()) {
            realUser = UserLocalServiceUtil.getUserById(realUserId.longValue());
        }
    }

    String doAsUserId = ParamUtil.getString(request, "doAsUserId");
    String doAsUserLanguageId = ParamUtil.getString(request, "doAsUserLanguageId");
    long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId");

    long refererPlid = ParamUtil.getLong(request, "refererPlid");

    if (LayoutLocalServiceUtil.fetchLayout(refererPlid) == null) {
        refererPlid = 0;
    }

    String controlPanelCategory = ParamUtil.getString(request, "controlPanelCategory");

    // Permission checker

    PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user);

    PermissionThreadLocal.setPermissionChecker(permissionChecker);
    //Modification start (code changed and moved to the bottom)
    // Locale
    /*
        Locale locale = (Locale)session.getAttribute(Globals.LOCALE_KEY);
            
        if (Validator.isNotNull(doAsUserLanguageId)) {
          locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
        }
            
        String i18nLanguageId = (String)request.getAttribute(
              WebKeys.I18N_LANGUAGE_ID);
            
        if (Validator.isNotNull(i18nLanguageId)) {
          locale = LocaleUtil.fromLanguageId(i18nLanguageId);
        }
        else if (locale == null) {
          if (signedIn) {
              locale = user.getLocale();
          }
          else {
            
              // User previously set their preferred language
            
              String languageId = CookieKeys.getCookie(
          request, CookieKeys.GUEST_LANGUAGE_ID, false);
            
              if (Validator.isNotNull(languageId)) {
      locale = LocaleUtil.fromLanguageId(languageId);
              }
            
              // Get locale from the request
            
              if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) {
      Enumeration<Locale> locales = request.getLocales();
            
      while (locales.hasMoreElements()) {
          Locale requestLocale = locales.nextElement();
            
          if (Validator.isNull(requestLocale.getCountry())) {
            
              // Locales must contain a country code
            
              requestLocale = LanguageUtil.getLocale(
                      requestLocale.getLanguage());
          }
            
          if (LanguageUtil.isAvailableLocale(requestLocale)) {
              locale = requestLocale;
            
              break;
          }
      }
              }
            
              // Get locale from the default user
            
              if (locale == null) {
      locale = user.getLocale();
              }
            
              if (Validator.isNull(locale.getCountry())) {
            
      // Locales must contain a country code
            
      locale = LanguageUtil.getLocale(locale.getLanguage());
              }
            
              if (!LanguageUtil.isAvailableLocale(locale)) {
      locale = user.getLocale();
              }
          }
            
          session.setAttribute(Globals.LOCALE_KEY, locale);
            
          LanguageUtil.updateCookie(request, response, locale);
        }*/
    //Modification end
    // Cookie support

    try {

        // LEP-4069

        CookieKeys.validateSupportCookie(request);
    } catch (Exception e) {
        CookieKeys.addSupportCookie(request, response);
    }

    // Time zone

    TimeZone timeZone = user.getTimeZone();

    if (timeZone == null) {
        timeZone = company.getTimeZone();
    }

    // Layouts

    if (signedIn) {
        updateUserLayouts(user);
    }

    Layout layout = null;
    List<Layout> layouts = null;

    long plid = ParamUtil.getLong(request, "p_l_id");

    if (plid > 0) {
        layout = LayoutLocalServiceUtil.getLayout(plid);

        long sourceGroupId = ParamUtil.getLong(request, "p_v_l_s_g_id");

        if ((sourceGroupId > 0) && (sourceGroupId != layout.getGroupId())) {
            Group sourceGroup = GroupLocalServiceUtil.getGroup(sourceGroupId);

            if (layout.isPublicLayout()
                    || SitesUtil.isUserGroupLayoutSetViewable(permissionChecker, layout.getGroup())) {

                layout = new VirtualLayout(layout, sourceGroup);
            } else {
                layout = null;
            }
        }
    } else {
        long groupId = ParamUtil.getLong(request, "groupId");
        boolean privateLayout = ParamUtil.getBoolean(request, "privateLayout");
        long layoutId = ParamUtil.getLong(request, "layoutId");

        if ((groupId > 0) && (layoutId > 0)) {
            layout = LayoutLocalServiceUtil.getLayout(groupId, privateLayout, layoutId);
        }
    }

    Boolean redirectToDefaultLayout = (Boolean) request.getAttribute(WebKeys.REDIRECT_TO_DEFAULT_LAYOUT);

    if (redirectToDefaultLayout == null) {
        redirectToDefaultLayout = Boolean.FALSE;
    }

    if (layout != null) {
        Group group = layout.getGroup();

        if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) {
            request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout);
        }

        String ppid = ParamUtil.getString(request, "p_p_id");

        if (Validator.isNull(controlPanelCategory) && Validator.isNotNull(ppid)
                && (LiferayWindowState.isPopUp(request) || LiferayWindowState.isExclusive(request))) {

            controlPanelCategory = _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + ppid;
        }

        boolean viewableGroup = LayoutPermissionUtil.contains(permissionChecker, layout, controlPanelCategory,
                true, ActionKeys.VIEW);
        boolean viewableStaging = GroupPermissionUtil.contains(permissionChecker, group.getGroupId(),
                ActionKeys.VIEW_STAGING);

        if (viewableStaging) {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
        } else if (!viewableGroup && group.isStagingGroup()) {
            layout = null;
        } else
        /* Permissions are managed by Mobile Portlet
        if (!isLoginRequest(request) &&
            (!viewableGroup ||
                (!redirectToDefaultLayout &&
          !LayoutPermissionUtil.contains(
              permissionChecker, layout, false,
              ActionKeys.VIEW)))) {
                
          if (user.isDefaultUser() &&
              PropsValues.AUTH_LOGIN_PROMPT_ENABLED) {
                
            throw new PrincipalException("User is not authenticated");
          }
                
          sb = new StringBundler(6);
                
          sb.append("User ");
          sb.append(user.getUserId());
          sb.append(" is not allowed to access the ");
          sb.append(layout.isPrivateLayout() ? "private" : "public");
          sb.append(" pages of group ");
          sb.append(layout.getGroupId());
                
          if (_log.isWarnEnabled()) {
            _log.warn(sb.toString());
          }
                
          throw new NoSuchLayoutException(sb.toString());
        } else*/ if (isLoginRequest(request) && !viewableGroup) {
            layout = null;
        } else if (group.isLayoutPrototype()) {
            layouts = new ArrayList<Layout>();
        } else {
            layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(),
                    LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

            if (!group.isControlPanel()) {
                doAsGroupId = 0;
            }
        }
    }

    List<Layout> unfilteredLayouts = layouts;

    if (layout == null) {
        Object[] defaultLayout = getDefaultLayout(request, user, signedIn);

        layout = (Layout) defaultLayout[0];
        layouts = (List<Layout>) defaultLayout[1];

        request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE);
    }

    Object[] viewableLayouts = getViewableLayouts(request, user, permissionChecker, layout, layouts);

    String layoutSetLogo = null;

    layout = (Layout) viewableLayouts[0];
    layouts = (List<Layout>) viewableLayouts[1];

    Group group = null;

    if (layout != null) {
        group = layout.getGroup();

        if (!group.isControlPanel()) {
            rememberVisitedGroupIds(request, group.getGroupId());
        }
    }

    LayoutTypePortlet layoutTypePortlet = null;

    layouts = mergeAdditionalLayouts(request, user, permissionChecker, layout, layouts);

    LayoutSet layoutSet = null;

    boolean hasCustomizeLayoutPermission = false;
    boolean hasUpdateLayoutPermission = false;

    boolean customizedView = SessionParamUtil.getBoolean(request, "customized_view", true);

    if (layout != null) {
        hasCustomizeLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.CUSTOMIZE);
        hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE);

        layoutSet = layout.getLayoutSet();

        if (company.isSiteLogo()) {
            long logoId = 0;

            if (layoutSet.isLogo()) {
                logoId = layoutSet.getLogoId();

                if (logoId == 0) {
                    logoId = layoutSet.getLiveLogoId();
                }
            } else {
                LayoutSet siblingLayoutSet = LayoutSetLocalServiceUtil.getLayoutSet(layout.getGroupId(),
                        !layout.isPrivateLayout());

                if (siblingLayoutSet.isLogo()) {
                    logoId = siblingLayoutSet.getLogoId();
                }
            }

            if (logoId > 0) {
                sb = new StringBundler(5);

                sb.append(imagePath);
                sb.append("/layout_set_logo?img_id=");
                sb.append(logoId);
                sb.append("&t=");
                sb.append(WebServerServletTokenUtil.getToken(logoId));

                layoutSetLogo = sb.toString();

                Image layoutSetLogoImage = ImageLocalServiceUtil.getCompanyLogo(logoId);

                companyLogo = layoutSetLogo;
                companyLogoHeight = layoutSetLogoImage.getHeight();
                companyLogoWidth = layoutSetLogoImage.getWidth();
            }
        }

        plid = layout.getPlid();

        // Updates to shared layouts are not reflected until the next time
        // the user logs in because group layouts are cached in the session

        layout = (Layout) layout.clone();

        layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

        boolean customizable = layoutTypePortlet.isCustomizable();

        if (!customizable || (group.isLayoutPrototype() || group.isLayoutSetPrototype())) {

            customizedView = false;
        }

        layoutTypePortlet.setCustomizedView(customizedView);
        layoutTypePortlet.setUpdatePermission(hasUpdateLayoutPermission);

        if (signedIn && customizable && customizedView && hasCustomizeLayoutPermission) {

            PortalPreferences portalPreferences = PortletPreferencesFactoryUtil.getPortalPreferences(companyId,
                    user.getUserId(), true);

            layoutTypePortlet.setPortalPreferences(portalPreferences);
        }

        LayoutClone layoutClone = LayoutCloneFactory.getInstance();

        if (layoutClone != null) {
            String typeSettings = layoutClone.get(request, plid);

            if (typeSettings != null) {
                UnicodeProperties typeSettingsProperties = new UnicodeProperties(true);

                typeSettingsProperties.load(typeSettings);

                String stateMax = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MAX);
                String stateMin = typeSettingsProperties.getProperty(LayoutTypePortletConstants.STATE_MIN);
                String modeAbout = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_ABOUT);
                String modeConfig = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_CONFIG);
                String modeEdit = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_EDIT);
                String modeEditDefaults = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS);
                String modeEditGuest = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST);
                String modeHelp = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_HELP);
                String modePreview = typeSettingsProperties
                        .getProperty(LayoutTypePortletConstants.MODE_PREVIEW);
                String modePrint = typeSettingsProperties.getProperty(LayoutTypePortletConstants.MODE_PRINT);

                layoutTypePortlet.setStateMax(stateMax);
                layoutTypePortlet.setStateMin(stateMin);
                layoutTypePortlet.setModeAbout(modeAbout);
                layoutTypePortlet.setModeConfig(modeConfig);
                layoutTypePortlet.setModeEdit(modeEdit);
                layoutTypePortlet.setModeEditDefaults(modeEditDefaults);
                layoutTypePortlet.setModeEditGuest(modeEditGuest);
                layoutTypePortlet.setModeHelp(modeHelp);
                layoutTypePortlet.setModePreview(modePreview);
                layoutTypePortlet.setModePrint(modePrint);
            }
        }

        request.setAttribute(WebKeys.LAYOUT, layout);
        request.setAttribute(WebKeys.LAYOUTS, layouts);
    }

    // Scope

    long scopeGroupId = PortalUtil.getScopeGroupId(request);

    if ((scopeGroupId <= 0) && (doAsGroupId > 0)) {
        scopeGroupId = doAsGroupId;
    }

    long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId);

    // Theme and color scheme

    Theme theme = null;
    ColorScheme colorScheme = null;

    boolean wapTheme = BrowserSnifferUtil.isWap(request);

    if ((layout != null) && group.isControlPanel()) {
        String themeId = PrefsPropsUtil.getString(companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID);
        String colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId();

        theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme);
        colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                wapTheme);

        if (!wapTheme && theme.isWapTheme()) {
            theme = ThemeLocalServiceUtil.getTheme(companyId, PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID,
                    false);
            colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId,
                    false);
        }

        request.setAttribute(WebKeys.THEME, theme);
        request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme);
    }

    boolean themeCssFastLoad = SessionParamUtil.getBoolean(request, "css_fast_load",
            PropsValues.THEME_CSS_FAST_LOAD);
    boolean themeImagesFastLoad = SessionParamUtil.getBoolean(request, "images_fast_load",
            PropsValues.THEME_IMAGES_FAST_LOAD);

    boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED;

    if (themeJsBarebone) {
        if (signedIn) {
            themeJsBarebone = false;
        }
    }

    boolean themeJsFastLoad = SessionParamUtil.getBoolean(request, "js_fast_load",
            PropsValues.JAVASCRIPT_FAST_LOAD);

    String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0");

    lifecycle = ParamUtil.getString(request, "p_t_lifecycle", lifecycle);

    boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated");

    String facebookCanvasPageURL = (String) request.getAttribute(WebKeys.FACEBOOK_CANVAS_PAGE_URL);

    boolean widget = false;

    Boolean widgetObj = (Boolean) request.getAttribute(WebKeys.WIDGET);

    if (widgetObj != null) {
        widget = widgetObj.booleanValue();
    }

    ////////// Modification start //////////

    // Locale
    Locale locale = null;
    String[] languageIds = request.getParameterMap().get("languageId");
    if (languageIds != null && languageIds.length > 0 && StringUtils.isNotEmpty(languageIds[0])) {
        Locale localeFromLanguageId = LocaleUtil.fromLanguageId(languageIds[0]);
        session.setAttribute(Globals.LOCALE_KEY, localeFromLanguageId);
    }
    try {
        locale = (Locale) session.getAttribute(Globals.LOCALE_KEY);
    } catch (IllegalStateException e) {
        _log.warn("Can't get locale from session, session is invalidated");
    }
    if (Validator.isNotNull(doAsUserLanguageId)) {
        locale = LocaleUtil.fromLanguageId(doAsUserLanguageId);
    }

    String i18nLanguageId = (String) request.getAttribute(WebKeys.I18N_LANGUAGE_ID);
    if (Validator.isNotNull(i18nLanguageId)) {
        locale = LocaleUtil.fromLanguageId(i18nLanguageId);
    }

    if (locale == null) {
        locale = LanguageDetectionUtil.detectLocale(request);
    }

    ////////// Modification end //////////

    // Theme display

    ThemeDisplay themeDisplay = ThemeDisplayFactory.create();
    //Modification start
    //    themeDisplay.setHttpServletRequest(request);
    //Modification end

    // Set the CDN host, portal URL, and Facebook application ID first
    // because other methods (setLookAndFeel) depend on them being set

    themeDisplay.setCDNHost(cdnHost);
    themeDisplay.setCDNDynamicResourcesHost(dynamicResourcesCDNHost);
    themeDisplay.setPortalURL(portalURL);
    themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL);
    themeDisplay.setWidget(widget);

    themeDisplay.setCompany(company);
    themeDisplay.setCompanyLogo(companyLogo);
    themeDisplay.setCompanyLogoHeight(companyLogoHeight);
    themeDisplay.setCompanyLogoWidth(companyLogoWidth);
    themeDisplay.setRealCompanyLogo(realCompanyLogo);
    themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight);
    themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth);
    themeDisplay.setUser(user);
    themeDisplay.setRealUser(realUser);
    themeDisplay.setDoAsUserId(doAsUserId);
    themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId);
    themeDisplay.setDoAsGroupId(doAsGroupId);
    themeDisplay.setRefererPlid(refererPlid);
    themeDisplay.setControlPanelCategory(controlPanelCategory);
    themeDisplay.setLayoutSet(layoutSet);
    themeDisplay.setLayoutSetLogo(layoutSetLogo);
    themeDisplay.setLayout(layout);
    themeDisplay.setLayouts(layouts);
    themeDisplay.setUnfilteredLayouts(unfilteredLayouts);
    themeDisplay.setPlid(plid);
    themeDisplay.setLayoutTypePortlet(layoutTypePortlet);
    themeDisplay.setScopeGroupId(scopeGroupId);
    themeDisplay.setParentGroupId(parentGroupId);
    themeDisplay.setSignedIn(signedIn);
    themeDisplay.setPermissionChecker(permissionChecker);
    themeDisplay.setLocale(locale);
    themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale));
    themeDisplay.setI18nLanguageId(i18nLanguageId);
    themeDisplay.setI18nPath(i18nPath);
    themeDisplay.setTimeZone(timeZone);
    themeDisplay.setLookAndFeel(theme, colorScheme);
    themeDisplay.setThemeCssFastLoad(themeCssFastLoad);
    themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad);
    themeDisplay.setThemeJsBarebone(themeJsBarebone);
    themeDisplay.setThemeJsFastLoad(themeJsFastLoad);
    themeDisplay.setServerName(request.getServerName());
    themeDisplay.setServerPort(request.getServerPort());
    themeDisplay.setSecure(request.isSecure());
    themeDisplay.setLifecycle(lifecycle);
    themeDisplay.setLifecycleAction(lifecycle.equals("1"));
    themeDisplay.setLifecycleRender(lifecycle.equals("0"));
    themeDisplay.setLifecycleResource(lifecycle.equals("2"));
    themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request));
    themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request));
    themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request));
    themeDisplay.setIsolated(isolated);
    themeDisplay.setPathApplet(contextPath.concat("/applets"));
    themeDisplay.setPathCms(contextPath.concat("/cms"));
    themeDisplay.setPathContext(contextPath);
    themeDisplay.setPathFlash(contextPath.concat("/flash"));
    themeDisplay.setPathFriendlyURLPrivateGroup(friendlyURLPrivateGroupPath);
    themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath);
    themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath);
    themeDisplay.setPathImage(imagePath);
    themeDisplay.setPathJavaScript(contextPath.concat("/html/js"));
    themeDisplay.setPathMain(mainPath);
    themeDisplay.setPathSound(contextPath.concat("/html/sound"));

    // Icons

    themeDisplay.setShowAddContentIcon(false);
    themeDisplay.setShowControlPanelIcon(signedIn);
    themeDisplay.setShowHomeIcon(true);
    themeDisplay.setShowMyAccountIcon(signedIn);
    themeDisplay.setShowPageSettingsIcon(false);
    themeDisplay.setShowPortalIcon(true);
    themeDisplay.setShowSignInIcon(!signedIn);
    themeDisplay.setShowSignOutIcon(signedIn);

    boolean showSiteContentIcon = false;

    long controlPanelPlid = 0;

    if (signedIn) {
        Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL);

        controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true);

        List<Portlet> siteContentPortlets = PortalUtil.getControlPanelPortlets(PortletCategoryKeys.CONTENT,
                themeDisplay);

        Portlet groupPagesPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.GROUP_PAGES);

        siteContentPortlets.remove(groupPagesPortlet);

        Portlet siteMembershipsAdminPortlet = PortletLocalServiceUtil
                .getPortletById(PortletKeys.SITE_MEMBERSHIPS_ADMIN);

        siteContentPortlets.remove(siteMembershipsAdminPortlet);

        Portlet siteSettingsPortlet = PortletLocalServiceUtil.getPortletById(PortletKeys.SITE_SETTINGS);

        siteContentPortlets.remove(siteSettingsPortlet);

        showSiteContentIcon = PortletPermissionUtil.contains(permissionChecker, scopeGroupId, controlPanelPlid,
                siteContentPortlets, ActionKeys.VIEW);
    }

    themeDisplay.setShowSiteContentIcon(showSiteContentIcon);

    themeDisplay.setShowStagingIcon(false);

    // Session

    if (PropsValues.SESSION_ENABLE_URL_WITH_SESSION_ID && !CookieKeys.hasSessionId(request)) {

        themeDisplay.setAddSessionIdToURL(true);
        themeDisplay.setSessionId(session.getId());
    }

    // URLs

    String urlControlPanel = friendlyURLPrivateGroupPath.concat(GroupConstants.CONTROL_PANEL_FRIENDLY_URL);

    if (Validator.isNotNull(doAsUserId)) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsUserId", doAsUserId);
    }

    if (scopeGroupId > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsGroupId", scopeGroupId);
    }

    if (refererPlid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", refererPlid);
    } else if (plid > 0) {
        urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", plid);
    }

    if (themeDisplay.isAddSessionIdToURL()) {
        urlControlPanel = PortalUtil.getURLWithSessionId(urlControlPanel, session.getId());
    }

    themeDisplay.setURLControlPanel(urlControlPanel);

    String siteContentURL = urlControlPanel;

    siteContentURL = HttpUtil.addParameter(siteContentURL, "controlPanelCategory", PortletCategoryKeys.CONTENT);

    themeDisplay.setURLSiteContent(siteContentURL);

    String currentURL = PortalUtil.getCurrentURL(request);

    themeDisplay.setURLCurrent(currentURL);

    String urlHome = PortalUtil.getHomeURL(request);

    themeDisplay.setURLHome(urlHome);

    if (layout != null) {
        if (layout.isTypePortlet()) {
            boolean freeformLayout = layoutTypePortlet.getLayoutTemplateId().equals("freeform");

            themeDisplay.setFreeformLayout(freeformLayout);

            if (hasUpdateLayoutPermission) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setShowLayoutTemplatesIcon(true);

                if (!group.isUser()) {
                    themeDisplay.setShowPageCustomizationIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));

                themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();");
            }

            if (hasCustomizeLayoutPermission && customizedView) {
                themeDisplay.setShowAddContentIconPermission(true);

                if (!LiferayWindowState.isMaximized(request)) {
                    themeDisplay.setShowAddContentIcon(true);
                }

                themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('"
                        .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');"));
            }
        }

        if (hasUpdateLayoutPermission) {
            themeDisplay.setShowPageSettingsIcon(true);

            LiferayPortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            pageSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            pageSettingsURL.setDoAsGroupId(scopeGroupId);
            pageSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                pageSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                pageSettingsURL.setParameter("tabs1", "public-pages");
            }

            pageSettingsURL.setParameter("closeRedirect", currentURL);
            pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            pageSettingsURL.setParameter("selPlid", String.valueOf(plid));
            pageSettingsURL.setPortletMode(PortletMode.VIEW);
            pageSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLPageSettings(pageSettingsURL);

            boolean site = group.isSite();

            if (!site && group.isStagingGroup()) {
                Group liveGroup = group.getLiveGroup();

                site = liveGroup.isSite();
            }

            if (site && GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                    ActionKeys.ASSIGN_MEMBERS)) {

                themeDisplay.setShowManageSiteMembershipsIcon(true);

                LiferayPortletURL manageSiteMembershipsURL = new PortletURLImpl(request,
                        PortletKeys.SITE_MEMBERSHIPS_ADMIN, controlPanelPlid, PortletRequest.RENDER_PHASE);

                manageSiteMembershipsURL.setControlPanelCategory(
                        _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_MEMBERSHIPS_ADMIN);
                manageSiteMembershipsURL.setDoAsGroupId(scopeGroupId);
                manageSiteMembershipsURL.setParameter("struts_action", "/sites_admin/edit_site_assignments");
                manageSiteMembershipsURL.setParameter("groupId", String.valueOf(scopeGroupId));
                manageSiteMembershipsURL.setParameter("selPlid", String.valueOf(plid));
                manageSiteMembershipsURL.setPortletMode(PortletMode.VIEW);
                manageSiteMembershipsURL.setWindowState(LiferayWindowState.POP_UP);

                themeDisplay.setURLManageSiteMemberships(manageSiteMembershipsURL);
            } else {
                themeDisplay.setShowManageSiteMembershipsIcon(false);
            }
        }

        boolean hasAddLayoutGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.ADD_LAYOUT);
        boolean hasAddLayoutLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout,
                ActionKeys.ADD_LAYOUT);
        boolean hasManageLayoutsGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_LAYOUTS);
        boolean hasManageStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.MANAGE_STAGING);
        boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.PUBLISH_STAGING);
        boolean hasUpdateGroupPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.UPDATE);
        boolean hasViewStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId,
                ActionKeys.VIEW_STAGING);

        if (!group.isControlPanel() && !group.isUser() && !group.isUserGroup() && hasUpdateGroupPermission) {

            themeDisplay.setShowSiteSettingsIcon(true);

            LiferayPortletURL siteSettingsURL = new PortletURLImpl(request, PortletKeys.SITE_SETTINGS,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.SITE_SETTINGS);
            siteSettingsURL.setDoAsGroupId(scopeGroupId);
            siteSettingsURL.setParameter("struts_action", "/sites_admin/edit_site");
            siteSettingsURL.setParameter("closeRedirect", currentURL);
            siteSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteSettingsURL.setPortletMode(PortletMode.VIEW);
            siteSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteSettings(siteSettingsURL);
        }

        if (!group.isLayoutPrototype() && (hasAddLayoutGroupPermission || hasAddLayoutLayoutPermission
                || hasManageLayoutsGroupPermission || hasUpdateGroupPermission)) {

            themeDisplay.setShowSiteMapSettingsIcon(true);

            LiferayPortletURL siteMapSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN,
                    controlPanelPlid, PortletRequest.RENDER_PHASE);

            siteMapSettingsURL.setControlPanelCategory(
                    _CONTROL_PANEL_CATEGORY_PORTLET_PREFIX + PortletKeys.LAYOUTS_ADMIN);
            siteMapSettingsURL.setDoAsGroupId(scopeGroupId);
            siteMapSettingsURL.setParameter("struts_action", "/layouts_admin/edit_layouts");

            if (layout.isPrivateLayout()) {
                siteMapSettingsURL.setParameter("tabs1", "private-pages");
            } else {
                siteMapSettingsURL.setParameter("tabs1", "public-pages");
            }

            siteMapSettingsURL.setParameter("closeRedirect", currentURL);
            siteMapSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId));
            siteMapSettingsURL.setPortletMode(PortletMode.VIEW);
            siteMapSettingsURL.setWindowState(LiferayWindowState.POP_UP);

            themeDisplay.setURLSiteMapSettings(siteMapSettingsURL);
        }

        if (group.hasStagingGroup() && !group.isStagingGroup()) {
            themeDisplay.setShowAddContentIcon(false);
            themeDisplay.setShowLayoutTemplatesIcon(false);
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        if (group.isControlPanel()) {
            themeDisplay.setShowPageSettingsIcon(false);
            themeDisplay.setURLPublishToLive(null);
        }

        // LEP-4987

        if (group.isStaged() || group.isStagingGroup()) {
            if (hasManageStagingPermission || hasPublishStagingPermission || hasUpdateLayoutPermission
                    || hasViewStagingPermission) {

                themeDisplay.setShowStagingIcon(true);
            }

            if (hasPublishStagingPermission) {
                PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUTS_ADMIN, plid,
                        PortletRequest.RENDER_PHASE);

                publishToLiveURL.setParameter("struts_action", "/layouts_admin/publish_layouts");

                if (layout.isPrivateLayout()) {
                    publishToLiveURL.setParameter("tabs1", "private-pages");
                } else {
                    publishToLiveURL.setParameter("tabs1", "public-pages");
                }

                publishToLiveURL.setParameter("pagesRedirect", currentURL);
                publishToLiveURL.setParameter("groupId", String.valueOf(scopeGroupId));
                publishToLiveURL.setParameter("selPlid", String.valueOf(plid));
                publishToLiveURL.setPortletMode(PortletMode.VIEW);
                publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE);

                themeDisplay.setURLPublishToLive(publishToLiveURL);
            }
        }

        PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid,
                PortletRequest.RENDER_PHASE);

        if (scopeGroupId > 0) {
            myAccountURL.setDoAsGroupId(scopeGroupId);
        }

        myAccountURL.setParameter("struts_action", "/my_account/edit_user");
        myAccountURL.setPortletMode(PortletMode.VIEW);

        if (refererPlid > 0) {
            myAccountURL.setRefererPlid(refererPlid);
        } else {
            myAccountURL.setRefererPlid(plid);
        }

        myAccountURL.setWindowState(WindowState.MAXIMIZED);

        themeDisplay.setURLMyAccount(myAccountURL);
    }

    if (!user.isActive() || (PrefsPropsUtil.getBoolean(companyId, PropsKeys.TERMS_OF_USE_REQUIRED)
            && !user.isAgreedToTermsOfUse())) {

        themeDisplay.setShowAddContentIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
    }

    if (layout.isLayoutPrototypeLinkActive()) {
        themeDisplay.setShowPageCustomizationIcon(false);
    }

    if (group.isLayoutPrototype()) {
        themeDisplay.setShowControlPanelIcon(false);
        themeDisplay.setShowHomeIcon(false);
        themeDisplay.setShowManageSiteMembershipsIcon(false);
        themeDisplay.setShowMyAccountIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(true);
        themeDisplay.setShowPortalIcon(false);
        themeDisplay.setShowSignInIcon(false);
        themeDisplay.setShowSignOutIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
        themeDisplay.setShowStagingIcon(false);
    }

    if (group.isLayoutSetPrototype()) {
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    if (group.hasStagingGroup() && !group.isStagingGroup()) {
        themeDisplay.setShowLayoutTemplatesIcon(false);
        themeDisplay.setShowPageCustomizationIcon(false);
        themeDisplay.setShowPageSettingsIcon(false);
        themeDisplay.setShowSiteContentIcon(false);
        themeDisplay.setShowSiteMapSettingsIcon(false);
        themeDisplay.setShowSiteSettingsIcon(false);
    }

    themeDisplay.setURLPortal(portalURL.concat(contextPath));

    String urlSignIn = mainPath.concat("/portal/login");

    urlSignIn = HttpUtil.addParameter(urlSignIn, "p_l_id", layout.getPlid());

    themeDisplay.setURLSignIn(urlSignIn);

    themeDisplay.setURLSignOut(mainPath.concat("/portal/logout"));

    PortletURL updateManagerURL = new PortletURLImpl(request, PortletKeys.UPDATE_MANAGER, plid,
            PortletRequest.RENDER_PHASE);

    updateManagerURL.setParameter("struts_action", "/update_manager/view");
    updateManagerURL.setPortletMode(PortletMode.VIEW);
    updateManagerURL.setWindowState(WindowState.MAXIMIZED);

    themeDisplay.setURLUpdateManager(updateManagerURL);

    return themeDisplay;
}