Example usage for javax.servlet.http HttpSession getAttributeNames

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

Introduction

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

Prototype

public Enumeration<String> getAttributeNames();

Source Link

Document

Returns an Enumeration of String objects containing the names of all the objects bound to this session.

Usage

From source file:org.eclipse.vtp.framework.engine.http.HttpConnector.java

/**
 * invokeProcessEngine./*from   w  ww .j  a  v  a  2s .c o m*/
 * 
 * @param req
 * @param res
 * @param httpSession
 * @param pathInfo
 * @param embeddedInvocation TODO
 * @throws IOException
 * @throws ServletException
 */
private void invokeProcessEngine(HttpServletRequest req, HttpServletResponse res, HttpSession httpSession,
        String pathInfo, Map<Object, Object> variableValues,
        @SuppressWarnings("rawtypes") Map<String, String[]> parameterValues, boolean embeddedInvocation)
        throws IOException, ServletException {
    boolean newSession = false;
    Integer depth = (Integer) httpSession.getAttribute("connector.depth");
    if (depth == null) {
        depth = new Integer(0);
    }
    String prefix = "connector.attributes.";
    String fullPrefix = prefix + depth.intValue() + ".";
    if (embeddedInvocation)
        httpSession.setAttribute(fullPrefix + "fragment", "true");
    Deployment deployment = null;
    String brand = null;
    String entryName = null;
    boolean subdialog = false;
    if (!pathInfo.startsWith(PATH_PREFIX)) {
        System.out.println("invoking process engine for new session: " + pathInfo);
        newSession = true;
        synchronized (this) {
            for (String path : deploymentsByPath.keySet()) {
                System.out.println("Comparing to deployment: " + path);
                if (pathInfo.equals(path) || pathInfo.startsWith(path) && pathInfo.length() > path.length()
                        && pathInfo.charAt(path.length()) == '/') {
                    deployment = deploymentsByPath.get(path);
                    System.out.println("Matching deployment found: " + deployment);
                    brand = req.getParameter("BRAND");
                    if (req.getParameter("SUBDIALOG") != null)
                        subdialog = Boolean.parseBoolean(req.getParameter("SUBDIALOG"));
                    if (pathInfo.length() > path.length() + 1) {
                        entryName = pathInfo.substring(path.length() + 1);
                        System.out.println("Entry point name: " + entryName);
                    }
                    break;
                }
            }
        }
        if (deployment == null) {
            res.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        if (entryName == null) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        pathInfo = NEXT_PATH;
        httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deployment.getProcessID());
    } else if (pathInfo.equals(LOG_PATH)) {
        if (req.getParameter("cmd") != null && req.getParameter("cmd").equals("set")) {
            String level = req.getParameter("level");
            if (level == null || (!level.equalsIgnoreCase("ERROR") && !level.equalsIgnoreCase("WARN")
                    && !level.equalsIgnoreCase("INFO") && !level.equalsIgnoreCase("DEBUG")))
                level = "INFO";
            System.setProperty("org.eclipse.vtp.loglevel", level);
        }
        writeLogging(req, res);
        return;
    } else {
        String deploymentID = (String) httpSession.getAttribute(fullPrefix + DEPLOYMENT_ID);
        synchronized (this) {
            deployment = deploymentsByID.get(deploymentID);
        }
        if (deployment == null) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
    }
    if (subdialog)
        httpSession.setAttribute(fullPrefix + "subdialog", "true");
    if (pathInfo.equals(INDEX_PATH)) {
        writeIndex(res, deployment);
        return;
    }
    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
    if (ServletFileUpload.isMultipartContent(new ServletRequestContext(req))) {
        System.out.println(
                "ServletFileUpload.isMultipartContent(new ServletRequestContext(httpRequest)) is true");
        try {
            List items = upload.parseRequest(req);
            for (int i = 0; i < items.size(); i++) {
                FileItem fui = (FileItem) items.get(i);
                if (fui.isFormField() || "text/plain".equals(fui.getContentType())) {
                    System.out.println("Form Field: " + fui.getFieldName() + " | " + fui.getString());
                    parameterValues.put(fui.getFieldName(), new String[] { fui.getString() });
                } else {
                    File temp = File.createTempFile(Guid.createGUID(), ".tmp");
                    fui.write(temp);
                    parameterValues.put(fui.getFieldName(), new String[] { temp.getAbsolutePath() });
                    fui.delete();
                    System.out.println("File Upload: " + fui.getFieldName());
                    System.out.println("\tTemp file name: " + temp.getAbsolutePath());
                    System.out.println("\tContent Type: " + fui.getContentType());
                    System.out.println("\tSize: " + fui.getSize());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    for (Enumeration e = req.getParameterNames(); e.hasMoreElements();) {
        String key = (String) e.nextElement();
        parameterValues.put(key, req.getParameterValues(key));
    }
    for (String key : parameterValues.keySet()) {
        String[] values = parameterValues.get(key);
        if (values == null || values.length == 0)
            System.out.println(key + " empty");
        else {
            System.out.println(key + " " + values[0]);
            for (int i = 1; i < values.length; i++)
                System.out.println("\t" + values[i]);
        }
    }
    IDocument document = null;
    if (pathInfo.equals(ABORT_PATH))
        document = deployment.abort(httpSession, req, res, prefix, depth.intValue(), variableValues,
                parameterValues);
    else if (pathInfo.equals(NEXT_PATH)) {
        if (brand == null && !newSession)
            document = deployment.next(httpSession, req, res, prefix, depth.intValue(), variableValues,
                    parameterValues);
        else
            document = deployment.start(httpSession, req, res, prefix, depth.intValue(), variableValues,
                    parameterValues, entryName, brand, subdialog);
    } else {
        res.sendError(HttpServletResponse.SC_NOT_FOUND);
        return;
    }
    if (document == null) {
        res.setStatus(HttpServletResponse.SC_NO_CONTENT);
        return;
    } else if (document instanceof ControllerDocument) {
        ControllerDocument cd = (ControllerDocument) document;
        if (cd.getTarget() == null) {
            @SuppressWarnings("unchecked")
            Map<String, Map<String, Object>> outgoing = (Map<String, Map<String, Object>>) httpSession
                    .getAttribute(fullPrefix + "outgoing-data");
            int newDepth = depth.intValue() - 1;
            if (newDepth == 0)
                httpSession.removeAttribute("connector.depth");
            else
                httpSession.setAttribute("connector.depth", new Integer(newDepth));
            String oldFullPrefix = fullPrefix;
            fullPrefix = prefix + newDepth + ".";
            Object[] params = (Object[]) httpSession.getAttribute(fullPrefix + "exitparams");
            if (params != null)
                for (int i = 0; i < params.length; i += 2)
                    parameterValues.put((String) params[i], (String[]) params[i + 1]);
            String[] paramNames = cd.getParameterNames();
            for (int i = 0; i < paramNames.length; ++i)
                parameterValues.put(paramNames[i], cd.getParameterValues(paramNames[i]));
            String[] variableNames = cd.getVariableNames();
            Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length);
            if (outgoing != null) {
                Map<String, Object> map = outgoing.get(cd.getParameterValues("exit")[0]);
                if (map != null) {
                    for (int i = 0; i < variableNames.length; ++i) {
                        Object mapping = map.get(variableNames[i]);
                        if (mapping != null)
                            variables.put(mapping, cd.getVariableValue(variableNames[i]));
                    }
                }
            }
            deployment.end(httpSession, prefix, depth.intValue());
            for (@SuppressWarnings("rawtypes")
            Enumeration e = httpSession.getAttributeNames(); e.hasMoreElements();) {
                String name = (String) e.nextElement();
                if (name.startsWith(oldFullPrefix))
                    httpSession.removeAttribute(name);
            }
            invokeProcessEngine(req, res, httpSession, NEXT_PATH, variables, parameterValues, newDepth > 0);
            return;
        } else {
            String[] paramNames = cd.getParameterNames();
            Object[] params = new Object[paramNames.length * 2];
            for (int i = 0; i < params.length; i += 2) {
                params[i] = paramNames[i / 2];
                params[i + 1] = cd.getParameterValues(paramNames[i / 2]);
            }
            httpSession.setAttribute(fullPrefix + "exitparams", params);
            String[] variableNames = cd.getVariableNames();
            Map<Object, Object> variables = new HashMap<Object, Object>(variableNames.length);
            for (int i = 0; i < variableNames.length; ++i)
                variables.put(variableNames[i], cd.getVariableValue(variableNames[i]));
            httpSession.setAttribute("connector.depth", new Integer(depth.intValue() + 1));
            fullPrefix = prefix + (depth.intValue() + 1) + ".";
            String deploymentId = cd.getTarget().substring(0, cd.getTarget().lastIndexOf('(') - 1);
            String entryPointName = cd.getTarget().substring(cd.getTarget().lastIndexOf('(') + 1,
                    cd.getTarget().length() - 1);
            httpSession.setAttribute(fullPrefix + DEPLOYMENT_ID, deploymentId);
            httpSession.setAttribute(fullPrefix + ENTRY_POINT_NAME, entryPointName);
            Map<String, Map<String, Object>> outgoing = new HashMap<String, Map<String, Object>>();
            String[] outPaths = cd.getOutgoingPaths();
            for (int i = 0; i < outPaths.length; ++i) {
                Map<String, Object> map = new HashMap<String, Object>();
                String[] names = cd.getOutgoingDataNames(outPaths[i]);
                for (int j = 0; j < names.length; ++j)
                    map.put(names[j], cd.getOutgoingDataValue(outPaths[i], names[j]));
                outgoing.put(outPaths[i], map);
            }
            httpSession.setAttribute(fullPrefix + "outgoing-data", outgoing);
            invokeProcessEngine(req, res, httpSession, "/" + deploymentId + "/" + entryPointName, variables,
                    parameterValues, true);
            return;
        }
    }
    res.setStatus(HttpServletResponse.SC_OK);
    if (!document.isCachable())
        res.setHeader("Cache-Control", "max-age=0, no-cache");
    res.setContentType(document.getContentType());
    OutputStream writer = res.getOutputStream();
    try {
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        XMLWriter xmlWriter = new XMLWriter(writer);
        xmlWriter.setCompactElements(true);
        transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult());
        if (reporter.isSeverityEnabled(IReporter.SEVERITY_INFO) && !document.isSecured()) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            xmlWriter = new XMLWriter(baos);
            xmlWriter.setCompactElements(true);
            transformer.transform(document.toXMLSource(), xmlWriter.toXMLResult());
            System.out.println(new String(baos.toByteArray(), "UTF-8"));
        }
    } catch (TransformerException e) {
        throw new ServletException(e);
    }
    writer.flush();
    writer.close();
}

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;//from   w ww  .j  a v  a2s.  co  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();

}