Examples of Broadcaster


Examples of org.atmosphere.cpr.Broadcaster

                if (!game.turn(cell)) {
                    writer.println("warning - invalid move");
                }
                writer.println(game.getJSON());

                Broadcaster bc = event.getBroadcaster();

                String response = game.getJSON();

                // broadcast the updated game state
                bc.broadcast(response);

                writer.flush();

                if (game.win() != -1) {
                    game = new TTTGame();
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

            return RPCUtil.createSimpleSerializationPolicy();
        }
    };

    public int doComet(GwtAtmosphereResource resource) throws ServletException, IOException {
        Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(Broadcaster.class, GWT_BROADCASTER_ID);
        if (broadcaster == null) {
            try {
                broadcaster = BroadcasterFactory.getDefault().get(DefaultBroadcaster.class, GWT_BROADCASTER_ID);
            } catch (IllegalAccessException ex) {
                logger.error("Failed to get broadcaster", ex);
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

                }
            });

            servletLatch.await();

            Broadcaster b = BroadcasterFactory.getDefault().lookup(DefaultBroadcaster.class, "/*");
            assertNotNull(b);
            b.broadcast("resume").get();

            try {
                latch.await();
            } catch (InterruptedException e) {
                fail(e.getMessage());
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

    @GET
    @Path("{name}")
    @Suspend(outputComments = true, resumeOnBroadcast = false, listeners = EventsLogger.class)
    public Broadcastable listen(@PathParam("name") String topic) throws JSONException {
        Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(DefaultBroadcaster.class, topic, true);
        logger.info("thread: {} LISTENING to '{}'", Thread.currentThread().getName(), broadcaster.getID());
        if (service == null) {
            throw new AssertionError();
        }
        return new Broadcastable(new JSONObject().put("from", "system").put("msg", "Connected !"), broadcaster);
    }
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

        @StringReader.ValidateDefaultValue(false)
        public class BroadcasterStringReader implements StringReader {
            @Override
            public Object fromString(String topic) {
                Broadcaster broadcaster = null;
                try {
                    AtmosphereResource<HttpServletRequest, HttpServletResponse> r =
                            (AtmosphereResource<HttpServletRequest, HttpServletResponse>)
                                    req.getAttribute(AtmosphereServlet.ATMOSPHERE_RESOURCE);
                    BroadcasterFactory bp = (BroadcasterFactory)
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

    @POST
    @Path("{name}")
    @Broadcast
    public Broadcastable publish(@PathParam("name") String topic, @FormParam("from") String from,
            @FormParam("msg") String message) throws JSONException {
        Broadcaster broadcaster = BroadcasterFactory.getDefault().lookup(DefaultBroadcaster.class, topic, true);
        logger.info("thread: {} PUBLISH to '{}' from {}: {}",
                new Object[]{Thread.currentThread().getName(), broadcaster.getID(), from, message});
        if (service == null) {
            throw new AssertionError();
        }
        return new Broadcastable(new JSONObject().put("from", from).put("msg", message), "", broadcaster);
    }
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

        public Broadcaster getBroadcaster() {
            return atm.getBroadcaster();
        }
        public Broadcaster createBroadcaster(String ID) {
            try {
                Broadcaster b = BroadcasterFactory.getDefault().get(DefaultBroadcaster.class, ID);
                atm.setBroadcaster(b);
                return b;
            } catch (IllegalAccessException e) {
            } catch (InstantiationException e) {
            }
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

        final CountDownLatch latch = new CountDownLatch(1);
        final CountDownLatch latch2 = new CountDownLatch(1);

        servletLatch = new CountDownLatch(1);
        AsyncHttpClient c = new AsyncHttpClient();
        Broadcaster b = null;
        try {
            long currentTime = System.currentTimeMillis();
            final AtomicReference<Response> r = new AtomicReference();
            c.prepareGet(urlTarget).execute(new AsyncCompletionHandler<Response>() {

                @Override
                public Response onCompleted(Response response) throws Exception {
                    r.set(response);
                    latch.countDown();
                    return response;
                }
            });

            servletLatch.await();

            String id = broadcasterId.get();

            b = BroadcasterFactory.getDefault().lookup(DefaultBroadcaster.class, id);
            assertNotNull(b);
            b.broadcast("resume").get();

            try {
                latch.await();
            } catch (InterruptedException e) {
                fail(e.getMessage());
                return;
            }

            long time = System.currentTimeMillis() - currentTime;
            if (time < 5000) {
                assertTrue(true);
            } else {
                assertFalse(false);
            }
            assertNotNull(r.get());
            assertEquals(r.get().getStatusCode(), 200);
            String resume = r.get().getResponseBody();
            assertEquals(resume, "resumeresume");

            c.prepareGet(urlTarget).execute(new AsyncCompletionHandler<Response>() {

                @Override
                public Response onCompleted(Response response) throws Exception {
                    r.set(response);
                    latch2.countDown();
                    return response;
                }
            });

            try {
                latch2.await();
            } catch (InterruptedException e) {
                fail(e.getMessage());
                return;
            }

            assertFalse(id.equals(broadcasterId.get()));
        } catch (Exception e) {
            logger.error("test failed", e);
            fail(e.getMessage());
        } finally {
           if (b != null) b.destroy();
        }
        c.close();
    }
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

        res.setContentType("text/html;charset=ISO-8859-1");
        if (req.getMethod().equalsIgnoreCase("GET")) {
            event.suspend();
           
            Broadcaster bc = event.getBroadcaster();
            String clusterType = event.getAtmosphereConfig().getInitParameter(CLUSTER);
            if (!filterAdded.getAndSet(true) && clusterType != null){
                if (clusterType.equals("jgroups")){
                    event.getAtmosphereConfig().getServletContext().log("JGroupsFilter enabled");
                    bc.getBroadcasterConfig().addFilter(
                            new JGroupsFilter(bc, event.getAtmosphereConfig().getWebServerName()));
                }
            }

            //Simple Broadcast
            bc.getBroadcasterConfig().addFilter(new XSSHtmlFilter());
            Future<String> f = bc.broadcast(event.getAtmosphereConfig().getWebServerName()
                    + "**has suspended a connection from "
                    + req.getRemoteAddr());

            try {
                // Wait for the push to occurs. This is blocking a thread as the Broadcast operation
                // is usually asynchronous, e.g executed using an {@link ExecuturService}
                f.get();
            } catch (InterruptedException ex) {
                logger.error("", ex);
            } catch (ExecutionException ex) {
                logger.error("", ex);
            }

            // Ping the connection every 30 seconds
            bc.scheduleFixedBroadcast(req.getRemoteAddr() + "**is still listening", 30, TimeUnit.SECONDS);

            // Delay a message until the next broadcast.
            bc.delayBroadcast("Delayed Chat message");
        } else if (req.getMethod().equalsIgnoreCase("POST")) {
            String action = req.getParameterValues("action")[0];
            String name = req.getParameterValues("name")[0];

            if ("login".equals(action)) {
View Full Code Here

Examples of org.atmosphere.cpr.Broadcaster

       
        String action = request.getParameter("action");     

        String sessionId = request.getSession().getId();
        HttpSession session = request.getSession();
        Broadcaster myBroadcasterFollower = (Broadcaster) session.getAttribute(sessionId);
        if (action != null) {
            if ("login".equals(action)) {
                response.setContentType("text/plain");
                response.setCharacterEncoding("UTF-8");
                              
                String name = request.getParameter("name");
               
                if (name == null) {
                    logger.error("Name cannot be null");
                    return;
                }
               
                session.setAttribute("name", name);
               
                myBroadcasterFollower.broadcast(BEGIN_SCRIPT_TAG
                        + toJsonp("Welcome back", name)
                        + END_SCRIPT_TAG);

                // Store the Broadcaster associated with this user so
                // we can retrieve it for supporting follower.
                atmoResource.getAtmosphereConfig().getServletContext().setAttribute(name, myBroadcasterFollower);
            } else if ("post".equals(action)) {
                String message = request.getParameter("message");
                String callback = request.getParameter("callback");
               
                if (message == null) {
                    logger.error("Message cannot be null");
                    return;
                }
               
                if (callback == null) {
                    callback = "alert";
                }

                if (myBroadcasterFollower != null){
                    myBroadcasterFollower.broadcast("<script id='comet_" + counter++ + "'>"
                            + "window.parent." + callback + "(" + message + ");</script>");
                } else {
                    throw new RuntimeException("Broadcaster was null");
                }
                response.getWriter().println("ok");
            } else if ("start".equals(action)) {
                String message = "{ message : 'Welcome'}";
                response.setContentType("text/html;charset=ISO-8859-1");

                String callback = request.getParameter("callback");
                if (callback == null) {
                    callback = "alert";
                }

                // Use one Broadcaster per AtmosphereResource
                try {
                    atmoResource.setBroadcaster(BroadcasterFactory.getDefault().get());
                } catch (Throwable t){
                    throw new IOException(t);
                }

                // Create a Broadcaster based on this session id.
                myBroadcasterFollower = atmoResource.getBroadcaster();
                atmoResource.suspend();

                session.setAttribute("atmoResource", atmoResource);
                session.setAttribute(sessionId, myBroadcasterFollower);

                response.getWriter().println("<script id='comet_" + counter++ + "'>"
                        + "window.parent." + callback + "(" + message + ");</script>");
                response.getWriter().println(startingMessage);
                response.getWriter().flush();
            } else if ("following".equals(action)) {
                response.setContentType("text/html");
                String follow = request.getParameter("message");
                String name = (String)session.getAttribute("name");
               
                if (follow == null) {
                    logger.error("Message cannot be null");
                    return;
                }     
               
                if (name == null) {
                    logger.error("Name cannot be null");
                    return;
                }
               
                Broadcaster outsiderBroadcaster
                        = (Broadcaster) atmoResource.getAtmosphereConfig().getServletContext().getAttribute(follow);
                                   
                AtmosphereResource r = (AtmosphereResource)session.getAttribute("atmoResource");
                if (outsiderBroadcaster == null){
                    myBroadcasterFollower.broadcast(BEGIN_SCRIPT_TAG
                        + toJsonp("Invalid Twitter user ", follow)
                        + END_SCRIPT_TAG, r);
                    return;
                }

                outsiderBroadcaster.addAtmosphereResource(r);
               
                myBroadcasterFollower.broadcast(BEGIN_SCRIPT_TAG
                        + toJsonp("You are now following ", follow)
                        + END_SCRIPT_TAG, r);
               
                outsiderBroadcaster.broadcast(BEGIN_SCRIPT_TAG
                        + toJsonp(name, " is now following " + follow)
                        + END_SCRIPT_TAG);
            }
        }
    }
View Full Code Here
TOP
Copyright © 2018 www.massapi.com. 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.