org.cometd.Message - java examples

Here are the examples of the java api org.cometd.Message taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

94 Examples 7

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
/*  // TODO: make sure this works properly. I think there's a chance of a deadlock
    public void testTakeMessage() throws Exception
    {
        Message[] messages = {
                m("a", "apple"),
                m("b", "bapple"),
                m("c", "capple"),
                m("d", "dapple"),
                m("e", "eapple"),
                m("f", "fapple")
        };
            
        final CountDownLatch todo = new CountDownLatch(messages.length); 

        // temporary variable to avoid error with abstract lists not implementing remove
        List<Message> messageList = new ArrayList<Message>();
        messageList.addAll(Arrays.asList(messages));
        _client.returnMessages(messageList);
                
        final ClientImpl threadClient = _client;
        for(int i = 0; i < _client.getMessages(); ++i)
        {
            final int x = i;
            (new Thread() {
                public void run()
                {
                    try
                    {
                        int sleep = 10;
                        Thread.sleep(sleep);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    
                    Message message = threadClient.takeMessage();
                    todo.countDown();
                    // System.out.print(todo.getCount() + " -- ");
                    // System.out.println(x + " in thread client: " + message + "; "+threadClient.getMessages() + " left");
                    
                    
                }
            }).start();
        }

        todo.await(5, TimeUnit.SECONDS);
    }
*/
private Message m(String key, String value) {
    Message message = new MessageImpl();
    message.put(key, value);
    return message;
}

19 View Complete Implementation : OortComet.java
Copyright MIT License
Author : napcs
@Override
protected void metaConnect(boolean success, Message message) {
    _connected = success;
    super.metaConnect(success, message);
}

19 View Complete Implementation : MessageImpl.java
Copyright Apache License 2.0
Author : ceefour
/* ------------------------------------------------------------ */
public void setreplacedociated(Message replacedociated) {
    if (_replacedociated != replacedociated) {
        if (_replacedociated != null)
            ((MessageImpl) _replacedociated).decRef();
        _replacedociated = replacedociated;
        if (_replacedociated != null)
            ((MessageImpl) _replacedociated).incRef();
    }
}

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
private List<Message> resultsList(Message m1, Message m2) {
    return Arrays.asList(new Message[] { m1, m2 });
}

19 View Complete Implementation : AbstractTransport.java
Copyright MIT License
Author : napcs
public abstract clreplaced AbstractTransport implements Transport {

    private HttpServletResponse _response;

    private Message _pollReply;

    public void setResponse(HttpServletResponse response) throws IOException {
        _response = response;
    }

    public HttpServletResponse getResponse() {
        return _response;
    }

    public Message getMetaConnectReply() {
        return _pollReply;
    }

    public void setMetaConnectReply(Message reply) {
        _pollReply = reply;
    }
}

19 View Complete Implementation : TimesyncExtension.java
Copyright Apache License 2.0
Author : ceefour
public Message rcvMeta(Message message) {
    Map<String, Object> ext = (Map<String, Object>) message.get(Bayeux.EXT_FIELD);
    if (ext != null) {
        Map<String, Object> sync = (Map<String, Object>) ext.get("timesync");
        if (sync != null)
            sync.put("ts", new Long(System.currentTimeMillis()));
    }
    return message;
}

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
/**
 * @author athena
 */
public clreplaced ClientImplTest extends TestCase {

    protected StandaloneClient _client;

    protected Message _message;

    protected void setUp() throws Exception {
        _client = new StandaloneClient();
        _message = new MessageImpl();
    }

    /*
     * QueueListener examples
     */
    public void testDeleteWhenFullQueue() throws Exception {
        Message delete = m("delete", "a");
        Message keep = m("keep", "b");
        Message add = m("add", "c");
        _client.setMaxQueue(2);
        _client.addListener(new DeleteWhenFullQueueListener());
        _client.deliver(delete);
        _client.deliver(keep);
        _client.deliver(add);
        replacedertEquals(resultsList(keep, add), _client.takeMessages());
    }

    public void testDiscardNewMessageQueue() throws Exception {
        Message keep1 = m("keep1", "a");
        Message keep2 = m("keep2", "b");
        Message discard = m("discard", "c");
        _client.setMaxQueue(2);
        _client.addListener(new DiscardNewMessageQueueListener());
        _client.deliver(keep1);
        _client.deliver(keep2);
        _client.deliver(discard);
        replacedertEquals(resultsList(keep1, keep2), _client.takeMessages());
    }

    public void testModifyExistingMessagesQueue() throws Exception {
        Message keep = m("keep", "a");
        Message delete = m("delete", "b");
        Message add = m("add", "c");
        _client.setMaxQueue(2);
        _client.addListener(new ModifyExistingMessagesQueueListener());
        _client.deliver(keep);
        _client.deliver(delete);
        _client.deliver(add);
        replacedertEquals(resultsList(keep, add), _client.takeMessages());
    }

    // TODO: improve this test?
    public void testTakeWhileQueueing() throws Exception {
        _client.setMaxQueue(2);
        _client.addListener(new DeleteWhenFullQueueListener());
        Message[] m = new Message[5];
        for (int i = 0; i < m.length; ++i) {
            m[i] = m(i + "", i + "");
        }
        (new Thread() {

            public void run() {
                while (true) {
                    _client.getQueue().poll();
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
            }
        }).start();
        for (Message message : m) {
            _client.deliver(message);
        }
        replacedertEquals(resultsList(m[m.length - 2], m[m.length - 1]), _client.takeMessages());
    }

    public void testId() throws Exception {
        AbstractBayeux bayeux = new BayeuxStub();
        // bayeux.setNodeId("nodeid");
        _client = new StandaloneClient(bayeux);
    // TODO
    }

    public void testMessageListener() throws Exception {
        _message.put("key", "value");
        _client.addListener(new CheckMessageListener(_message));
        _client.addListener(new CheckMessageListener(_message));
        _client.deliver(_message);
    }

    public void testRemoveListener() throws Exception {
    // TODO
    }

    public void testDeliverListener() throws Exception {
        final boolean[] called = { false };
        _client.addListener(new DeliverListener() {

            public void deliver(Client client, Queue<Message> queue) {
                called[0] = true;
            }
        });
        Message ping = m("ping", "hello");
        _client.deliver(ping);
        replacedertFalse(called[0]);
        _client.doDeliverListeners();
        replacedertTrue(called[0]);
    }

    /*  // TODO: make sure this works properly. I think there's a chance of a deadlock
    public void testTakeMessage() throws Exception
    {
        Message[] messages = {
                m("a", "apple"),
                m("b", "bapple"),
                m("c", "capple"),
                m("d", "dapple"),
                m("e", "eapple"),
                m("f", "fapple")
        };
            
        final CountDownLatch todo = new CountDownLatch(messages.length); 

        // temporary variable to avoid error with abstract lists not implementing remove
        List<Message> messageList = new ArrayList<Message>();
        messageList.addAll(Arrays.asList(messages));
        _client.returnMessages(messageList);
                
        final ClientImpl threadClient = _client;
        for(int i = 0; i < _client.getMessages(); ++i)
        {
            final int x = i;
            (new Thread() {
                public void run()
                {
                    try
                    {
                        int sleep = 10;
                        Thread.sleep(sleep);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                    
                    Message message = threadClient.takeMessage();
                    todo.countDown();
                    // System.out.print(todo.getCount() + " -- ");
                    // System.out.println(x + " in thread client: " + message + "; "+threadClient.getMessages() + " left");
                    
                    
                }
            }).start();
        }

        todo.await(5, TimeUnit.SECONDS);
    }
*/
    private Message m(String key, String value) {
        Message message = new MessageImpl();
        message.put(key, value);
        return message;
    }

    private List<Message> resultsList(Message m1, Message m2) {
        return Arrays.asList(new Message[] { m1, m2 });
    }

    clreplaced StandaloneClient extends ClientImpl {

        public StandaloneClient() {
            super(new BayeuxStub(), "standalone");
        }

        public StandaloneClient(AbstractBayeux bayeux) {
            super(bayeux, "standalone");
        }

        /*
         * Warn for methods that require a proper Bayeux object
         */
        @Override
        public void deliver(Client from, String toChannel, Object data, String id) {
            System.err.println("Method unsupported!");
        }

        public void deliver(Message message) {
            doDelivery(null, message);
        }

        @Override
        public void remove(boolean timeout) {
            System.err.println("Method unsupported!");
        }

        @Override
        public void setBrowserId(String id) {
            System.err.println("Method unsupported!");
        }
    }

    /*
     * stub out and use to initialize a "standalone" client 
     */
    static clreplaced BayeuxStub extends AbstractBayeux {

        public BayeuxStub() {
            try {
                _random = SecureRandom.getInstance("SHA1PRNG");
            } catch (Exception e) {
                _random = new Random();
            }
            // lacks the context hashcode from AbstractBayeux#initialize()
            _random.setSeed(_random.nextLong() ^ hashCode() ^ Runtime.getRuntime().freeMemory());
        }

        public ClientImpl newRemoteClient() {
            return null;
        }
    }

    static clreplaced DeleteWhenFullQueueListener implements QueueListener {

        public boolean queueMaxed(Client client, Message message) {
            client.getQueue().poll();
            return true;
        }
    }

    static clreplaced DiscardNewMessageQueueListener implements QueueListener {

        public boolean queueMaxed(Client client, Message message) {
            return false;
        }
    }

    static clreplaced ModifyExistingMessagesQueueListener implements QueueListener {

        public boolean queueMaxed(Client client, Message message) {
            Iterator<Message> queueIterator = client.getQueue().iterator();
            boolean removed = false;
            while (queueIterator.hasNext()) {
                Message m = queueIterator.next();
                if (m.get("delete") != null) {
                    queueIterator.remove();
                    removed = true;
                }
            }
            return removed;
        }
    }

    static clreplaced CheckMessageListener implements MessageListener {

        Message _message;

        public CheckMessageListener(Message message) {
            _message = message;
        }

        public void deliver(Client fromClient, Client toClient, Message msg) {
            replacedertEquals(_message, msg);
        }
    }
}

19 View Complete Implementation : TimestampExtension.java
Copyright Apache License 2.0
Author : ceefour
public Message rcv(Message message) {
    return message;
}

19 View Complete Implementation : AbstractCometdServlet.java
Copyright MIT License
Author : napcs
/**
 * Cometd Filter Servlet implementing the {@link AbstractBayeux} protocol.
 *
 * The Servlet can be initialized with a json file mapping channels to
 * {@link DataFilter} definitions. The servlet init parameter "filters" should
 * point to a webapplication resource containing a JSON array of filter
 * definitions. For example:
 *
 * <pre>
 *  [
 *    {
 *      "channels": "/**",
 *      "clreplaced"   : "org.mortbay.cometd.filter.NoMarkupFilter",
 *      "init"    : {}
 *    }
 *  ]
 * </pre>
 *
 * The following init parameters can be used to configure the servlet:
 * <dl>
 * <dt>timeout</dt>
 * <dd>The server side poll timeout in milliseconds (default 250000). This is
 * how long the server will hold a reconnect request before responding.</dd>
 *
 * <dt>interval</dt>
 * <dd>The client side poll timeout in milliseconds (default 0). How long a
 * client will wait between reconnects</dd>
 *
 * <dt>maxInterval</dt>
 * <dd>The max client side poll timeout in milliseconds (default 30000). A
 * client will be removed if a connection is not received in this time.
 *
 * <dt>maxLazyLatency</dt>
 * <dd>The max time in ms(default 0) that a client with lazy messages will wait before
 * sending a response. If 0, then the client will wait until the next timeout or
 * non-lazy message.
 *
 * <dt>multiFrameInterval</dt>
 * <dd>the client side poll timeout if multiple connections are detected from
 * the same browser (default 1500).</dd>
 *
 * <dt>JSONCommented</dt>
 * <dd>If "true" then the server will accept JSON wrapped in a comment and will
 * generate JSON wrapped in a comment. This is a defence against Ajax Hijacking.
 * </dd>
 *
 * <dt>filters</dt>
 * <dd>the location of a JSON file describing {@link DataFilter} instances to be
 * installed</dd>
 *
 * <dt>requestAvailable</dt>
 * <dd>If true, the current request is made available via the
 * {@link AbstractBayeux#getCurrentRequest()} method</dd>
 *
 * <dt>logLevel</dt>
 * <dd>0=none, 1=info, 2=debug</dd>
 *
 * <dt>jsonDebug</dt>
 * <dd>If true, JSON complete json input will be kept for debug.</dd>
 *
 * <dt>channelIdCacheLimit</dt>
 * <dd>The limit of the {@link ChannelId} cache: -1 to disable caching, 0 for no limits,
 * any positive value to clear the cache once the limit has been reached</dd>
 *
 * <dt>refsThreshold</dt>
 * <dd>The number of message refs at which the a single message response will be
 * cached instead of being generated for every client delivered to. Done to
 * optimize a single message being sent to multiple clients.</dd>
 * </dl>
 *
 * @author gregw
 * @author aabeling: added JSONP transport
 *
 * @see {@link AbstractBayeux}
 * @see {@link ChannelId}
 */
public abstract clreplaced AbstractCometdServlet extends GenericServlet {

    public static final String CLIENT_ATTR = "org.mortbay.cometd.client";

    public static final String TRANSPORT_ATTR = "org.mortbay.cometd.transport";

    public static final String MESSAGE_PARAM = "message";

    public static final String TUNNEL_INIT_PARAM = "tunnelInit";

    public static final String HTTP_CLIENT_ID = "BAYEUX_HTTP_CLIENT";

    public final static String BROWSER_ID = "BAYEUX_BROWSER";

    protected AbstractBayeux _bayeux;

    public final static int __DEFAULT_REFS_THRESHOLD = 0;

    protected int _refsThreshold = __DEFAULT_REFS_THRESHOLD;

    protected boolean _jsonDebug;

    public AbstractBayeux getBayeux() {
        return _bayeux;
    }

    protected abstract AbstractBayeux newBayeux();

    @Override
    public void init() throws ServletException {
        synchronized (AbstractCometdServlet.clreplaced) {
            _bayeux = (AbstractBayeux) getServletContext().getAttribute(Bayeux.ATTRIBUTE);
            if (_bayeux == null) {
                _bayeux = newBayeux();
            }
        }
        synchronized (_bayeux) {
            boolean was_initialized = _bayeux.isInitialized();
            _bayeux.initialize(getServletContext());
            if (!was_initialized) {
                String filters = getInitParameter("filters");
                if (filters != null) {
                    try {
                        InputStream is = getServletContext().getResourcereplacedtream(filters);
                        if (is == null)
                            throw new FileNotFoundException(filters);
                        Object[] objects = (Object[]) JSON.parse(new InputStreamReader(getServletContext().getResourcereplacedtream(filters), "utf-8"));
                        for (int i = 0; objects != null && i < objects.length; i++) {
                            Map<?, ?> filter_def = (Map<?, ?>) objects[i];
                            String fc = (String) filter_def.get("clreplaced");
                            if (fc != null)
                                Log.warn(filters + " file uses deprecated \"clreplaced\" name. Use \"filter\" instead");
                            else
                                fc = (String) filter_def.get("filter");
                            Clreplaced<?> c = Thread.currentThread().getContextClreplacedLoader().loadClreplaced(fc);
                            DataFilter filter = (DataFilter) c.newInstance();
                            if (filter instanceof JSONDataFilter)
                                ((JSONDataFilter) filter).init(filter_def.get("init"));
                            _bayeux.getChannel((String) filter_def.get("channels"), true).addDataFilter(filter);
                        }
                    } catch (Exception e) {
                        getServletContext().log("Could not parse: " + filters, e);
                        throw new ServletException(e);
                    }
                }
                String timeout = getInitParameter("timeout");
                if (timeout != null)
                    _bayeux.setTimeout(Long.parseLong(timeout));
                String maxInterval = getInitParameter("maxInterval");
                if (maxInterval != null)
                    _bayeux.setMaxInterval(Long.parseLong(maxInterval));
                String commentedJSON = getInitParameter("JSONCommented");
                _bayeux.setJSONCommented(commentedJSON != null && Boolean.parseBoolean(commentedJSON));
                String l = getInitParameter("logLevel");
                if (l != null && l.length() > 0)
                    _bayeux.setLogLevel(Integer.parseInt(l));
                String interval = getInitParameter("interval");
                if (interval != null)
                    _bayeux.setInterval(Long.parseLong(interval));
                String maxLazy = getInitParameter("maxLazyLatency");
                if (maxLazy != null)
                    _bayeux.setMaxLazyLatency(Integer.parseInt(maxLazy));
                String mfInterval = getInitParameter("multiFrameInterval");
                if (mfInterval != null)
                    _bayeux.setMultiFrameInterval(Integer.parseInt(mfInterval));
                String requestAvailable = getInitParameter("requestAvailable");
                _bayeux.setRequestAvailable(requestAvailable != null && Boolean.parseBoolean(requestAvailable));
                String async = getInitParameter("asyncDeliver");
                if (async != null)
                    getServletContext().log("asyncDeliver no longer supported");
                String refsThreshold = getInitParameter("refsThreshold");
                if (refsThreshold != null)
                    _refsThreshold = Integer.parseInt(refsThreshold);
                String jsonDebugParam = getInitParameter("jsonDebug");
                _jsonDebug = Boolean.parseBoolean(jsonDebugParam);
                String channelIdCacheLimit = getInitParameter("channelIdCacheLimit");
                if (channelIdCacheLimit != null)
                    _bayeux.setChannelIdCacheLimit(Integer.parseInt(channelIdCacheLimit));
                _bayeux.generateAdvice();
                if (_bayeux.isLogInfo()) {
                    getServletContext().log("timeout=" + timeout);
                    getServletContext().log("interval=" + interval);
                    getServletContext().log("maxInterval=" + maxInterval);
                    getServletContext().log("multiFrameInterval=" + mfInterval);
                    getServletContext().log("filters=" + filters);
                    getServletContext().log("refsThreshold=" + refsThreshold);
                }
            }
        }
        getServletContext().setAttribute(Bayeux.ATTRIBUTE, _bayeux);
    }

    protected abstract void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;

    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        if (_bayeux.isRequestAvailable())
            _bayeux.setCurrentRequest(request);
        try {
            service(request, response);
        } finally {
            if (_bayeux.isRequestAvailable())
                _bayeux.setCurrentRequest(null);
        }
    }

    protected String findBrowserId(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (BROWSER_ID.equals(cookie.getName()))
                    return cookie.getValue();
            }
        }
        return null;
    }

    protected String setBrowserId(HttpServletRequest request, HttpServletResponse response) {
        String browser_id = Long.toHexString(request.getRemotePort()) + Long.toString(_bayeux.getRandom(), 36) + Long.toString(System.currentTimeMillis(), 36) + Long.toString(request.getRemotePort(), 36);
        Cookie cookie = new Cookie(BROWSER_ID, browser_id);
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
        return browser_id;
    }

    private static Message[] __EMPTY_BATCH = new Message[0];

    protected Message[] getMessages(HttpServletRequest request) throws IOException, ServletException {
        String messageString = null;
        try {
            // Get message batches either as JSON body or as message parameters
            if (request.getContentType() != null && !request.getContentType().startsWith("application/x-www-form-urlencoded")) {
                if (_jsonDebug) {
                    messageString = IO.toString(request.getReader());
                    return _bayeux.parse(messageString);
                }
                return _bayeux.parse(request.getReader());
            }
            String[] batches = request.getParameterValues(MESSAGE_PARAM);
            if (batches == null || batches.length == 0)
                return __EMPTY_BATCH;
            if (batches.length == 1) {
                messageString = batches[0];
                return _bayeux.parse(messageString);
            }
            List<Message> messages = new ArrayList<Message>();
            for (String batch : batches) {
                if (batch == null)
                    continue;
                messageString = batch;
                _bayeux.parseTo(messageString, messages);
            }
            return messages.toArray(new Message[messages.size()]);
        } catch (IOException x) {
            throw x;
        } catch (Exception x) {
            return handleJSONParseException(request, messageString, x);
        }
    }

    /**
     * Override to customize the handling of JSON parse exceptions.
     * Default behavior is to log at warn level on logger "org.cometd.json" and to throw a ServletException that
     * wraps the original exception.
     *
     * @param request the request object
     * @param messageString the JSON text, if available; can be null if the JSON is not buffered before being parsed.
     * @param x the exception thrown during parsing
     * @return a non-null array of messages, possibly empty, if the JSON parse exception is recoverable
     * @throws ServletException if the JSON parsing is not recoverable
     */
    protected Message[] handleJSONParseException(HttpServletRequest request, String messageString, Exception x) throws ServletException {
        Log.getLogger("org.cometd.json").warn("Exception parsing JSON: " + messageString, x);
        throw new ServletException("Exception parsing JSON: |" + messageString + "|", x);
    }
}

19 View Complete Implementation : MessagePool.java
Copyright Apache License 2.0
Author : ceefour
/* ------------------------------------------------------------ */
public void parseTo(String fodder, List<Message> messages) {
    Object batch = _batchJSON.parse(new JSON.StringSource(fodder));
    if (batch == null)
        return;
    if (batch.getClreplaced().isArray()) {
        Message[] msgs = (Message[]) batch;
        for (int m = 0; m < msgs.length; m++) messages.add(msgs[m]);
    } else
        messages.add((Message) batch);
}

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
/*
     * QueueListener examples
     */
public void testDeleteWhenFullQueue() throws Exception {
    Message delete = m("delete", "a");
    Message keep = m("keep", "b");
    Message add = m("add", "c");
    _client.setMaxQueue(2);
    _client.addListener(new DeleteWhenFullQueueListener());
    _client.deliver(delete);
    _client.deliver(keep);
    _client.deliver(add);
    replacedertEquals(resultsList(keep, add), _client.takeMessages());
}

19 View Complete Implementation : MessageImpl.java
Copyright MIT License
Author : napcs
public clreplaced MessageImpl extends HashMap<String, Object> implements Message, org.mortbay.util.ajax.JSON.Generator {

    Message _replacedociated;

    ByteBuffer _buffer;

    String _channel;

    String _clientId;

    Object _data;

    Object _ext;

    String _id;

    String _json;

    boolean _lazy = false;

    final MessagePool _pool;

    AtomicInteger _refs = new AtomicInteger();

    /* ------------------------------------------------------------ */
    public MessageImpl() {
        super(8);
        _pool = null;
    }

    /* ------------------------------------------------------------ */
    public MessageImpl(MessagePool bayeux) {
        super(8);
        _pool = bayeux;
    }

    /* ------------------------------------------------------------ */
    public void addJSON(StringBuffer buffer) {
        buffer.append(getJSON());
    }

    /* ------------------------------------------------------------ */
    /*
     * (non-Javadoc)
     * 
     * @see java.util.HashMap#clear()
     */
    @Override
    public void clear() {
        setreplacedociated(null);
        _buffer = null;
        _channel = null;
        _clientId = null;
        _data = null;
        _ext = null;
        _id = null;
        _json = null;
        _lazy = false;
        // TODO recycle
        _ext = null;
        _refs.set(0);
        Iterator<Map.Entry<String, Object>> iterator = super.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            String key = entry.getKey();
            if (Bayeux.CHANNEL_FIELD.equals(key))
                entry.setValue(null);
            else if (Bayeux.ID_FIELD.equals(key))
                entry.setValue(null);
            else if (Bayeux.TIMESTAMP_FIELD.equals(key))
                entry.setValue(null);
            else if (Bayeux.DATA_FIELD.equals(key))
                entry.setValue(null);
            else if (Bayeux.EXT_FIELD.equals(key))
                entry.setValue(null);
            else
                iterator.remove();
        }
        super.clear();
    }

    /* ------------------------------------------------------------ */
    public Object clone() {
        MessageImpl msg = new MessageImpl();
        msg.putAll(this);
        msg._channel = _channel;
        msg._clientId = _clientId;
        msg._id = _id;
        return msg;
    }

    /* ------------------------------------------------------------ */
    public void decRef() {
        int r = _refs.decrementAndGet();
        if (r == 0 && _pool != null) {
            setreplacedociated(null);
            _pool.recycleMessage(this);
        } else if (r < 0)
            throw new IllegalStateException();
    }

    /* ------------------------------------------------------------ */
    /*
     * (non-Javadoc)
     * 
     * @see java.util.HashMap#entrySet()
     */
    @Override
    public Set<java.util.Map.Entry<String, Object>> entrySet() {
        return Collections.unmodifiableSet(super.entrySet());
    }

    /* ------------------------------------------------------------ */
    public Message getreplacedociated() {
        return _replacedociated;
    }

    /* ------------------------------------------------------------ */
    public ByteBuffer getBuffer() {
        return _buffer;
    }

    /* ------------------------------------------------------------ */
    public String getChannel() {
        return _channel;
    }

    /* ------------------------------------------------------------ */
    public String getClientId() {
        if (_clientId == null)
            _clientId = (String) get(Bayeux.CLIENT_FIELD);
        return _clientId;
    }

    /* ------------------------------------------------------------ */
    public Object getData() {
        return _data;
    }

    /* ------------------------------------------------------------ */
    public Map<String, Object> getExt(boolean create) {
        Object ext = _ext == null ? get(Bayeux.EXT_FIELD) : _ext;
        if (ext instanceof Map)
            return (Map<String, Object>) ext;
        if (ext instanceof JSON.Literal) {
            JSON json = _pool == null ? JSON.getDefault() : _pool.getMsgJSON();
            _ext = ext = json.fromJSON(ext.toString());
            super.put(Bayeux.EXT_FIELD, ext);
            return (Map<String, Object>) ext;
        }
        if (!create)
            return null;
        _ext = ext = new HashMap<String, Object>();
        super.put(Bayeux.EXT_FIELD, ext);
        return (Map<String, Object>) ext;
    }

    /* ------------------------------------------------------------ */
    public String getId() {
        return _id;
    }

    /* ------------------------------------------------------------ */
    public String getJSON() {
        if (_json == null) {
            JSON json = _pool == null ? JSON.getDefault() : _pool.getMsgJSON();
            StringBuffer buf = new StringBuffer(json.getStringBufferSize());
            synchronized (buf) {
                json.appendMap(buf, this);
                _json = buf.toString();
            }
        }
        return _json;
    }

    /* ------------------------------------------------------------ */
    public int getRefs() {
        return _refs.get();
    }

    /* ------------------------------------------------------------ */
    public void incRef() {
        _refs.incrementAndGet();
    }

    /* ------------------------------------------------------------ */
    /**
     * Lazy messages are queued but do not wake up waiting clients.
     *
     * @return true if message is lazy
     */
    public boolean isLazy() {
        return _lazy;
    }

    /* ------------------------------------------------------------ */
    public boolean isSuccessful() {
        Boolean bool = (Boolean) get(Bayeux.SUCCESSFUL_FIELD);
        return bool != null && bool.booleanValue();
    }

    /* ------------------------------------------------------------ */
    /*
     * (non-Javadoc)
     * 
     * @see java.util.HashMap#keySet()
     */
    @Override
    public Set<String> keySet() {
        return Collections.unmodifiableSet(super.keySet());
    }

    /* ------------------------------------------------------------ */
    /*
     * (non-Javadoc)
     * 
     * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
     */
    @Override
    public Object put(String key, Object value) {
        _json = null;
        _buffer = null;
        if (Bayeux.CHANNEL_FIELD.equals(key))
            _channel = (String) value;
        else if (Bayeux.ID_FIELD.equals(key))
            _id = value.toString();
        else if (Bayeux.CLIENT_FIELD.equals(key))
            _clientId = (String) value;
        else if (Bayeux.DATA_FIELD.equals(key))
            _data = value;
        else if (Bayeux.EXT_FIELD.equals(key))
            _ext = value;
        return super.put(key, value);
    }

    /* ------------------------------------------------------------ */
    /*
     * (non-Javadoc)
     * 
     * @see java.util.HashMap#putAll(java.util.Map)
     */
    @Override
    public void putAll(Map<? extends String, ? extends Object> m) {
        _json = null;
        _buffer = null;
        super.putAll(m);
        _channel = (String) get(Bayeux.CHANNEL_FIELD);
        Object id = get(Bayeux.ID_FIELD);
        _id = id == null ? null : id.toString();
        _data = get(Bayeux.DATA_FIELD);
    }

    /* ------------------------------------------------------------ */
    /*
     * (non-Javadoc)
     * 
     * @see java.util.HashMap#remove(java.lang.Object)
     */
    @Override
    public Object remove(Object key) {
        _json = null;
        _buffer = null;
        if (Bayeux.CHANNEL_FIELD.equals(key))
            _channel = null;
        else if (Bayeux.ID_FIELD.equals(key))
            _id = null;
        else if (Bayeux.DATA_FIELD.equals(key))
            _data = null;
        else if (Bayeux.EXT_FIELD.equals(key))
            _ext = null;
        return super.remove(key);
    }

    /* ------------------------------------------------------------ */
    public void setreplacedociated(Message replacedociated) {
        if (_replacedociated != replacedociated) {
            if (_replacedociated != null)
                ((MessageImpl) _replacedociated).decRef();
            _replacedociated = replacedociated;
            if (_replacedociated != null)
                ((MessageImpl) _replacedociated).incRef();
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * @param buffer
     *            A cached buffer containing HTTP response headers and message
     *            content, to be reused when sending one message to multiple
     *            clients
     */
    public void setBuffer(ByteBuffer buffer) {
        _buffer = buffer;
    }

    /* ------------------------------------------------------------ */
    /**
     * Lazy messages are queued but do not wake up waiting clients.
     *
     * @param lazy
     *            true if message is lazy
     */
    public void setLazy(boolean lazy) {
        _lazy = lazy;
    }

    /* ------------------------------------------------------------ */
    public String toString() {
        return getJSON();
    }
}

19 View Complete Implementation : TimesyncExtension.java
Copyright Apache License 2.0
Author : ceefour
public Message send(Message message) {
    return message;
}

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
public void testModifyExistingMessagesQueue() throws Exception {
    Message keep = m("keep", "a");
    Message delete = m("delete", "b");
    Message add = m("add", "c");
    _client.setMaxQueue(2);
    _client.addListener(new ModifyExistingMessagesQueueListener());
    _client.deliver(keep);
    _client.deliver(delete);
    _client.deliver(add);
    replacedertEquals(resultsList(keep, add), _client.takeMessages());
}

19 View Complete Implementation : TimestampExtension.java
Copyright Apache License 2.0
Author : ceefour
public Message sendMeta(Message message) {
    message.put(AbstractBayeux.TIMESTAMP_FIELD, _dateCache.format(System.currentTimeMillis()));
    return message;
}

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
public void testDeliverListener() throws Exception {
    final boolean[] called = { false };
    _client.addListener(new DeliverListener() {

        public void deliver(Client client, Queue<Message> queue) {
            called[0] = true;
        }
    });
    Message ping = m("ping", "hello");
    _client.deliver(ping);
    replacedertFalse(called[0]);
    _client.doDeliverListeners();
    replacedertTrue(called[0]);
}

19 View Complete Implementation : TimesyncExtension.java
Copyright Apache License 2.0
Author : ceefour
public Message sendMeta(Message message) {
    Message replacedociated = message.getreplacedociated();
    if (replacedociated != null) {
        Map<String, Object> ext = (Map<String, Object>) replacedociated.get(Bayeux.EXT_FIELD);
        if (ext != null) {
            Map<String, Object> sync = (Map<String, Object>) ext.get("timesync");
            if (sync != null) {
                final long ts = ((Long) sync.get("ts")).longValue();
                final long p = System.currentTimeMillis() - ts;
                sync.put("p", new Long(p));
                ext = (Map<String, Object>) message.get(Bayeux.EXT_FIELD);
                if (ext == null) {
                    ext = new HashMap<String, Object>();
                    message.put(Bayeux.EXT_FIELD, ext);
                }
                ext.put("timesync", sync);
            }
        }
    }
    return message;
}

19 View Complete Implementation : BayeuxClient.java
Copyright Apache License 2.0
Author : ceefour
/* ------------------------------------------------------------ */
/* (non-Javadoc)
     * @see dojox.cometd.Client#subscribe(java.lang.String)
     */
private void publish(Message msg) {
    synchronized (_outQ) {
        _outQ.add(msg);
        if (_batch == 0 && _initialized && _push == null)
            _push = new Publish();
    }
}

19 View Complete Implementation : AbstractTransport.java
Copyright Apache License 2.0
Author : ceefour
public void setPollReply(Message reply) {
    _pollReply = reply;
}

19 View Complete Implementation : OortComet.java
Copyright MIT License
Author : napcs
@Override
protected void metaPublishFail(Throwable e, Message[] messages) {
    // TODO Auto-generated method stub
    super.metaPublishFail(e, messages);
}

19 View Complete Implementation : MessageImpl.java
Copyright Apache License 2.0
Author : ceefour
public clreplaced MessageImpl extends HashMap<String, Object> implements Message, org.mortbay.util.ajax.JSON.Generator {

    MessagePool _pool;

    String _clientId;

    String _json;

    String _channel;

    String _id;

    Object _data;

    Message _replacedociated;

    AtomicInteger _refs = new AtomicInteger();

    private ByteBuffer _buffer;

    /* ------------------------------------------------------------ */
    public MessageImpl() {
        super(8);
    }

    /* ------------------------------------------------------------ */
    public MessageImpl(MessagePool bayeux) {
        super(8);
        _pool = bayeux;
    }

    /* ------------------------------------------------------------ */
    public int getRefs() {
        return _refs.get();
    }

    /* ------------------------------------------------------------ */
    public void incRef() {
        _refs.getAndIncrement();
    }

    /* ------------------------------------------------------------ */
    public void decRef() {
        int r = _refs.decrementAndGet();
        if (r == 0 && _pool != null)
            _pool.recycleMessage(this);
        else if (r < 0)
            throw new IllegalStateException();
    }

    /* ------------------------------------------------------------ */
    public String getChannel() {
        return _channel;
    }

    /* ------------------------------------------------------------ */
    public String getClientId() {
        if (_clientId == null)
            _clientId = (String) get(Bayeux.CLIENT_FIELD);
        return _clientId;
    }

    /* ------------------------------------------------------------ */
    public String getId() {
        return _id;
    }

    /* ------------------------------------------------------------ */
    public Object getData() {
        return _data;
    }

    /* ------------------------------------------------------------ */
    public void addJSON(StringBuffer buffer) {
        buffer.append(getJSON());
    }

    /* ------------------------------------------------------------ */
    public String getJSON() {
        if (_json == null) {
            JSON json = _pool == null ? JSON.getDefault() : _pool.getMsgJSON();
            StringBuffer buf = new StringBuffer(json.getStringBufferSize());
            synchronized (buf) {
                json.appendMap(buf, this);
                _json = buf.toString();
            }
        }
        return _json;
    }

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see java.util.HashMap#clear()
     */
    @Override
    public void clear() {
        _json = null;
        _buffer = null;
        _id = null;
        _channel = null;
        _clientId = null;
        setreplacedociated(null);
        _refs.set(0);
        Iterator<Map.Entry<String, Object>> iterator = super.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Object> entry = iterator.next();
            String key = entry.getKey();
            if (Bayeux.CHANNEL_FIELD.equals(key))
                entry.setValue(null);
            else if (Bayeux.ID_FIELD.equals(key))
                entry.setValue(null);
            else if (Bayeux.TIMESTAMP_FIELD.equals(key))
                entry.setValue(null);
            else if (Bayeux.DATA_FIELD.equals(key))
                entry.setValue(null);
            else
                iterator.remove();
        }
        super.clear();
    }

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see java.util.HashMap#put(java.lang.Object, java.lang.Object)
     */
    @Override
    public Object put(String key, Object value) {
        _json = null;
        _buffer = null;
        if (Bayeux.CHANNEL_FIELD.equals(key))
            _channel = (String) value;
        else if (Bayeux.ID_FIELD.equals(key))
            _id = value.toString();
        else if (Bayeux.CLIENT_FIELD.equals(key))
            _clientId = (String) value;
        else if (Bayeux.DATA_FIELD.equals(key))
            _data = value;
        return super.put(key, value);
    }

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see java.util.HashMap#putAll(java.util.Map)
     */
    @Override
    public void putAll(Map<? extends String, ? extends Object> m) {
        _json = null;
        _buffer = null;
        super.putAll(m);
        _channel = (String) get(Bayeux.CHANNEL_FIELD);
        Object id = get(Bayeux.ID_FIELD);
        _id = id == null ? null : id.toString();
        _data = get(Bayeux.DATA_FIELD);
    }

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see java.util.HashMap#remove(java.lang.Object)
     */
    @Override
    public Object remove(Object key) {
        _json = null;
        _buffer = null;
        if (Bayeux.CHANNEL_FIELD.equals(key))
            _channel = null;
        else if (Bayeux.ID_FIELD.equals(key))
            _id = null;
        else if (Bayeux.DATA_FIELD.equals(key))
            _data = null;
        return super.remove(key);
    }

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see java.util.HashMap#entrySet()
     */
    @Override
    public Set<java.util.Map.Entry<String, Object>> entrySet() {
        return Collections.unmodifiableSet(super.entrySet());
    }

    /* ------------------------------------------------------------ */
    /* (non-Javadoc)
     * @see java.util.HashMap#keySet()
     */
    @Override
    public Set<String> keySet() {
        return Collections.unmodifiableSet(super.keySet());
    }

    /* ------------------------------------------------------------ */
    public Message getreplacedociated() {
        return _replacedociated;
    }

    /* ------------------------------------------------------------ */
    public void setreplacedociated(Message replacedociated) {
        if (_replacedociated != replacedociated) {
            if (_replacedociated != null)
                ((MessageImpl) _replacedociated).decRef();
            _replacedociated = replacedociated;
            if (_replacedociated != null)
                ((MessageImpl) _replacedociated).incRef();
        }
    }

    /* ------------------------------------------------------------ */
    /**
     * @param buffer A cached buffer containing HTTP response headers
     * and message content, to be reused when sending one message
     * to multiple clients
     */
    public void setBuffer(ByteBuffer buffer) {
        _buffer = buffer;
    }

    /* ------------------------------------------------------------ */
    public ByteBuffer getBuffer() {
        return _buffer;
    }
}

19 View Complete Implementation : AbstractTransport.java
Copyright MIT License
Author : napcs
public void setMetaConnectReply(Message reply) {
    _pollReply = reply;
}

19 View Complete Implementation : AbstractCometdServlet.java
Copyright Apache License 2.0
Author : ceefour
/**
 * Cometd Filter Servlet implementing the {@link AbstractBayeux} protocol.
 *
 * The Servlet can be initialized with a json file mapping channels to
 * {@link DataFilter} definitions. The servlet init parameter "filters" should
 * point to a webapplication resource containing a JSON array of filter
 * definitions. For example:
 *
 * <pre>
 *  [
 *    {
 *      "channels": "/**",
 *      "clreplaced"   : "org.mortbay.cometd.filter.NoMarkupFilter",
 *      "init"    : {}
 *    }
 *  ]
 * </pre>
 * The following init parameters can be used to configure the servlet:<dl>
 * <dt>timeout</dt>
 * <dd>The server side poll timeout in milliseconds (default 250000). This is how
 * long the server will hold a reconnect request before responding.</dd>
 *
 * <dt>interval</dt>
 * <dd>The client side poll timeout in milliseconds (default 0). How long a client
 * will wait between reconnects</dd>
 *
 * <dt>maxInterval</dt>
 * <dd>The max client side poll timeout in milliseconds (default 30000). A client will
 * be removed if a connection is not received in this time.
 *
 * <dt>multiFrameInterval</dt>
 * <dd>the client side poll timeout
 * if multiple connections are detected from the same browser (default 1500).</dd>
 *
 * <dt>JSONCommented</dt>
 * <dd>If "true" then the server will accept JSON wrapped
 * in a comment and will generate JSON wrapped in a comment. This is a defence against
 * Ajax Hijacking.</dd>
 *
 * <dt>filters</dt>
 * <dd>the location of a JSON file describing {@link DataFilter} instances to be installed</dd>
 *
 * <dt>requestAvailable</dt>
 * <dd>If true, the current request is made available via the {@link AbstractBayeux#getCurrentRequest()} method</dd>
 *
 * <dt>loglevel</dt>
 * <dd>0=none, 1=info, 2=debug</dd>
 *
 * <dt>directDeliver</dt>
 * <dd>true if published messages are delivered directly to subscribers (default). If false, a message copy is created with only supported fields (default true).</dd>
 *
 * <dt>refsThreshold</dt>
 * <dd>The number of message refs at which the a single message response will be
 * cached instead of being generated for every client delivered to. Done to optimize
 * a single message being sent to multiple clients.</dd>
 * </dl>
 *
 * @author gregw
 * @author aabeling: added JSONP transport
 *
 * @see {@link AbstractBayeux}
 * @see {@link ChannelId}
 */
public abstract clreplaced AbstractCometdServlet extends GenericServlet {

    public static final String CLIENT_ATTR = "org.mortbay.cometd.client";

    public static final String TRANSPORT_ATTR = "org.mortbay.cometd.transport";

    public static final String MESSAGE_PARAM = "message";

    public static final String TUNNEL_INIT_PARAM = "tunnelInit";

    public static final String HTTP_CLIENT_ID = "BAYEUX_HTTP_CLIENT";

    public final static String BROWSER_ID = "BAYEUX_BROWSER";

    protected AbstractBayeux _bayeux;

    public final static int __DEFAULT_REFS_THRESHOLD = 1;

    protected int _refsThreshold = __DEFAULT_REFS_THRESHOLD;

    public AbstractBayeux getBayeux() {
        return _bayeux;
    }

    protected abstract AbstractBayeux newBayeux();

    @Override
    public void init() throws ServletException {
        synchronized (AbstractCometdServlet.clreplaced) {
            _bayeux = (AbstractBayeux) getServletContext().getAttribute(Bayeux.DOJOX_COMETD_BAYEUX);
            if (_bayeux == null) {
                _bayeux = newBayeux();
            }
        }
        synchronized (_bayeux) {
            boolean was_initialized = _bayeux.isInitialized();
            _bayeux.initialize(getServletContext());
            if (!was_initialized) {
                String filters = getInitParameter("filters");
                if (filters != null) {
                    try {
                        InputStream is = getServletContext().getResourcereplacedtream(filters);
                        if (is == null)
                            throw new FileNotFoundException(filters);
                        Object[] objects = (Object[]) JSON.parse(new InputStreamReader(getServletContext().getResourcereplacedtream(filters), "utf-8"));
                        for (int i = 0; objects != null && i < objects.length; i++) {
                            Map<?, ?> filter_def = (Map<?, ?>) objects[i];
                            String fc = (String) filter_def.get("clreplaced");
                            if (fc != null)
                                Log.warn(filters + " file uses deprecated \"clreplaced\" name. Use \"filter\" instead");
                            else
                                fc = (String) filter_def.get("filter");
                            Clreplaced<?> c = Thread.currentThread().getContextClreplacedLoader().loadClreplaced(fc);
                            DataFilter filter = (DataFilter) c.newInstance();
                            if (filter instanceof JSONDataFilter)
                                ((JSONDataFilter) filter).init(filter_def.get("init"));
                            _bayeux.getChannel((String) filter_def.get("channels"), true).addDataFilter(filter);
                        }
                    } catch (Exception e) {
                        getServletContext().log("Could not parse: " + filters, e);
                        throw new ServletException(e);
                    }
                }
                String timeout = getInitParameter("timeout");
                if (timeout != null)
                    _bayeux.setTimeout(Long.parseLong(timeout));
                String maxInterval = getInitParameter("maxInterval");
                if (maxInterval != null)
                    _bayeux.setMaxInterval(Long.parseLong(maxInterval));
                String commentedJSON = getInitParameter("JSONCommented");
                _bayeux.setJSONCommented(commentedJSON != null && Boolean.parseBoolean(commentedJSON));
                String l = getInitParameter("logLevel");
                if (l != null && l.length() > 0)
                    _bayeux.setLogLevel(Integer.parseInt(l));
                String interval = getInitParameter("interval");
                if (interval != null)
                    _bayeux.setInterval(Long.parseLong(interval));
                String mfInterval = getInitParameter("multiFrameInterval");
                if (mfInterval != null)
                    _bayeux.setMultiFrameInterval(Integer.parseInt(mfInterval));
                String requestAvailable = getInitParameter("requestAvailable");
                _bayeux.setRequestAvailable(requestAvailable != null && Boolean.parseBoolean(requestAvailable));
                String direct = getInitParameter("directDeliver");
                if (direct != null)
                    _bayeux.setDirectDeliver(Boolean.parseBoolean(direct));
                String async = getInitParameter("asyncDeliver");
                if (async != null)
                    getServletContext().log("asyncDeliver no longer supported");
                String refsThreshold = getInitParameter("refsThreshold");
                if (refsThreshold != null)
                    _refsThreshold = Integer.parseInt(refsThreshold);
                _bayeux.generateAdvice();
                if (_bayeux.isLogInfo()) {
                    getServletContext().log("timeout=" + timeout);
                    getServletContext().log("interval=" + interval);
                    getServletContext().log("maxInterval=" + maxInterval);
                    getServletContext().log("multiFrameInterval=" + mfInterval);
                    getServletContext().log("filters=" + filters);
                    getServletContext().log("refsThreshold=" + refsThreshold);
                }
            }
        }
        getServletContext().setAttribute(Bayeux.DOJOX_COMETD_BAYEUX, _bayeux);
    }

    protected abstract void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException;

    @Override
    public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        if (_bayeux.isRequestAvailable())
            _bayeux.setCurrentRequest(request);
        try {
            service(request, response);
        } finally {
            if (_bayeux.isRequestAvailable())
                _bayeux.setCurrentRequest(null);
        }
    }

    protected String browserId(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (BROWSER_ID.equals(cookie.getName()))
                    return cookie.getValue();
            }
        }
        return null;
    }

    protected String newBrowserId(HttpServletRequest request, HttpServletResponse response) {
        String browser_id = Long.toHexString(request.getRemotePort()) + Long.toString(_bayeux.getRandom(), 36) + Long.toString(System.currentTimeMillis(), 36) + Long.toString(request.getRemotePort(), 36);
        Cookie cookie = new Cookie(BROWSER_ID, browser_id);
        cookie.setPath("/");
        cookie.setMaxAge(-1);
        response.addCookie(cookie);
        return browser_id;
    }

    private static Message[] __EMPTY_BATCH = new Message[0];

    protected Message[] getMessages(HttpServletRequest request) throws IOException {
        String fodder = null;
        try {
            // Get message batches either as JSON body or as message parameters
            if (request.getContentType() != null && !request.getContentType().startsWith("application/x-www-form-urlencoded")) {
                return _bayeux.parse(request.getReader());
            }
            String[] batches = request.getParameterValues(MESSAGE_PARAM);
            if (batches == null || batches.length == 0)
                return __EMPTY_BATCH;
            if (batches.length == 0) {
                fodder = batches[0];
                return _bayeux.parse(fodder);
            }
            List<Message> messages = new ArrayList<Message>();
            for (int i = 0; i < batches.length; i++) {
                if (batches[i] == null)
                    continue;
                fodder = batches[i];
                _bayeux.parseTo(fodder, messages);
            }
            return messages.toArray(new Message[messages.size()]);
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new Error(fodder, e);
        }
    }
}

19 View Complete Implementation : StatisticsExtension.java
Copyright MIT License
Author : napcs
/**
 * Override to be able to modify the message that has been identified as a statistics request
 * @param message the bayeux message identified as statistics request
 */
protected void onStatisticsRequest(Message message) {
}

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
public void testDiscardNewMessageQueue() throws Exception {
    Message keep1 = m("keep1", "a");
    Message keep2 = m("keep2", "b");
    Message discard = m("discard", "c");
    _client.setMaxQueue(2);
    _client.addListener(new DiscardNewMessageQueueListener());
    _client.deliver(keep1);
    _client.deliver(keep2);
    _client.deliver(discard);
    replacedertEquals(resultsList(keep1, keep2), _client.takeMessages());
}

19 View Complete Implementation : TimestampExtension.java
Copyright Apache License 2.0
Author : ceefour
public Message rcvMeta(Message message) {
    return message;
}

19 View Complete Implementation : ClientImplTest.java
Copyright MIT License
Author : napcs
/*  // TODO: make sure this works properly. I think there's a chance of a deadlock
    public void testTakeMessage() throws Exception
    {
        Message[] messages = {
                m("a", "apple"),
                m("b", "bapple"),
                m("c", "capple"),
                m("d", "dapple"),
                m("e", "eapple"),
                m("f", "fapple")
        };

        final CountDownLatch todo = new CountDownLatch(messages.length);

        // temporary variable to avoid error with abstract lists not implementing remove
        List<Message> messageList = new ArrayList<Message>();
        messageList.addAll(Arrays.asList(messages));
        _client.returnMessages(messageList);

        final ClientImpl threadClient = _client;
        for(int i = 0; i < _client.getMessages(); ++i)
        {
            final int x = i;
            (new Thread() {
                public void run()
                {
                    try
                    {
                        int sleep = 10;
                        Thread.sleep(sleep);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }

                    Message message = threadClient.takeMessage();
                    todo.countDown();
                    // System.out.print(todo.getCount() + " -- ");
                    // System.out.println(x + " in thread client: " + message + "; "+threadClient.getMessages() + " left");


                }
            }).start();
        }

        todo.await(5, TimeUnit.SECONDS);
    }
*/
private Message m(String key, String value) {
    Message message = new MessageImpl();
    message.put(key, value);
    return message;
}

19 View Complete Implementation : AbstractTransport.java
Copyright Apache License 2.0
Author : ceefour
public abstract clreplaced AbstractTransport implements Transport {

    private HttpServletResponse _response;

    private Message _pollReply;

    public void setResponse(HttpServletResponse response) throws IOException {
        _response = response;
    }

    public HttpServletResponse getResponse() {
        return _response;
    }

    public Message getPollReply() {
        return _pollReply;
    }

    public void setPollReply(Message reply) {
        _pollReply = reply;
    }
}

19 View Complete Implementation : TimestampExtension.java
Copyright Apache License 2.0
Author : ceefour
public Message send(Message message) {
    message.put(AbstractBayeux.TIMESTAMP_FIELD, _dateCache.format(System.currentTimeMillis()));
    return message;
}

19 View Complete Implementation : ClientImplTest.java
Copyright Apache License 2.0
Author : ceefour
// TODO: improve this test?
public void testTakeWhileQueueing() throws Exception {
    _client.setMaxQueue(2);
    _client.addListener(new DeleteWhenFullQueueListener());
    Message[] m = new Message[5];
    for (int i = 0; i < m.length; ++i) {
        m[i] = m(i + "", i + "");
    }
    (new Thread() {

        public void run() {
            while (true) {
                _client.getQueue().poll();
                try {
                    Thread.sleep(100);
                } catch (Exception e) {
                }
            }
        }
    }).start();
    for (Message message : m) {
        _client.deliver(message);
    }
    replacedertEquals(resultsList(m[m.length - 2], m[m.length - 1]), _client.takeMessages());
}

19 View Complete Implementation : ClientImplTest.java
Copyright MIT License
Author : napcs
/**
 * @author athena
 */
public clreplaced ClientImplTest extends TestCase {

    protected StandaloneClient _client;

    protected Message _message;

    protected void setUp() throws Exception {
        _client = new StandaloneClient();
        _message = new MessageImpl();
    }

    public void testThrowingListeners() throws Exception {
        Message message = m("count", "1");
        ClientListener listener1 = new ThrowingMultiListener();
        MultiListener multiListener = new MultiListener();
        _client.setMaxQueue(1);
        _client.addListener(listener1);
        _client.addListener(multiListener);
        _client.deliver(message);
        replacedertTrue(multiListener.messageListenerCalled());
        multiListener.reset();
        _client.deliver(message);
        replacedertTrue(multiListener.queueListenerCalled());
        replacedertTrue(multiListener.messageListenerCalled());
        multiListener.reset();
        _client.doDeliverListeners();
        replacedertTrue(multiListener.deliverListenerCalled());
        multiListener.reset();
        _client.remove(false);
        replacedertTrue(multiListener.removeListenerCalled());
        multiListener.reset();
    }

    /*
     * QueueListener examples
     */
    public void testDeleteWhenFullQueue() throws Exception {
        Message delete = m("delete", "a");
        Message keep = m("keep", "b");
        Message add = m("add", "c");
        _client.setMaxQueue(2);
        _client.addListener(new DeleteWhenFullQueueListener());
        _client.deliver(delete);
        _client.deliver(keep);
        _client.deliver(add);
        replacedertEquals(resultsList(keep, add), _client.takeMessages());
    }

    public void testDiscardNewMessageQueue() throws Exception {
        Message keep1 = m("keep1", "a");
        Message keep2 = m("keep2", "b");
        Message discard = m("discard", "c");
        _client.setMaxQueue(2);
        _client.addListener(new DiscardNewMessageQueueListener());
        _client.deliver(keep1);
        _client.deliver(keep2);
        _client.deliver(discard);
        replacedertEquals(resultsList(keep1, keep2), _client.takeMessages());
    }

    public void testModifyExistingMessagesQueue() throws Exception {
        Message keep = m("keep", "a");
        Message delete = m("delete", "b");
        Message add = m("add", "c");
        _client.setMaxQueue(2);
        _client.addListener(new ModifyExistingMessagesQueueListener());
        _client.deliver(keep);
        _client.deliver(delete);
        _client.deliver(add);
        replacedertEquals(resultsList(keep, add), _client.takeMessages());
    }

    // TODO: improve this test?
    public void testTakeWhileQueueing() throws Exception {
        _client.setMaxQueue(2);
        _client.addListener(new DeleteWhenFullQueueListener());
        Message[] m = new Message[5];
        for (int i = 0; i < m.length; ++i) {
            m[i] = m(i + "", i + "");
        }
        (new Thread() {

            public void run() {
                while (true) {
                    _client.getQueue().poll();
                    try {
                        Thread.sleep(100);
                    } catch (Exception e) {
                    }
                }
            }
        }).start();
        for (Message message : m) {
            _client.deliver(message);
        }
        replacedertEquals(resultsList(m[m.length - 2], m[m.length - 1]), _client.takeMessages());
    }

    public void testId() throws Exception {
        AbstractBayeux bayeux = new BayeuxStub();
        // bayeux.setNodeId("nodeid");
        _client = new StandaloneClient(bayeux);
        bayeux.addClient(_client, null);
    // TODO
    }

    public void testMessageListener() throws Exception {
        _message.put("key", "value");
        _client.addListener(new CheckMessageListener(_message));
        _client.addListener(new CheckMessageListener(_message));
        _client.deliver(_message);
    }

    public void testRemoveListener() throws Exception {
    // TODO
    }

    public void testDeliverListener() throws Exception {
        final boolean[] called = { false };
        _client.addListener(new DeliverListener() {

            public void deliver(Client client, Queue<Message> queue) {
                called[0] = true;
            }
        });
        Message ping = m("ping", "hello");
        _client.deliver(ping);
        replacedertFalse(called[0]);
        _client.doDeliverListeners();
        replacedertTrue(called[0]);
    }

    /*  // TODO: make sure this works properly. I think there's a chance of a deadlock
    public void testTakeMessage() throws Exception
    {
        Message[] messages = {
                m("a", "apple"),
                m("b", "bapple"),
                m("c", "capple"),
                m("d", "dapple"),
                m("e", "eapple"),
                m("f", "fapple")
        };

        final CountDownLatch todo = new CountDownLatch(messages.length);

        // temporary variable to avoid error with abstract lists not implementing remove
        List<Message> messageList = new ArrayList<Message>();
        messageList.addAll(Arrays.asList(messages));
        _client.returnMessages(messageList);

        final ClientImpl threadClient = _client;
        for(int i = 0; i < _client.getMessages(); ++i)
        {
            final int x = i;
            (new Thread() {
                public void run()
                {
                    try
                    {
                        int sleep = 10;
                        Thread.sleep(sleep);
                    }
                    catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }

                    Message message = threadClient.takeMessage();
                    todo.countDown();
                    // System.out.print(todo.getCount() + " -- ");
                    // System.out.println(x + " in thread client: " + message + "; "+threadClient.getMessages() + " left");


                }
            }).start();
        }

        todo.await(5, TimeUnit.SECONDS);
    }
*/
    private Message m(String key, String value) {
        Message message = new MessageImpl();
        message.put(key, value);
        return message;
    }

    private List<Message> resultsList(Message m1, Message m2) {
        return Arrays.asList(new Message[] { m1, m2 });
    }

    clreplaced StandaloneClient extends ClientImpl {

        public StandaloneClient() {
            super(new BayeuxStub(), "standalone");
        }

        public StandaloneClient(AbstractBayeux bayeux) {
            super(bayeux, "standalone");
        }

        /*
         * Warn for methods that require a proper Bayeux object
         */
        @Override
        public void deliver(Client from, String toChannel, Object data, String id) {
            System.err.println("Method unsupported!");
        }

        public void deliver(Message message) {
            doDelivery(null, message);
        }

        // @Override
        // public void remove(boolean timeout)
        // {
        // System.err.println("Method unsupported!");
        // }
        @Override
        public void setBrowserId(String id) {
            System.err.println("Method unsupported!");
        }
    }

    /*
     * stub out and use to initialize a "standalone" client
     */
    static clreplaced BayeuxStub extends AbstractBayeux {

        public BayeuxStub() {
            try {
                _random = SecureRandom.getInstance("SHA1PRNG");
            } catch (Exception e) {
                _random = new Random();
            }
            // lacks the context hashcode from AbstractBayeux#initialize()
            _random.setSeed(_random.nextLong() ^ hashCode() ^ Runtime.getRuntime().freeMemory());
        }

        public ClientImpl newRemoteClient() {
            return null;
        }
    }

    static clreplaced DeleteWhenFullQueueListener implements QueueListener {

        public boolean queueMaxed(Client from, Client client, Message message) {
            client.getQueue().poll();
            return true;
        }
    }

    static clreplaced DiscardNewMessageQueueListener implements QueueListener {

        public boolean queueMaxed(Client from, Client client, Message message) {
            return false;
        }
    }

    static clreplaced ModifyExistingMessagesQueueListener implements QueueListener {

        public boolean queueMaxed(Client from, Client client, Message message) {
            Iterator<Message> queueIterator = client.getQueue().iterator();
            boolean removed = false;
            while (queueIterator.hasNext()) {
                Message m = queueIterator.next();
                if (m.get("delete") != null) {
                    queueIterator.remove();
                    removed = true;
                }
            }
            return removed;
        }
    }

    static clreplaced CheckMessageListener implements MessageListener {

        Message _message;

        public CheckMessageListener(Message message) {
            _message = message;
        }

        public void deliver(Client fromClient, Client toClient, Message msg) {
            replacedertEquals(_message, msg);
        }
    }

    private static clreplaced ThrowingMultiListener implements RemoveListener, QueueListener, MessageListener, DeliverListener {

        public void removed(String s, boolean b) {
            throw new RuntimeException();
        }

        public boolean queueMaxed(Client client, Client client1, Message message) {
            throw new RuntimeException();
        }

        public void deliver(Client client, Client client1, Message message) {
            throw new RuntimeException();
        }

        public void deliver(Client client, Queue<Message> messages) {
            throw new RuntimeException();
        }
    }

    private static clreplaced MultiListener implements RemoveListener, QueueListener, MessageListener, DeliverListener {

        private boolean removeCalled;

        private boolean queueCalled;

        private boolean messageCalled;

        private boolean deliverCalled;

        public void removed(String s, boolean b) {
            removeCalled = true;
        }

        public boolean queueMaxed(Client client, Client client1, Message message) {
            queueCalled = true;
            return true;
        }

        public void deliver(Client client, Client client1, Message message) {
            messageCalled = true;
        }

        public void deliver(Client client, Queue<Message> messages) {
            deliverCalled = true;
        }

        private boolean removeListenerCalled() {
            return removeCalled;
        }

        private boolean queueListenerCalled() {
            return queueCalled;
        }

        private boolean messageListenerCalled() {
            return messageCalled;
        }

        private boolean deliverListenerCalled() {
            return deliverCalled;
        }

        public void reset() {
            removeCalled = false;
            queueCalled = false;
            messageCalled = false;
            deliverCalled = false;
        }
    }
}

18 View Complete Implementation : BayeuxService.java
Copyright Apache License 2.0
Author : ceefour
/* ------------------------------------------------------------ */
private void invoke(final Method method, final Client fromClient, final Client toClient, final Message msg) {
    if (_threadPool == null)
        doInvoke(method, fromClient, toClient, msg);
    else {
        _threadPool.dispatch(new Runnable() {

            public void run() {
                try {
                    ((MessageImpl) msg).incRef();
                    doInvoke(method, fromClient, toClient, msg);
                } finally {
                    ((MessageImpl) msg).decRef();
                }
            }
        });
    }
}

18 View Complete Implementation : JSONPTransport.java
Copyright Apache License 2.0
Author : ceefour
public void send(Message message) throws IOException {
    if (message != null) {
        if (_responses == 0) {
            HttpServletResponse response = getResponse();
            response.setContentType(_mimeType);
            _out = response.getWriter();
            if (_commented)
                _out.write("/*");
            _out.write(this._jsonp == null ? __DEFAULT_CALLBACK : _jsonp);
            _out.write("([");
        } else {
            _out.write(",\r\n");
        }
        String r = (message instanceof MessageImpl) ? ((MessageImpl) message).getJSON() : JSON.toString(message);
        ((MessageImpl) message).decRef();
        _responses++;
        _out.write(r);
    }
}

18 View Complete Implementation : MessagePool.java
Copyright Apache License 2.0
Author : ceefour
/* ------------------------------------------------------------ */
public MessageImpl newMessage(Message replacedociated) {
    MessageImpl message = _messagePool.poll();
    if (message == null)
        message = new MessageImpl(this);
    message.incRef();
    if (replacedociated != null)
        message.setreplacedociated(replacedociated);
    return message;
}

18 View Complete Implementation : MessagePoolTest.java
Copyright Apache License 2.0
Author : ceefour
public void testParse() throws Exception {
    MessagePool pool = new MessagePool();
    Message[] messages = pool.parse(test);
    replacedertEquals(9, messages.length);
}

18 View Complete Implementation : AckExtension.java
Copyright MIT License
Author : napcs
public Message rcvMeta(Client from, Message message) {
    if (Bayeux.META_HANDSHAKE.equals(message.getChannel())) {
        Map<String, Object> ext = message.getExt(false);
        _serverSupportsAcks = ext != null && Boolean.TRUE.equals(ext.get(EXT_FIELD));
    } else if (_serverSupportsAcks && Boolean.TRUE.equals(message.get(Bayeux.SUCCESSFUL_FIELD)) && Bayeux.META_CONNECT.equals(message.getChannel())) {
        Map<String, Object> ext = message.getExt(false);
        if (ext != null) {
            Object ack = ext.get(EXT_FIELD);
            if (ack instanceof Number)
                _ackId = ((Number) ack).intValue();
        }
    }
    return message;
}

18 View Complete Implementation : AckExtension.java
Copyright MIT License
Author : napcs
public Message sendMeta(Client from, Message message) {
    if (Bayeux.META_HANDSHAKE.equals(message.getChannel())) {
        message.getExt(true).put(EXT_FIELD, Boolean.TRUE);
        _ackId = -1;
    } else if (_serverSupportsAcks && Bayeux.META_CONNECT.equals(message.getChannel())) {
        message.getExt(true).put(EXT_FIELD, _ackId);
    }
    return message;
}

18 View Complete Implementation : AckExtension.java
Copyright MIT License
Author : napcs
public Message rcv(Client from, Message message) {
    return message;
}

18 View Complete Implementation : AckExtension.java
Copyright MIT License
Author : napcs
public Message send(Client from, Message message) {
    return message;
}

18 View Complete Implementation : TimesyncClientExtension.java
Copyright MIT License
Author : napcs
public Message sendMeta(Client from, Message message) {
    Map<String, Object> ext = message.getExt(true);
    long now = System.currentTimeMillis();
    JSON.Literal timesync = new JSON.Literal("{\"tc\":" + now + ",\"l\":" + _lag + ",\"o\":" + _offset + "}");
    ext.put("timesync", timesync);
    return message;
}

18 View Complete Implementation : TimesyncClientExtension.java
Copyright MIT License
Author : napcs
public Message rcvMeta(Client from, Message message) {
    Map<String, Object> ext = message.getExt(false);
    if (ext != null) {
        Map<String, Object> sync = (Map<String, Object>) ext.get("timesync");
        if (sync != null) {
            long now = System.currentTimeMillis();
            final long tc = ((Number) sync.get("tc")).longValue();
            final long ts = ((Number) sync.get("ts")).longValue();
            final int p = ((Number) sync.get("p")).intValue();
            // final int a=((Number)sync.get("a")).intValue();
            int l2 = (int) ((now - tc - p) / 2);
            int o2 = (int) (ts - tc - l2);
            _lag = _lag == 0 ? l2 : (_lag + l2) / 2;
            _offset = _offset == 0 ? o2 : (_offset + o2) / 2;
        }
    }
    return message;
}

18 View Complete Implementation : OortComet.java
Copyright MIT License
Author : napcs
@Override
protected String extendOut(String message) {
    if (message == BayeuxClient.Handshake.__HANDSHAKE) {
        try {
            Message[] msg = _msgPool.parse(message);
            Map<String, Object> oort = new HashMap<String, Object>();
            oort.put("oort", _oort.getURL());
            oort.put("oortSecret", _oort.getSecret());
            oort.put("comet", _cometUrl);
            Map<String, Object> ext = msg[0].getExt(true);
            ext.put("oort", oort);
            super.extendOut(msg[0]);
            message = _msgPool.getJSON().toJSON(msg);
            for (Message m : msg) if (m instanceof MessageImpl)
                ((MessageImpl) m).decRef();
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
    } else
        message = super.extendOut(message);
    System.err.println(_oort.getURL() + " ==> " + message);
    return message;
}

18 View Complete Implementation : OortComet.java
Copyright MIT License
Author : napcs
@Override
protected void metaHandshake(boolean success, boolean reestablish, Message message) {
    synchronized (_oort) {
        _handshook = success;
        super.metaHandshake(success, reestablish, message);
        if (success) {
            Map<String, Object> ext = (Map<String, Object>) message.get("ext");
            if (ext != null) {
                Map<String, Object> oort = (Map<String, Object>) ext.get("oort");
                if (oort != null) {
                    _cometSecret = (String) oort.get("cometSecret");
                    startBatch();
                    subscribe("/oort/cloud");
                    for (String channel : _oort._channels) subscribe(channel);
                    publish("/oort/cloud", _oort.getKnownComets(), _cometSecret);
                    endBatch();
                }
            }
            System.err.println(_oort.getURL() + " <== " + ext);
        }
    }
}

18 View Complete Implementation : AbstractBayeux.java
Copyright MIT License
Author : napcs
/* ------------------------------------------------------------ */
protected Message extendRcv(ClientImpl from, Message message) {
    if (_extensions != null) {
        for (int i = _extensions.length; message != null && i-- > 0; ) message = _extensions[i].rcv(from, message);
    }
    if (from != null) {
        Extension[] client_exs = from.getExtensions();
        if (client_exs != null) {
            for (int i = client_exs.length; message != null && i-- > 0; ) message = client_exs[i].rcv(from, message);
        }
    }
    return message;
}

18 View Complete Implementation : AbstractBayeux.java
Copyright MIT License
Author : napcs
/* ------------------------------------------------------------ */
public Message extendSendMeta(ClientImpl from, Message message) {
    if (_extensions != null) {
        for (int i = 0; message != null && i < _extensions.length; i++) message = _extensions[i].sendMeta(from, message);
    }
    if (from != null) {
        Extension[] client_exs = from.getExtensions();
        if (client_exs != null) {
            for (int i = 0; message != null && i < client_exs.length; i++) message = client_exs[i].sendMeta(from, message);
        }
    }
    return message;
}

18 View Complete Implementation : AbstractBayeux.java
Copyright MIT License
Author : napcs
/* ------------------------------------------------------------ */
protected Message extendRcvMeta(ClientImpl from, Message message) {
    if (_extensions != null) {
        for (int i = _extensions.length; message != null && i-- > 0; ) message = _extensions[i].rcvMeta(from, message);
    }
    if (from != null) {
        Extension[] client_exs = from.getExtensions();
        if (client_exs != null) {
            for (int i = client_exs.length; message != null && i-- > 0; ) message = client_exs[i].rcvMeta(from, message);
        }
    }
    return message;
}

18 View Complete Implementation : AbstractBayeux.java
Copyright MIT License
Author : napcs
/* ------------------------------------------------------------ */
protected Message extendSendBayeux(Client from, Message message) {
    if (_extensions != null) {
        for (int i = 0; message != null && i < _extensions.length; i++) {
            message = _extensions[i].send(from, message);
        }
    }
    return message;
}

18 View Complete Implementation : AbstractBayeux.java
Copyright MIT License
Author : napcs
/* ------------------------------------------------------------ */
/**
 * Publish data to a channel. Creates a message and delivers it to the root channel.
 *
 * @param to the channel id to publish to
 * @param from the client that publishes
 * @param data the data to publish
 * @param msgId the message id
 * @param lazy whether the message is published lazily
 */
protected void doPublish(ChannelId to, Client from, Object data, String msgId, boolean lazy) {
    final MessageImpl message = newMessage();
    message.put(CHANNEL_FIELD, to.toString());
    if (msgId == null) {
        long id = message.hashCode() ^ (to == null ? 0 : to.hashCode()) ^ (from == null ? 0 : from.hashCode());
        id = id < 0 ? -id : id;
        message.put(ID_FIELD, Long.toString(id, 36));
    } else
        message.put(ID_FIELD, msgId);
    message.put(DATA_FIELD, data);
    message.setLazy(lazy);
    final Message m = extendSendBayeux(from, message);
    if (m != null)
        _root.doDelivery(to, from, m);
    if (m instanceof MessageImpl)
        ((MessageImpl) m).decRef();
}

18 View Complete Implementation : BayeuxService.java
Copyright MIT License
Author : napcs
/* ------------------------------------------------------------ */
private void invoke(final Method method, final Client fromClient, final Client toClient, final Message msg) {
    if (_threadPool == null) {
        doInvoke(method, fromClient, toClient, msg);
    } else {
        ((MessageImpl) msg).incRef();
        _threadPool.dispatch(new Runnable() {

            public void run() {
                asyncDoInvoke(method, fromClient, toClient, msg);
            }
        });
    }
}

18 View Complete Implementation : BayeuxService.java
Copyright MIT License
Author : napcs
protected void asyncDoInvoke(Method method, Client fromClient, Client toClient, Message msg) {
    try {
        doInvoke(method, fromClient, toClient, msg);
    } finally {
        ((MessageImpl) msg).decRef();
    }
}