List of usage examples for io.netty.channel ChannelPromise cause
Throwable cause();
From source file:ccwihr.client.t2.HttpResponseHandler.java
License:Apache License
/** * Wait (sequentially) for a time duration for each anticipated response * * @param timeout Value of time to wait for each response * @param unit Units associated with {@code timeout} * @see HttpResponseHandler#put(int, io.netty.channel.ChannelFuture, io.netty.channel.ChannelPromise) *///w w w .j a v a 2 s . com public void awaitResponses(long timeout, TimeUnit unit) { Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet() .iterator(); while (itr.hasNext()) { Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next(); ChannelFuture writeFuture = entry.getValue().getKey(); if (!writeFuture.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); } if (!writeFuture.isSuccess()) { throw new RuntimeException(writeFuture.cause()); } ChannelPromise promise = entry.getValue().getValue(); if (!promise.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); } if (!promise.isSuccess()) { throw new RuntimeException(promise.cause()); } System.out.println("---Stream id: " + entry.getKey() + " received---"); itr.remove(); } }
From source file:cn.jpush.api.common.connection.HttpResponseHandler.java
License:Apache License
/** * Wait (sequentially) for a time duration for each anticipated response * * @param timeout Value of time to wait for each response * @param unit Units associated with {@code timeout} * @see HttpResponseHandler#put(int, ChannelFuture, ChannelPromise) *///from w w w. j av a2 s . c o m public void awaitResponses(long timeout, TimeUnit unit) { Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet() .iterator(); while (itr.hasNext()) { Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next(); ChannelFuture writeFuture = entry.getValue().getKey(); if (!writeFuture.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); } if (!writeFuture.isSuccess()) { throw new RuntimeException(writeFuture.cause()); } ChannelPromise promise = entry.getValue().getValue(); if (!promise.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); } if (!promise.isSuccess()) { throw new RuntimeException(promise.cause()); } System.out.println("---Stream id: " + entry.getKey() + " received---"); System.out.println("---Stream id: " + promise.toString()); itr.remove(); } }
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//from w ww. ja v a2s . 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.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandlerTest.java
License:Open Source License
/** Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND). */ @Test//from www.ja v a 2 s . c o m public void httpErrorsAreSupported() throws IOException { EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null)); ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream()); DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, "abcdef", out); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); response.headers().set(HttpHeaders.HOST, "localhost"); response.headers().set(HttpHeaders.CONTENT_LENGTH, 0); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ch.writeInbound(response); ch.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.NOT_FOUND); // No data should have been written to the OutputStream and it should have been closed. assertThat(out.size()).isEqualTo(0); // The caller is responsible for closing the stream. verify(out, never()).close(); assertThat(ch.isOpen()).isTrue(); }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandlerTest.java
License:Open Source License
/** * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a * Content-Length header.// ww w.j av a 2s.c om */ @Test public void httpErrorsWithContentAreSupported() throws IOException { EmbeddedChannel ch = new EmbeddedChannel(new HttpDownloadHandler(null)); ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream()); DownloadCommand cmd = new DownloadCommand(CACHE_URI, true, "abcdef", out); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND); ByteBuf errorMessage = ByteBufUtil.writeAscii(ch.alloc(), "Error message"); response.headers().set(HttpHeaders.HOST, "localhost"); response.headers().set(HttpHeaders.CONTENT_LENGTH, String.valueOf(errorMessage.readableBytes())); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE); ch.writeInbound(response); // The promise must not be done because we haven't received the error message yet. assertThat(writePromise.isDone()).isFalse(); ch.writeInbound(new DefaultHttpContent(errorMessage)); ch.writeInbound(LastHttpContent.EMPTY_LAST_CONTENT); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.NOT_FOUND); // No data should have been written to the OutputStream and it should have been closed. assertThat(out.size()).isEqualTo(0); // The caller is responsible for closing the stream. verify(out, never()).close(); assertThat(ch.isOpen()).isFalse(); }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpUploadHandlerTest.java
License:Open Source License
/** Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND). */ @Test/* w w w.j ava 2 s . co m*/ public void httpErrorsAreSupported() { EmbeddedChannel ch = new EmbeddedChannel(new HttpUploadHandler(null)); ByteArrayInputStream data = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 }); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(new UploadCommand(CACHE_URI, true, "abcdef", data, 5), writePromise); HttpRequest request = ch.readOutbound(); assertThat(request).isInstanceOf(HttpRequest.class); HttpChunkedInput content = ch.readOutbound(); assertThat(content).isInstanceOf(HttpChunkedInput.class); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.FORBIDDEN); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.CLOSE); ch.writeInbound(response); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.FORBIDDEN); assertThat(ch.isOpen()).isFalse(); }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpUploadHandlerTest.java
License:Open Source License
/** * Test that the handler correctly supports http error codes i.e. 404 (NOT FOUND) with a * Content-Length header./*from ww w . jav a2 s. c o m*/ */ @Test public void httpErrorsWithContentAreSupported() { EmbeddedChannel ch = new EmbeddedChannel(new HttpUploadHandler(null)); ByteArrayInputStream data = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5 }); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(new UploadCommand(CACHE_URI, true, "abcdef", data, 5), writePromise); HttpRequest request = ch.readOutbound(); assertThat(request).isInstanceOf(HttpRequest.class); HttpChunkedInput content = ch.readOutbound(); assertThat(content).isInstanceOf(HttpChunkedInput.class); ByteBuf errorMsg = ByteBufUtil.writeAscii(ch.alloc(), "error message"); FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_FOUND, errorMsg); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ch.writeInbound(response); assertThat(writePromise.isDone()).isTrue(); assertThat(writePromise.cause()).isInstanceOf(HttpException.class); assertThat(((HttpException) writePromise.cause()).response().status()) .isEqualTo(HttpResponseStatus.NOT_FOUND); assertThat(ch.isOpen()).isTrue(); }
From source file:com.turo.pushy.apns.ApnsClientHandler.java
License:Open Source License
private void writePushNotification(final ChannelHandlerContext context, final PushNotificationPromise responsePromise, final ChannelPromise writePromise) { if (context.channel().isActive()) { final int streamId = this.connection().local().incrementAndGetNextStreamId(); if (streamId > 0) { // We'll attach the push notification and response promise to the stream as soon as the stream is created. // Because we're using a StreamBufferingEncoder under the hood, there's no guarantee as to when the stream // will actually be created, and so we attach these in the onStreamAdded listener to make sure everything // is happening in a predictable order. this.unattachedResponsePromisesByStreamId.put(streamId, responsePromise); final ApnsPushNotification pushNotification = responsePromise.getPushNotification(); final Http2Headers headers = getHeadersForPushNotification(pushNotification, streamId); final ChannelPromise headersPromise = context.newPromise(); this.encoder().writeHeaders(context, streamId, headers, 0, false, headersPromise); log.trace("Wrote headers on stream {}: {}", streamId, headers); final ByteBuf payloadBuffer = context.alloc().ioBuffer(INITIAL_PAYLOAD_BUFFER_CAPACITY); payloadBuffer.writeBytes(pushNotification.getPayload().getBytes(StandardCharsets.UTF_8)); final ChannelPromise dataPromise = context.newPromise(); this.encoder().writeData(context, streamId, payloadBuffer, 0, true, dataPromise); log.trace("Wrote payload on stream {}: {}", streamId, pushNotification.getPayload()); final PromiseCombiner promiseCombiner = new PromiseCombiner(); promiseCombiner.addAll((ChannelFuture) headersPromise, dataPromise); promiseCombiner.finish(writePromise); writePromise.addListener(new GenericFutureListener<ChannelPromise>() { @Override/*from w w w. j a va2 s . co m*/ public void operationComplete(final ChannelPromise future) { if (!future.isSuccess()) { log.trace("Failed to write push notification on stream {}.", streamId, future.cause()); responsePromise.tryFailure(future.cause()); } } }); } else { // This is very unlikely, but in the event that we run out of stream IDs, we need to open a new // connection. Just closing the context should be enough; automatic reconnection should take things // from there. writePromise.tryFailure(STREAMS_EXHAUSTED_EXCEPTION); context.channel().close(); } } else { writePromise.tryFailure(STREAM_CLOSED_BEFORE_REPLY_EXCEPTION); } }
From source file:http.HTTPResponseHandler.java
License:Open Source License
/** * Provide asynchronous response to HTTP2 request * * @param streamId StreamID/*w w w. ja v a2 s.c o m*/ * @return Response string */ public String getResponse(int streamId) { String message = streamIdResponseMap.get(streamId); if (message != null) { return message; } else { Entry<ChannelFuture, ChannelPromise> channelFutureChannelPromiseEntry = streamIdPromiseMap .get(streamId); if (channelFutureChannelPromiseEntry != null) { ChannelFuture writeFuture = channelFutureChannelPromiseEntry.getKey(); if (!writeFuture.awaitUninterruptibly(ServerUtil.HTTP2_RESPONSE_TIME_OUT, ServerUtil.HTTP2_RESPONSE_TIME_UNIT)) { streamIdPromiseMap.remove(streamId); throw new IllegalStateException("Timed out waiting to write for stream id " + streamId); } if (!writeFuture.isSuccess()) { streamIdPromiseMap.remove(streamId); throw new RuntimeException(writeFuture.cause()); } ChannelPromise promise = channelFutureChannelPromiseEntry.getValue(); if (!promise.awaitUninterruptibly(ServerUtil.HTTP2_RESPONSE_TIME_OUT, ServerUtil.HTTP2_RESPONSE_TIME_UNIT)) { streamIdPromiseMap.remove(streamId); throw new IllegalStateException("Timed out waiting for response on stream id " + streamId); } if (!promise.isSuccess()) { streamIdPromiseMap.remove(streamId); throw new RuntimeException(promise.cause()); } } } return streamIdResponseMap.get(streamId); }
From source file:http2.client.HttpResponseHandler.java
License:Apache License
/** * anticipated : ?/*from www.j ava2s . c o m*/ * Wait (sequentially) for a time duration for each anticipated response * * @param timeout Value of time to wait for each response * @param unit Units associated with {@code timeout} * @see HttpResponseHandler#put(int, ChannelFuture, ChannelPromise) */ public void awaitResponses(long timeout, TimeUnit unit) { Iterator<Entry<Integer, Entry<ChannelFuture, ChannelPromise>>> itr = streamidPromiseMap.entrySet() .iterator(); while (itr.hasNext()) { Entry<Integer, Entry<ChannelFuture, ChannelPromise>> entry = itr.next(); ChannelFuture writeFuture = entry.getValue().getKey(); // if (!writeFuture.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting to write for stream id " + entry.getKey()); } // if (!writeFuture.isSuccess()) { throw new RuntimeException(writeFuture.cause()); } // ChannelPromise promise = entry.getValue().getValue(); if (!promise.awaitUninterruptibly(timeout, unit)) { throw new IllegalStateException("Timed out waiting for response on stream id " + entry.getKey()); } if (!promise.isSuccess()) { throw new RuntimeException(promise.cause()); } System.out.println("---Stream id: " + entry.getKey() + " received---"); itr.remove(); } }