Jetty继续处理程序注册

时间:2013-05-23 11:06:10

标签: jetty handler continuations

我正在编写一个servlet,它在现有的java系统(“MyJavaSystem”)上运行命令并将输出写入用户。 执行的命令是异步的,servlet必须将每个结果行返回给客户端。 我正在使用Jetty和Continuation。

这是我的代码:

public class MyServlet extends HttpServlet {
    private static final long timeoutMs = 6000;
    public MyJavaSystem sys;
    Continuation continuation = null;

    public MyServlet (MyJavaSystem a) { sys = a; }

    @Override
    public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException  {
        String commandResult = (String)request.getAttribute("results");
        if (commandResult == null)
        {       
            continuation = ContinuationSupport.getContinuation(request);
            if (continuation.isInitial())
            {
                continuation.setTimeout(timeoutMs);
            }
            if (continuation.isExpired()) 
            {
                response.getWriter().write("Timeout");
                return;
            }       
            if ( request.getParameter("command") != null && ! request.getParameter("command").equals("") ) 
            {
                // Execute command
                sys.execute(request.getParameter("command"));

                // suspend the request
                continuation.suspend();

                // ---- Here I need to register myHandler and myHandler2
            }
        } else {
            // Write command result line to user
            response.getWriter().write(commandResult); 
            continuation.complete();
        }

    }
    // Called by sys every new line in command output
    public void myHandler(String commandOutput)
    {
        if (continuation != null)
        {
            continuation.setAttribute("results",commandOutput);
            continuation.resume();
        }
    }
    // Called by sys when the command is done
    public void myHandler2(String commandOutput)
    {
        if (continuation != null)
        {
            continuation.setAttribute("results",commandOutput);
            continuation.complete();
        }
    }
}

sys.execute()是一个非阻塞调用(由于系统实现),myHandler(),myHandler2()函数将在命令执行期间由外部java sys调用。

如何注册此处理程序? 如果我运行上面的代码我得到:

    FATAL EXCEPTION: Thread-726
    java.lang.IllegalStateException: IDLE, initial 
    at org.eclipse.jetty.server.AsyncContinuation.dispatch(AsyncContinuation.java:427)
    at org.eclipse.jetty.server.AsyncContinuation.resume(AsyncContinuation.java:892) 
    at mypackage.MyServlet.myHandler(MyServlet.java:22)

0 个答案:

没有答案