use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest in project flink by apache.
the class RestClient method sendRequest.
public <M extends MessageHeaders<R, P, U>, U extends MessageParameters, R extends RequestBody, P extends ResponseBody> CompletableFuture<P> sendRequest(String targetAddress, int targetPort, M messageHeaders, U messageParameters, R request, Collection<FileUpload> fileUploads, RestAPIVersion apiVersion) throws IOException {
Preconditions.checkNotNull(targetAddress);
Preconditions.checkArgument(NetUtils.isValidHostPort(targetPort), "The target port " + targetPort + " is not in the range [0, 65535].");
Preconditions.checkNotNull(messageHeaders);
Preconditions.checkNotNull(request);
Preconditions.checkNotNull(messageParameters);
Preconditions.checkNotNull(fileUploads);
Preconditions.checkState(messageParameters.isResolved(), "Message parameters were not resolved.");
if (!messageHeaders.getSupportedAPIVersions().contains(apiVersion)) {
throw new IllegalArgumentException(String.format("The requested version %s is not supported by the request (method=%s URL=%s). Supported versions are: %s.", apiVersion, messageHeaders.getHttpMethod(), messageHeaders.getTargetRestEndpointURL(), messageHeaders.getSupportedAPIVersions().stream().map(RestAPIVersion::getURLVersionPrefix).collect(Collectors.joining(","))));
}
String versionedHandlerURL = "/" + apiVersion.getURLVersionPrefix() + messageHeaders.getTargetRestEndpointURL();
String targetUrl = MessageParameters.resolveUrl(versionedHandlerURL, messageParameters);
LOG.debug("Sending request of class {} to {}:{}{}", request.getClass(), targetAddress, targetPort, targetUrl);
// serialize payload
StringWriter sw = new StringWriter();
objectMapper.writeValue(sw, request);
ByteBuf payload = Unpooled.wrappedBuffer(sw.toString().getBytes(ConfigConstants.DEFAULT_CHARSET));
Request httpRequest = createRequest(targetAddress + ':' + targetPort, targetUrl, messageHeaders.getHttpMethod().getNettyHttpMethod(), payload, fileUploads);
final JavaType responseType;
final Collection<Class<?>> typeParameters = messageHeaders.getResponseTypeParameters();
if (typeParameters.isEmpty()) {
responseType = objectMapper.constructType(messageHeaders.getResponseClass());
} else {
responseType = objectMapper.getTypeFactory().constructParametricType(messageHeaders.getResponseClass(), typeParameters.toArray(new Class<?>[typeParameters.size()]));
}
return submitRequest(targetAddress, targetPort, httpRequest, responseType);
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest in project flink by apache.
the class RestClient method submitRequest.
private <P extends ResponseBody> CompletableFuture<P> submitRequest(String targetAddress, int targetPort, Request httpRequest, JavaType responseType) {
final ChannelFuture connectFuture = bootstrap.connect(targetAddress, targetPort);
final CompletableFuture<Channel> channelFuture = new CompletableFuture<>();
connectFuture.addListener((ChannelFuture future) -> {
if (future.isSuccess()) {
channelFuture.complete(future.channel());
} else {
channelFuture.completeExceptionally(future.cause());
}
});
return channelFuture.thenComposeAsync(channel -> {
ClientHandler handler = channel.pipeline().get(ClientHandler.class);
CompletableFuture<JsonResponse> future;
boolean success = false;
try {
if (handler == null) {
throw new IOException("Netty pipeline was not properly initialized.");
} else {
httpRequest.writeTo(channel);
future = handler.getJsonFuture();
success = true;
}
} catch (IOException e) {
future = FutureUtils.completedExceptionally(new ConnectionException("Could not write request.", e));
} finally {
if (!success) {
channel.close();
}
}
return future;
}, executor).thenComposeAsync((JsonResponse rawResponse) -> parseResponse(rawResponse, responseType), executor);
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest in project flink by apache.
the class FileUploadHandler method handleError.
private void handleError(ChannelHandlerContext ctx, String errorMessage, HttpResponseStatus responseStatus, @Nullable Throwable e) {
HttpRequest tmpRequest = currentHttpRequest;
deleteUploadedFiles();
reset();
LOG.warn(errorMessage, e);
HandlerUtils.sendErrorResponse(ctx, tmpRequest, new ErrorResponseBody(errorMessage), responseStatus, Collections.emptyMap());
ReferenceCountUtil.release(tmpRequest);
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest in project flink by apache.
the class Prio0InboundChannelHandlerFactory method createHandler.
@Override
public Optional<ChannelHandler> createHandler(Configuration configuration, Map<String, String> responseHeaders) throws ConfigurationException {
String redirectFromUrl = configuration.getString(REDIRECT_FROM_URL);
String redirectToUrl = configuration.getString(REDIRECT_TO_URL);
if (!redirectFromUrl.isEmpty() && !redirectToUrl.isEmpty()) {
return Optional.of(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof HttpRequest) {
HttpRequest httpRequest = (HttpRequest) msg;
if (httpRequest.uri().equals(redirectFromUrl)) {
httpRequest.setUri(redirectToUrl);
}
}
ctx.fireChannelRead(ReferenceCountUtil.retain(msg));
}
});
}
return Optional.empty();
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.HttpRequest in project flink by apache.
the class AbstractHandlerTest method testFileCleanup.
@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));
}
Aggregations