List of usage examples for io.netty.channel ChannelPromise setSuccess
ChannelPromise setSuccess();
From source file:io.grpc.netty.WriteBufferingAndExceptionHandlerTest.java
License:Apache License
@Test public void writesBuffered() throws Exception { final AtomicBoolean handlerAdded = new AtomicBoolean(); final AtomicBoolean flush = new AtomicBoolean(); final AtomicReference<Object> write = new AtomicReference<>(); final WriteBufferingAndExceptionHandler handler = new WriteBufferingAndExceptionHandler( new ChannelOutboundHandlerAdapter() { @Override//from www .j av a2 s . c om public void handlerAdded(ChannelHandlerContext ctx) throws Exception { assertFalse(handlerAdded.getAndSet(true)); super.handlerAdded(ctx); } @Override public void flush(ChannelHandlerContext ctx) throws Exception { assertFalse(flush.getAndSet(true)); super.flush(ctx); } @Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) { assertNull(write.getAndSet(msg)); promise.setSuccess(); } }); LocalAddress addr = new LocalAddress("local"); ChannelFuture cf = new Bootstrap().channel(LocalChannel.class).handler(handler).group(group).register(); chan = cf.channel(); cf.sync(); ChannelFuture sf = new ServerBootstrap().channel(LocalServerChannel.class) .childHandler(new ChannelHandlerAdapter() { }).group(group).bind(addr); server = sf.channel(); sf.sync(); assertTrue(handlerAdded.get()); chan.write(new Object()); chan.connect(addr).sync(); assertNull(write.get()); chan.flush(); assertNull(write.get()); assertFalse(flush.get()); assertThat(chan.pipeline().context(handler)).isNotNull(); chan.eventLoop().submit(new Runnable() { @Override public void run() { handler.writeBufferedAndRemove(chan.pipeline().context(handler)); } }).sync(); assertThat(chan.pipeline().context(handler)).isNull(); assertThat(write.get().getClass()).isSameInstanceAs(Object.class); assertTrue(flush.get()); assertThat(chan.pipeline()).doesNotContain(handler); }
From source file:io.lettuce.core.protocol.CommandHandlerTest.java
License:Apache License
@Test public void shouldRecordCorrectFirstResponseLatency() throws Exception { ChannelPromise channelPromise = new DefaultChannelPromise(channel, ImmediateEventExecutor.INSTANCE); channelPromise.setSuccess(); sut.channelRegistered(context);/*from w w w. j a v a 2s . com*/ sut.channelActive(context); LatencyMeteredCommand<String, String, String> wrapped = new LatencyMeteredCommand<>(command); sut.write(context, wrapped, channelPromise); Thread.sleep(10); sut.channelRead(context, Unpooled.wrappedBuffer("*1\r\n+OK\r\n".getBytes())); verify(latencyCollector).recordCommandLatency(any(), any(), eq(CommandType.APPEND), gt(0L), gt(0L)); sut.channelUnregistered(context); }
From source file:jmeter.plugins.http2.sampler.HttpResponseHandler.java
License:Apache License
@Override protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { System.err.println("HttpResponseHandler unexpected message received: " + msg); return;//ww w. j av a 2 s . c o m } ChannelPromise promise = streamidPromiseMap.get(streamId); if (promise == null) { System.err.println("Message received for unknown stream id " + streamId); } else { // Do stuff with the message (for now just print it) ByteBuf content = msg.content(); if (content.isReadable()) { int contentLength = content.readableBytes(); byte[] arr = new byte[contentLength]; content.readBytes(arr); System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8)); } promise.setSuccess(); // Set result streamidResponseMap.put(streamId, msg); } }
From source file:net.epsilony.utils.codec.modbus.ModbusMasterCodecTest.java
License:Open Source License
@Test public void test() throws InterruptedException, ExecutionException { SimpModbusMasterChannelInitializer init = new SimpModbusMasterChannelInitializer(); EmbeddedChannel channel = new EmbeddedChannel(init); ChannelPromise newPromise = channel.newPromise(); System.out.println(channel.isRegistered()); ModbusClientMaster master = new ModbusClientMaster() { @Override//from w ww. j av a2 s . c om protected ChannelFuture genConnectFuture() { this.initializer = init; newPromise.setSuccess(); return newPromise; } }; CompletableFuture<ModbusResponse> future = master .request(new ModbusRequest(0, 0, MF.readRegisters(ModbusRegisterType.COIL, 0, 10))); future.get(); }
From source file:netty.mmb.http2.Client.HttpResponseHandler.java
License:Apache License
@Override protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { System.err.println("HttpResponseHandler unexpected message received: " + msg); return;// w w w. ja v a2 s . c om } ChannelPromise promise = streamidPromiseMap.get(streamId); if (promise == null) { System.err.println("Message received for unknown stream id " + streamId); } else { // Do stuff with the message (for now just print it) ByteBuf content = msg.content(); if (content.isReadable()) { int contentLength = content.readableBytes(); byte[] arr = new byte[contentLength]; content.readBytes(arr); System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8)); } promise.setSuccess(); } }
From source file:netty5.http.client.HttpResponseHandler.java
License:Apache License
@Override protected void messageReceived(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception { Integer streamId = msg.headers().getInt(HttpUtil.ExtensionHeaderNames.STREAM_ID.text()); if (streamId == null) { System.err.println("HttpResponseHandler unexpected message received: " + msg); return;/*from w w w . j ava 2 s . c om*/ } ChannelPromise promise = streamidPromiseMap.get(streamId); if (promise == null) { System.err.println("Message received for unknown stream id " + streamId); } else { // Do stuff with the message (for now just print it) ByteBuf content = msg.content(); if (content.isReadable()) { int contentLength = content.readableBytes(); byte[] arr = new byte[contentLength]; content.readBytes(arr); System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8)); } promise.setSuccess(); } }
From source file:org.apache.pulsar.broker.service.Consumer.java
License:Apache License
/** * Dispatch a list of entries to the consumer. <br/> * <b>It is also responsible to release entries data and recycle entries object.</b> * * @return a promise that can be use to track when all the data has been written into the socket *//*from w ww .j a va2 s.co m*/ public Pair<ChannelPromise, Integer> sendMessages(final List<Entry> entries) { final ChannelHandlerContext ctx = cnx.ctx(); final MutablePair<ChannelPromise, Integer> sentMessages = new MutablePair<ChannelPromise, Integer>(); final ChannelPromise writePromise = ctx.newPromise(); sentMessages.setLeft(writePromise); if (entries.isEmpty()) { if (log.isDebugEnabled()) { log.debug("[{}] List of messages is empty, triggering write future immediately for consumerId {}", subscription, consumerId); } writePromise.setSuccess(); sentMessages.setRight(0); return sentMessages; } try { sentMessages.setRight(updatePermitsAndPendingAcks(entries)); } catch (PulsarServerException pe) { log.warn("[{}] [{}] consumer doesn't support batch-message {}", subscription, consumerId, cnx.getRemoteEndpointProtocolVersion()); subscription.markTopicWithBatchMessagePublished(); sentMessages.setRight(0); // disconnect consumer: it will update dispatcher's availablePermits and resend pendingAck-messages of this // consumer to other consumer disconnect(); return sentMessages; } ctx.channel().eventLoop().execute(() -> { for (int i = 0; i < entries.size(); i++) { Entry entry = entries.get(i); PositionImpl pos = (PositionImpl) entry.getPosition(); MessageIdData.Builder messageIdBuilder = MessageIdData.newBuilder(); MessageIdData messageId = messageIdBuilder.setLedgerId(pos.getLedgerId()) .setEntryId(pos.getEntryId()).build(); ByteBuf metadataAndPayload = entry.getDataBuffer(); // increment ref-count of data and release at the end of process: so, we can get chance to call entry.release metadataAndPayload.retain(); // skip checksum by incrementing reader-index if consumer-client doesn't support checksum verification if (cnx.getRemoteEndpointProtocolVersion() < ProtocolVersion.v6.getNumber()) { readChecksum(metadataAndPayload); } if (log.isDebugEnabled()) { log.debug("[{}] Sending message to consumerId {}, entry id {}", subscription, consumerId, pos.getEntryId()); } // We only want to pass the "real" promise on the last entry written ChannelPromise promise = ctx.voidPromise(); if (i == (entries.size() - 1)) { promise = writePromise; } ctx.write(Commands.newMessage(consumerId, messageId, metadataAndPayload), promise); messageId.recycle(); messageIdBuilder.recycle(); entry.release(); } ctx.flush(); }); return sentMessages; }
From source file:org.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java
License:Apache License
@Override public void channelRead(final ChannelHandlerContext ctx, final Object msg) { if (msg instanceof FullHttpRequest) { final FullHttpRequest req = (FullHttpRequest) msg; if ("/favicon.ico".equals(req.getUri())) { sendError(ctx, NOT_FOUND, "Gremlin Server doesn't have a favicon.ico"); ReferenceCountUtil.release(msg); return; }//w w w . j av a 2 s. c o m if (is100ContinueExpected(req)) { ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE)); } if (req.getMethod() != GET && req.getMethod() != POST) { sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString()); ReferenceCountUtil.release(msg); return; } final Quartet<String, Map<String, Object>, String, Map<String, String>> requestArguments; try { requestArguments = getRequestArguments(req); } catch (IllegalArgumentException iae) { sendError(ctx, BAD_REQUEST, iae.getMessage()); ReferenceCountUtil.release(msg); return; } final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json"); final Pair<String, MessageTextSerializer> serializer = chooseSerializer(acceptString); if (null == serializer) { sendError(ctx, BAD_REQUEST, String.format("no serializer for requested Accept header: %s", acceptString)); ReferenceCountUtil.release(msg); return; } final String origin = req.headers().get(ORIGIN); final boolean keepAlive = isKeepAlive(req); // not using the req any where below here - assume it is safe to release at this point. ReferenceCountUtil.release(msg); try { logger.debug("Processing request containing script [{}] and bindings of [{}] on {}", requestArguments.getValue0(), requestArguments.getValue1(), Thread.currentThread().getName()); final ChannelPromise promise = ctx.channel().newPromise(); final AtomicReference<Object> resultHolder = new AtomicReference<>(); promise.addListener(future -> { // if failed then the error was already written back to the client as part of the eval future // processing of the exception if (future.isSuccess()) { logger.debug( "Preparing HTTP response for request with script [{}] and bindings of [{}] with result of [{}] on [{}]", requestArguments.getValue0(), requestArguments.getValue1(), resultHolder.get(), Thread.currentThread().getName()); final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, (ByteBuf) resultHolder.get()); response.headers().set(CONTENT_TYPE, serializer.getValue0()); response.headers().set(CONTENT_LENGTH, response.content().readableBytes()); // handle cors business if (origin != null) response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin); if (!keepAlive) { ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE); } else { response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE); ctx.writeAndFlush(response); } } }); final Timer.Context timerContext = evalOpTimer.time(); final Bindings bindings; try { bindings = createBindings(requestArguments.getValue1(), requestArguments.getValue3()); } catch (IllegalStateException iae) { sendError(ctx, BAD_REQUEST, iae.getMessage()); ReferenceCountUtil.release(msg); return; } // provide a transform function to serialize to message - this will force serialization to occur // in the same thread as the eval. after the CompletableFuture is returned from the eval the result // is ready to be written as a ByteBuf directly to the response. nothing should be blocking here. final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(requestArguments.getValue0(), requestArguments.getValue2(), bindings, FunctionUtils.wrapFunction(o -> { // stopping the timer here is roughly equivalent to where the timer would have been stopped for // this metric in other contexts. we just want to measure eval time not serialization time. timerContext.stop(); logger.debug( "Transforming result of request with script [{}] and bindings of [{}] with result of [{}] on [{}]", requestArguments.getValue0(), requestArguments.getValue1(), o, Thread.currentThread().getName()); final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID()) .code(ResponseStatusCode.SUCCESS).result(IteratorUtils.asList(o)).create(); // http server is sessionless and must handle commit on transactions. the commit occurs // before serialization to be consistent with how things work for websocket based // communication. this means that failed serialization does not mean that you won't get // a commit to the database attemptCommit(requestArguments.getValue3(), graphManager, settings.strictTransactionManagement); try { return Unpooled.wrappedBuffer(serializer.getValue1() .serializeResponseAsString(responseMessage).getBytes(UTF8)); } catch (Exception ex) { logger.warn(String.format("Error during serialization for %s", responseMessage), ex); throw ex; } })); evalFuture.exceptionally(t -> { if (t.getMessage() != null) sendError(ctx, INTERNAL_SERVER_ERROR, t.getMessage(), Optional.of(t)); else sendError(ctx, INTERNAL_SERVER_ERROR, String .format("Error encountered evaluating script: %s", requestArguments.getValue0()), Optional.of(t)); promise.setFailure(t); return null; }); evalFuture.thenAcceptAsync(r -> { // now that the eval/serialization is done in the same thread - complete the promise so we can // write back the HTTP response on the same thread as the original request resultHolder.set(r); promise.setSuccess(); }, gremlinExecutor.getExecutorService()); } catch (Exception ex) { // tossed to exceptionCaught which delegates to sendError method final Throwable t = ExceptionUtils.getRootCause(ex); throw new RuntimeException(null == t ? ex : t); } } }
From source file:org.elasticsearch.hadoop.http.netty4.pipelining.HttpPipeliningHandler.java
License:Apache License
@Override public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { if (msg instanceof HttpPipelinedResponse) { boolean channelShouldClose = false; synchronized (holdingQueue) { if (holdingQueue.size() < maxEventsHeld) { holdingQueue.add((HttpPipelinedResponse) msg); while (!holdingQueue.isEmpty()) { final HttpPipelinedResponse response = holdingQueue.peek(); if (response.sequence() != writeSequence) { break; }//from ww w .ja v a 2s . c o m holdingQueue.remove(); ctx.write(response.response(), response.promise()); writeSequence++; } } else { channelShouldClose = true; } } if (channelShouldClose) { try { Netty4Utils.closeChannels(Collections.singletonList(ctx.channel())); } finally { ((HttpPipelinedResponse) msg).release(); promise.setSuccess(); } } } else { ctx.write(msg, promise); } }
From source file:org.fusesource.hawtdispatch.netty.HawtSocketChannel.java
License:Apache License
@Override public ChannelFuture shutdownOutput(final ChannelPromise promise) { EventLoop loop = eventLoop();/* w ww . j a v a 2s . c om*/ if (loop.inEventLoop()) { boolean success = false; try { javaChannel().socket().shutdownOutput(); success = true; promise.setSuccess(); } catch (Throwable t) { promise.setFailure(t); } finally { if (success) { outputShutdown = true; } } } else { loop.execute(new Runnable() { @Override public void run() { shutdownOutput(promise); } }); } return promise; }