Java Code Examples for org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled#wrappedBuffer()

The following examples show how to use org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled#wrappedBuffer() . 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: PipelineErrorHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String error) {
	if (ctx.channel().isActive()) {
		DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
			HttpResponseStatus.INTERNAL_SERVER_ERROR,
			Unpooled.wrappedBuffer(error.getBytes(ConfigConstants.DEFAULT_CHARSET)));

		response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
		response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

		ctx.writeAndFlush(response);
	}
}
 
Example 2
Source File: ConstantTextHandler.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, RoutedRequest routed) throws Exception {
	HttpResponse response = new DefaultFullHttpResponse(
		HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(encodedText));

	response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, encodedText.length);
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");

	KeepAliveWrite.flush(ctx, routed.getRequest(), response);
}
 
Example 3
Source File: HandlerRedirectUtils.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
public static HttpResponse getResponse(HttpResponseStatus status, @Nullable String message) {
	ByteBuf messageByteBuf = message == null ? Unpooled.buffer(0)
		: Unpooled.wrappedBuffer(message.getBytes(ENCODING));
	FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, messageByteBuf);
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=" + ENCODING.name());
	response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

	return response;
}
 
Example 4
Source File: AbstractHandlerTest.java    From Flink-CEPplus 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 5
Source File: PipelineErrorHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String error) {
	if (ctx.channel().isActive()) {
		DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
			HttpResponseStatus.INTERNAL_SERVER_ERROR,
			Unpooled.wrappedBuffer(error.getBytes(ConfigConstants.DEFAULT_CHARSET)));

		response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
		response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

		ctx.writeAndFlush(response);
	}
}
 
Example 6
Source File: ConstantTextHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx, RoutedRequest routed) throws Exception {
	HttpResponse response = new DefaultFullHttpResponse(
		HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(encodedText));

	response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, encodedText.length);
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");

	KeepAliveWrite.flush(ctx, routed.getRequest(), response);
}
 
Example 7
Source File: HandlerRedirectUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
public static HttpResponse getResponse(HttpResponseStatus status, @Nullable String message) {
	ByteBuf messageByteBuf = message == null ? Unpooled.buffer(0)
		: Unpooled.wrappedBuffer(message.getBytes(ENCODING));
	FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, messageByteBuf);
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=" + ENCODING.name());
	response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

	return response;
}
 
Example 8
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 9
Source File: PipelineErrorHandler.java    From flink with Apache License 2.0 5 votes vote down vote up
private void sendError(ChannelHandlerContext ctx, String error) {
	if (ctx.channel().isActive()) {
		DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1,
			HttpResponseStatus.INTERNAL_SERVER_ERROR,
			Unpooled.wrappedBuffer(error.getBytes(ConfigConstants.DEFAULT_CHARSET)));

		response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain");
		response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

		ctx.writeAndFlush(response);
	}
}
 
Example 10
Source File: HandlerRedirectUtils.java    From flink with Apache License 2.0 5 votes vote down vote up
public static HttpResponse getResponse(HttpResponseStatus status, @Nullable String message) {
	ByteBuf messageByteBuf = message == null ? Unpooled.buffer(0)
		: Unpooled.wrappedBuffer(message.getBytes(ENCODING));
	FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status, messageByteBuf);
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=" + ENCODING.name());
	response.headers().set(HttpHeaders.Names.CONTENT_LENGTH, response.content().readableBytes());

	return response;
}
 
Example 11
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 12
Source File: RestClient.java    From Flink-CEPplus with Apache License 2.0 4 votes vote down vote up
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(0 <= targetPort && targetPort < 65536, "The target port " + targetPort + " is not in the range (0, 65536].");
	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);
}
 
Example 13
Source File: RestClient.java    From flink with Apache License 2.0 4 votes vote down vote up
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(0 <= targetPort && targetPort < 65536, "The target port " + targetPort + " is not in the range (0, 65536].");
	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);
}
 
Example 14
Source File: RestClient.java    From flink with Apache License 2.0 4 votes vote down vote up
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);
}