Package org.atmosphere.cpr

Examples of org.atmosphere.cpr.AtmosphereResourceImpl


                    final AtomicReference<Future<?>> f = new AtomicReference<Future<?>>();
                    f.set(suspendTimer.scheduleAtFixedRate(new Runnable() {
                        @Override
                        public void run() {
                            if (!w.get().isClosed() && (System.currentTimeMillis() - w.get().lastTick()) > action.timeout()) {
                                AtmosphereResourceImpl impl = state.resource();
                                if (impl != null) {
                                    asynchronousProcessor.endRequest(impl, false);
                                    f.get().cancel(true);
                                }
                            }
View Full Code Here


    /**
     * {@inheritDoc}
     */
    @Override
    public void close() {
        AtmosphereResourceImpl impl = AtmosphereResourceImpl.class.cast(resource());
        if (impl != null) {
            channel.write(new CloseWebSocketFrame()).addListener(ChannelFutureListener.CLOSE);
        }
    }
View Full Code Here

                            msg.setPadding(messages.size() > 1);
                            try {
                                sendMessage(msg.toString());
                            } catch (Exception e) {

                                AtmosphereResourceImpl resource = session.getAtmosphereResourceImpl();
                                // if BroadcastCache is available, add the message to the cache
                                if (resource != null && DefaultBroadcaster.class.isAssignableFrom(resource.getBroadcaster().getClass())) {
                                    resource.getBroadcaster().getBroadcasterConfig().getBroadcasterCache().
                                            addToCache(resource.getBroadcaster().getID(), resource.uuid(),
                                                    new BroadcastMessage(msg));
                                }
                            }
                            break;
                        default:
View Full Code Here

            logger.trace("Session[" + session.getSessionId() + "]: " + "sendMessage(String): " + message);

            synchronized (this) {
                if (is_open) {

                    AtmosphereResourceImpl resource = session.getAtmosphereResourceImpl();

                    logger.trace("Session[" + session.getSessionId() + "]: " + resource.getRequest().getMethod() + "sendMessage");

                    try {
                        writeData(resource.getResponse(), message);
                    } catch (Exception e) {
                        if (!resource.isCancelled()) {
                            logger.trace("calling from " + this.getClass().getName() + " : " + "sendMessage ON FORCE UN RESUME");
                            try {
                                finishSend(resource.getResponse());
                            } catch (IOException ex) {
                                logger.trace("", ex);
                            }

                            resource.resume();
                        }
                        throw new SocketIOException(e);
                    }
                    if (!isStreamingConnection) {
                        try {
                            finishSend(resource.getResponse());
                        } catch (IOException e) {
                            logger.trace("", e);
                        }
                        resource.resume();
                    } else {
                        logger.trace("calling from " + this.getClass().getName() + " : " + "sendMessage");
                        session.startHeartbeatTimer();
                    }
                } else {
View Full Code Here

        @Override
        public Action handle(AtmosphereRequest request, final AtmosphereResponse response, SocketIOSession session) throws IOException {
            logger.trace("Session id[" + session.getSessionId() + "] method=" + request.getMethod() + "  response HashCode=" + response.hashCode());

            AtmosphereResourceImpl resource = (AtmosphereResourceImpl) request.getAttribute(ApplicationConfig.ATMOSPHERE_RESOURCE);

            if ("GET".equals(request.getMethod())) {
                synchronized (this) {
                    if (!is_open) {
                        response.sendError(AtmosphereResponse.SC_NOT_FOUND);
                    } else {
                        if (!isStreamingConnection) {
                            if (resource != null) {
                                resource.getRequest().setAttribute(SocketIOAtmosphereHandler.SOCKETIO_SESSION_ID, session.getSessionId());
                                resource.getRequest().setAttribute(SocketIOAtmosphereHandler.SOCKETIO_SESSION_OUTBOUND, session.getTransportHandler());
                                session.setAtmosphereResourceImpl(resource);

                                resource.addEventListener(new AtmosphereResourceEventListenerAdapter() {
                                    @Override
                                    public void onResume(AtmosphereResourceEvent event) {
                                        if (event.isResumedOnTimeout()) {
                                            event.getResource().write(new SocketIOPacketImpl(PacketType.NOOP).toString());
                                        }
                                    }
                                });

                                session.clearTimeoutTimer();
                                request.setAttribute(SESSION_KEY, session);
                                boolean resume = false;

                                StringBuilder data = new StringBuilder();
                                // if there is a Broadcaster cache, retrieve the messages from the cache, and send them
                                if (DefaultBroadcaster.class.isAssignableFrom(resource.getBroadcaster().getClass())) {

                                    List<Object> cachedMessages = resource.getBroadcaster().getBroadcasterConfig().getBroadcasterCache()
                                            .retrieveFromCache(resource.getBroadcaster().getID(), resource.uuid());

                                    if (cachedMessages != null && !cachedMessages.isEmpty()) {
                                        if (cachedMessages.size() > 1) {
                                            for (Object object : cachedMessages) {
                                                String msg = object.toString();
                                                data.append(SocketIOPacketImpl.SOCKETIO_MSG_DELIMITER)
                                                        .append(msg.length())
                                                        .append(SocketIOPacketImpl.SOCKETIO_MSG_DELIMITER).append(msg);
                                            }
                                        } else if (cachedMessages.size() == 1) {
                                            data.append(cachedMessages.get(0));
                                        }

                                        // something to send ?
                                        if (!data.toString().isEmpty()) {
                                            startSend(response);
                                            writeData(response, data.toString());
                                            finishSend(response);

                                            // force a resume, because we sent data
                                            resource.resume();

                                            resume = true;
                                        }
                                    }

                                }

                                if (!resume) {
                                    resource.disableSuspend(false);
                                    resource.suspend(session.getRequestSuspendTime());
                                    resource.disableSuspend(true);
                                }
                            }
                        } else {
                            // won't happend, by should be for xhr-streaming transport
                            response.sendError(AtmosphereResponse.SC_NOT_FOUND);
                        }
                    }
                }
            } else if ("POST".equals(request.getMethod())) {
                if (is_open) {
                    int size = request.getContentLength();
                    if (size == 0) {
                        response.sendError(AtmosphereResponse.SC_BAD_REQUEST);
                    } else {
                        String data = (String) request.getAttribute(POST_MESSAGE_RECEIVED);
                        if (data == null) {
                            data = decodePostData(request.getContentType(), extractString(request.getReader()));
                        }
                        if (data == null || data.length() == 0) {
                            data = SocketIOSessionManagerImpl.mapper.readValue(request.getParameter("d"), String.class);
                        }
                        if (data != null && data.length() > 0) {

                            List<SocketIOPacketImpl> list = SocketIOPacketImpl.parse(data);

                            synchronized (session) {
                                for (SocketIOPacketImpl msg : list) {

                                    if (msg.getFrameType().equals(SocketIOPacketImpl.PacketType.EVENT)) {

                                        // send message on the suspended request
                                        session.onMessage(session.getAtmosphereResourceImpl(), session.getTransportHandler(), msg.getData());

                                        // send completion flag on the post request
                                        writeData(response, SocketIOPacketImpl.POST_RESPONSE);

                                    } else {
                                        // send completion flag on the post request
                                        writeData(response, SocketIOPacketImpl.POST_RESPONSE);
                                    }
                                }
                            }
                        }
                    }
                    // force a resume on a POST request
                    resource.resume();
                }
            } else {
                response.sendError(AtmosphereResponse.SC_BAD_REQUEST);
            }
            return Action.CANCELLED;
View Full Code Here

  @Override
  public void onRequest()
  {
    TesterBroadcaster broadcaster = (TesterBroadcaster) eventBus.getBroadcaster();

    AtmosphereResource atmosphereResource = new AtmosphereResourceImpl();
    AtmosphereRequest atmosphereRequest = AtmosphereRequest.wrap(wicketTester.getRequest());
    AtmosphereResponse atmosphereResponse = AtmosphereResponse.wrap(wicketTester.getResponse());
    TesterAsyncSupport asyncSupport = new TesterAsyncSupport();
    atmosphereResource.initialize(broadcaster.getApplicationConfig(), broadcaster, atmosphereRequest, atmosphereResponse,
        asyncSupport, new AtmosphereHandlerAdapter());

    atmosphereResource.setBroadcaster(broadcaster);
    broadcaster.addAtmosphereResource(atmosphereResource);

    String uuid = atmosphereResource.uuid();
    Page page = getComponent().getPage();

    page.setMetaData(ATMOSPHERE_UUID, uuid);
    eventBus.registerPage(uuid, page);
  }
View Full Code Here

    @Override
    @SuppressWarnings("unchecked")
    public void onStateChange(AtmosphereResourceEvent event) throws IOException {

        // Original Value
        AtmosphereResourceImpl r = AtmosphereResourceImpl.class.cast(event.getResource());
        AtmosphereRequest request = r.getRequest(false);
        Boolean resumeOnBroadcast = r.resumeOnBroadcast();
        if (!resumeOnBroadcast) {
            // For legacy reason, check the attribute as well
            Object o = request.getAttribute(ApplicationConfig.RESUME_ON_BROADCAST);
            if (o != null && Boolean.class.isAssignableFrom(o.getClass())) {
                resumeOnBroadcast = Boolean.class.cast(o);
            }
        }

        // Disable resume so cached message can be send in one chunk.
        if (resumeOnBroadcast) {
            r.resumeOnBroadcast(false);
            request.setAttribute(ApplicationConfig.RESUME_ON_BROADCAST, false);
        }

        RemoteEndpointImpl remoteEndpoint = (RemoteEndpointImpl) request.getAttribute(RemoteEndpointImpl.class.getName());

        if (remoteEndpoint != null) {
            if (event.isCancelled() || event.isClosedByClient()) {
                remoteEndpoint.status().status(event.isCancelled() ? Status.STATUS.UNEXPECTED_CLOSE : Status.STATUS.CLOSED_BY_CLIENT);
                request.removeAttribute(RemoteEndpointImpl.class.getName());
                trackedUUID.remove(r.uuid());

                invokeOpenOrClose(onCloseMethod, remoteEndpoint);
            } else if (event.isResumedOnTimeout() || event.isResuming()) {
                remoteEndpoint.status().status(Status.STATUS.CLOSED_BY_TIMEOUT);
                request.removeAttribute(RemoteEndpointImpl.class.getName());

                invokeOpenOrClose(onTimeoutMethod, remoteEndpoint);
            } else {
                super.onStateChange(event);
            }
        }

        if (resumeOnBroadcast && r.isSuspended()) {
            r.resume();
        }
    }
View Full Code Here

    @Test
    public void testWriteTimeout() throws ExecutionException, InterruptedException, ServletException {
        final CountDownLatch latch = new CountDownLatch(1);
        final CountDownLatch guard = new CountDownLatch(1);

        ar = new AtmosphereResourceImpl(config,
                broadcaster,
                mock(AtmosphereRequest.class),
                AtmosphereResponse.newInstance(),
                mock(BlockingIOCometSupport.class),
                atmosphereHandler);
View Full Code Here

        assertEquals(t.get().getMessage(), "Unable to write after 2000");
    }

    @Test
    public void testNoWriteTimeout() throws ExecutionException, InterruptedException, ServletException {
        ar = new AtmosphereResourceImpl(config,
                broadcaster,
                mock(AtmosphereRequest.class),
                AtmosphereResponse.newInstance(),
                mock(BlockingIOCometSupport.class),
                atmosphereHandler);
View Full Code Here

        }
    }

    @Override
    public Action inspect(final AtmosphereResource r) {
        final AtmosphereResourceImpl impl = AtmosphereResourceImpl.class.cast(r);
        final AtmosphereRequest request = impl.getRequest(false);
        final AtmosphereResponse response = impl.getResponse(false);

        // Check heartbeat
        if (clientHeartbeatFrequencyInSeconds > 0) {
            byte[] body = IOUtils.readEntirelyAsByte(r);
View Full Code Here

TOP

Related Classes of org.atmosphere.cpr.AtmosphereResourceImpl

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