Search in sources :

Example 11 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project sockjs-netty by cgbystrom.

the class JsonpPollingTransport method writeRequested.

@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof Frame) {
        final Frame frame = (Frame) e.getMessage();
        HttpResponse response = createResponse(CONTENT_TYPE_JAVASCRIPT);
        response.setHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
        response.setHeader(HttpHeaders.Names.CACHE_CONTROL, "no-store, no-cache, must-revalidate, max-age=0");
        ChannelBuffer escapedContent = ChannelBuffers.dynamicBuffer();
        Frame.escapeJson(Frame.encode(frame, false), escapedContent);
        String m = jsonpCallback + "(\"" + escapedContent.toString(CharsetUtil.UTF_8) + "\");\r\n";
        e.getFuture().addListener(ChannelFutureListener.CLOSE);
        final ChannelBuffer content = ChannelBuffers.copiedBuffer(m, CharsetUtil.UTF_8);
        response.setContent(content);
        response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, content.readableBytes());
        ctx.sendDownstream(new DownstreamMessageEvent(e.getChannel(), e.getFuture(), response, e.getRemoteAddress()));
        transportMetrics.messagesSent.mark();
        transportMetrics.messagesSentSize.update(content.readableBytes());
    } else {
        super.writeRequested(ctx, e);
    }
}
Also used : Frame(com.cgbystrom.sockjs.Frame) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 12 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project sockjs-netty by cgbystrom.

the class WebSocketTransport method handleWebSocketFrame.

private void handleWebSocketFrame(ChannelHandlerContext ctx, Channel channel, WebSocketFrame frame) throws IOException {
    // Check for closing frame
    if (frame instanceof CloseWebSocketFrame) {
        handshaker.close(ctx.getChannel(), (CloseWebSocketFrame) frame);
        return;
    } else if (frame instanceof PingWebSocketFrame) {
        ctx.getChannel().write(new PongWebSocketFrame(frame.getBinaryData()));
        return;
    } else if (frame instanceof TextWebSocketFrame) {
        // Send the uppercase string back.
        String request = ((TextWebSocketFrame) frame).getText();
        ChannelBuffer payload = frame.getBinaryData();
        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Channel %s received '%s'", ctx.getChannel().getId(), request));
        }
        if (frame.getBinaryData().readableBytes() == 0) {
            return;
        }
        ChannelBufferInputStream cbis = new ChannelBufferInputStream(payload);
        String[] messages;
        if (payload.getByte(0) == '[') {
            // decode array
            messages = mapper.readValue(cbis, String[].class);
        } else if (payload.getByte(0) == '"') {
            // decode string
            messages = new String[1];
            messages[0] = mapper.readValue(cbis, String.class);
        } else {
            throw new IOException("Expected message as string or string[]");
        }
        for (String message : messages) {
            SockJsMessage jsMessage = new SockJsMessage(message);
            ctx.sendUpstream(new UpstreamMessageEvent(channel, jsMessage, channel.getRemoteAddress()));
        }
    } else if (frame instanceof PongWebSocketFrame) {
    // Ignore
    } else {
        logger.error("Unhandled frame type: " + frame.getClass().getSimpleName());
    }
}
Also used : ChannelBufferInputStream(org.jboss.netty.buffer.ChannelBufferInputStream) IOException(java.io.IOException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 13 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project sockjs-netty by cgbystrom.

the class EventSourceTransport method writeRequested.

@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof Frame) {
        Frame frame = (Frame) e.getMessage();
        if (headerSent.compareAndSet(false, true)) {
            HttpResponse response = createResponse(CONTENT_TYPE_EVENT_STREAM);
            ctx.sendDownstream(new DownstreamMessageEvent(e.getChannel(), e.getFuture(), response, e.getRemoteAddress()));
            ctx.sendDownstream(new DownstreamMessageEvent(e.getChannel(), e.getFuture(), new DefaultHttpChunk(NEW_LINE), e.getRemoteAddress()));
        }
        ChannelBuffer wrappedContent = ChannelBuffers.wrappedBuffer(FRAME_BEGIN, Frame.encode(frame, false), FRAME_END);
        ctx.sendDownstream(new DownstreamMessageEvent(e.getChannel(), e.getFuture(), new DefaultHttpChunk(wrappedContent), e.getRemoteAddress()));
        logResponseSize(e.getChannel(), wrappedContent);
    } else {
        super.writeRequested(ctx, e);
    }
}
Also used : Frame(com.cgbystrom.sockjs.Frame) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 14 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project weave by continuuity.

the class MessageFetcher method sendFetchRequest.

private void sendFetchRequest() {
    ChannelBuffer fetchBody = ChannelBuffers.buffer(12);
    fetchBody.writeLong(offset.get());
    fetchBody.writeInt(maxSize);
    sender.send(KafkaRequest.createFetch(topic, partition, fetchBody, MessageFetcher.this));
}
Also used : ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 15 with ChannelBuffer

use of org.jboss.netty.buffer.ChannelBuffer in project weave by continuuity.

the class SimpleKafkaClient method preparePublish.

@Override
public PreparePublish preparePublish(final String topic, final Compression compression) {
    final Map<Integer, MessageSetEncoder> encoders = Maps.newHashMap();
    return new PreparePublish() {

        @Override
        public PreparePublish add(byte[] payload, Object partitionKey) {
            return add(ByteBuffer.wrap(payload), partitionKey);
        }

        @Override
        public PreparePublish add(ByteBuffer payload, Object partitionKey) {
            // TODO: Partition
            int partition = 0;
            MessageSetEncoder encoder = encoders.get(partition);
            if (encoder == null) {
                encoder = getEncoder(compression);
                encoders.put(partition, encoder);
            }
            encoder.add(ChannelBuffers.wrappedBuffer(payload));
            return this;
        }

        @Override
        public ListenableFuture<?> publish() {
            List<ListenableFuture<?>> futures = Lists.newArrayListWithCapacity(encoders.size());
            for (Map.Entry<Integer, MessageSetEncoder> entry : encoders.entrySet()) {
                futures.add(doPublish(topic, entry.getKey(), entry.getValue().finish()));
            }
            encoders.clear();
            return Futures.allAsList(futures);
        }

        private ListenableFuture<?> doPublish(String topic, int partition, ChannelBuffer messageSet) {
            final KafkaRequest request = KafkaRequest.createProduce(topic, partition, messageSet);
            final SettableFuture<?> result = SettableFuture.create();
            final ConnectionPool.ConnectResult connection = connectionPool.connect(getTopicBroker(topic, partition).getAddress());
            connection.getChannelFuture().addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    try {
                        future.getChannel().write(request).addListener(getPublishChannelFutureListener(result, null, connection));
                    } catch (Exception e) {
                        result.setException(e);
                    }
                }
            });
            return result;
        }
    };
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) PreparePublish(com.continuuity.weave.kafka.client.PreparePublish) ByteBuffer(java.nio.ByteBuffer) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) FetchException(com.continuuity.weave.kafka.client.FetchException) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) Map(java.util.Map)

Aggregations

ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)312 Test (org.junit.Test)63 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)59 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)49 Test (org.testng.annotations.Test)49 HttpChunk (org.jboss.netty.handler.codec.http.HttpChunk)46 DefaultHttpChunk (org.jboss.netty.handler.codec.http.DefaultHttpChunk)43 HttpChunkTrailer (org.jboss.netty.handler.codec.http.HttpChunkTrailer)37 DefaultHttpChunkTrailer (org.jboss.netty.handler.codec.http.DefaultHttpChunkTrailer)34 Checkpoint (com.linkedin.databus.core.Checkpoint)27 ByteBuffer (java.nio.ByteBuffer)27 BootstrapDatabaseTooOldException (com.linkedin.databus2.core.container.request.BootstrapDatabaseTooOldException)25 IOException (java.io.IOException)23 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)23 ArrayList (java.util.ArrayList)21 Channel (org.jboss.netty.channel.Channel)19 ChannelFuture (org.jboss.netty.channel.ChannelFuture)18 ChannelPipeline (org.jboss.netty.channel.ChannelPipeline)17 BlockLogBuffer (org.neo4j.com.BlockLogBuffer)16 Map (java.util.Map)14