org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest Java Examples

The following examples show how to use org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest. 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: HandlerUtils.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the given response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param httpRequest originating http request
 * @param response which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 * @param <P> type of the response
 */
public static <P extends ResponseBody> CompletableFuture<Void> sendResponse(
		ChannelHandlerContext channelHandlerContext,
		HttpRequest httpRequest,
		P response,
		HttpResponseStatus statusCode,
		Map<String, String> headers) {
	StringWriter sw = new StringWriter();
	try {
		mapper.writeValue(sw, response);
	} catch (IOException ioe) {
		LOG.error("Internal server error. Could not map response to JSON.", ioe);
		return sendErrorResponse(
			channelHandlerContext,
			httpRequest,
			new ErrorResponseBody("Internal server error. Could not map response to JSON."),
			HttpResponseStatus.INTERNAL_SERVER_ERROR,
			headers);
	}
	return sendResponse(
		channelHandlerContext,
		httpRequest,
		sw.toString(),
		statusCode,
		headers);
}
 
Example #2
Source File: RouterHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
private void routed(
		ChannelHandlerContext channelHandlerContext,
		RouteResult<?> routeResult,
		HttpRequest httpRequest) {
	ChannelInboundHandler handler = (ChannelInboundHandler) routeResult.target();

	// The handler may have been added (keep alive)
	ChannelPipeline pipeline     = channelHandlerContext.pipeline();
	ChannelHandler addedHandler = pipeline.get(ROUTED_HANDLER_NAME);
	if (handler != addedHandler) {
		if (addedHandler == null) {
			pipeline.addAfter(ROUTER_HANDLER_NAME, ROUTED_HANDLER_NAME, handler);
		} else {
			pipeline.replace(addedHandler, ROUTED_HANDLER_NAME, handler);
		}
	}

	RoutedRequest<?> request = new RoutedRequest<>(routeResult, httpRequest);
	channelHandlerContext.fireChannelRead(request.retain());
}
 
Example #3
Source File: StaticFileServerHandler.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
protected void respondAsLeader(ChannelHandlerContext channelHandlerContext, RoutedRequest routedRequest, T gateway) throws Exception {
	final HttpRequest request = routedRequest.getRequest();
	final String requestPath;

	// make sure we request the "index.html" in case there is a directory request
	if (routedRequest.getPath().endsWith("/")) {
		requestPath = routedRequest.getPath() + "index.html";
	}
	// in case the files being accessed are logs or stdout files, find appropriate paths.
	else if (routedRequest.getPath().equals("/jobmanager/log") || routedRequest.getPath().equals("/jobmanager/stdout")) {
		requestPath = "";
	} else {
		requestPath = routedRequest.getPath();
	}

	respondToRequest(channelHandlerContext, request, requestPath);
}
 
Example #4
Source File: RouterHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest) {
	if (HttpHeaders.is100ContinueExpected(httpRequest)) {
		channelHandlerContext.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
		return;
	}

	// Route
	HttpMethod method = httpRequest.getMethod();
	QueryStringDecoder qsd = new QueryStringDecoder(httpRequest.uri());
	RouteResult<?> routeResult = router.route(method, qsd.path(), qsd.parameters());

	if (routeResult == null) {
		respondNotFound(channelHandlerContext, httpRequest);
		return;
	}

	routed(channelHandlerContext, routeResult, httpRequest);
}
 
Example #5
Source File: AbstractHandler.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private CompletableFuture<Void> handleException(Throwable throwable, ChannelHandlerContext ctx, HttpRequest httpRequest) {
	if (throwable instanceof RestHandlerException) {
		RestHandlerException rhe = (RestHandlerException) throwable;
		if (log.isDebugEnabled()) {
			log.error("Exception occurred in REST handler.", rhe);
		} else {
			log.error("Exception occurred in REST handler: {}", rhe.getMessage());
		}
		return HandlerUtils.sendErrorResponse(
			ctx,
			httpRequest,
			new ErrorResponseBody(rhe.getMessage()),
			rhe.getHttpResponseStatus(),
			responseHeaders);
	} else {
		log.error("Unhandled exception.", throwable);
		String stackTrace = String.format("<Exception on server side:%n%s%nEnd of exception on server side>",
			ExceptionUtils.stringifyException(throwable));
		return HandlerUtils.sendErrorResponse(
			ctx,
			httpRequest,
			new ErrorResponseBody(Arrays.asList("Internal server error.", stackTrace)),
			HttpResponseStatus.INTERNAL_SERVER_ERROR,
			responseHeaders);
	}
}
 
Example #6
Source File: HandlerUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the given response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param httpRequest originating http request
 * @param response which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 * @param <P> type of the response
 */
public static <P extends ResponseBody> CompletableFuture<Void> sendResponse(
		ChannelHandlerContext channelHandlerContext,
		HttpRequest httpRequest,
		P response,
		HttpResponseStatus statusCode,
		Map<String, String> headers) {
	StringWriter sw = new StringWriter();
	try {
		mapper.writeValue(sw, response);
	} catch (IOException ioe) {
		LOG.error("Internal server error. Could not map response to JSON.", ioe);
		return sendErrorResponse(
			channelHandlerContext,
			httpRequest,
			new ErrorResponseBody("Internal server error. Could not map response to JSON."),
			HttpResponseStatus.INTERNAL_SERVER_ERROR,
			headers);
	}
	return sendResponse(
		channelHandlerContext,
		httpRequest,
		sw.toString(),
		statusCode,
		headers);
}
 
Example #7
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 #8
Source File: AbstractJobManagerFileHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected CompletableFuture<Void> respondToRequest(ChannelHandlerContext ctx, HttpRequest httpRequest, HandlerRequest<EmptyRequestBody, M> handlerRequest, RestfulGateway gateway) {
	File file = getFile(handlerRequest);
	if (file != null && file.exists()) {
		try {
			HandlerUtils.transferFile(
				ctx,
				file,
				httpRequest);
		} catch (FlinkException e) {
			throw new CompletionException(new FlinkException("Could not transfer file to client.", e));
		}
		return CompletableFuture.completedFuture(null);
	} else {
		return HandlerUtils.sendErrorResponse(
			ctx,
			httpRequest,
			new ErrorResponseBody("This file does not exist in JobManager log dir."),
			HttpResponseStatus.NOT_FOUND,
			Collections.emptyMap());
	}
}
 
Example #9
Source File: RouterHandler.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest) {
	if (HttpHeaders.is100ContinueExpected(httpRequest)) {
		channelHandlerContext.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
		return;
	}

	// Route
	HttpMethod method = httpRequest.getMethod();
	QueryStringDecoder qsd = new QueryStringDecoder(httpRequest.uri());
	RouteResult<?> routeResult = router.route(method, qsd.path(), qsd.parameters());

	if (routeResult == null) {
		respondNotFound(channelHandlerContext, httpRequest);
		return;
	}

	routed(channelHandlerContext, routeResult, httpRequest);
}
 
Example #10
Source File: RouterHandler.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
private void routed(
		ChannelHandlerContext channelHandlerContext,
		RouteResult<?> routeResult,
		HttpRequest httpRequest) {
	ChannelInboundHandler handler = (ChannelInboundHandler) routeResult.target();

	// The handler may have been added (keep alive)
	ChannelPipeline pipeline     = channelHandlerContext.pipeline();
	ChannelHandler addedHandler = pipeline.get(ROUTED_HANDLER_NAME);
	if (handler != addedHandler) {
		if (addedHandler == null) {
			pipeline.addAfter(ROUTER_HANDLER_NAME, ROUTED_HANDLER_NAME, handler);
		} else {
			pipeline.replace(addedHandler, ROUTED_HANDLER_NAME, handler);
		}
	}

	RoutedRequest<?> request = new RoutedRequest<>(routeResult, httpRequest);
	channelHandlerContext.fireChannelRead(request.retain());
}
 
Example #11
Source File: StaticFileServerHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void respondAsLeader(ChannelHandlerContext channelHandlerContext, RoutedRequest routedRequest, T gateway) throws Exception {
	final HttpRequest request = routedRequest.getRequest();
	final String requestPath;

	// make sure we request the "index.html" in case there is a directory request
	if (routedRequest.getPath().endsWith("/")) {
		requestPath = routedRequest.getPath() + "index.html";
	} else {
		requestPath = routedRequest.getPath();
	}

	try {
		respondToRequest(channelHandlerContext, request, requestPath);
	} catch (RestHandlerException rhe) {
		HandlerUtils.sendErrorResponse(
			channelHandlerContext,
			routedRequest.getRequest(),
			new ErrorResponseBody(rhe.getMessage()),
			rhe.getHttpResponseStatus(),
			responseHeaders);
	}
}
 
Example #12
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 #13
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 #14
Source File: StaticFileServerHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void respondAsLeader(ChannelHandlerContext channelHandlerContext, RoutedRequest routedRequest, T gateway) throws Exception {
	final HttpRequest request = routedRequest.getRequest();
	final String requestPath;

	// make sure we request the "index.html" in case there is a directory request
	if (routedRequest.getPath().endsWith("/")) {
		requestPath = routedRequest.getPath() + "index.html";
	}
	// in case the files being accessed are logs or stdout files, find appropriate paths.
	else if (routedRequest.getPath().equals("/jobmanager/log") || routedRequest.getPath().equals("/jobmanager/stdout")) {
		requestPath = "";
	} else {
		requestPath = routedRequest.getPath();
	}

	respondToRequest(channelHandlerContext, request, requestPath);
}
 
Example #15
Source File: RouterHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
private void routed(
		ChannelHandlerContext channelHandlerContext,
		RouteResult<?> routeResult,
		HttpRequest httpRequest) {
	ChannelInboundHandler handler = (ChannelInboundHandler) routeResult.target();

	// The handler may have been added (keep alive)
	ChannelPipeline pipeline     = channelHandlerContext.pipeline();
	ChannelHandler addedHandler = pipeline.get(ROUTED_HANDLER_NAME);
	if (handler != addedHandler) {
		if (addedHandler == null) {
			pipeline.addAfter(ROUTER_HANDLER_NAME, ROUTED_HANDLER_NAME, handler);
		} else {
			pipeline.replace(addedHandler, ROUTED_HANDLER_NAME, handler);
		}
	}

	RoutedRequest<?> request = new RoutedRequest<>(routeResult, httpRequest);
	channelHandlerContext.fireChannelRead(request.retain());
}
 
Example #16
Source File: RouterHandler.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest) {
	if (HttpHeaders.is100ContinueExpected(httpRequest)) {
		channelHandlerContext.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
		return;
	}

	// Route
	HttpMethod method = httpRequest.getMethod();
	QueryStringDecoder qsd = new QueryStringDecoder(httpRequest.uri());
	RouteResult<?> routeResult = router.route(method, qsd.path(), qsd.parameters());

	if (routeResult == null) {
		respondNotFound(channelHandlerContext, httpRequest);
		return;
	}

	routed(channelHandlerContext, routeResult, httpRequest);
}
 
Example #17
Source File: HandlerUtils.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Sends the given response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param httpRequest originating http request
 * @param response which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 * @param <P> type of the response
 */
public static <P extends ResponseBody> CompletableFuture<Void> sendResponse(
		ChannelHandlerContext channelHandlerContext,
		HttpRequest httpRequest,
		P response,
		HttpResponseStatus statusCode,
		Map<String, String> headers) {
	StringWriter sw = new StringWriter();
	try {
		mapper.writeValue(sw, response);
	} catch (IOException ioe) {
		LOG.error("Internal server error. Could not map response to JSON.", ioe);
		return sendErrorResponse(
			channelHandlerContext,
			httpRequest,
			new ErrorResponseBody("Internal server error. Could not map response to JSON."),
			HttpResponseStatus.INTERNAL_SERVER_ERROR,
			headers);
	}
	return sendResponse(
		channelHandlerContext,
		httpRequest,
		sw.toString(),
		statusCode,
		headers);
}
 
Example #18
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 httpRequest originating http request
 * @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,
		@Nonnull HttpRequest httpRequest,
		@Nonnull String message,
		@Nonnull HttpResponseStatus statusCode,
		@Nonnull Map<String, String> headers) {

	return sendResponse(
		channelHandlerContext,
		HttpHeaders.isKeepAlive(httpRequest),
		message,
		statusCode,
		headers);
}
 
Example #19
Source File: PipelineErrorHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest message) {
	// we can't deal with this message. No one in the pipeline handled it. Log it.
	logger.warn("Unknown message received: {}", message);
	HandlerUtils.sendErrorResponse(
		ctx,
		message,
		new ErrorResponseBody("Bad request received."),
		HttpResponseStatus.BAD_REQUEST,
		Collections.emptyMap());
}
 
Example #20
Source File: HandlerUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the given error response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param httpRequest originating http request
 * @param errorMessage which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 */
public static CompletableFuture<Void> sendErrorResponse(
		ChannelHandlerContext channelHandlerContext,
		HttpRequest httpRequest,
		ErrorResponseBody errorMessage,
		HttpResponseStatus statusCode,
		Map<String, String> headers) {

	return sendErrorResponse(
		channelHandlerContext,
		HttpHeaders.isKeepAlive(httpRequest),
		errorMessage,
		statusCode,
		headers);
}
 
Example #21
Source File: AbstractHandlerTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileCleanup() throws Exception {
	final Path dir = temporaryFolder.newFolder().toPath();
	final Path file = dir.resolve("file");
	Files.createFile(file);

	RestfulGateway mockRestfulGateway = TestingRestfulGateway.newBuilder()
		.build();

	final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () ->
		CompletableFuture.completedFuture(mockRestfulGateway);

	CompletableFuture<Void> requestProcessingCompleteFuture = new CompletableFuture<>();
	TestHandler handler = new TestHandler(requestProcessingCompleteFuture, mockGatewayRetriever);

	RouteResult<?> routeResult = new RouteResult<>("", "", Collections.emptyMap(), Collections.emptyMap(), "");
	HttpRequest request = new DefaultFullHttpRequest(
		HttpVersion.HTTP_1_1,
		HttpMethod.GET,
		TestHandler.TestHeaders.INSTANCE.getTargetRestEndpointURL(),
		Unpooled.wrappedBuffer(new byte[0]));
	RoutedRequest<?> routerRequest = new RoutedRequest<>(routeResult, request);

	Attribute<FileUploads> attribute = new SimpleAttribute();
	attribute.set(new FileUploads(dir));
	Channel channel = mock(Channel.class);
	when(channel.attr(any(AttributeKey.class))).thenReturn(attribute);

	ChannelHandlerContext context = mock(ChannelHandlerContext.class);
	when(context.channel()).thenReturn(channel);

	handler.respondAsLeader(context, routerRequest, mockRestfulGateway);

	// the (asynchronous) request processing is not yet complete so the files should still exist
	Assert.assertTrue(Files.exists(file));
	requestProcessingCompleteFuture.complete(null);
	Assert.assertFalse(Files.exists(file));
}
 
Example #22
Source File: RedirectingSslHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	HttpRequest request = msg instanceof HttpRequest ? (HttpRequest) msg : null;
	String path = request == null ? "" : request.uri();
	String redirectAddress = getRedirectAddress(ctx);
	log.trace("Received non-SSL request, redirecting to {}{}", redirectAddress, path);
	HttpResponse response = HandlerRedirectUtils.getRedirectResponse(
		redirectAddress, path, HttpResponseStatus.MOVED_PERMANENTLY);
	if (request != null) {
		KeepAliveWrite.flush(ctx, request, response);
	} else {
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example #23
Source File: RouterHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
private void respondNotFound(ChannelHandlerContext channelHandlerContext, HttpRequest request) {
	LOG.trace("Request could not be routed to any handler. Uri:{} Method:{}", request.getUri(), request.getMethod());
	HandlerUtils.sendErrorResponse(
		channelHandlerContext,
		request,
		new ErrorResponseBody("Not found."),
		HttpResponseStatus.NOT_FOUND,
		responseHeaders);
}
 
Example #24
Source File: RouterHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
private void respondNotFound(ChannelHandlerContext channelHandlerContext, HttpRequest request) {
	LOG.trace("Request could not be routed to any handler. Uri:{} Method:{}", request.getUri(), request.getMethod());
	HandlerUtils.sendErrorResponse(
		channelHandlerContext,
		request,
		new ErrorResponseBody("Not found."),
		HttpResponseStatus.NOT_FOUND,
		responseHeaders);
}
 
Example #25
Source File: RedirectingSslHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
	HttpRequest request = msg instanceof HttpRequest ? (HttpRequest) msg : null;
	String path = request == null ? "" : request.uri();
	String redirectAddress = getRedirectAddress(ctx);
	log.trace("Received non-SSL request, redirecting to {}{}", redirectAddress, path);
	HttpResponse response = HandlerRedirectUtils.getRedirectResponse(
		redirectAddress, path, HttpResponseStatus.MOVED_PERMANENTLY);
	if (request != null) {
		KeepAliveWrite.flush(ctx, request, response);
	} else {
		ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
	}
}
 
Example #26
Source File: AbstractHandlerTest.java    From flink with Apache License 2.0 5 votes vote down vote up
@Test
public void testFileCleanup() throws Exception {
	final Path dir = temporaryFolder.newFolder().toPath();
	final Path file = dir.resolve("file");
	Files.createFile(file);

	RestfulGateway mockRestfulGateway = new TestingRestfulGateway.Builder()
		.build();

	final GatewayRetriever<RestfulGateway> mockGatewayRetriever = () ->
		CompletableFuture.completedFuture(mockRestfulGateway);

	CompletableFuture<Void> requestProcessingCompleteFuture = new CompletableFuture<>();
	TestHandler handler = new TestHandler(requestProcessingCompleteFuture, mockGatewayRetriever);

	RouteResult<?> routeResult = new RouteResult<>("", "", Collections.emptyMap(), Collections.emptyMap(), "");
	HttpRequest request = new DefaultFullHttpRequest(
		HttpVersion.HTTP_1_1,
		HttpMethod.GET,
		TestHandler.TestHeaders.INSTANCE.getTargetRestEndpointURL(),
		Unpooled.wrappedBuffer(new byte[0]));
	RoutedRequest<?> routerRequest = new RoutedRequest<>(routeResult, request);

	Attribute<FileUploads> attribute = new SimpleAttribute();
	attribute.set(new FileUploads(dir));
	Channel channel = mock(Channel.class);
	when(channel.attr(any(AttributeKey.class))).thenReturn(attribute);

	ChannelHandlerContext context = mock(ChannelHandlerContext.class);
	when(context.channel()).thenReturn(channel);

	handler.respondAsLeader(context, routerRequest, mockRestfulGateway);

	// the (asynchronous) request processing is not yet complete so the files should still exist
	Assert.assertTrue(Files.exists(file));
	requestProcessingCompleteFuture.complete(null);
	Assert.assertFalse(Files.exists(file));
}
 
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 httpRequest originating http request
 * @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,
		@Nonnull HttpRequest httpRequest,
		@Nonnull String message,
		@Nonnull HttpResponseStatus statusCode,
		@Nonnull Map<String, String> headers) {

	return sendResponse(
		channelHandlerContext,
		HttpHeaders.isKeepAlive(httpRequest),
		message,
		statusCode,
		headers);
}
 
Example #28
Source File: HandlerUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Sends the given error response and status code to the given channel.
 *
 * @param channelHandlerContext identifying the open channel
 * @param httpRequest originating http request
 * @param errorMessage which should be sent
 * @param statusCode of the message to send
 * @param headers additional header values
 */
public static CompletableFuture<Void> sendErrorResponse(
		ChannelHandlerContext channelHandlerContext,
		HttpRequest httpRequest,
		ErrorResponseBody errorMessage,
		HttpResponseStatus statusCode,
		Map<String, String> headers) {

	return sendErrorResponse(
		channelHandlerContext,
		HttpHeaders.isKeepAlive(httpRequest),
		errorMessage,
		statusCode,
		headers);
}
 
Example #29
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 #30
Source File: HttpTestClient.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Sends a simple GET request to the given path. You only specify the $path part of
 * http://$host:$host/$path.
 *
 * @param path The $path to GET (http://$host:$host/$path)
 */
public void sendGetRequest(String path, FiniteDuration timeout) throws TimeoutException, InterruptedException {
	if (!path.startsWith("/")) {
		path = "/" + path;
	}

	HttpRequest getRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1,
			HttpMethod.GET, path);
	getRequest.headers().set(HttpHeaders.Names.HOST, host);
	getRequest.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);

	sendRequest(getRequest, timeout);
}