Package org.mortbay.util.ajax

Examples of org.mortbay.util.ajax.Continuation


    private static final long serialVersionUID = 1L;

    public String sayHello(String sender)
    {       
        HttpServletRequest request = getThreadLocalRequest();
        Continuation continuation = ContinuationSupport.getContinuation(request, null);
        if(continuation.isNew() || !continuation.isPending())
        {
            request.setAttribute("ts", Long.valueOf(System.currentTimeMillis()));
            continuation.suspend(5000);       
        }
        long elapsed = System.currentTimeMillis() - ((Long)request.getAttribute("ts")).longValue();
        return "Hello world *" + sender + "* resumed after " + elapsed + " ms";
    }   
View Full Code Here


        }
        else
        {
            final InputStream in=request.getInputStream();
            final OutputStream out=response.getOutputStream();
            final Continuation continuation = ContinuationSupport.getContinuation(request,request);


            if (!continuation.isPending())
            {
                final byte[] buffer = new byte[4096]; // TODO avoid this!
                String uri=request.getRequestURI();
                if (request.getQueryString()!=null)
                    uri+="?"+request.getQueryString();

                HttpURI url=proxyHttpURI(request.getScheme(),
                        request.getServerName(),
                        request.getServerPort(),
                        uri);
               
                if (url==null)
                {
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }

                HttpExchange exchange = new HttpExchange()
                {

                    protected void onRequestCommitted() throws IOException
                    {
                    }

                    protected void onRequestComplete() throws IOException
                    {
                    }

                    protected void onResponseComplete() throws IOException
                    {
                        continuation.resume();
                    }

                    protected void onResponseContent(Buffer content) throws IOException
                    {
                        // TODO Avoid this copy
                        while (content.hasContent())
                        {
                            int len=content.get(buffer,0,buffer.length);
                            out.write(buffer,0,len)// May block here for a little bit!
                        }
                    }

                    protected void onResponseHeaderComplete() throws IOException
                    {
                    }

                    protected void onResponseStatus(Buffer version, int status, Buffer reason) throws IOException
                    {
                        if (reason!=null && reason.length()>0)
                            response.setStatus(status,reason.toString());
                        else
                            response.setStatus(status);

                    }

                    protected void onResponseHeader(Buffer name, Buffer value) throws IOException
                    {
                        String s = name.toString().toLowerCase();
                        if (!_DontProxyHeaders.contains(s))
                            response.addHeader(name.toString(),value.toString());
                    }

                };
               
                exchange.setVersion(request.getProtocol());
                exchange.setMethod(request.getMethod());
               
                exchange.setURL(url.toString());
               
                // check connection header
                String connectionHdr = request.getHeader("Connection");
                if (connectionHdr!=null)
                {
                    connectionHdr=connectionHdr.toLowerCase();
                    if (connectionHdr.indexOf("keep-alive")<&&
                            connectionHdr.indexOf("close")<0)
                        connectionHdr=null;
                }

                // copy headers
                boolean xForwardedFor=false;
                boolean hasContent=false;
                long contentLength=-1;
                Enumeration enm = request.getHeaderNames();
                while (enm.hasMoreElements())
                {
                    // TODO could be better than this!
                    String hdr=(String)enm.nextElement();
                    String lhdr=hdr.toLowerCase();

                    if (_DontProxyHeaders.contains(lhdr))
                        continue;
                    if (connectionHdr!=null && connectionHdr.indexOf(lhdr)>=0)
                        continue;

                    if ("content-type".equals(lhdr))
                        hasContent=true;
                    if ("content-length".equals(lhdr))
                        contentLength=request.getContentLength();

                    Enumeration vals = request.getHeaders(hdr);
                    while (vals.hasMoreElements())
                    {
                        String val = (String)vals.nextElement();
                        if (val!=null)
                        {
                            exchange.setRequestHeader(lhdr,val);
                            xForwardedFor|="X-Forwarded-For".equalsIgnoreCase(hdr);
                        }
                    }
                }

                // Proxy headers
                exchange.setRequestHeader("Via","1.1 (jetty)");
                if (!xForwardedFor)
                    exchange.addRequestHeader("X-Forwarded-For",
                            request.getRemoteAddr());

                if (hasContent)
                    exchange.setRequestContentSource(in);

                _client.send(exchange);

                continuation.suspend(30000);
            }
        }
    }
View Full Code Here

    /* ------------------------------------------------------------ */
    public void setContinuation(Continuation continuation)
    {
        synchronized (this)
        {
            Continuation oldContinuation = _continuation;
            _continuation = continuation;
            Log.debug("Old continuation {}, new continuation {}", oldContinuation, continuation);

            // There can be a suspended old continuation if the remote client reloads or
            // somehow re-issues a new long poll request with an outstanding long poll request.
            // In this case we resume() the existing continuation, otherwise
            // it will expire, this method is entered again with a null argument, and a timeout
            // to expire this client will be scheduled (which is wrong because client expiration
            // must be handled by the new continuation and not by the old one, which dies here)
            if (oldContinuation != null && oldContinuation.isPending())
            {
                try
                {
                    int responseCode = HttpServletResponse.SC_REQUEST_TIMEOUT;
                    Log.debug("Sending {} on old continuation {}", responseCode, oldContinuation);
                    HttpServletResponse response = (HttpServletResponse)oldContinuation.getObject();
                    response.sendError(responseCode);
                }
                catch(Exception x)
                {
                    Log.ignore(x);
                }

                try
                {
                    Log.debug("Resuming old continuation {}", oldContinuation);
                    // The response is committed so this resume() will be blocked by ContinuationCometdServlet
                    oldContinuation.resume();
                }
                catch (Exception x)
                {
                    Log.ignore(x);
                }
View Full Code Here

                }

                setCurrentConnection(this);
                long io = 0;

                Continuation continuation = _request.getContinuation();
                if (continuation != null && continuation.isPending())
                {
                    Log.debug("resume continuation {}",continuation);
                    if (_request.getMethod() == null)
                        throw new IllegalStateException();
                    handleRequest();
                }
                else
                {
                    // If we are not ended then parse available
                    if (!_parser.isComplete())
                        io = _parser.parseAvailable();

                    // Do we have more generating to do?
                    // Loop here because some writes may take multiple steps and
                    // we need to flush them all before potentially blocking in
                    // the
                    // next loop.
                    while (_generator.isCommitted() && !_generator.isComplete())
                    {
                        long written = _generator.flush();
                        io += written;
                        if (written <= 0)
                            break;
                        if (_endp.isBufferingOutput())
                            _endp.flush();
                    }

                    // Flush buffers
                    if (_endp.isBufferingOutput())
                    {
                        _endp.flush();
                        if (!_endp.isBufferingOutput())
                            no_progress = 0;
                    }

                    if (io > 0)
                        no_progress = 0;
                    else if (no_progress++ >= 2)
                        return;
                }
            }
            catch (HttpException e)
            {
                if (Log.isDebugEnabled())
                {
                    Log.debug("uri=" + _uri);
                    Log.debug("fields=" + _requestFields);
                    Log.debug(e);
                }
                _generator.sendError(e.getStatus(),e.getReason(),null,true);

                _parser.reset(true);
                _endp.close();
                throw e;
            }
            finally
            {
                setCurrentConnection(null);

                more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();

                synchronized (this)
                {
                    _handling = false;

                    if (_destroy)
                    {
                        destroy();
                        return;
                    }
                }

                if (_parser.isComplete() && _generator.isComplete() && !_endp.isBufferingOutput())
                {
                    if (!_generator.isPersistent())
                    {
                        _parser.reset(true);
                        more_in_buffer = false;
                    }

                    if (more_in_buffer)
                    {
                        reset(false);
                        more_in_buffer = _parser.isMoreInBuffer() || _endp.isBufferingInput();
                    }
                    else
                        reset(true);

                    no_progress = 0;
                }

                Continuation continuation = _request.getContinuation();
                if (continuation != null && continuation.isPending())
                {
                    break;
                }
                else if (_generator.isCommitted() && !_generator.isComplete() && _endp instanceof SelectChannelEndPoint) // TODO
                                                                                                                         // remove
View Full Code Here

            return;
        }
       
        if (request.getParameter("continue")!=null)
        {
            Continuation continuation = ContinuationSupport.getContinuation(request, null);
            continuation.suspend(Long.parseLong(request.getParameter("continue")));
        }
       
        base_request.setHandled(true);
        response.setHeader(HttpHeaders.CONTENT_TYPE,MimeTypes.TEXT_HTML);
       
View Full Code Here

            if (request.getParameter("resume")!=null)
                resume_after=Integer.parseInt(request.getParameter("resume"));
            if (request.getParameter("complete")!=null)
                complete_after=Integer.parseInt(request.getParameter("complete"));
           
            final Continuation continuation = ContinuationSupport.getContinuation(request,this);
            if (!(continuation.isPending() || continuation.isResumed()))
            {
                if (read_before>0)
                {
                    byte[] buf=new byte[read_before];
                    request.getInputStream().read(buf);
                }
                else if (read_before<0)
                {
                    InputStream in = request.getInputStream();
                    int b=in.read();
                    while(b!=-1)
                        b=in.read();
                }

                if (suspend_for>=0)
                {
                    try
                    {
                        if (suspend_for>0)
                            continuation.suspend(suspend_for);
                        else
                            continuation.suspend(100L);
                    }
                    finally
                    {

                        if (complete_after>0)
                        {
                            TimerTask complete = new TimerTask()
                            {
                                public void run()
                                {
                                    try
                                    {
                                        response.setStatus(200);
                                        response.getOutputStream().print("COMPLETED");
                                        response.flushBuffer();
                                        continuation.resume();
                                    }
                                    catch(Exception e)
                                    {
                                        e.printStackTrace();
                                    }
                                }
                            };
                            synchronized (_timer)
                            {
                                _timer.schedule(complete,complete_after);
                            }
                        }
                        else if (complete_after==0)
                        {
                            response.setStatus(200);
                            response.getOutputStream().print("COMPLETED");
                            response.flushBuffer();
                            continuation.resume();
                        }
                       
                        if (resume_after>0)
                        {
                            TimerTask resume = new TimerTask()
                            {
                                public void run()
                                {
                                    continuation.resume();
                                }
                            };
                            synchronized (_timer)
                            {
                                _timer.schedule(resume,resume_after);
                            }
                        }
                        else if (resume_after==0)
                        {
                            continuation.resume();
                        }
                    }
                }
                else if (sleep_for>=0)
                {
                    try
                    {
                        Thread.sleep(sleep_for);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    response.setStatus(200);
                    response.getOutputStream().print("SLEPT");
                    base_request.setHandled(true);
                    return;
                }
                else
                {
                    response.setStatus(200);
                    response.getOutputStream().print("NORMAL");
                    base_request.setHandled(true);
                    return;
                }
               
               
               
            }
            else if (response.isCommitted())
            {
                base_request.setHandled(true);
            }
            else if (continuation.isResumed())
            {
                response.setStatus(200);
                response.getOutputStream().print("RESUMED");
                base_request.setHandled(true);
            }
View Full Code Here

                default:
                {
                    // insert a delay before throttling the request
                    if (_insertHeaders)
                        ((HttpServletResponse)response).addHeader("DoSFilter","delayed");
                    Continuation continuation = ContinuationSupport.getContinuation((HttpServletRequest)request,this);
                    request.setAttribute(__TRACKER,tracker);
                    continuation.suspend(_delayMs);
                    // can fall through if this was a waiting continuation
                }
            }
        }

        // Throttle the request
        boolean accepted = false;
        try
        {
            // check if we can afford to accept another request at this time
            accepted = _passes.tryAcquire(_waitMs,TimeUnit.MILLISECONDS);

            if (!accepted)
            {
                // we were not accepted, so either we suspend to wait,or if we were woken up we insist or we fail

                final Continuation continuation = ContinuationSupport.getContinuation((HttpServletRequest)request,this);
               
                Boolean throttled = (Boolean)request.getAttribute(__THROTTLED);
                if (throttled!=Boolean.TRUE && _throttleMs>0)
                {
                    int priority = getPriority(request,tracker);
                    request.setAttribute(__THROTTLED,Boolean.TRUE);
                    if (_insertHeaders)
                        ((HttpServletResponse)response).addHeader("DoSFilter","throttled");
                    synchronized (this)
                    {
                        _queue[priority].add(continuation);
                        continuation.reset();
                        if(continuation.suspend(_throttleMs))
                        {
                            // handle waiting continuation strangeness
                            // continuation was waiting and was resumed.
                            _passes.acquire();
                            accepted = true;
                        }
                        // can fall through if this was a waiting continuation
                    }
                }
                // else were we resumed?
                else if (continuation.isResumed())
                {
                    // we were resumed and somebody stole our pass, so we wait for the next one.
                    _passes.acquire();
                    accepted = true;
                }
            }
           
            // if we were accepted (either immediately or after throttle)
            if (accepted)      
                // call the chain
                doFilterChain(filterchain,srequest,sresponse);
            else               
            {
                // fail the request
                if (_insertHeaders)
                    ((HttpServletResponse)response).addHeader("DoSFilter","unavailable");
                ((HttpServletResponse)response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            }
        }
        catch (InterruptedException e)
        {
            _context.log("DoS",e);
            ((HttpServletResponse)response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
        finally
        {
            if (accepted)
            {
                // wake up the next highest priority request.
                synchronized (_queue)
                {
                    for (int p = _queue.length; p-- > 0;)
                    {
                        Continuation continuation = _queue[p].poll();

                        if (continuation != null)
                        {
                            continuation.resume();
                            break;
                        }
                    }
                }
                _passes.release();
View Full Code Here

                {
                    request.setAttribute(_suspended,Boolean.FALSE);
                }
                else
                {
                    Continuation continuation =  ContinuationSupport.getContinuation((HttpServletRequest)request,_queue);
                    int priority = getPriority(request);
                    suspended=Boolean.TRUE;
                    request.setAttribute(_suspended,suspended);
                    synchronized (_queue)
                    {
                        _queue[priority].add(continuation);
                        continuation.suspend(_suspendMs);
                        // may fall through here if waiting continuation
                    }
                }
            }
            
            if (suspended!=null && suspended.booleanValue())
            {
                request.setAttribute(_suspended,Boolean.FALSE);
                Continuation continuation =  ContinuationSupport.getContinuation((HttpServletRequest)request,_queue);
                if (continuation.isResumed())
                {
                    _passes.acquire();
                    accepted = true;
                }
                else
                {
                    // Timeout! try 1 more time.
                    accepted = _passes.tryAcquire(_waitMs,TimeUnit.MILLISECONDS);
                }
            }
            else if (!accepted)
            {
                // pass through resume of previously accepted request
                _passes.acquire();
                accepted = true;
            }

            if (accepted)
            {
                chain.doFilter(request,response);
            }
            else
                ((HttpServletResponse)response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
           
        }
        catch (InterruptedException e)
        {
            _context.log("QoS",e);
            ((HttpServletResponse)response).sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
        }
        finally
        {
            if (accepted)
            {
                synchronized (_queue)
                {
                    for (int p = _queue.length; p-- > 0;)
                    {
                        Continuation continuation = _queue[p].poll();
                        if (continuation != null)
                        {
                            continuation.resume();
                            break;
                        }
                    }
                }
                _passes.release();
View Full Code Here

                try{close();}
                catch(IOException e2){Log.ignore(e2);}
            }
            finally
            {
                Continuation continuation =  _connection.getRequest().getContinuation();
                if (continuation != null && continuation.isPending())
                {
                    // We have a continuation
                    // TODO something!
                }
                else
View Full Code Here

            {
                member = new Member(session,null);
                room.put(session.getId(),member);
            }

            Continuation continuation = ContinuationSupport.getContinuation(request, room);
           
            if (!member.hasMessages())
            {  
                if (member.getContinuation()!=null && member.getContinuation()!=continuation)
                {
                    // duplicate frames!
                    Message duplicate = new Message("System","Multiple frames/tabs/windows from same browser!",true);
                    Message action = new Message("System","Please use only one frame/tab/window",true);
                    member.addMessage(duplicate);
                    member.addMessage(action);
                    try
                    {
                        Thread.sleep(5000);
                    }
                    catch(Exception e)
                    {}
                }
                else
                {
                    member.setContinuation(continuation);
                    continuation.suspend(timeoutMS);
                }
            }
           
            if (member.getContinuation()==continuation)
                member.setContinuation(null);
View Full Code Here

TOP

Related Classes of org.mortbay.util.ajax.Continuation

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.