List of usage examples for io.netty.channel ChannelHandlerContext alloc
ByteBufAllocator alloc();
From source file:io.airlift.drift.transport.netty.ThriftClientHandler.java
License:Apache License
private void sendMessage(ChannelHandlerContext context, ThriftRequest thriftRequest, ChannelPromise promise) throws Exception { // todo ONEWAY_SEQUENCE_ID is a header protocol thing... make sure this works with framed and unframed int sequenceId = thriftRequest.isOneway() ? ONEWAY_SEQUENCE_ID : this.sequenceId.incrementAndGet(); RequestHandler requestHandler = new RequestHandler(thriftRequest, sequenceId); // register timeout requestHandler.registerRequestTimeout(context.executor()); // write request ByteBuf requestBuffer = requestHandler.encodeRequest(context.alloc()); // register request if we are expecting a response if (!thriftRequest.isOneway()) { if (pendingRequests.putIfAbsent(sequenceId, requestHandler) != null) { requestHandler.onChannelError( new TTransportException("Another request with the same sequenceId is already in progress")); }//from w ww .j a va 2s . c o m } try { ChannelFuture sendFuture = context.write(requestBuffer, promise); sendFuture.addListener(future -> messageSent(context, sendFuture, requestHandler)); } catch (Throwable t) { onError(context, t); } }
From source file:io.aos.netty5.memcache.binary.MemcacheClientHandler.java
License:Apache License
/** * Transforms basic string requests to binary memcache requests *//*from w ww. j a v a 2s . com*/ @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { String command = (String) msg; if (command.startsWith("get ")) { String key = command.substring("get ".length()); BinaryMemcacheRequest req = new DefaultBinaryMemcacheRequest(key); req.setOpcode(BinaryMemcacheOpcodes.GET); req.setKeyLength((short) key.length()); req.setTotalBodyLength(key.length()); ctx.write(req, promise); } else if (command.startsWith("set ")) { String[] parts = command.split(" ", 3); if (parts.length < 3) { throw new IllegalArgumentException("Malformed Command: " + command); } String key = parts[1]; String value = parts[2]; ByteBuf content = Unpooled.wrappedBuffer(value.getBytes(CharsetUtil.UTF_8)); ByteBuf extras = ctx.alloc().buffer(8); BinaryMemcacheRequest req = new DefaultFullBinaryMemcacheRequest(key, extras, content); req.setOpcode(BinaryMemcacheOpcodes.SET); req.setKeyLength((short) key.length()); req.setExtrasLength((byte) 8); req.setTotalBodyLength(key.length() + 8 + value.length()); ctx.write(req, promise); } else { throw new IllegalStateException("Unknown Message: " + msg); } }
From source file:io.codis.nedis.handler.RedisDuplexHandler.java
License:Apache License
private void writeTxn(ChannelHandlerContext ctx, TxnRedisRequest req, ChannelPromise promise) { switch (req.getCmd()) { case MULTI: { if (inMulti) { req.getPromise().tryFailure(new IllegalStateException("Already in MULTI")); break; }/*w ww . java2s .c o m*/ inMulti = true; ctx.write(RedisRequestEncoder.encode(ctx.alloc(), MULTI.raw), promise); entryQ.addLast(new Entry(req.getPromise(), System.nanoTime())); entryQ.addLast(TXN_MARKER); break; } case EXEC: { if (!inMulti) { req.getPromise().tryFailure(new IllegalStateException("not in MULTI")); break; } ctx.write(RedisRequestEncoder.encode(ctx.alloc(), EXEC.raw), promise); inMulti = false; entryQ.addLast(TXN_MARKER); entryQ.addLast(new Entry(req.getPromise(), System.nanoTime())); break; } case DISCARD: { if (!inMulti) { req.getPromise().tryFailure(new IllegalStateException("not in MULTI")); break; } ctx.write(RedisRequestEncoder.encode(ctx.alloc(), DISCARD.raw), promise); inMulti = false; entryQ.addLast(TXN_MARKER); entryQ.addLast(new Entry(req.getPromise(), System.nanoTime())); break; } default: throw new IllegalArgumentException(req.getCmd() + " is not a transactional command"); } }
From source file:io.gatling.http.client.body.multipart.impl.MultipartChunkedInput.java
License:Apache License
@Override @Deprecated public ByteBuf readChunk(ChannelHandlerContext ctx) throws Exception { return readChunk(ctx.alloc()); }
From source file:io.gatling.http.client.impl.DigestAuthHandler.java
License:Apache License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { if (digestHeader == null) { // initial state if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; if (response.status() == HttpResponseStatus.UNAUTHORIZED) { String authenticateHeader = getHeaderWithPrefix(response.headers().getAll(WWW_AUTHENTICATE), "Digest"); if (authenticateHeader != null) { digestHeader = realm.computeAuthorizationHeader(tx.request.getMethod(), tx.request.getUri(), authenticateHeader); return; }/*from w w w.ja v a2s. c o m*/ } } // nothing this handler can do about it // either we don't need authentication, or auth scheme is not Digest ctx.fireChannelRead(msg); } else if (msg instanceof LastHttpContent) { // send new request // FIXME make sure connection can be reused, otherwise use a new one // FIXME check what happens if buildRequest throws WritableRequest request = WritableRequestBuilder.buildRequest(tx.request, ctx.alloc(), config, false); request.getRequest().headers().add(AUTHORIZATION, digestHeader); // FIXME write can throw Exception!!! request.write(ctx); ctx.pipeline().remove(this); } // initial response chunks are just ignored }
From source file:io.gatling.http.client.impl.Http2AppHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { HttpTx tx = (HttpTx) msg;//w ww .j a v a 2s . c o m nextStreamId += 2; if (tx.requestTimeout.isDone()) { channelPool.offer(ctx.channel()); return; } try { WritableRequest request = WritableRequestBuilder.buildRequest(tx.request, ctx.alloc(), config, true); tx.closeConnection = HttpUtils.isConnectionClose(request.getRequest().headers()); LOGGER.debug("Write request {}", request); request.write(ctx).addListener(f -> { if (f.isSuccess()) { Http2Stream stream = connection.stream(nextStreamId); stream.setProperty(propertyKey, tx); } else { crash(ctx, f.cause(), tx.listener, true); } }); } catch (Exception e) { crash(ctx, e, tx.listener, true); } }
From source file:io.gatling.http.client.impl.HttpAppHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { HttpTx tx = (HttpTx) msg;// w w w. j a v a2 s . co m setActive(tx); if (tx.requestTimeout.isDone()) { setInactive(); return; } try { WritableRequest request = WritableRequestBuilder.buildRequest(tx.request, ctx.alloc(), config, false); tx.closeConnection = HttpUtils.isConnectionClose(request.getRequest().headers()); LOGGER.debug("Write request {}", request); request.write(ctx); } catch (Exception e) { crash(ctx, e, true); } }
From source file:io.gatling.http.client.impl.WebSocketHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { if (msg instanceof HttpTx) { HttpTx tx = (HttpTx) msg;/*from w w w.j a v a 2 s . com*/ setActive(tx); if (tx.requestTimeout.isDone()) { return; } try { WritableRequest request = WritableRequestBuilder.buildRequest(tx.request, ctx.alloc(), config, false); handshaker = WebSocketClientHandshakerFactory.newHandshaker(tx.request.getUri().toJavaNetURI(), WebSocketVersion.V13, null, true, request.getRequest().headers(), config.getWebSocketMaxFramePayloadLength()); handshaker.handshake(ctx.channel()); } catch (Exception e) { crash(ctx, e, true); } } else { // all other messages are CONNECT request and WebSocket frames LOGGER.debug("ctx.write msg={}", msg); ctx.write(msg, promise); } }
From source file:io.gomint.proxprox.network.tcp.PacketDecompressor.java
License:BSD License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { int size = in.readInt(); if (size == 0) { out.add(in.slice().retain());//from w ww . j av a2 s. co m in.skipBytes(in.readableBytes()); } else { ByteBuf decompressed = ctx.alloc().directBuffer(); try { zlib.process(in, decompressed); Preconditions.checkState(decompressed.readableBytes() == size, "Decompressed packet size mismatch"); out.add(decompressed); decompressed = null; } finally { if (decompressed != null) { decompressed.release(); } } } }
From source file:io.grpc.alts.internal.TsiFrameHandler.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { checkState(protector != null, "decode() called after close()"); protector.unprotect(in, out, ctx.alloc()); }