Examples of AtmosphereResponse


Examples of org.atmosphere.cpr.AtmosphereResponse

            }
        });
    }

    private Action injectMessage(AtmosphereResource r) {
        final AtmosphereResponse response = r.getResponse();
        final AtmosphereRequest request = r.getRequest();

        String body = IOUtils.readEntirely(r).toString();
        try {
            if (!body.isEmpty() && body.startsWith("d=")) {
                body = URLDecoder.decode(body, "UTF-8");
                body = body.substring(2);
                response.setStatus(200);
                response.write("ok", true).flushBuffer();
                reInject(request, response, body);
            } else {
                String[] messages = parseMessageString(body);
                for (String m : messages) {
                    if (m == null) continue;
                    reInject(request, response, m);
                }
                response.setStatus(204);
            }
        } catch (Exception e) {
            logger.error("", e);
        }
        return Action.CANCELLED;
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

public class LongPollingTransport extends TransportBasedListener {
    private static final Logger logger = LoggerFactory.getLogger(LongPollingTransport.class);

    @Override
    public void onSuspend(AtmosphereResourceEvent event) {
        AtmosphereResponse response = event.getResource().getResponse();
        response.setContentType("application/javascript");
        try {
            response.write("o\r\n\r\n".getBytes(), true).flushBuffer();
            response.closeStreamOrWriter();
        } catch (IOException e) {
            logger.trace("", e);
        }

    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

public class SSETransport extends TransportBasedListener {
    private static final Logger logger = LoggerFactory.getLogger(SSETransport.class);
    @Override
    public void onSuspend(AtmosphereResourceEvent event) {
        AtmosphereResponse response = event.getResource().getResponse();
        try {
            response.write("o".getBytes()).flushBuffer();
        } catch (IOException e) {
            logger.trace("", e);
        }
    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

import org.atmosphere.cpr.AtmosphereResponse;

public class WebSocketTransport extends TransportBasedListener {
    @Override
    public void onPreSuspend(AtmosphereResourceEvent event) {
        AtmosphereResponse response = event.getResource().getResponse();
        response.setContentType("text/plain");

        response.write("o\n".getBytes());
    }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

  }

  @Override
  protected void push(Entry entry)
  {
    AtmosphereResponse response = entry.resource.getResponse();
    String message = entry.message.toString();
    response.write(message);
  }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

  {
    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);
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

  }

  @Override
  protected void push(Entry entry)
  {
    AtmosphereResponse response = entry.resource.getResponse();
    String message = entry.message.toString();
    response.write(message);
  }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

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


      AtmosphereResponse response = event.getResource().getResponse();
      AtmosphereResource resource = event.getResource();

      if (event.isSuspended()) {

        // Set content type before do response.getWriter()
        // http://docs.oracle.com/javaee/5/api/javax/servlet/ServletResponse.html#setContentType(java.lang.String)
        response.setContentType("text/plain; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");


        if (event.getMessage().getClass().isArray()) {

          LOG.fine("SEND MESSAGE ARRAY " + event.getMessage().toString());

          List<Object> list = Arrays.asList(event.getMessage());

          response.getOutputStream().write(MSG_SEPARATOR.getBytes(MSG_CHARSET));
          for (Object object : list) {
            String message = (String) object;
            message += MSG_SEPARATOR;
            response.getOutputStream().write(message.getBytes(MSG_CHARSET));
          }

        } else if (event.getMessage() instanceof List) {

          LOG.fine("SEND MESSAGE LIST " + event.getMessage().toString());

          @SuppressWarnings("unchecked")
          List<Object> list = List.class.cast(event.getMessage());

          response.getOutputStream().write(MSG_SEPARATOR.getBytes(MSG_CHARSET));
          for (Object object : list) {
            String message = (String) object;
            message += MSG_SEPARATOR;
            response.getOutputStream().write(message.getBytes(MSG_CHARSET));
          }

        } else if (event.getMessage() instanceof String) {

          LOG.fine("SEND MESSAGE " + event.getMessage().toString());

          String message = (String) event.getMessage();
          response.getOutputStream().write(message.getBytes(MSG_CHARSET));
        }



        try {

          response.flushBuffer();

          switch (resource.transport()) {
            case JSONP:
            case LONG_POLLING:
              event.getResource().resume();
              break;
            case WEBSOCKET:
            case STREAMING:
            case SSE:
              response.getOutputStream().flush();
              break;
            default:
              LOG.info("Unknown transport");
              break;
          }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

            ok = true;
        }

        if (ok && request.getAttribute(SWAGGER_SOCKET_DISPATCHED) == null) {

            AtmosphereResponse response = r.getResponse();
            response.setContentType("application/json");

            logger.debug("Method {} Transport {}", request.getMethod(), r.transport());
            // Suspend to keep the connection OPEN.
            if (request.getMethod() == "GET" && r.transport().equals(AtmosphereResource.TRANSPORT.LONG_POLLING)) {
                r.resumeOnBroadcast(true).suspend();

                BlockingQueue<AtmosphereResource> queue = (BlockingQueue<AtmosphereResource>)
                        getContextValue(request, SUSPENDED_RESPONSE);
                if (queue == null) {
                    queue = new LinkedBlockingQueue<AtmosphereResource>();
                    request.getSession().setAttribute(SUSPENDED_RESPONSE, queue);
                }
                queue.offer(r);

                String identity = (String) getContextValue(request, IDENTITY);
                schedule(r, identity);

                return Action.SUSPEND;
            }

            AtmosphereFramework framework = r.getAtmosphereConfig().framework();
            StringBuilder d = new StringBuilder();
            try {
                InputStreamReader isr = new InputStreamReader(request.getInputStream());
                BufferedReader bufReader = new BufferedReader(isr);
                char[] charBuffer = new char[8192];

                for (int readCount = bufReader.read(charBuffer); readCount > -1; readCount = bufReader.read(charBuffer)) {
                    d.append(charBuffer, 0, readCount);
                }

                String data = d.toString();

                if (data.length() == 0) {
                    return Action.CANCELLED;
                }

                String message = data.substring(0, 20).replaceAll(" ", "");
                logger.debug(data);
                if (message.startsWith("{\"handshake\"")) {
                    // This will fail if the message is not well formed.
                    HandshakeMessage handshakeMessage = mapper.readValue(data, HandshakeMessage.class);

                    // If we missed the CloseReason for whatever reason (IE is a good candidate), make sure we swap the previous session anyway.
                    String identity = (String) getContextValue(request, IDENTITY);
                    if (identity == null) {
                        identity = UUID.randomUUID().toString();
                    } else {
                        logger.debug("Client disconnected {}, cleaning session {}", identity);
                        try {
                            Enumeration<String> e = request.getSession().getAttributeNames();
                            while (e.hasMoreElements()) {
                                request.getSession().removeAttribute(e.nextElement());
                            }
                        } catch (Exception ex) {
                            logger.warn("", ex);
                        }
                    }
                    addContextValue(request, IDENTITY, identity);

                    StatusMessage statusMessage = new StatusMessage.Builder().status(new StatusMessage.Status(200, "OK"))
                            .identity(identity).build();
                    response.setContentType("application/json");
                    response.getOutputStream().write(mapper.writeValueAsBytes(statusMessage));

                    if (r.transport() == AtmosphereResource.TRANSPORT.WEBSOCKET) {
                        schedule(r, identity);
                    }

                    if (!delegateHandshake) {
                        return Action.CANCELLED;
                    }
                } else if (message.startsWith("{\"close\"")) {
                    CloseMessage c = mapper.readValue(data, CloseMessage.class);

                    logger.debug("Client disconnected {} with reason {}", c.getClose().getIdentity(), c.getClose().getReason());
                    try {
                        request.getSession().invalidate();
                    } catch (Exception ex) {
                        logger.warn("", ex);
                    }
                    return Action.CANCELLED;
                } else {
                    Message swaggerSocketMessage = mapper.readValue(data, Message.class);
                    swaggerSocketMessage.transactionID(UUID.randomUUID().toString());

                    String identity = (String) getContextValue(request, IDENTITY);

                    if (!swaggerSocketMessage.getIdentity().equals(identity)) {
                        StatusMessage statusMessage = new StatusMessage.Builder().status(new StatusMessage.Status(503, "Not Allowed"))
                                .identity(swaggerSocketMessage.getIdentity()).build();
                        response.getOutputStream().write(mapper.writeValueAsBytes(statusMessage));
                        return Action.CANCELLED;
                    }

                    transactionIdentity.set(swaggerSocketMessage.transactionID());

                    List<Request> requests = swaggerSocketMessage.getRequests();
                    addContextValue(request, swaggerSocketMessage.transactionID() + RESPONSE_COUNTER, new AtomicInteger(requests.size()));

                    AtmosphereRequest ar;
                    for (Request req : requests) {
                        ar = toAtmosphereRequest(request, req);
                        try {
                            ar.setAttribute(SWAGGER_SOCKET_DISPATCHED, "true");

                            // This is a new request, we must clean the Websocket AtmosphereResource.
                            request.removeAttribute(INJECTED_ATMOSPHERE_RESOURCE);
                            response.request(ar);
                            attachWriter(r);
                            ssRequest.set(req);
                            request.setAttribute("swaggerSocketRequest", req);

                            Action action = framework.doCometSupport(ar, response);
                            if (action.type() == Action.TYPE.SUSPEND) {
                                ar.destroyable(false);
                                response.destroyable(false);
                            }
                        } catch (ServletException e) {
                            logger.warn("", e);
                            return Action.CANCELLED;
                        }
View Full Code Here

Examples of org.atmosphere.cpr.AtmosphereResponse

    }

    private final void attachWriter(final AtmosphereResource r) {
        final AtmosphereRequest request = r.getRequest();

        AtmosphereResponse res = r.getResponse();
        AsyncIOWriter writer = res.getAsyncIOWriter();

        BlockingQueue<AtmosphereResource> queue = (BlockingQueue<AtmosphereResource>)
                getContextValue(request, SUSPENDED_RESPONSE);
        if (queue == null) {
            queue = new LinkedBlockingQueue<AtmosphereResource>();
            request.getSession().setAttribute(SUSPENDED_RESPONSE, queue);
        }

        if (AtmosphereInterceptorWriter.class.isAssignableFrom(writer.getClass())) {
            // WebSocket already had one.
            if (r.transport() != AtmosphereResource.TRANSPORT.WEBSOCKET) {
                writer = new AtmosphereInterceptorWriter() {

                    @Override
                    protected void writeReady(AtmosphereResponse response, byte[] data) throws IOException {

                        // We are buffering response.
                        if (data == null) return;

                        BlockingQueue<AtmosphereResource> queue =
                                (BlockingQueue<AtmosphereResource>) getContextValue(request, SUSPENDED_RESPONSE);
                        if (queue != null) {
                            AtmosphereResource resource;
                            try {
                                // TODO: Should this be configurable
                                // We stay suspended for 60 seconds
                                resource = queue.poll(60, TimeUnit.SECONDS);
                            } catch (InterruptedException e) {
                                logger.trace("", e);
                                return;
                            }

                            if (resource == null) {
                                logger.debug("No resource was suspended, resuming the second connection.");
                            } else {

                                logger.trace("Resuming {}", resource.uuid());

                                try {
                                    OutputStream o = resource.getResponse().getResponse().getOutputStream();
                                    o.write(data);
                                    o.flush();

                                    resource.resume();
                                } catch (IOException ex) {
                                    logger.warn("", ex);
                                }
                            }
                        } else {
                            logger.error("Queue was null");
                        }
                    }

                    /**
                     * Add an {@link AsyncIOInterceptor} that will be invoked in the order it was added.
                     *
                     * @param filter {@link AsyncIOInterceptor
                     * @return this
                     */
                    public AtmosphereInterceptorWriter interceptor(AsyncIOInterceptor filter) {
                        if (!filters.contains(filter)) {
                            filters.addLast(filter);
                        }
                        return this;
                    }
                };
                res.asyncIOWriter(writer);
            }
            //REVIST need a better way to add a custom filter at the first entry and not at the last as
            // e.g. interceptor(AsyncIOInterceptor interceptor, int position)
            LinkedList<AsyncIOInterceptor> filters = AtmosphereInterceptorWriter.class.cast(writer).filters();
            if (!filters.contains(interceptor)) {
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.