Example usage for javax.servlet.http HttpSession setMaxInactiveInterval

List of usage examples for javax.servlet.http HttpSession setMaxInactiveInterval

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession setMaxInactiveInterval.

Prototype

public void setMaxInactiveInterval(int interval);

Source Link

Document

Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

Usage

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 a2s .  c  o  m*/
 * <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:com.aurel.track.prop.LoginBL.java

/**
 *
 * @param username//  www . ja va  2 s .co  m
 * @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;
    }
}

From source file:org.kchine.r.server.http.frontend.CommandServlet.java

protected void doAny(final HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    HttpSession session = null;
    Object result = null;//  ww w . ja  v  a  2  s.c o  m

    try {
        final String command = request.getParameter("method");
        do {

            if (command.equals("ping")) {
                result = "pong";
                break;
            } else if (command.equals("logon")) {

                session = request.getSession(false);
                if (session != null) {
                    result = session.getId();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                boolean namedAccessMode = login.contains("@@");
                String sname = null;
                if (namedAccessMode) {
                    sname = login.substring(login.indexOf("@@") + "@@".length());
                    login = login.substring(0, login.indexOf("@@"));
                }

                System.out.println("login :" + login);
                System.out.println("pwd :" + pwd);

                if (_rkit == null && (!login.equals(System.getProperty("login"))
                        || !pwd.equals(System.getProperty("pwd")))) {
                    result = new BadLoginPasswordException();
                    break;
                }

                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                RPFSessionInfo.get().put("LOGIN", login);
                RPFSessionInfo.get().put("REMOTE_ADDR", request.getRemoteAddr());
                RPFSessionInfo.get().put("REMOTE_HOST", request.getRemoteHost());

                boolean nopool = !options.keySet().contains("nopool")
                        || ((String) options.get("nopool")).equals("")
                        || !((String) options.get("nopool")).equalsIgnoreCase("false");
                boolean save = options.keySet().contains("save")
                        && ((String) options.get("save")).equalsIgnoreCase("true");
                boolean selfish = options.keySet().contains("selfish")
                        && ((String) options.get("selfish")).equalsIgnoreCase("true");

                String privateName = (String) options.get("privatename");

                int memoryMin = DEFAULT_MEMORY_MIN;
                int memoryMax = DEFAULT_MEMORY_MAX;
                try {
                    if (options.get("memorymin") != null)
                        memoryMin = Integer.decode((String) options.get("memorymin"));
                    if (options.get("memorymax") != null)
                        memoryMax = Integer.decode((String) options.get("memorymax"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                boolean privateEngineMode = false;
                RServices r = null;
                URL[] codeUrls = null;

                if (_rkit == null) {

                    if (namedAccessMode) {

                        try {
                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    r = (RServices) ((DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                            System.getProperty("submit.ssh.host"),
                                            Integer.decode(System.getProperty("submit.ssh.port")),
                                            System.getProperty("submit.ssh.user"),
                                            System.getProperty("submit.ssh.password"),
                                            System.getProperty("submit.ssh.biocep.home"),
                                            "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                            "db", new Class<?>[] { DBLayerInterface.class })).lookup(sname);
                                }

                            } else {

                                if (PoolUtils.isStubCandidate(sname)) {
                                    r = (RServices) PoolUtils.hexToStub(sname,
                                            PoolUtils.class.getClassLoader());
                                } else {
                                    ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    if (spFactory == null) {
                                        result = new NoRegistryAvailableException();
                                        break;
                                    }
                                    r = (RServices) spFactory.getServantProvider().getRegistry().lookup(sname);
                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
                        if (nopool) {

                            /*                         
                            ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                                    
                            if (spFactory == null) {
                               result = new NoRegistryAvailableException();
                               break;
                            }
                                    
                            String nodeName = options.keySet().contains("node") ? (String) options.get("node") : System
                                  .getProperty("private.servant.node.name");
                            Registry registry = spFactory.getServantProvider().getRegistry();
                            NodeManager nm = null;
                            try {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name") + "_" + nodeName);
                            } catch (NotBoundException nbe) {
                               nm = (NodeManager) registry.lookup(System.getProperty("node.manager.name"));
                            } catch (Exception e) {
                               result = new NoNodeManagerFound();
                               break;
                            }
                            r = (RServices) nm.createPrivateServant(nodeName);
                             */

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                DBLayerInterface dbLayer = (DBLayerInterface) SSHTunnelingProxy.getDynamicProxy(
                                        System.getProperty("submit.ssh.host"),
                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                        System.getProperty("submit.ssh.user"),
                                        System.getProperty("submit.ssh.password"),
                                        System.getProperty("submit.ssh.biocep.home"),
                                        "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                        "db", new Class<?>[] { DBLayerInterface.class });
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) dbLayer.lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {

                                    final String uid = (privateName != null && !privateName.equals(""))
                                            ? privateName
                                            : UUID.randomUUID().toString();
                                    final String[] jobIdHolder = new String[1];
                                    new Thread(new Runnable() {
                                        public void run() {
                                            try {

                                                String command = "java -Dlog.file="
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/log/%{uid}.log" + " -Drmi.port.start="
                                                        + System.getProperty("submit.ssh.rmi.port.start")
                                                        + " -Dname=%{uid}" + " -Dnaming.mode=db" + " -Ddb.host="
                                                        + System.getProperty("submit.ssh.host") + " -Dwait=true"
                                                        + " -jar "
                                                        + System.getProperty("submit.ssh.biocep.home")
                                                        + "/biocep-core.jar";

                                                jobIdHolder[0] = SSHUtils.execSshBatch(command, uid,
                                                        System.getProperty("submit.ssh.prefix"),
                                                        System.getProperty("submit.ssh.host"),
                                                        Integer.decode(System.getProperty("submit.ssh.port")),
                                                        System.getProperty("submit.ssh.user"),
                                                        System.getProperty("submit.ssh.password"),
                                                        System.getProperty("submit.ssh.biocep.home"));
                                                System.out.println("jobId:" + jobIdHolder[0]);

                                            } catch (Exception e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }).start();

                                    long TIMEOUT = Long.decode(System.getProperty("submit.ssh.timeout"));
                                    long tStart = System.currentTimeMillis();
                                    while ((System.currentTimeMillis() - tStart) < TIMEOUT) {
                                        try {
                                            r = (RServices) dbLayer.lookup(uid);
                                        } catch (Exception e) {

                                        }
                                        if (r != null)
                                            break;
                                        try {
                                            Thread.sleep(10);
                                        } catch (Exception e) {
                                        }
                                    }

                                    if (r != null) {
                                        try {
                                            r.setJobId(jobIdHolder[0]);
                                        } catch (Exception e) {
                                            r = null;
                                        }
                                    }

                                }

                            } else {
                                System.out.println("LocalHttpServer.getLocalHttpServerPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                System.out.println("LocalRmiRegistry.getLocalRmiRegistryPort():"
                                        + LocalHttpServer.getLocalHttpServerPort());
                                if (privateName != null && !privateName.equals("")) {
                                    try {
                                        r = (RServices) LocalRmiRegistry.getInstance().lookup(privateName);
                                    } catch (Exception e) {
                                        //e.printStackTrace();
                                    }
                                }

                                if (r == null) {
                                    codeUrls = (URL[]) options.get("urls");
                                    System.out.println("CODE URL->" + Arrays.toString(codeUrls));
                                    //String 
                                    r = ServerManager.createR(System.getProperty("r.binary"), false, false,
                                            PoolUtils.getHostIp(), LocalHttpServer.getLocalHttpServerPort(),
                                            ServerManager.getRegistryNamingInfo(PoolUtils.getHostIp(),
                                                    LocalRmiRegistry.getLocalRmiRegistryPort()),
                                            memoryMin, memoryMax, privateName, false, codeUrls, null,
                                            (_webAppMode ? "javaws" : "standard"), null, "127.0.0.1");
                                }

                                privateEngineMode = true;
                            }

                        } else {

                            if (System.getProperty("submit.mode") != null
                                    && System.getProperty("submit.mode").equals("ssh")) {

                                ServantProvider servantProvider = (ServantProvider) SSHTunnelingProxy
                                        .getDynamicProxy(System.getProperty("submit.ssh.host"),
                                                Integer.decode(System.getProperty("submit.ssh.port")),
                                                System.getProperty("submit.ssh.user"),
                                                System.getProperty("submit.ssh.password"),
                                                System.getProperty("submit.ssh.biocep.home"),
                                                "java -Dpools.provider.factory=org.kchine.rpf.db.ServantsProviderFactoryDB -Dpools.dbmode.defaultpoolname=R -Dpools.dbmode.shutdownhook.enabled=false -cp %{install.dir}/biocep-core.jar org.kchine.rpf.SSHTunnelingWorker %{file}",
                                                "servant.provider", new Class<?>[] { ServantProvider.class });
                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxy()
                                            : servantProvider.borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? servantProvider.borrowServantProxyNoWait()
                                            : servantProvider.borrowServantProxyNoWait(poolname));
                                }

                                System.out.println("---> borrowed : " + r);

                            } else {
                                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();

                                if (spFactory == null) {
                                    result = new NoRegistryAvailableException();
                                    break;
                                }

                                boolean wait = options.keySet().contains("wait")
                                        && ((String) options.get("wait")).equalsIgnoreCase("true");
                                String poolname = ((String) options.get("poolname"));
                                if (wait) {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxy()
                                            : spFactory.getServantProvider().borrowServantProxy(poolname));
                                } else {
                                    r = (RServices) (poolname == null || poolname.trim().equals("")
                                            ? spFactory.getServantProvider().borrowServantProxyNoWait()
                                            : spFactory.getServantProvider()
                                                    .borrowServantProxyNoWait(poolname));
                                }
                            }
                        }
                    }
                } else {
                    r = _rkit.getR();
                }

                if (r == null) {
                    result = new NoServantAvailableException();
                    break;
                }

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "RS");
                session.setAttribute("R", r);
                session.setAttribute("NOPOOL", nopool);
                session.setAttribute("SAVE", save);
                session.setAttribute("LOGIN", login);
                session.setAttribute("NAMED_ACCESS_MODE", namedAccessMode);
                session.setAttribute("PROCESS_ID", r.getProcessId());
                session.setAttribute("JOB_ID", r.getJobId());
                session.setAttribute("SELFISH", selfish);
                session.setAttribute("IS_RELAY", _rkit != null);

                if (privateName != null)
                    session.setAttribute("PRIVATE_NAME", privateName);

                if (codeUrls != null && codeUrls.length > 0) {
                    session.setAttribute("CODEURLS", codeUrls);
                }

                session.setAttribute("THREADS", new ThreadsHolder());

                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                Vector<HttpSession> sessionVector = ((HashMap<RServices, Vector<HttpSession>>) getServletContext()
                        .getAttribute("R_SESSIONS")).get(r);
                if (sessionVector == null) {
                    sessionVector = new Vector<HttpSession>();
                    ((HashMap<RServices, Vector<HttpSession>>) getServletContext().getAttribute("R_SESSIONS"))
                            .put(r, sessionVector);
                }

                sessionVector.add(session);

                if (_rkit == null && save) {
                    UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"), r);
                }

                System.out.println("---> Has Collaboration Listeners:" + r.hasRCollaborationListeners());
                if (selfish || !r.hasRCollaborationListeners()) {
                    try {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                        GDDevice[] devices = r.listDevices();
                        for (int i = 0; i < devices.length; ++i) {
                            String deviceName = devices[i].getId();
                            System.out.println("??? ---- deviceName=" + deviceName);
                            session.setAttribute(deviceName, devices[i]);
                        }

                    } finally {
                        if (_rkit != null && _safeModeEnabled)
                            ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                    }
                }

                if (privateEngineMode) {

                    if (options.get("newdevice") != null) {
                        GDDevice deviceProxy = null;
                        GDDevice[] dlist = r.listDevices();
                        if (dlist == null || dlist.length == 0) {
                            deviceProxy = r.newDevice(480, 480);
                        } else {
                            deviceProxy = dlist[0];
                        }
                        String deviceName = deviceProxy.getId();
                        session.setAttribute(deviceName, deviceProxy);
                        session.setAttribute("maindevice", deviceProxy);
                        saveSessionAttributes(session);
                    }

                    if (options.get("newgenericcallbackdevice") != null) {
                        GenericCallbackDevice genericCallBackDevice = null;
                        GenericCallbackDevice[] clist = r.listGenericCallbackDevices();
                        if (clist == null || clist.length == 0) {
                            genericCallBackDevice = r.newGenericCallbackDevice();
                        } else {
                            genericCallBackDevice = clist[0];
                        }
                        String genericCallBackDeviceName = genericCallBackDevice.getId();
                        session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                        session.setAttribute("maingenericcallbackdevice", genericCallBackDevice);
                        saveSessionAttributes(session);
                    }

                }

                result = session.getId();

                break;

            } else if (command.equals("logondb")) {

                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }

                String login = (String) PoolUtils.hexToObject(request.getParameter("login"));
                String pwd = (String) PoolUtils.hexToObject(request.getParameter("pwd"));
                HashMap<String, Object> options = (HashMap<String, Object>) PoolUtils
                        .hexToObject(request.getParameter("options"));
                if (options == null)
                    options = new HashMap<String, Object>();
                System.out.println("options:" + options);

                session = request.getSession(true);

                Integer sessionTimeOut = null;
                try {
                    if (options.get("sessiontimeout") != null)
                        sessionTimeOut = Integer.decode((String) options.get("sessiontimeout"));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                if (sessionTimeOut != null) {
                    session.setMaxInactiveInterval(sessionTimeOut);
                }

                session.setAttribute("TYPE", "DBS");
                session.setAttribute("REGISTRY", (DBLayer) spFactory.getServantProvider().getRegistry());
                session.setAttribute("SUPERVISOR",
                        new SupervisorUtils((DBLayer) spFactory.getServantProvider().getRegistry()));
                session.setAttribute("THREADS", new ThreadsHolder());
                ((HashMap<String, HttpSession>) getServletContext().getAttribute("SESSIONS_MAP"))
                        .put(session.getId(), session);
                saveSessionAttributes(session);

                result = session.getId();

                break;

            }

            session = request.getSession(false);
            if (session == null) {
                result = new NotLoggedInException();
                break;
            }

            if (command.equals("logoff")) {

                if (session.getAttribute("TYPE").equals("RS")) {
                    if (_rkit != null) {
                        /*
                        Enumeration<String> attributeNames = session.getAttributeNames();
                        while (attributeNames.hasMoreElements()) {
                           String aname = attributeNames.nextElement();
                           if (session.getAttribute(aname) instanceof GDDevice) {
                              try {
                                 _rkit.getRLock().lock();
                                 ((GDDevice) session.getAttribute(aname)).dispose();
                              } catch (Exception e) {
                                 e.printStackTrace();
                              } finally {
                                 _rkit.getRLock().unlock();
                              }
                           }
                        }
                        */
                    }
                }

                try {

                    session.invalidate();

                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                result = null;
                break;
            }

            final boolean[] stop = { false };
            final HttpSession currentSession = session;

            if (command.equals("invoke")) {

                String servantName = (String) PoolUtils.hexToObject(request.getParameter("servantname"));
                final Object servant = session.getAttribute(servantName);
                if (servant == null) {
                    throw new Exception("Bad Servant Name :" + servantName);
                }
                String methodName = (String) PoolUtils.hexToObject(request.getParameter("methodname"));

                ClassLoader urlClassLoader = this.getClass().getClassLoader();
                if (session.getAttribute("CODEURLS") != null) {
                    urlClassLoader = new URLClassLoader((URL[]) session.getAttribute("CODEURLS"),
                            this.getClass().getClassLoader());
                }

                Class<?>[] methodSignature = (Class[]) PoolUtils
                        .hexToObject(request.getParameter("methodsignature"));

                final Method m = servant.getClass().getMethod(methodName, methodSignature);
                if (m == null) {
                    throw new Exception("Bad Method Name :" + methodName);
                }
                final Object[] methodParams = (Object[]) PoolUtils
                        .hexToObject(request.getParameter("methodparameters"), urlClassLoader);
                final Object[] resultHolder = new Object[1];
                Runnable rmiRunnable = new Runnable() {
                    public void run() {
                        try {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                            resultHolder[0] = m.invoke(servant, methodParams);
                            if (resultHolder[0] == null)
                                resultHolder[0] = RMICALL_DONE;
                        } catch (InvocationTargetException ite) {
                            if (ite.getCause() instanceof ConnectException) {
                                currentSession.invalidate();
                                resultHolder[0] = new NotLoggedInException();
                            } else {
                                resultHolder[0] = ite.getCause();
                            }
                        } catch (Exception e) {
                            final boolean wasInterrupted = Thread.interrupted();
                            if (wasInterrupted) {
                                resultHolder[0] = new RmiCallInterrupted();
                            } else {
                                resultHolder[0] = e;
                            }
                        } finally {
                            if (_rkit != null && _safeModeEnabled)
                                ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                        }
                    }
                };

                Thread rmiThread = InterruptibleRMIThreadFactory.getInstance().newThread(rmiRunnable);
                ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().add(rmiThread);
                rmiThread.start();

                long t1 = System.currentTimeMillis();

                while (resultHolder[0] == null) {

                    if ((System.currentTimeMillis() - t1) > RMICALL_TIMEOUT_MILLISEC || stop[0]) {
                        rmiThread.interrupt();
                        resultHolder[0] = new RmiCallTimeout();
                        break;
                    }

                    try {
                        Thread.sleep(10);
                    } catch (Exception e) {
                    }
                }
                try {
                    ((ThreadsHolder) session.getAttribute("THREADS")).getThreads().remove(rmiThread);
                } catch (IllegalStateException e) {
                }

                if (resultHolder[0] instanceof Throwable) {
                    throw (Throwable) resultHolder[0];
                }

                if (resultHolder[0] == RMICALL_DONE) {
                    result = null;
                } else {
                    result = resultHolder[0];
                }

                break;

            }

            if (command.equals("interrupt")) {
                final Vector<Thread> tvec = (Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS"))
                        .getThreads().clone();
                for (int i = 0; i < tvec.size(); ++i) {
                    try {
                        tvec.elementAt(i).interrupt();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                stop[0] = true;
                ((Vector<Thread>) ((ThreadsHolder) session.getAttribute("THREADS")).getThreads())
                        .removeAllElements();
                result = null;
                break;
            } else if (command.equals("saveimage")) {
                UserUtils.saveWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("loadimage")) {
                UserUtils.loadWorkspace((String) session.getAttribute("LOGIN"),
                        (RServices) session.getAttribute("R"));
                result = null;
                break;
            } else if (command.equals("newdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    boolean broadcasted = new Boolean(request.getParameter("broadcasted"));
                    GDDevice deviceProxy = null;
                    if (broadcasted) {
                        deviceProxy = ((RServices) session.getAttribute("R")).newBroadcastedDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    } else {
                        deviceProxy = ((RServices) session.getAttribute("R")).newDevice(
                                Integer.decode(request.getParameter("width")),
                                Integer.decode(request.getParameter("height")));
                    }

                    String deviceName = deviceProxy.getId();
                    System.out.println("deviceName=" + deviceName);
                    session.setAttribute(deviceName, deviceProxy);
                    saveSessionAttributes(session);
                    result = deviceName;
                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("listdevices")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();

                    result = new Vector<String>();
                    for (Enumeration<String> e = session.getAttributeNames(); e.hasMoreElements();) {
                        String attributeName = e.nextElement();
                        if (attributeName.startsWith("device_")) {
                            ((Vector<String>) result).add(attributeName);
                        }
                    }

                    break;

                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newgenericcallbackdevice")) {
                try {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawLock();
                    GenericCallbackDevice genericCallBackDevice = ((RServices) session.getAttribute("R"))
                            .newGenericCallbackDevice();

                    String genericCallBackDeviceName = genericCallBackDevice.getId();
                    session.setAttribute(genericCallBackDeviceName, genericCallBackDevice);
                    saveSessionAttributes(session);

                    result = genericCallBackDeviceName;

                    break;
                } finally {
                    if (_rkit != null && _safeModeEnabled)
                        ((ExtendedReentrantLock) _rkit.getRLock()).rawUnlock();
                }
            } else if (command.equals("newspreadsheetmodeldevice")) {

                String spreadsheetModelDeviceId = request.getParameter("id");
                SpreadsheetModelRemote model = null;

                if (spreadsheetModelDeviceId == null || spreadsheetModelDeviceId.equals("")) {
                    model = ((RServices) session.getAttribute("R")).newSpreadsheetTableModelRemote(
                            Integer.decode(request.getParameter("rowcount")),
                            Integer.decode(request.getParameter("colcount")));
                } else {
                    model = ((RServices) session.getAttribute("R"))
                            .getSpreadsheetTableModelRemote(spreadsheetModelDeviceId);
                }

                SpreadsheetModelDevice spreadsheetDevice = model.newSpreadsheetModelDevice();
                String spreadsheetDeviceId = spreadsheetDevice.getId();
                session.setAttribute(spreadsheetDeviceId, spreadsheetDevice);
                saveSessionAttributes(session);
                result = spreadsheetDeviceId;
                break;

            } else if (command.equals("list")) {
                ServantProviderFactory spFactory = ServantProviderFactory.getFactory();
                if (spFactory == null) {
                    result = new NoRegistryAvailableException();
                    break;
                }
                result = spFactory.getServantProvider().getRegistry().list();
                break;
            }

        } while (true);

    } catch (TunnelingException te) {
        result = te;
        te.printStackTrace();
    } catch (Throwable e) {
        result = new TunnelingException("Server Side", e);
        e.printStackTrace();
    }
    response.setContentType("application/x-java-serialized-object");
    new ObjectOutputStream(response.getOutputStream()).writeObject(result);
    response.flushBuffer();

}