use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest 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.handler.codec.http.FullHttpRequest in project netty by netty.
the class HttpProxyHandlerTest method testInitialMessage.
private static void testInitialMessage(InetSocketAddress socketAddress, String expectedUrl, String expectedHostHeader, HttpHeaders headers, boolean ignoreDefaultPortsInConnectHostHeader) throws Exception {
InetSocketAddress proxyAddress = new InetSocketAddress(NetUtil.LOCALHOST, 8080);
ChannelPromise promise = mock(ChannelPromise.class);
verifyNoMoreInteractions(promise);
ChannelHandlerContext ctx = mock(ChannelHandlerContext.class);
when(ctx.connect(same(proxyAddress), isNull(InetSocketAddress.class), same(promise))).thenReturn(promise);
HttpProxyHandler handler = new HttpProxyHandler(new InetSocketAddress(NetUtil.LOCALHOST, 8080), headers, ignoreDefaultPortsInConnectHostHeader);
handler.connect(ctx, socketAddress, null, promise);
FullHttpRequest request = (FullHttpRequest) handler.newInitialMessage(ctx);
try {
assertEquals(HttpVersion.HTTP_1_1, request.protocolVersion());
assertEquals(expectedUrl, request.uri());
HttpHeaders actualHeaders = request.headers();
assertEquals(expectedHostHeader, actualHeaders.get(HttpHeaderNames.HOST));
if (headers != null) {
// The actual request header is a strict superset of the custom header
for (String name : headers.names()) {
assertEquals(headers.getAll(name), actualHeaders.getAll(name));
}
}
} finally {
request.release();
}
verify(ctx).connect(proxyAddress, null, promise);
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project netty by netty.
the class WebSocketClientHandshaker method handshake.
/**
* Begins the opening handshake
*
* @param channel
* Channel
* @param promise
* the {@link ChannelPromise} to be notified when the opening handshake is sent
*/
public final ChannelFuture handshake(Channel channel, final ChannelPromise promise) {
ChannelPipeline pipeline = channel.pipeline();
HttpResponseDecoder decoder = pipeline.get(HttpResponseDecoder.class);
if (decoder == null) {
HttpClientCodec codec = pipeline.get(HttpClientCodec.class);
if (codec == null) {
promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " + "an HttpResponseDecoder or HttpClientCodec"));
return promise;
}
}
FullHttpRequest request = newHandshakeRequest();
channel.writeAndFlush(request).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (future.isSuccess()) {
ChannelPipeline p = future.channel().pipeline();
ChannelHandlerContext ctx = p.context(HttpRequestEncoder.class);
if (ctx == null) {
ctx = p.context(HttpClientCodec.class);
}
if (ctx == null) {
promise.setFailure(new IllegalStateException("ChannelPipeline does not contain " + "an HttpRequestEncoder or HttpClientCodec"));
return;
}
p.addAfter(ctx.name(), "ws-encoder", newWebSocketEncoder());
promise.setSuccess();
} else {
promise.setFailure(future.cause());
}
}
});
return promise;
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project netty by netty.
the class WebSocketClientHandshaker07 method newHandshakeRequest.
/**
* /**
* <p>
* Sends the opening request to the server:
* </p>
*
* <pre>
* GET /chat HTTP/1.1
* Host: server.example.com
* Upgrade: websocket
* Connection: Upgrade
* Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
* Sec-WebSocket-Origin: http://example.com
* Sec-WebSocket-Protocol: chat, superchat
* Sec-WebSocket-Version: 7
* </pre>
*/
@Override
protected FullHttpRequest newHandshakeRequest() {
URI wsURL = uri();
// Get 16 bit nonce and base 64 encode it
byte[] nonce = WebSocketUtil.randomBytes(16);
String key = WebSocketUtil.base64(nonce);
String acceptSeed = key + MAGIC_GUID;
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
expectedChallengeResponseString = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug("WebSocket version 07 client handshake key: {}, expected response: {}", key, expectedChallengeResponseString);
}
// Format request
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, upgradeUrl(wsURL), Unpooled.EMPTY_BUFFER);
HttpHeaders headers = request.headers();
if (customHeaders != null) {
headers.add(customHeaders);
if (!headers.contains(HttpHeaderNames.HOST)) {
// Only add HOST header if customHeaders did not contain it.
//
// See https://github.com/netty/netty/issues/10101
headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
}
} else {
headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
}
headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE).set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key);
if (!headers.contains(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN)) {
headers.set(HttpHeaderNames.SEC_WEBSOCKET_ORIGIN, websocketOriginValue(wsURL));
}
String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
}
headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version().toAsciiString());
return request;
}
use of org.apache.flink.shaded.netty4.io.netty.handler.codec.http.FullHttpRequest in project netty by netty.
the class WebSocketClientHandshaker13 method newHandshakeRequest.
/**
* /**
* <p>
* Sends the opening request to the server:
* </p>
*
* <pre>
* GET /chat HTTP/1.1
* Host: server.example.com
* Upgrade: websocket
* Connection: Upgrade
* Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
* Origin: http://example.com
* Sec-WebSocket-Protocol: chat, superchat
* Sec-WebSocket-Version: 13
* </pre>
*/
@Override
protected FullHttpRequest newHandshakeRequest() {
URI wsURL = uri();
// Get 16 bit nonce and base 64 encode it
byte[] nonce = WebSocketUtil.randomBytes(16);
String key = WebSocketUtil.base64(nonce);
String acceptSeed = key + MAGIC_GUID;
byte[] sha1 = WebSocketUtil.sha1(acceptSeed.getBytes(CharsetUtil.US_ASCII));
expectedChallengeResponseString = WebSocketUtil.base64(sha1);
if (logger.isDebugEnabled()) {
logger.debug("WebSocket version 13 client handshake key: {}, expected response: {}", key, expectedChallengeResponseString);
}
// Format request
FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, upgradeUrl(wsURL), Unpooled.EMPTY_BUFFER);
HttpHeaders headers = request.headers();
if (customHeaders != null) {
headers.add(customHeaders);
if (!headers.contains(HttpHeaderNames.HOST)) {
// Only add HOST header if customHeaders did not contain it.
//
// See https://github.com/netty/netty/issues/10101
headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
}
} else {
headers.set(HttpHeaderNames.HOST, websocketHostValue(wsURL));
}
headers.set(HttpHeaderNames.UPGRADE, HttpHeaderValues.WEBSOCKET).set(HttpHeaderNames.CONNECTION, HttpHeaderValues.UPGRADE).set(HttpHeaderNames.SEC_WEBSOCKET_KEY, key);
if (!headers.contains(HttpHeaderNames.ORIGIN)) {
headers.set(HttpHeaderNames.ORIGIN, websocketOriginValue(wsURL));
}
String expectedSubprotocol = expectedSubprotocol();
if (expectedSubprotocol != null && !expectedSubprotocol.isEmpty()) {
headers.set(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL, expectedSubprotocol);
}
headers.set(HttpHeaderNames.SEC_WEBSOCKET_VERSION, version().toAsciiString());
return request;
}
Aggregations