Example usage for javax.servlet ServletContext getAttribute

List of usage examples for javax.servlet ServletContext getAttribute

Introduction

In this page you can find the example usage for javax.servlet ServletContext getAttribute.

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the servlet container attribute with the given name, or null if there is no attribute by that name.

Usage

From source file:com.liferay.portal.util.PortalInstances.java

private long _initCompany(ServletContext ctx, String webId) {

    // Begin initializing company

    if (_log.isDebugEnabled()) {
        _log.debug("Begin initializing company with web id " + webId);
    }/*www.  ja  va  2s. c o m*/

    long companyId = 0;

    try {
        Company company = CompanyLocalServiceUtil.checkCompany(webId);

        companyId = company.getCompanyId();
    } catch (Exception e) {
        _log.error(e, e);
    }

    CompanyThreadLocal.setCompanyId(companyId);

    // Initialize display

    if (_log.isDebugEnabled()) {
        _log.debug("Initialize display");
    }

    try {
        String xml = Http.URLtoString(ctx.getResource("/WEB-INF/liferay-display.xml"));

        PortletCategory portletCategory = (PortletCategory) WebAppPool.get(String.valueOf(companyId),
                WebKeys.PORTLET_CATEGORY);

        if (portletCategory == null) {
            portletCategory = new PortletCategory();
        }

        PortletCategory newPortletCategory = PortletLocalServiceUtil.getEARDisplay(xml);

        portletCategory.merge(newPortletCategory);

        WebAppPool.put(String.valueOf(companyId), WebKeys.PORTLET_CATEGORY, portletCategory);
    } catch (Exception e) {
        _log.error(e, e);
    }

    // Check journal content search

    if (_log.isDebugEnabled()) {
        _log.debug("Check journal content search");
    }

    if (GetterUtil
            .getBoolean(PropsUtil.get(CompanyImpl.SYSTEM, PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP))
            || GetterUtil.getBoolean(PropsUtil.get(PropsUtil.JOURNAL_SYNC_CONTENT_SEARCH_ON_STARTUP))) {

        try {
            JournalContentSearchLocalServiceUtil.checkContentSearches(companyId);
        } catch (Exception e) {
            _log.error(e, e);
        }
    }

    // Scheduler

    if (_log.isDebugEnabled()) {
        _log.debug("Scheduler");
    }

    try {
        if (GetterUtil.getBoolean(PropsUtil.get(PropsUtil.SCHEDULER_ENABLED))) {

            Iterator itr = PortletLocalServiceUtil.getPortlets(companyId).iterator();

            while (itr.hasNext()) {
                Portlet portlet = (Portlet) itr.next();

                String className = portlet.getSchedulerClass();

                if (portlet.isActive() && Validator.isNotNull(className)) {
                    Scheduler scheduler = (Scheduler) InstancePool.get(className);

                    scheduler.schedule();
                }
            }
        }
    } catch (ObjectAlreadyExistsException oaee) {
    } catch (Exception e) {
        _log.error(e, e);
    }

    // SMTP message listener

    if (_log.isDebugEnabled()) {
        _log.debug("SMTP message listener");
    }

    try {
        Iterator itr = PortletLocalServiceUtil.getPortlets(companyId).iterator();

        while (itr.hasNext()) {
            Portlet portlet = (Portlet) itr.next();

            MessageListener smtpMessageListener = portlet.getSmtpMessageListenerInstance();

            if (portlet.isActive() && (smtpMessageListener != null)) {
                SMTPServerUtil.addListener(smtpMessageListener);
            }
        }
    } catch (ObjectAlreadyExistsException oaee) {
    } catch (Exception e) {
        _log.error(e, e);
    }

    // LDAP Import

    try {
        if (PortalLDAPUtil.isImportOnStartup(companyId)) {
            PortalLDAPUtil.importFromLDAP(companyId);
        }
    } catch (Exception e) {
        _log.error(e, e);
    }

    // Message resources

    if (_log.isDebugEnabled()) {
        _log.debug("Message resources");
    }

    MultiMessageResources messageResources = (MultiMessageResources) ctx.getAttribute(Globals.MESSAGES_KEY);

    messageResources.setServletContext(ctx);

    WebAppPool.put(String.valueOf(companyId), Globals.MESSAGES_KEY, messageResources);

    // Process application startup events

    if (_log.isDebugEnabled()) {
        _log.debug("Process application startup events");
    }

    try {
        EventsProcessor.process(PropsUtil.getArray(PropsUtil.APPLICATION_STARTUP_EVENTS),
                new String[] { String.valueOf(companyId) });
    } catch (Exception e) {
        _log.error(e, e);
    }

    // End initializing company

    if (_log.isDebugEnabled()) {
        _log.debug("End initializing company with web id " + webId + " and company id " + companyId);
    }

    addCompanyId(companyId);

    return companyId;
}

From source file:com.rapid.core.Application.java

public Control getControl(ServletContext servletContext, String id) {
    Control control = null;//w  w  w  .j av  a 2s.  com
    // check we have pages and an id
    if (_pages != null && id != null) {
        // if the id is not a zero length string
        if (id.length() > 0) {
            // split the id parts on the underscore
            String[] idParts = id.split("_");
            // get the first part into a page id
            String pageId = idParts[0];
            try {
                // get the specified page
                Page page = _pages.getPage(servletContext, pageId);
                // check we got a page
                if (page == null) {
                    // no page matching this control id prefix so just loop all pages
                    for (String loopPageId : _pages.getPageIds()) {
                        // fetch this page
                        page = _pages.getPage(servletContext, loopPageId);
                        // look for the control
                        control = page.getControl(id);
                        // if we found it return it!
                        if (control != null)
                            return control;
                    }
                } else {
                    // look for the control in the page according to its prefix
                    control = page.getControl(id);
                    // return it if we found it!
                    if (control != null)
                        return control;
                }
            } catch (Exception ex) {
                // get the logger
                Logger logger = (Logger) servletContext.getAttribute("logger");
                // log this exception
                logger.error("Error loading page when getting control", ex);
            }
        } // id length > 0 check               
    } // id and page non-null check
      // couldn't find it either in specified page, or all pages
    return null;
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

/**
 * Processes requests from the client for both HTTP <code>GET</code>
 * and <code>POST</code> methods.
 *
 * @param request servlet request//  w  w  w  . j  a v  a 2s.c  o  m
 * @param response servlet response
 */
protected void processRequest(String requestType, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String responseFormat = response_format_prop;
    // flags that the user has not set the response format
    boolean defaultResponseFormat = response_format_prop.equals("XML") ? true : false;
    ServiceOperationInterface service = null;
    String callbackFunction = null;

    log.info(">> Start processRequest(" + requestType + ") at " + new Date());

    try {
        ServletContext context = getServletContext();

        String scriptName = request.getParameter(PARAM_SCRIPTNAME1); // look for "service=xxxx"
        String contextPath = "";

        /* If the service parameter is not specified then use the URL to get the service name... */

        if (scriptName == null) {
            scriptName = request.getPathInfo();
            contextPath = request.getContextPath();

            /*
            //Put this in for debugging...
            System.out.println("****** -> pathInfo       [" + request.getPathInfo() + "]");
            System.out.println("****** -> pathTranslated [" + request.getPathTranslated() + "]");
            System.out.println("****** -> contextPath    [" + request.getContextPath() + "]");
            System.out.println("****** -> localAddr      [" + request.getLocalAddr() + "]");
            System.out.println("****** -> localName      [" + request.getLocalName() + "]");
            System.out.println("****** -> requestURI     [" + request.getRequestURI() + "]");//*****
            System.out.println("****** -> servletPath    [" + request.getServletPath() + "]");
            */

            if (scriptName == null) {
                scriptName = "UNSPECIFIED_SERVICE";
            }
        }

        /* See if the URI is mapped to another service... */
        ServiceMapping serviceMapping;
        serviceMapping = serviceMapper.getURIMapping(""/*contextPath*/, scriptName, requestType);

        if (serviceMapping != null) {
            log.info("Redirect URI to [" + serviceMapping.getServiceName() + "]");

            scriptName = serviceMapping.getServiceName();

            /* If the URI has been mapped then see if the "Accept" header specifies the return type required... */
            String accept = request.getHeader("Accept");

            if (accept.indexOf("text/xml") != -1) {
                responseFormat = "XML";
                defaultResponseFormat = false;
            }
            if (accept.indexOf("text/json") != -1) {
                responseFormat = "JSON";
                defaultResponseFormat = false;
            }

        }

        if (scriptName.startsWith("/")) {
            scriptName = scriptName.substring(1, scriptName.length());
        }

        /**
         * If "log" service invoked then process it...
         */
        if (scriptName.equals("log")) {
            returnHTMLLog(response);
            return;
        }

        /**
         * If "health" service invoked then process it...
         */
        if (scriptName.equals("health")) {
            returnHealth(response);
            return;
        }

        /* Check for the flag to return XML or JSON objects... */

        if (request.getParameter(PARAM_RETURNXML) != null) {
            println(">> Servlet will return XML object.");
            responseFormat = "XML";
            defaultResponseFormat = false;
        } else if (request.getParameter(PARAM_RETURNJSON) != null) {
            println(">> Servlet will return XML object.");
            responseFormat = "JSON";
            defaultResponseFormat = false;
        } else if (request.getParameter(PARAM_RETURNRAW) != null) {
            println(">> Servlet will return raw text object.");
            responseFormat = "RAW";
            defaultResponseFormat = false;
        }

        /* Check for the callback function parameter... */

        callbackFunction = request.getParameter(PARAM_CALLBACK);

        /**
         * Check to see if the client wants a "Service Mapping Description" (SMD) for the 'service'...
         */

        if (request.getParameter(PARAM_SMD) != null) {

            log.info("Client wants SMD for [" + scriptName + "]");

            try {
                ServicePool pool = null;
                Map availableServices = null;
                ServiceMappingDescription smd = null;
                ServiceScriptPool serviceScriptPool = null;
                String serviceScriptName = null;
                String returnString = null;

                pool = (ServicePool) context.getAttribute(ATTRIB_SERVICE_POOL);
                availableServices = pool.getAvailableServices();
                smd = new ServiceMappingDescription(request.getRequestURL().toString(),
                        request.getRequestURL().toString() + "?smd", null);

                for (Iterator it = availableServices.values().iterator(); it.hasNext();) {

                    serviceScriptPool = (ServiceScriptPool) it.next();

                    serviceScriptName = serviceScriptPool.getPoolName();

                    /**
                     * If the service script name begins with the passed in script name then add it to the
                     * service mapping description...
                     */

                    log.debug("scriptName = [" + scriptName + "], serviceScriptName = [" + serviceScriptName
                            + "]");

                    if (scriptName.equals("") || serviceScriptName.startsWith(scriptName + "/")
                            || serviceScriptName.equals(scriptName)) {

                        smd.addOperation(serviceScriptName);

                        service = serviceScriptPool.getService();

                        smd.setOperationDescription(service.getScriptDescription());
                        smd.setOperationTransport(service.getHTTPMethods());
                        smd.setOperationEnvelope("URL");
                        smd.setOperationContentType(service.getResponseFormat());
                        smd.setOperationParameters(serviceScriptPool.getServiceParameters());
                        smd.setOperationReturns(serviceScriptPool.getServiceReturns());

                    }

                }

                returnString = smd.getSMDJSONString();

                writeResponse(returnString, "JSONRAW", callbackFunction, response);

            } catch (Exception ex) {
                log.error("Exception getting SMD: " + ex.toString());
                ex.printStackTrace();
            }

            return;
        }

        /**
         * Get the service and run it...
         */

        println(">> Client wants to invoke the service [" + scriptName + "]");

        try {
            service = getServiceScript(scriptName);
        } catch (Exception ex) {
            errorResponse(response,
                    "Could not get an instance of the service [" + scriptName + "]: " + ex.toString(),
                    responseFormat, callbackFunction);
            return;
        }

        if (service == null) {
            errorResponse(response, "Service [" + scriptName + "] not found.", responseFormat,
                    callbackFunction);
            return;
        }

        /**
         * If the script exists in the toaster pool then invoke it
         */

        println(">> Checking login required");

        try {
            if (service.getLoginRequired().equals("true")) {

                HttpSession session = request.getSession(false);
                Object loggedIn = null;

                if (session != null) {
                    loggedIn = session.getAttribute(ATTRIB_LOGGED_IN);
                }

                log.trace("**** SESSION   = " + session);
                log.trace("**** Logged In = " + loggedIn);

                if (session == null || loggedIn == null || loggedIn.equals("true") == false) {
                    errorResponse(response,
                            "The service " + scriptName + " requires you to be logged in to run it.",
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }

                /* Check that the logged in user is authorised to run the service... */

                String validUsers;
                String[] validUsersArray;
                String user;
                String loggedInUser;
                boolean validUser;

                validUsers = service.getValidUsers();
                validUsersArray = validUsers.split("[,]");

                loggedInUser = (String) session.getAttribute(ATTRIB_LOGGED_IN_USER);

                validUser = false;

                for (int idx = 0; idx < validUsersArray.length; idx++) {
                    user = validUsersArray[idx].trim();
                    if (user.equals("*")) {
                        validUser = true;
                        break;
                    }
                    if (user.equals(loggedInUser)) {
                        validUser = true;
                        break;
                    }
                }

                if (validUser == false) {
                    log.error("The user [" + loggedInUser + "] is not authorised to invoke the service ["
                            + scriptName + "]");
                    errorResponse(response, "You are not authorised to invoke the service [" + scriptName + "]",
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }

            }
        } catch (Exception ex) {
            errorResponse(response, "Could not check if login required for this service. " + ex.toString(),
                    responseFormat, callbackFunction);
            return;
        }

        boolean scriptInputSet = false;

        /*
         * Go through the set of parameters passed to us and set them up in the service instance...
         */
        for (Enumeration e = request.getParameterNames(); e.hasMoreElements();) {

            String parameterName = (String) e.nextElement();

            if (parameterName.equals(PARAM_SCRIPTNAME1) == true
                    || parameterName.equals(PARAM_SCRIPTNAME2) == true
                    || parameterName.equals(PARAM_RETURNXML) == true
                    || parameterName.equals(PARAM_RETURNJSON) == true
                    || parameterName.equals(PARAM_CALLBACK) == true) {
                continue;
            }

            String parameterValue = (String) request.getParameter(parameterName);

            if (parameterName.equals(PARAM_INPUTXML) == true) {
                service.setInputXML(parameterValue);
                scriptInputSet = true;
                continue;
            }

            if (parameterName.equals(PARAM_INPUTJSON) == true) {

                try {
                    // The input object is a JSON object... so convert it into XML...
                    JSONObject json = new JSONObject(parameterValue);

                    service.setInputXML(XML.toString(json));
                    scriptInputSet = true;
                    println("JSON converted to \n" + XML.toString(json));
                } catch (JSONException ex) {
                    errorResponse(response,
                            "Could not create JSON object." + ex.toString() + ". " + ex.getStackTrace(),
                            responseFormat, callbackFunction);
                    freeServiceScript(service);
                    return;
                }
                continue;
            }

            /* Any leftover parameters are query parameters. */
            println("Query Parameter found... Setting " + parameterName + " to " + parameterValue);
            service.setParameter(parameterName, parameterValue);

        } // End of parameters for loop

        /* If there is content in the request then, unless we have already set it, this is the input to the script... */

        if (requestType.equals("POST") && scriptInputSet == false) {

            try {
                BufferedReader reader = request.getReader();
                StringBuffer buf = new StringBuffer();
                String line;
                String postData;

                while ((line = reader.readLine()) != null) {
                    buf.append(line);
                }

                postData = buf.toString();

                log.debug("POST DATA: " + postData);

                if (postData.startsWith("<")) {
                    service.setInputXML(postData);
                    scriptInputSet = true;
                } else {
                    try {
                        // The input object is a JSON object... so convert it into XML...
                        JSONObject json = new JSONObject(postData);

                        service.setInputXML(XML.toString(json));
                        scriptInputSet = true;
                        log.debug("POST JSON converted to \n" + XML.toString(json));
                    } catch (JSONException ex) {
                        errorResponse(response, "Could not convert POSTed JSON object." + ex.toString() + ". "
                                + ex.getStackTrace(), responseFormat, callbackFunction);
                        freeServiceScript(service);
                        return;
                    }
                }

            } catch (Exception ex) {
                log.warn("Exception getting posted data: " + ex.toString());
                errorResponse(response, "Could not convert posted data.", responseFormat, callbackFunction);
                freeServiceScript(service);
                return;
            }

        }

        /* If the service name has been redirected then set any parameters that where embedded in the URI... */
        if (serviceMapping != null) {
            Properties serviceParameters = serviceMapping.getParameters();
            String paramName;
            String paramValue;
            for (Enumeration<Object> en = serviceParameters.keys(); en.hasMoreElements();) {
                paramName = (String) en.nextElement();
                paramValue = (String) serviceParameters.get(paramName);
                service.setParameter(paramName, paramValue);
            }
        }

        String serviceResultString = null;

        /**
         * Run the service script...
         */

        service.setSessionRequest(request);
        service.setSessionResponse(response);
        service.setCallbackFunction(callbackFunction);

        /* Check if the service has a predefined output format... */
        /* If the user has specified a format then that is used.. */

        String operationResponseFormat;

        operationResponseFormat = service.getResponseFormat();

        if (defaultResponseFormat == true && operationResponseFormat != null
                && operationResponseFormat.equals("") == false) {
            responseFormat = operationResponseFormat;
        }

        service.setInvokeResponseFormat(responseFormat);

        /* If this is a priviledged operation then pass in a reference to the servlet... */

        String priviledgedOperation = service.getPriviledged();

        if (priviledgedOperation.compareToIgnoreCase("true") == 0
                || priviledgedOperation.compareToIgnoreCase("yes") == 0
                || priviledgedOperation.compareToIgnoreCase("y") == 0) {

            service.setPriviledgedHelper(this);
        }

        serviceResultString = service.invokeOperation();

        if (serviceResultString == null) {
            errorResponse(response,
                    "Error invoking the operation.<br><b>" + service.getScriptMessage() + "</b>",
                    responseFormat, callbackFunction);
            freeServiceScript(service);
            return;
        }

        /* Return the results... */

        if (serviceResultString != null && serviceResultString.equals("") == false) {
            writeResponse(serviceResultString, responseFormat, callbackFunction, response);
        }

        println(">> Service script executed successfully.");

        /* Free the service instance... */

        freeServiceScript(service);

    } catch (Exception ex) {
        errorResponse(response, "Exception processing request: " + ex.toString(), responseFormat,
                callbackFunction);
        ex.printStackTrace();
        try {
            freeServiceScript(service);
        } catch (Exception x) {
            log.warn("Exception freeing a service instance: " + x.toString());
        }
        return;
    }

    println(">> Finished processRequest() at " + new Date());

}

From source file:com.redsqirl.auth.UserInfoBean.java

/**
 * login/*from  ww  w  .ja  va 2  s  .  co m*/
 * 
 * Method to validate permission of the user and call init.
 * 
 * @return String - success or failure
 * @author Igor.Souza
 */
public String login() {
    logger.warn("login");
    setMsnError(null);
    cancel = false;
    checkPassword = false;
    buildBackend = true;
    setAlreadySignedInOtherMachine(null);
    setAlreadySignedIn(null);
    String licenseKey = null;
    String licence = "";

    if (getUserName() == null || "".equals(getUserName())) {
        setMsnError(getMessageResources("login_error_user_required"));
        return "failure";
    }

    if (getPassword() == null || "".equals(getPassword())) {
        setMsnError(getMessageResources("login_error_password_required"));
        return "failure";
    }

    FacesContext fCtx = FacesContext.getCurrentInstance();
    ServletContext sc = (ServletContext) fCtx.getExternalContext().getContext();
    HttpSession session = (HttpSession) fCtx.getExternalContext().getSession(true);

    try {
        Connection conn = new Connection(hostname);
        conn.connect();

        if (conn.isAuthMethodAvailable(userName, "publickey")) {
            logger.debug("--> public key auth method supported by server");
        } else {
            logger.debug("--> public key auth method not supported by server");
        }
        if (conn.isAuthMethodAvailable(userName, "keyboard-interactive")) {
            logger.debug("--> keyboard interactive auth method supported by server");
        } else {
            logger.debug("--> keyboard interactive auth method not supported by server");
        }
        if (conn.isAuthMethodAvailable(userName, "password")) {
            logger.debug("--> password auth method supported by server");
        } else {
            logger.warn("--> password auth method not supported by server");
        }

        checkPassword = conn.authenticateWithPassword(userName, password);

        if (!checkPassword) {
            setMsnError("Authentication Error");
            setAlreadySignedInOtherMachine(null);

            logger.warn("Authentication Error");

            return "failure";
        }
        try {
            File licenseP = new File(WorkflowPrefManager.getPathSystemLicence());
            logger.warn("path licence " + WorkflowPrefManager.getPathSystemLicence());
            Properties props = new Properties();
            logger.warn(ProjectID.get());

            String[] value = ProjectID.get().trim().split("-");
            if (value != null && value.length > 1) {
                licenseKey = value[0].replaceAll("[0-9]", "") + value[value.length - 1];

                if (licenseP.exists()) {
                    props.load(new FileInputStream(licenseP));
                    logger.warn(props.toString());

                    licenseKey = licenseKey.replaceAll("[^A-Za-z0-9]", "").toLowerCase();
                    logger.warn(licenseKey);
                    licence = props.getProperty(licenseKey);
                } else {
                    setMsnError("Could not find license key");
                    logger.warn("Could not find license key");
                    invalidateSession();
                    return "failure";
                }

                if (licence == null || licence.isEmpty()) {
                    setMsnError("License key was empty");
                    logger.warn("License key was empty");
                    invalidateSession();
                    return "failure";
                }

                Decrypter decrypt = new Decrypter();
                decrypt.decrypt(licence);

                //setNumberCluster(decrypt.getNumberCluster());

                /*File file = new File(WorkflowPrefManager.getPathUsersFolder());
                int homes = 0;
                if(file.exists()){
                   homes = file.list().length;
                }*/

                Map<String, String> params = new HashMap<String, String>();

                //params.put(Decrypter.clusterNb, String.valueOf(homes));

                //params.put(Decrypter.mac, decrypt.getMACAddress());
                params.put(Decrypter.name, licenseKey);

                DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
                params.put(Decrypter.date, formatter.format(new Date()));

                if (!decrypt.validateExpiredKey(params)) {
                    setMsnError("License Key is expired");
                    logger.warn("License Key is expired");
                    invalidateSession();
                    return "failure";
                }

                boolean valid = decrypt.validateAllValuesSoft(params);

                if (!valid) {
                    setMsnError("License Key is Invalid");
                    logger.warn("License Key is Invalid");
                    invalidateSession();
                    return "failure";
                }

            } else {
                setMsnError("Project Version is Invalid");
                logger.warn("Project Version is Invalid");
                invalidateSession();
                return "failure";
            }

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            setMsnError("Failed to get license");
            invalidateSession();
            return "failure";
        }

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        invalidateSession();
        setMsnError("error - Please Contact Your Administrator");
        return "failure";
    }

    UsageRecordWriter usageRecordLog = new UsageRecordWriter(licence, userName);
    Map<String, UsageRecordWriter> sessionUsageRecordWriter = (Map<String, UsageRecordWriter>) sc
            .getAttribute("usageRecordLog");
    if (sessionUsageRecordWriter == null) {
        sessionUsageRecordWriter = new HashMap<String, UsageRecordWriter>();
    }
    sessionUsageRecordWriter.put(userName, usageRecordLog);
    sc.setAttribute("usageRecordLog", sessionUsageRecordWriter);

    @SuppressWarnings("unchecked")
    Map<String, HttpSession> sessionLoginMap = (Map<String, HttpSession>) sc.getAttribute("sessionLoginMap");

    HttpSession sessionLogin = sessionLoginMap.get(userName);
    if (sessionLogin != null) {

        logger.warn("validateSecondLogin sessionLogin");

        if (sessionLogin.getId().equals(session.getId())) {
            setAlreadySignedInOtherMachine(null);
            setAlreadySignedIn("twice");

            logger.warn("Already Authenticated twice");
            usageRecordLog().addError("ERROR LOGIN", "Already Authenticated twice");

            return "failure";
        } else if (forceSignIn.equalsIgnoreCase("T")) {
            //Invalidate the session
            invalidateSession(sessionLogin);
        } else {
            setAlreadySignedInOtherMachine("two");
            logger.warn("Already Authenticated two");
            usageRecordLog().addError("ERROR LOGIN", "Already Authenticated two");
            return "failure";
        }
    }

    logger.info("update progressbar");
    setValueProgressBar(5);

    logger.info("validateSecondLogin end");

    usageRecordLog().addSuccess("LOGIN");

    return init();
}

From source file:gov.nih.nci.cadsr.sentinel.database.DBAlertOracle.java

static private synchronized int setupPoolX(HttpSession session_, String dsurl_, String username_,
        String password_) {/*  w  ww.  ja va  2s.c  o m*/
    // Get the Servlet Context and see if a pool already exists.
    ServletContext sc = session_.getServletContext();
    if (sc.getAttribute(DBAlert._DATASOURCE) != null)
        return 0;

    OracleConnectionPoolDataSource ocpds = (OracleConnectionPoolDataSource) sc.getAttribute(_DBPOOL);
    if (ocpds != null)
        return 0;

    ocpds = setupPool(dsurl_, username_, password_);
    if (ocpds != null) {
        // Remember the pool in the Servlet Context.
        sc.setAttribute(_DBPOOL + ".ds", ocpds);
        sc.setAttribute(_DBPOOL + ".user", username_);
        sc.setAttribute(_DBPOOL + ".pswd", password_);
        return 0;
    }
    return -1;
}

From source file:jp.or.openid.eiwg.scim.operation.Operation.java

/**
 * ?/* w  w  w  . j  a  v  a 2  s  .co  m*/
 *
 * @param context
 * @param request
 * @param attributes
 * @param requestJson
 */
public LinkedHashMap<String, Object> createUserInfo(ServletContext context, HttpServletRequest request,
        String attributes, String requestJson) {
    LinkedHashMap<String, Object> result = null;

    Set<String> returnAttributeNameSet = new HashSet<>();

    // ?
    setError(0, null, null);

    // ??
    if (attributes != null && !attributes.isEmpty()) {
        // 
        String[] tempList = attributes.split(",");
        for (int i = 0; i < tempList.length; i++) {
            String attributeName = tempList[i].trim();
            // ???????
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null && !attributeSchema.isEmpty()) {
                returnAttributeNameSet.add(attributeName);
            } else {
                // ???????
                String message = String.format(MessageConstants.ERROR_INVALID_ATTRIBUTES, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    }

    // ?
    if (requestJson == null || requestJson.isEmpty()) {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // (JSON)?
    ObjectMapper mapper = new ObjectMapper();
    LinkedHashMap<String, Object> requestObject = null;
    try {
        requestObject = mapper.readValue(requestJson, new TypeReference<LinkedHashMap<String, Object>>() {
        });
    } catch (JsonParseException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (JsonMappingException e) {
        String datailMessage = e.getMessage();
        datailMessage = datailMessage.substring(0, datailMessage.indexOf('\n'));
        setError(HttpServletResponse.SC_BAD_REQUEST, null,
                MessageConstants.ERROR_INVALID_REQUEST + "(" + datailMessage + ")");
        return result;
    } catch (IOException e) {
        setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null, MessageConstants.ERROR_UNKNOWN);
        return result;
    }

    // ?
    if (requestObject != null && !requestObject.isEmpty()) {
        Iterator<String> attributeIt = requestObject.keySet().iterator();
        while (attributeIt.hasNext()) {
            // ???
            String attributeName = attributeIt.next();
            // ?
            LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context,
                    attributeName, true);
            if (attributeSchema != null) {
                // ????
                Object mutability = attributeSchema.get("mutability");
                if (mutability != null && mutability.toString().equalsIgnoreCase("readOnly")) {
                    // readOnly 
                    String message = String.format(MessageConstants.ERROR_READONLY_ATTRIBUTE, attributeName);
                    setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                    return result;
                }

                // ??
                // ()
            } else {
                // ????
                String message = String.format(MessageConstants.ERROR_UNKNOWN_ATTRIBUTE, attributeName);
                setError(HttpServletResponse.SC_BAD_REQUEST, null, message);
                return result;
            }
        }
    } else {
        // 
        setError(HttpServletResponse.SC_BAD_REQUEST, null, MessageConstants.ERROR_INVALID_REQUEST);
        return result;
    }

    // ?
    // ()

    LinkedHashMap<String, Object> newUserInfo = new LinkedHashMap<String, Object>();

    // id?
    UUID uuid = UUID.randomUUID();
    newUserInfo.put("id", uuid.toString());

    Iterator<String> attributeIt = requestObject.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();
        // ?
        Object attributeValue = requestObject.get(attributeName);

        newUserInfo.put(attributeName, attributeValue);
    }

    // meta?
    LinkedHashMap<String, Object> metaValues = new LinkedHashMap<String, Object>();
    // meta.resourceType 
    metaValues.put("resourceType", "User");
    // meta.created 
    SimpleDateFormat xsdDateTime = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
    xsdDateTime.setTimeZone(TimeZone.getTimeZone("UTC"));
    metaValues.put("created", xsdDateTime.format(new Date()));
    // meta.location 
    String location = request.getScheme() + "://" + request.getServerName();
    int serverPort = request.getServerPort();
    if (serverPort != 80 && serverPort != 443) {
        location += ":" + Integer.toString(serverPort);
    }
    location += request.getContextPath();
    location += "/scim/Users/" + uuid.toString();
    metaValues.put("location", location);
    newUserInfo.put("meta", metaValues);

    // (??)
    @SuppressWarnings("unchecked")
    ArrayList<LinkedHashMap<String, Object>> users = (ArrayList<LinkedHashMap<String, Object>>) context
            .getAttribute("Users");
    if (users == null) {
        users = new ArrayList<LinkedHashMap<String, Object>>();
    }
    users.add(newUserInfo);
    context.setAttribute("Users", users);

    // ??
    result = new LinkedHashMap<String, Object>();
    attributeIt = newUserInfo.keySet().iterator();
    while (attributeIt.hasNext()) {
        // ???
        String attributeName = attributeIt.next();

        // ?
        LinkedHashMap<String, Object> attributeSchema = SCIMUtil.getUserAttributeInfo(context, attributeName,
                true);
        Object returned = attributeSchema.get("returned");

        if (returned != null && returned.toString().equalsIgnoreCase("never")) {
            continue;
        }

        // ?
        Object attributeValue = newUserInfo.get(attributeName);

        result.put(attributeName, attributeValue);
    }

    return result;
}

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

public static WGACore retrieve(ServletContext servletContext) {
    return (WGACore) servletContext.getAttribute(ATTRIB_CORE);
}

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  . jav a  2 s. c o  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.aurel.track.prop.LoginBL.java

/**
 *
 * @param username//  w  w  w  . j av  a 2  s . c om
 * @param userPwd
 * @param nonce
 * @param request
 * @param anonymousLogin
 * @return Map with two entries: 1. "errors": ArrayList<LabelValueBean>; 2.
 *         "mappingEnum": Integer with 2: bad credentials, 6: license
 *         problems, 7: forward to URL, 8: first time admin user, 18:
 *         request license, 9: standard login
 *
 */
public static Map<String, Object> setEnvironment(String username, String userPwd, String nonce,
        HttpServletRequest request, Map<String, Object> sessionMap, boolean anonymousLogin,
        boolean usingContainerBasedAuthentication, boolean springAuthenticated) {
    HttpSession httpSession = request.getSession();
    ArrayList<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    HashMap<String, Object> result = new HashMap<String, Object>();
    Integer mappingEnum = 0;

    // Make things robust
    if (username == null) {
        username = "x";
    }
    if (userPwd == null) {
        userPwd = "x";
    }
    // Move locale to one that we actually have, in case there
    // was a request for a locale that we do not have
    Locale locale = LocaleHandler.getExistingLocale(request.getLocales());
    LocaleHandler.exportLocaleToSession(sessionMap, locale);
    Support support = new Support();
    support.setURIs(request);
    if (username != null) {
        ACCESSLOGGER.info("LOGON: User '" + username.trim() + "' trying to log on" + " at "
                + new Date().toString() + " from " + request.getRemoteAddr());
    }
    ServletContext servletContext = org.apache.struts2.ServletActionContext.getServletContext();
    try {
        if (!Torque.isInit()) {
            Torque.init(HandleHome.getTorqueProperties(servletContext, true));
            LOGGER.debug("Database is " + Torque.getDefaultDB());
            LOGGER.info("Torque was re-initialized.");
        }
    } catch (Exception e) {
        LOGGER.error(e.getMessage());
        LOGGER.error("Could not initialize Torque (1)");
        LOGGER.error(ExceptionUtils.getStackTrace(e));
        errors.add(new LabelValueBean("errGeneralError",
                getText("logon.err.noDataBase", locale) + ":" + e.getMessage()));
        mappingEnum = 1;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }
    TPersonBean personBean = null;
    if (anonymousLogin) {
        personBean = PersonBL.getAnonymousIfActive();
    } else {
        try {
            String pwd = "";
            if (nonce == null || nonce.length() == 0) {
                pwd = userPwd; // clear text
            } else {
                pwd = decrypt(nonce.charAt(0), userPwd); // key is first
                // character of
                // nonce
            }
            personBean = PersonBL.loadByLoginNameWithRights(username);

            if (personBean != null) {
                personBean.setPlainPwd(pwd);

                if (personBean.isDisabled()) {
                    errors.add(
                            new LabelValueBean("errCredentials", getText("logon.err.user.disabled", locale)));
                    ACCESSLOGGER
                            .warn("LOGON: User " + personBean.getLoginName() + " is disabled, login refused!");
                } else if (usingContainerBasedAuthentication == false && springAuthenticated == false
                        && !personBean.authenticate(pwd)) {
                    ACCESSLOGGER.warn("LOGON: Wrong password given for user " + personBean.getFullName()
                            + " at " + new Date().toString() + " from " + request.getRemoteAddr());
                    errors.add(new LabelValueBean("errCredentials",
                            getText("logon.err.password.mismatch", locale)));
                }
            } else {
                ACCESSLOGGER.warn("LOGON: No such user: " + username + " at " + new Date().toString() + " from "
                        + request.getRemoteAddr());
                errors.add(
                        new LabelValueBean("errCredentials", getText("logon.err.password.mismatch", locale)));
                LOGGER.debug("User '" + username + "' is not in database...");
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("Could not initialize Torque (2)");
            LOGGER.error(ExceptionUtils.getStackTrace(e));
            errors.add(new LabelValueBean("errGeneralError", getText("logon.err.noDataBase", locale)));
        }
    }

    if (errors.size() > 0 || personBean == null) {
        mappingEnum = 2;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    // At this point, we have successfully identified the user.
    // Try to set the users preferred locale
    if (personBean.getPrefLocale() != null && !"".equals(personBean.getPrefLocale())) {
        // get as stored in user profile
        locale = LocaleHandler.getExistingLocale(LocaleHandler.getLocaleFromString(personBean.getPrefLocale()));
    }
    if (locale == null) {
        // rely on browser settings
        locale = LocaleHandler.getExistingLocale(request.getLocales());
    }
    personBean.setLocale(locale);

    // set the bean with the last saved login date and save the actual date
    // as
    // last login date in the database
    personBean.setLastButOneLogin(personBean.getLastLogin());
    personBean.setLastLogin(new Date());
    PersonBL.saveSimple(personBean);
    LocaleHandler.exportLocaleToSession(sessionMap, locale);

    // -----------------------------------------------------

    // check if opState
    // (reject users, but not admin, in maintenance state)
    ApplicationBean appBean = ApplicationBean.getInstance();

    if (appBean == null) {
        LOGGER.error("appBean == null: this should never happen");
        mappingEnum = 3;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    httpSession.setAttribute(Constants.APPLICATION_BEAN, appBean);

    TSiteBean siteBean = DAOFactory.getFactory().getSiteDAO().load1();

    if (ApplicationBean.OPSTATE_MAINTENNANCE.equals(siteBean.getOpState()) && !personBean.getIsSysAdmin()) {
        // print error, refuse login
        errors.add(new LabelValueBean("errGeneralError", getText("logon.err.maintenance", locale)));
        mappingEnum = 4;
        result.put("errors", errors);
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    Runtime rt = Runtime.getRuntime();
    long mbyte = 1024 * 1024;
    long freeMemoryMB = rt.freeMemory() / mbyte;
    if (freeMemoryMB < 50 && !personBean.getIsSysAdmin()) {
        rt.gc();
        freeMemoryMB = rt.freeMemory() / mbyte;
        if (freeMemoryMB < 50) {
            errors.add(new LabelValueBean("errGeneralError", getText("logon.err.freeMemory", locale)));
            mappingEnum = 19;
            result.put("errors", errors);
            result.put("mappingEnum", mappingEnum);
            return result;
        }
    }

    // Save our logged-in user in the session
    // and set a cookie so she can conveniently point
    // directly to issues without having to log on for
    // the next CookieTimeout seconds

    httpSession.setAttribute(Constants.USER_KEY, personBean);

    int maxItemsProUser = GeneralSettings.getMaxItems();
    FilterUpperTO filterUpperTO = new FilterUpperTO();
    TreeFilterExecuterFacade.prepareFilterUpperTO(filterUpperTO, personBean, locale, null, null);
    int noOfProjectRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterProjectRoleItems(filterUpperTO,
            personBean, locale, maxItemsProUser);
    int noOfRACIRoleItemsProUser = LoadTreeFilterItemCounts.countTreeFilterRACIRoleItems(filterUpperTO,
            personBean, locale, maxItemsProUser);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Maximum number of items per user " + maxItemsProUser);
        LOGGER.debug(
                "Number of project role items accessible by " + username + ": " + noOfProjectRoleItemsProUser);
        LOGGER.debug("Number of RACI role items accessible by " + username + ": " + noOfRACIRoleItemsProUser);
    }
    boolean projectRoleItemsAboveLimit = noOfProjectRoleItemsProUser >= maxItemsProUser;
    boolean raciRoleItemsAboveLimit = noOfRACIRoleItemsProUser >= maxItemsProUser;
    personBean.setProjectRoleItemsAboveLimit(Boolean.valueOf(projectRoleItemsAboveLimit));
    personBean.setRaciRoleItemsAboveLimit(Boolean.valueOf(raciRoleItemsAboveLimit));
    PersonBL.setLicensedFeatures(personBean);

    List<TListTypeBean> issueTypes = IssueTypeBL.loadAllByPerson(personBean.getObjectID(), locale);
    httpSession.setAttribute("issueTypesJSON", JSONUtility.encodeIssueTypes(issueTypes));
    Integer sessionTimeoutMinutes = personBean.getSessionTimeoutMinutes();
    if (sessionTimeoutMinutes != null && sessionTimeoutMinutes.intValue() != 0) {
        httpSession.setMaxInactiveInterval(sessionTimeoutMinutes * 60);
    }
    // load the my filters in the menu
    List<FilterInMenuTO> myFilters = FilterBL.loadMyMenuFiltersWithTooltip(personBean, locale);

    httpSession.setAttribute(FilterBL.MY_MENU_FILTERS_JSON, FilterInMenuJSON.encodeFiltersInMenu(myFilters));

    List<FilterInMenuTO> lastQueries = FilterInMenuBL.getLastExecutedQueries(personBean, locale);

    httpSession.setAttribute(FilterBL.LAST_EXECUTED_FILTERS_JSON,
            FilterInMenuJSON.encodeFiltersInMenu(lastQueries));
    httpSession.setAttribute(ShortcutBL.SHORTCUTS_JSON, ShortcutBL.encodeShortcutsJSON());

    // modules
    List modules = getModuleDescriptors(personBean);
    httpSession.setAttribute("usedModules", modules);
    httpSession.setAttribute("usedModulesJSON", MasterHomeJSON.encodeModules(modules, personBean));
    httpSession.setAttribute("loggedInPersonUserLevel", personBean.getUserLevel());
    httpSession.setAttribute("clientUserLevelID", TPersonBean.USERLEVEL.CLIENT);

    // maxFileSize
    int maxFileSize = AttachBL.getMaxFileSize(siteBean);
    httpSession.setAttribute("MAXFILESIZE", maxFileSize);

    // ------------------------------------------------------
    // Create a new SessionBean for this session and bind it to the session

    SessionBean sBean = new SessionBean();
    httpSession.setAttribute(Constants.SESSION_BEAN, sBean);

    ItemLockBL.removeLockedIssuesByUser(personBean.getObjectID());

    ACCESSLOGGER.info("LOGON: User '" + personBean.getLoginName().trim() + "' (" + personBean.getFullName()
            + ")" + " logged in at " + new Date().toString() + " from " + request.getRemoteAddr());

    LicenseManager lm = appBean.getLicenseManager();
    if (lm != null) {
        int rf = lm.getErrorCode();
        boolean haveLicenseErrors = false;
        switch (rf) {
        case 1:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.needCommercial", locale)));
            break;
        case 2:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.expired", locale)));
            break;
        case 3:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.full.exceeded", locale)));
            break;
        case 4:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError", getText("logon.err.license.invalid",
                    new String[] { ApplicationBean.getIpNumbersString() }, locale)));
            break;
        case 7:
            haveLicenseErrors = true;
            errors.add(new LabelValueBean("errLicenseError",
                    getText("logon.err.license.limited.exceeded", locale)));
            break;
        case 8:
            haveLicenseErrors = true;
            errors.add(
                    new LabelValueBean("errLicenseError", getText("logon.err.license.gantt.exceeded", locale)));
            break;
        default:
            break;
        }

        if (haveLicenseErrors == true) {
            mappingEnum = 6;
            result.put("errors", errors);
            result.put("mappingEnum", mappingEnum);
            return result;
        }
    }

    result.put("errors", errors);

    httpSession.setAttribute("DESIGNPATH", personBean.getDesignPath());

    Boolean isMobileDevice = LogoffBL.isThisAMobileDevice(request);
    httpSession.setAttribute("mobile", isMobileDevice);

    LOGGER.debug("Mobile is " + httpSession.getAttribute("mobile"));

    // check for post-login forward
    String forwardUrl = (String) httpSession.getAttribute(Constants.POSTLOGINFORWARD);
    if (forwardUrl != null) {
        LOGGER.debug("Forward URL found :" + forwardUrl);
        mappingEnum = 7;
        result.put("mappingEnum", mappingEnum);
        return result;

    }

    Map ret = new GroovyScriptExecuter().handleEvent(IEventSubscriber.EVENT_POST_USER_LOGGED_IN, new HashMap());
    if (ret.get(BINDING_PARAMS.CONTINUE).equals(Boolean.FALSE)) {
        mappingEnum = 10;
        result.put("mappingEnum", mappingEnum);
        return result;
    }

    String extendedKey = ApplicationBean.getInstance().getExtendedKey();

    if (extendedKey == null || extendedKey.length() < 10) { // no empty keys
        // allowed
        mappingEnum = 18;
        result.put("mappingEnum", mappingEnum);
        return result;

    }

    String firstTime = (String) servletContext.getAttribute("FirstTime");

    result.put("user", personBean);

    if (personBean.getIsSysAdmin() && firstTime != null && firstTime.equals("FT")) {

        servletContext.removeAttribute("FirstTime");
        mappingEnum = 8;
        result.put("mappingEnum", mappingEnum);
        return result;

    } else {
        // Forward control to the specified success URI
        mappingEnum = 9;
        result.put("mappingEnum", mappingEnum);
        return result;
    }
}