org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture Java Examples

The following examples show how to use org.apache.flink.shaded.netty4.io.netty.channel.ChannelFuture. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpTestClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a request to to the server.
 *
 * <pre>
 * HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/overview");
 * request.headers().set(HttpHeaders.Names.HOST, host);
 * request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
 *
 * sendRequest(request);
 * </pre>
 *
 * @param request The {@link HttpRequest} to send to the server
 */
public void sendRequest(HttpRequest request, FiniteDuration timeout) throws InterruptedException, TimeoutException {
	LOG.debug("Writing {}.", request);

	// Make the connection attempt.
	ChannelFuture connect = bootstrap.connect(host, port);

	Channel channel;
	if (connect.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
		channel = connect.channel();
	}
	else {
		throw new TimeoutException("Connection failed");
	}

	channel.writeAndFlush(request);
}
 
Example #2
Source File: HttpTestClient.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a request to to the server.
 *
 * <pre>
 * HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/overview");
 * request.headers().set(HttpHeaders.Names.HOST, host);
 * request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
 *
 * sendRequest(request);
 * </pre>
 *
 * @param request The {@link HttpRequest} to send to the server
 */
public void sendRequest(HttpRequest request, FiniteDuration timeout) throws InterruptedException, TimeoutException {
	LOG.debug("Writing {}.", request);

	// Make the connection attempt.
	ChannelFuture connect = bootstrap.connect(host, port);

	Channel channel;
	if (connect.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
		channel = connect.channel();
	}
	else {
		throw new TimeoutException("Connection failed");
	}

	channel.writeAndFlush(request);
}
 
Example #3
Source File: NettyPartitionRequestClient.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a task event backwards to an intermediate result partition producer.
 *
 * <p>Backwards task events flow between readers and writers and therefore
 * will only work when both are running at the same time, which is only
 * guaranteed to be the case when both the respective producer and
 * consumer task run pipelined.
 */
@Override
public void sendTaskEvent(ResultPartitionID partitionId, TaskEvent event, final RemoteInputChannel inputChannel) throws IOException {
	checkNotClosed();

	tcpChannel.writeAndFlush(new TaskEventRequest(event, partitionId, inputChannel.getInputChannelId()))
			.addListener(
					new ChannelFutureListener() {
						@Override
						public void operationComplete(ChannelFuture future) throws Exception {
							if (!future.isSuccess()) {
								SocketAddress remoteAddr = future.channel().remoteAddress();
								inputChannel.onError(new LocalTransportException(
									String.format("Sending the task event to '%s' failed.", remoteAddr),
									future.channel().localAddress(), future.cause()
								));
							}
						}
					});
}
 
Example #4
Source File: AbstractTaskManagerFileHandlerTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture write(Object msg, ChannelPromise promise) {
	if (msg instanceof DefaultFileRegion) {
		final DefaultFileRegion defaultFileRegion = (DefaultFileRegion) msg;

		try (final FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
			fileOutputStream.getChannel();

			defaultFileRegion.transferTo(fileOutputStream.getChannel(), 0L);
		} catch (IOException ioe) {
			throw new RuntimeException(ioe);
		}
	}

	return new DefaultChannelPromise(new EmbeddedChannel());
}
 
Example #5
Source File: HttpTestClient.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a request to to the server.
 *
 * <pre>
 * HttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/overview");
 * request.headers().set(HttpHeaders.Names.HOST, host);
 * request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
 *
 * sendRequest(request);
 * </pre>
 *
 * @param request The {@link HttpRequest} to send to the server
 */
public void sendRequest(HttpRequest request, Duration timeout) throws InterruptedException, TimeoutException {
	LOG.debug("Writing {}.", request);

	// Make the connection attempt.
	ChannelFuture connect = bootstrap.connect(host, port);

	Channel channel;
	if (connect.await(timeout.toMillis(), TimeUnit.MILLISECONDS)) {
		channel = connect.channel();
	}
	else {
		throw new TimeoutException("Connection failed");
	}

	channel.writeAndFlush(request);
}
 
Example #6
Source File: AbstractTaskManagerFileHandlerTest.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture write(Object msg, ChannelPromise promise) {
	if (msg instanceof DefaultFileRegion) {
		final DefaultFileRegion defaultFileRegion = (DefaultFileRegion) msg;

		try (final FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
			fileOutputStream.getChannel();

			defaultFileRegion.transferTo(fileOutputStream.getChannel(), 0L);
		} catch (IOException ioe) {
			throw new RuntimeException(ioe);
		}
	}

	return new DefaultChannelPromise(new EmbeddedChannel());
}
 
Example #7
Source File: PartitionRequestClientFactory.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	if (future.isSuccess()) {
		handInChannel(future.channel());
	}
	else if (future.cause() != null) {
		notifyOfError(new RemoteTransportException(
				"Connecting to remote task manager + '" + connectionId.getAddress() +
						"' has failed. This might indicate that the remote task " +
						"manager has been lost.",
				connectionId.getAddress(), future.cause()));
	}
	else {
		notifyOfError(new LocalTransportException(
			String.format(
				"Connecting to remote task manager '%s' has been cancelled.",
				connectionId.getAddress()),
			null));
	}
}
 
Example #8
Source File: NettyPartitionRequestClient.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a task event backwards to an intermediate result partition producer.
 *
 * <p>Backwards task events flow between readers and writers and therefore
 * will only work when both are running at the same time, which is only
 * guaranteed to be the case when both the respective producer and
 * consumer task run pipelined.
 */
@Override
public void sendTaskEvent(ResultPartitionID partitionId, TaskEvent event, final RemoteInputChannel inputChannel) throws IOException {
	checkNotClosed();

	tcpChannel.writeAndFlush(new TaskEventRequest(event, partitionId, inputChannel.getInputChannelId()))
			.addListener(
					new ChannelFutureListener() {
						@Override
						public void operationComplete(ChannelFuture future) throws Exception {
							if (!future.isSuccess()) {
								SocketAddress remoteAddr = future.channel().remoteAddress();
								inputChannel.onError(new LocalTransportException(
									String.format("Sending the task event to '%s' failed.", remoteAddr),
									future.channel().localAddress(), future.cause()
								));
							}
						}
					});
}
 
Example #9
Source File: PartitionRequestClient.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a task event backwards to an intermediate result partition producer.
 * <p>
 * Backwards task events flow between readers and writers and therefore
 * will only work when both are running at the same time, which is only
 * guaranteed to be the case when both the respective producer and
 * consumer task run pipelined.
 */
public void sendTaskEvent(ResultPartitionID partitionId, TaskEvent event, final RemoteInputChannel inputChannel) throws IOException {
	checkNotClosed();

	tcpChannel.writeAndFlush(new TaskEventRequest(event, partitionId, inputChannel.getInputChannelId()))
			.addListener(
					new ChannelFutureListener() {
						@Override
						public void operationComplete(ChannelFuture future) throws Exception {
							if (!future.isSuccess()) {
								SocketAddress remoteAddr = future.channel().remoteAddress();
								inputChannel.onError(new LocalTransportException(
									String.format("Sending the task event to '%s' failed.", remoteAddr),
									future.channel().localAddress(), future.cause()
								));
							}
						}
					});
}
 
Example #10
Source File: AbstractTaskManagerFileHandlerTest.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public ChannelFuture write(Object msg, ChannelPromise promise) {
	if (msg instanceof DefaultFileRegion) {
		final DefaultFileRegion defaultFileRegion = (DefaultFileRegion) msg;

		try (final FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
			fileOutputStream.getChannel();

			defaultFileRegion.transferTo(fileOutputStream.getChannel(), 0L);
		} catch (IOException ioe) {
			throw new RuntimeException(ioe);
		}
	}

	return new DefaultChannelPromise(new EmbeddedChannel());
}
 
Example #11
Source File: PartitionRequestClientFactory.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	if (future.isSuccess()) {
		handInChannel(future.channel());
	}
	else if (future.cause() != null) {
		notifyOfError(new RemoteTransportException(
				"Connecting to remote task manager + '" + connectionId.getAddress() +
						"' has failed. This might indicate that the remote task " +
						"manager has been lost.",
				connectionId.getAddress(), future.cause()));
	}
	else {
		notifyOfError(new LocalTransportException(
			String.format(
				"Connecting to remote task manager '%s' has been cancelled.",
				connectionId.getAddress()),
			null));
	}
}
 
Example #12
Source File: Client.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	if (future.isSuccess()) {
		handInChannel(future.channel());
	} else {
		close(future.cause());
	}
}
 
Example #13
Source File: AbstractServerHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	long durationNanos = System.nanoTime() - creationNanos;
	long durationMillis = TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS);

	if (future.isSuccess()) {
		LOG.debug("Request {} was successfully answered after {} ms.", request, durationMillis);
		stats.reportSuccessfulRequest(durationMillis);
	} else {
		LOG.debug("Request {} failed after {} ms due to: {}", request, durationMillis, future.cause());
		stats.reportFailedRequest();
	}
}
 
Example #14
Source File: KeepAliveWrite.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture flush(ChannelHandlerContext ctx, HttpRequest request, HttpResponse response) {
	if (!HttpHeaders.isKeepAlive(request)) {
		return ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	} else {
		response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
		return ctx.writeAndFlush(response);
	}
}
 
Example #15
Source File: KeepAliveWrite.java    From flink with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture flush(ChannelHandlerContext ctx, HttpRequest request, HttpResponse response) {
	if (!HttpHeaders.isKeepAlive(request)) {
		return ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	} else {
		response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
		return ctx.writeAndFlush(response);
	}
}
 
Example #16
Source File: KeepAliveWrite.java    From flink with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture flush(Channel ch, HttpRequest req, HttpResponse res) {
	if (!HttpHeaders.isKeepAlive(req)) {
		return ch.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
	} else {
		res.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
		return ch.writeAndFlush(res);
	}
}
 
Example #17
Source File: HandlerUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the given response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param keepAlive If the connection should be kept alive.
 * @param message which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 */
public static CompletableFuture<Void> sendResponse(
		@Nonnull ChannelHandlerContext channelHandlerContext,
		boolean keepAlive,
		@Nonnull String message,
		@Nonnull HttpResponseStatus statusCode,
		@Nonnull Map<String, String> headers) {
	HttpResponse response = new DefaultHttpResponse(HTTP_1_1, statusCode);

	response.headers().set(CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE);

	for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
		response.headers().set(headerEntry.getKey(), headerEntry.getValue());
	}

	if (keepAlive) {
		response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
	}

	byte[] buf = message.getBytes(ConfigConstants.DEFAULT_CHARSET);
	ByteBuf b = Unpooled.copiedBuffer(buf);
	HttpHeaders.setContentLength(response, buf.length);

	// write the initial line and the header.
	channelHandlerContext.write(response);

	channelHandlerContext.write(b);

	ChannelFuture lastContentFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

	// close the connection, if no keep-alive is needed
	if (!keepAlive) {
		lastContentFuture.addListener(ChannelFutureListener.CLOSE);
	}

	return toCompletableFuture(lastContentFuture);
}
 
Example #18
Source File: HandlerUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
private static CompletableFuture<Void> toCompletableFuture(final ChannelFuture channelFuture) {
	final CompletableFuture<Void> completableFuture = new CompletableFuture<>();
	channelFuture.addListener(future -> {
		if (future.isSuccess()) {
			completableFuture.complete(null);
		} else {
			completableFuture.completeExceptionally(future.cause());
		}
	});
	return completableFuture;
}
 
Example #19
Source File: RestClient.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(Channel channel) {
	ChannelFuture future = channel.writeAndFlush(httpRequest);
	// this should never be false as we explicitly set the encoder to use multipart messages
	if (bodyRequestEncoder.isChunked()) {
		future = channel.writeAndFlush(bodyRequestEncoder);
	}

	// release data and remove temporary files if they were created, once the writing is complete
	future.addListener((ignored) -> bodyRequestEncoder.cleanFiles());
}
 
Example #20
Source File: CreditBasedPartitionRequestClientHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	try {
		if (future.isSuccess()) {
			writeAndFlushNextMessageIfPossible(future.channel());
		} else if (future.cause() != null) {
			notifyAllChannelsOfErrorAndClose(future.cause());
		} else {
			notifyAllChannelsOfErrorAndClose(new IllegalStateException("Sending cancelled by user."));
		}
	} catch (Throwable t) {
		notifyAllChannelsOfErrorAndClose(t);
	}
}
 
Example #21
Source File: PartitionRequestQueue.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	try {
		if (future.isSuccess()) {
			writeAndFlushNextMessageIfPossible(future.channel());
		} else if (future.cause() != null) {
			handleException(future.channel(), future.cause());
		} else {
			handleException(future.channel(), new IllegalStateException("Sending cancelled by user."));
		}
	} catch (Throwable t) {
		handleException(future.channel(), t);
	}
}
 
Example #22
Source File: Client.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	if (future.isSuccess()) {
		handInChannel(future.channel());
	} else {
		close(future.cause());
	}
}
 
Example #23
Source File: AbstractServerHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	long durationNanos = System.nanoTime() - creationNanos;
	long durationMillis = TimeUnit.MILLISECONDS.convert(durationNanos, TimeUnit.NANOSECONDS);

	if (future.isSuccess()) {
		LOG.debug("Request {} was successfully answered after {} ms.", request, durationMillis);
		stats.reportSuccessfulRequest(durationMillis);
	} else {
		LOG.debug("Request {} failed after {} ms due to: {}", request, durationMillis, future.cause());
		stats.reportFailedRequest();
	}
}
 
Example #24
Source File: PartitionRequestQueue.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	try {
		if (future.isSuccess()) {
			writeAndFlushNextMessageIfPossible(future.channel());
		} else if (future.cause() != null) {
			handleException(future.channel(), future.cause());
		} else {
			handleException(future.channel(), new IllegalStateException("Sending cancelled by user."));
		}
	} catch (Throwable t) {
		handleException(future.channel(), t);
	}
}
 
Example #25
Source File: KeepAliveWrite.java    From flink with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture flush(ChannelHandlerContext ctx, HttpRequest request, HttpResponse response) {
	if (!HttpHeaders.isKeepAlive(request)) {
		return ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	} else {
		response.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
		return ctx.writeAndFlush(response);
	}
}
 
Example #26
Source File: KeepAliveWrite.java    From flink with Apache License 2.0 5 votes vote down vote up
public static ChannelFuture flush(Channel ch, HttpRequest req, HttpResponse res) {
	if (!HttpHeaders.isKeepAlive(req)) {
		return ch.writeAndFlush(res).addListener(ChannelFutureListener.CLOSE);
	} else {
		res.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
		return ch.writeAndFlush(res);
	}
}
 
Example #27
Source File: HandlerUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the given response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param keepAlive If the connection should be kept alive.
 * @param message which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 */
public static CompletableFuture<Void> sendResponse(
		@Nonnull ChannelHandlerContext channelHandlerContext,
		boolean keepAlive,
		@Nonnull String message,
		@Nonnull HttpResponseStatus statusCode,
		@Nonnull Map<String, String> headers) {
	HttpResponse response = new DefaultHttpResponse(HTTP_1_1, statusCode);

	response.headers().set(CONTENT_TYPE, RestConstants.REST_CONTENT_TYPE);

	for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
		response.headers().set(headerEntry.getKey(), headerEntry.getValue());
	}

	if (keepAlive) {
		response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
	}

	byte[] buf = message.getBytes(ConfigConstants.DEFAULT_CHARSET);
	ByteBuf b = Unpooled.copiedBuffer(buf);
	HttpHeaders.setContentLength(response, buf.length);

	// write the initial line and the header.
	channelHandlerContext.write(response);

	channelHandlerContext.write(b);

	ChannelFuture lastContentFuture = channelHandlerContext.writeAndFlush(LastHttpContent.EMPTY_LAST_CONTENT);

	// close the connection, if no keep-alive is needed
	if (!keepAlive) {
		lastContentFuture.addListener(ChannelFutureListener.CLOSE);
	}

	return toCompletableFuture(lastContentFuture);
}
 
Example #28
Source File: CreditBasedPartitionRequestClientHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
	try {
		if (future.isSuccess()) {
			writeAndFlushNextMessageIfPossible(future.channel());
		} else if (future.cause() != null) {
			notifyAllChannelsOfErrorAndClose(future.cause());
		} else {
			notifyAllChannelsOfErrorAndClose(new IllegalStateException("Sending cancelled by user."));
		}
	} catch (Throwable t) {
		notifyAllChannelsOfErrorAndClose(t);
	}
}
 
Example #29
Source File: HandlerUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
private static CompletableFuture<Void> toCompletableFuture(final ChannelFuture channelFuture) {
	final CompletableFuture<Void> completableFuture = new CompletableFuture<>();
	channelFuture.addListener(future -> {
		if (future.isSuccess()) {
			completableFuture.complete(null);
		} else {
			completableFuture.completeExceptionally(future.cause());
		}
	});
	return completableFuture;
}
 
Example #30
Source File: RestClient.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(Channel channel) {
	ChannelFuture future = channel.writeAndFlush(httpRequest);
	// this should never be false as we explicitly set the encoder to use multipart messages
	if (bodyRequestEncoder.isChunked()) {
		future = channel.writeAndFlush(bodyRequestEncoder);
	}

	// release data and remove temporary files if they were created, once the writing is complete
	future.addListener((ignored) -> bodyRequestEncoder.cleanFiles());
}