use of org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled in project component-runtime by Talend.
the class ServingProxyHandler method channelRead0.
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final FullHttpRequest request) {
if (!request.decoderResult().isSuccess()) {
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
api.getExecutor().execute(() -> {
final Map<String, String> headers = StreamSupport.stream(Spliterators.spliteratorUnknownSize(request.headers().iteratorAsString(), Spliterator.IMMUTABLE), false).collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
final Attribute<String> baseAttr = ctx.channel().attr(Handlers.BASE);
Optional<Response> matching = api.getResponseLocator().findMatching(new RequestImpl((baseAttr == null || baseAttr.get() == null ? "" : baseAttr.get()) + request.uri(), request.method().name(), headers), api.getHeaderFilter());
if (!matching.isPresent()) {
if (HttpMethod.CONNECT.name().equalsIgnoreCase(request.method().name())) {
final Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put(HttpHeaderNames.CONNECTION.toString(), HttpHeaderValues.KEEP_ALIVE.toString());
responseHeaders.put(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
matching = of(new ResponseImpl(responseHeaders, HttpResponseStatus.OK.code(), Unpooled.EMPTY_BUFFER.array()));
if (api.getSslContext() != null) {
final SSLEngine sslEngine = api.getSslContext().createSSLEngine();
sslEngine.setUseClientMode(false);
ctx.channel().pipeline().addFirst("ssl", new SslHandler(sslEngine, true));
final String uri = request.uri();
final String[] parts = uri.split(":");
ctx.channel().attr(Handlers.BASE).set("https://" + parts[0] + (parts.length > 1 && !"443".equals(parts[1]) ? ":" + parts[1] : ""));
}
} else {
sendError(ctx, new HttpResponseStatus(HttpURLConnection.HTTP_BAD_REQUEST, "You are in proxy mode. No response was found for the simulated request. Please ensure to capture it for next executions. " + request.method().name() + " " + request.uri()));
return;
}
}
final Response resp = matching.get();
final ByteBuf bytes = ofNullable(resp.payload()).map(Unpooled::copiedBuffer).orElse(Unpooled.EMPTY_BUFFER);
final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(resp.status()), bytes);
HttpUtil.setContentLength(response, bytes.array().length);
if (!api.isSkipProxyHeaders()) {
response.headers().set("X-Talend-Proxy-JUnit", "true");
}
ofNullable(resp.headers()).ifPresent(h -> h.forEach((k, v) -> response.headers().set(k, v)));
ctx.writeAndFlush(response);
});
}
use of org.apache.flink.shaded.netty4.io.netty.buffer.Unpooled in project component-runtime by Talend.
the class PassthroughHandler method doHttpRequest.
private void doHttpRequest(final FullHttpRequest request, final ChannelHandlerContext ctx) {
try {
final Attribute<String> baseAttr = ctx.channel().attr(Handlers.BASE);
final String requestUri = (baseAttr == null || baseAttr.get() == null ? "" : baseAttr.get()) + request.uri();
// do the remote request with all the incoming data and save it
// note: this request must be synchronous for now
final Response resp;
try {
final URL url = new URL(requestUri);
final HttpURLConnection connection = HttpURLConnection.class.cast(url.openConnection(Proxy.NO_PROXY));
connection.setConnectTimeout(30000);
connection.setReadTimeout(20000);
if (HttpsURLConnection.class.isInstance(connection) && api.getSslContext() != null) {
final HttpsURLConnection httpsURLConnection = HttpsURLConnection.class.cast(connection);
httpsURLConnection.setHostnameVerifier((h, s) -> true);
httpsURLConnection.setSSLSocketFactory(api.getSslContext().getSocketFactory());
}
request.headers().forEach(e -> connection.setRequestProperty(e.getKey(), e.getValue()));
if (request.method() != null) {
final String requestMethod = request.method().name();
connection.setRequestMethod(requestMethod);
if (!"HEAD".equalsIgnoreCase(requestMethod) && request.content().readableBytes() > 0) {
connection.setDoOutput(true);
request.content().readBytes(connection.getOutputStream(), request.content().readableBytes());
}
}
final int responseCode = connection.getResponseCode();
final int defaultLength = ofNullable(connection.getHeaderField("content-length")).map(Integer::parseInt).orElse(8192);
resp = new ResponseImpl(connection.getHeaderFields().entrySet().stream().filter(e -> e.getKey() != null).filter(h -> !api.getHeaderFilter().test(h.getKey())).collect(toMap(Map.Entry::getKey, e -> e.getValue().stream().collect(Collectors.joining(",")))), responseCode, responseCode <= 399 ? slurp(connection.getInputStream(), defaultLength) : slurp(connection.getErrorStream(), defaultLength));
} catch (final Exception e) {
log.error(e.getMessage(), e);
sendError(ctx, HttpResponseStatus.BAD_REQUEST);
return;
}
beforeResponse(requestUri, request, resp);
final ByteBuf bytes = ofNullable(resp.payload()).map(Unpooled::copiedBuffer).orElse(Unpooled.EMPTY_BUFFER);
final HttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.valueOf(resp.status()), bytes);
HttpUtil.setContentLength(response, bytes.array().length);
ofNullable(resp.headers()).ifPresent(h -> h.forEach((k, v) -> response.headers().set(k, v)));
ctx.writeAndFlush(response);
} finally {
request.release();
}
}
Aggregations