List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:com.github.milenkovicm.kafka.handler.MetadataHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { final ControlTuple tuple = (ControlTuple) msg; final int currentCorrelation = correlation++; ByteBuf kafkaMessage = createMetadataRequest(ctx.alloc(), tuple.topicName, currentCorrelation); // not sure if it is possible that tread may read response message before it // puts future in the map. that's why I have it here . acks.put(currentCorrelation, tuple.promise); promise.addListener(new GenericFutureListener<ChannelPromise>() { @Override// w w w .ja v a 2 s .c o m public void operationComplete(ChannelPromise future) throws Exception { // shouldn't be possible to cancel this operation // if (future.isCancelled()) { // tuple.promise.cancel(true); // return; // } if (future.isDone() && !future.isSuccess()) { acks.remove(currentCorrelation); tuple.promise.setFailure(future.cause()); } } }); super.write(ctx, kafkaMessage, promise); }
From source file:com.github.pgasync.impl.netty.NettyPgProtocolStream.java
License:Apache License
ChannelHandler newSslInitiator() { return new ByteToMessageDecoder() { @Override//from w w w. j ava 2 s. c o m protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (in.readableBytes() < 1) { return; } if ('S' != in.readByte()) { ctx.fireExceptionCaught( new IllegalStateException("SSL required but not supported by backend server")); return; } ctx.pipeline().remove(this); ctx.pipeline().addFirst(SslContextBuilder.forClient() .trustManager(InsecureTrustManagerFactory.INSTANCE).build().newHandler(ctx.alloc())); } }; }
From source file:com.github.sparkfy.network.protocol.MessageEncoder.java
License:Apache License
/*** * Encodes a Message by invoking its encode() method. For non-data messages, we will add one * ByteBuf to 'out' containing the total frame length, the message type, and the message itself. * In the case of a ChunkFetchSuccess, we will also add the ManagedBuffer corresponding to the * data to 'out', in order to enable zero-copy transfer. *//* w w w .ja v a 2 s . c o m*/ @Override public void encode(ChannelHandlerContext ctx, Message in, List<Object> out) throws Exception { Object body = null; long bodyLength = 0; boolean isBodyInFrame = false; // If the message has a body, take it out to enable zero-copy transfer for the payload. if (in.body() != null) { try { bodyLength = in.body().size(); body = in.body().convertToNetty(); isBodyInFrame = in.isBodyInFrame(); } catch (Exception e) { in.body().release(); if (in instanceof AbstractResponseMessage) { AbstractResponseMessage resp = (AbstractResponseMessage) in; // Re-encode this message as a failure response. String error = e.getMessage() != null ? e.getMessage() : "null"; logger.error( String.format("Error processing %s for client %s", in, ctx.channel().remoteAddress()), e); encode(ctx, resp.createFailureResponse(error), out); } else { throw e; } return; } } Message.Type msgType = in.type(); // All messages have the frame length, message type, and message itself. The frame length // may optionally include the length of the body data, depending on what message is being // sent. int headerLength = 8 + msgType.encodedLength() + in.encodedLength(); long frameLength = headerLength + (isBodyInFrame ? bodyLength : 0); ByteBuf header = ctx.alloc().heapBuffer(headerLength); header.writeLong(frameLength); msgType.encode(header); in.encode(header); assert header.writableBytes() == 0; if (body != null) { // We transfer ownership of the reference on in.body() to MessageWithHeader. // This reference will be freed when MessageWithHeader.deallocate() is called. out.add(new MessageWithHeader(in.body(), header, body, bodyLength)); } else { out.add(header); } }
From source file:com.github.wens.netty.web.impl.ResponseImp.java
License:Apache License
public ResponseImp(String charset, ChannelHandlerContext ctx, HttpResponse response) { this.charset = charset; this.ctx = ctx; this.response = response; this.byteBuf = ctx.alloc().buffer(100); }
From source file:com.goodgamenow.source.serverquery.MasterQueryHandler.java
License:Open Source License
/** * Fires a Datagram packet with its associated query to the master server. * * @param ctx channel handler context//from ww w. j a va 2s . c o m * @exception UnsupportedEncodingException */ @Override public void channelActive(ChannelHandlerContext ctx) throws UnsupportedEncodingException { if (0L == startTime) { startTime = System.currentTimeMillis(); } // create the query buffer ByteBuf buf = ctx.alloc().buffer().writeByte(MSG_TYPE).writeByte(query.region.code) .writeBytes(lastAddress.getBytes("US-ASCII")).writeByte(NULL_TERMINATOR) .writeBytes(query.filter.getBytes("UTF-8")).writeByte(NULL_TERMINATOR); // Master server results are paged, sending last address received // back to master will give us another page. ctx.writeAndFlush(new DatagramPacket(buf, masterAddress)); }
From source file:com.gxkj.demo.netty.discard.DiscardClientHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) throws Exception { this.ctx = ctx; // Initialize the message. content = ctx.alloc().directBuffer(messageSize).writeZero(messageSize); // Send the initial messages. generateTraffic();/*w w w . jav a 2s .co m*/ }
From source file:com.hop.hhxx.example.discard.DiscardClientHandler.java
License:Apache License
@Override public void channelActive(ChannelHandlerContext ctx) { this.ctx = ctx; // Initialize the message. content = ctx.alloc().directBuffer(io.netty.example.discard.DiscardClient.SIZE) .writeZero(io.netty.example.discard.DiscardClient.SIZE); // Send the initial messages. generateTraffic();/*from www . j a v a2 s .c o m*/ }
From source file:com.hop.hhxx.example.http2.helloworld.multiplex.server.HelloWorldHttp2Handler.java
License:Apache License
/** * If receive a frame with end-of-stream set, send a pre-canned response. *//*from w w w. j ava 2s. co m*/ public void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) throws Exception { if (headers.isEndStream()) { ByteBuf content = ctx.alloc().buffer(); content.writeBytes(RESPONSE_BYTES); ByteBufUtil.writeAscii(content, " - via HTTP/2"); sendResponse(ctx, content); } }
From source file:com.hop.hhxx.example.http2.helloworld.server.HelloWorldHttp2Handler.java
License:Apache License
@Override public void onHeadersRead(ChannelHandlerContext ctx, int streamId, Http2Headers headers, int padding, boolean endOfStream) { if (endOfStream) { ByteBuf content = ctx.alloc().buffer(); content.writeBytes(RESPONSE_BYTES.duplicate()); ByteBufUtil.writeAscii(content, " - via HTTP/2"); sendResponse(ctx, streamId, content); }/*ww w . ja v a2s. co m*/ }
From source file:com.hop.hhxx.example.http2.tiles.Http2RequestHandler.java
License:Apache License
private void handlePage(ChannelHandlerContext ctx, String streamId, int latency, FullHttpRequest request) { byte[] body = io.netty.example.http2.tiles.Html.body(latency); ByteBuf content = ctx.alloc().buffer(io.netty.example.http2.tiles.Html.HEADER.length + body.length + io.netty.example.http2.tiles.Html.FOOTER.length); content.writeBytes(io.netty.example.http2.tiles.Html.HEADER); content.writeBytes(body);//from w w w.ja v a2 s.co m content.writeBytes(Html.FOOTER); FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, content); response.headers().set(CONTENT_TYPE, "text/html; charset=UTF-8"); sendResponse(ctx, streamId, latency, response, request); }