Java Code Examples for io.netty.handler.codec.http.HttpRequest

The following examples show how to use io.netty.handler.codec.http.HttpRequest. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: zuul   Source File: HttpBodySizeRecordingChannelHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
{
    State state = null;
    
    // Reset the state as each new inbound request comes in.
    if (msg instanceof HttpRequest) {
        state = createNewState(ctx.channel());
    }
    
    // Update the inbound body size with this chunk.
    if (msg instanceof HttpContent) {
        if (state == null) {
            state = getOrCreateCurrentState(ctx.channel());
        }
        state.inboundBodySize += ((HttpContent) msg).content().readableBytes();
    }

    super.channelRead(ctx, msg);
}
 
Example 2
Source Project: browserup-proxy   Source File: HttpUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Identify the host of an HTTP request. This method uses the URI of the request if possible, otherwise it attempts to find the host
 * in the request headers.
 *
 * @param httpRequest HTTP request to parse the host from
 * @return the host the request is connecting to, or null if no host can be found
 */
public static String getHostFromRequest(HttpRequest httpRequest) {
    // try to use the URI from the request first, if the URI starts with http:// or https://. checking for http/https avoids confusing
    // java's URI class when the request is for a malformed URL like '//some-resource'.
    String host = null;
    if (startsWithHttpOrHttps(httpRequest.getUri())) {
        try {
            URI uri = new URI(httpRequest.getUri());
            host = uri.getHost();
        } catch (URISyntaxException e) {
        }
    }

    // if there was no host in the URI, attempt to grab the host from the Host header
    if (host == null || host.isEmpty()) {
        host = parseHostHeader(httpRequest, false);
    }

    return host;
}
 
Example 3
Source Project: AndroidHttpCapture   Source File: HarCaptureFilter.java    License: MIT License 6 votes vote down vote up
protected void captureRequestCookies(HttpRequest httpRequest) {
    String cookieHeader = httpRequest.headers().get(HttpHeaders.Names.COOKIE);
    if (cookieHeader == null) {
        return;
    }

    Set<Cookie> cookies = ServerCookieDecoder.LAX.decode(cookieHeader);

    for (Cookie cookie : cookies) {
        HarCookie harCookie = new HarCookie();

        harCookie.setName(cookie.name());
        harCookie.setValue(cookie.value());

        harEntry.getRequest().getCookies().add(harCookie);
    }
}
 
Example 4
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        this.httpRequest = (HttpRequest) httpObject;
    }

    if (httpObject instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) httpObject;

        storeRequestContent(httpContent);

        if (httpContent instanceof LastHttpContent) {
            LastHttpContent lastHttpContent = (LastHttpContent) httpContent;
            trailingHeaders = lastHttpContent .trailingHeaders();
        }
    }

    return null;
}
 
Example 5
Source Project: browserup-proxy   Source File: HttpsHostCaptureFilter.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        if (ProxyUtils.isCONNECT(httpRequest)) {
            Attribute<String> hostname = ctx.channel().attr(AttributeKey.valueOf(HOST_ATTRIBUTE_NAME));
            String hostAndPort = httpRequest.uri();

            // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the
            // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example)
            // would be unexpected.
            String hostNoDefaultPort = BrowserUpHttpUtil.removeMatchingPort(hostAndPort, 443);
            hostname.set(hostNoDefaultPort);
        }
    }

    return null;
}
 
Example 6
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest req = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }
        boolean keepAlive = HttpHeaders.isKeepAlive(req);
        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer(CONTENT));
        response.headers().set(CONTENT_TYPE, "text/plain");
        response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

        if (!keepAlive) {
            ctx.write(response).addListener(ChannelFutureListener.CLOSE);
        } else {
            response.headers().set(CONNECTION, Values.KEEP_ALIVE);
            ctx.write(response);
        }
    }
}
 
Example 7
@Override
public void run(String... strings) {
	String websocketPath = "/wss";
	webScoketServer = new WebSocketServer();
	
	BaseHttpResource httpResource = new HttpResourceThymeleaf();
	httpResource.setRootDir("static/websocket/");
	httpResource.setDefaultIndexName("websocket.html");
	httpResource.setHttpResourceProcess(new HttpResourceProcess() {
		@Override
		public void porcessResPath(HttpRequest req, String reqPath,
				Map<String, Object> reqParameter) {
			if  (httpResource.getDefaultIndexName().equalsIgnoreCase(reqPath) && (reqParameter != null)) {
				reqParameter.put("socketurl", WebSocketUtil.getWebSocketLocation(webScoketServer.getSslCtx() != null, req, websocketPath));
			}
		}
	});
	

	webScoketServer.setHttpResource(httpResource);
	webScoketServer.setWebsocketPath(websocketPath);
	webScoketServer.setWebSocketEvent(new WebSocketEventChat());
	webScoketServer.bind(8989);
	
	NettyLog.info("websocket server run end "); 
}
 
Example 8
Source Project: nitmproxy   Source File: Http2FrontendHandler.java    License: MIT License 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    LOGGER.info("[Client ({})] => [Server ({})] : {}",
                connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                msg);

    if (msg instanceof FullHttpRequest) {
        String streamId = ((HttpRequest) msg).headers().get(
                HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
        if (streamId == null) {
            throw new IllegalStateException("No streamId");
        }
        streams.offer(streamId);
    } else if (msg instanceof HttpObject) {
        throw new IllegalStateException("Cannot handle message: " + msg.getClass());
    }

    outboundChannel.writeAndFlush(msg);
}
 
Example 9
Source Project: bromium   Source File: RecordRequestFilter.java    License: MIT License 6 votes vote down vote up
@Override
public HttpResponse filterRequest(HttpRequest httpRequest, HttpMessageContents httpMessageContents, HttpMessageInfo httpMessageInfo) {
    for (EventDetector eventDetector: eventDetectors) {
        if (eventDetector.canDetectPredicate().test(httpRequest)) {
            try {
                Optional<Map<String, String>> optionalEvent = eventDetector.getConverter().convert(httpRequest);

                if (optionalEvent.isPresent()) {
                    Map<String, String> event = optionalEvent.get();
                    recordingState.storeTestCaseStep(event);
                    logger.info("Recorded event {}", event);
                }

            } catch (UnsupportedEncodingException | MalformedURLException e) {
                logger.error("Error while trying to convert test case step", e);
            }
        }
    }

    return null;
}
 
Example 10
Source Project: serve   Source File: ModelServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testMetricManager"})
public void testInvalidRootRequest() throws InterruptedException {
    Channel channel = TestUtils.connect(false, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.METHOD_NOT_ALLOWED.code());
    Assert.assertEquals(resp.getMessage(), ERROR_METHOD_NOT_ALLOWED);
}
 
Example 11
Source Project: zuul   Source File: HttpLifecycleChannelHandler.java    License: Apache License 2.0 6 votes vote down vote up
protected static boolean fireCompleteEventIfNotAlready(ChannelHandlerContext ctx, CompleteReason reason)
{
    // Only allow this method to run once per request.
    Attribute<State> attr = ctx.channel().attr(ATTR_STATE);
    State state = attr.get();

    if (state == null || state != State.STARTED)
        return false;
    
    attr.set(State.COMPLETED);

    HttpRequest request = ctx.channel().attr(ATTR_HTTP_REQ).get();
    HttpResponse response = ctx.channel().attr(ATTR_HTTP_RESP).get();

    // Cleanup channel attributes.
    ctx.channel().attr(ATTR_HTTP_REQ).set(null);
    ctx.channel().attr(ATTR_HTTP_RESP).set(null);

    // Fire the event to whole pipeline.
    ctx.pipeline().fireUserEventTriggered(new CompleteEvent(reason, request, response));
    
    return true;
}
 
Example 12
Source Project: zuul   Source File: HttpBodySizeRecordingChannelHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception
{
    State state = null;

    // Reset the state as each new outbound request goes out.
    if (msg instanceof HttpRequest) {
        state = createNewState(ctx.channel());
    }

    // Update the outbound body size with this chunk.
    if (msg instanceof HttpContent) {
        if (state == null) {
            state = getOrCreateCurrentState(ctx.channel());
        }
        state.outboundBodySize += ((HttpContent) msg).content().readableBytes();
    }

    super.write(ctx, msg, promise);
}
 
Example 13
Source Project: styx   Source File: NettyToStyxRequestDecoderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void acceptsMalformedCookiesWithRelaxedValidation() {
    HttpRequest request = new DefaultFullHttpRequest(HTTP_1_1, GET, "http://foo.com/");
    request.headers().set(HOST, "http://foo.com/");
    request.headers().set("Cookie", "ABC01=\"1\"; ABC02=1; guid=a,b");

    NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder()
            .uniqueIdSupplier(uniqueIdSupplier)
            .build();

    LiveHttpRequest styxRequest = decoder.makeAStyxRequestFrom(request, Flux.empty())
            .build();

    LiveHttpRequest expected = new LiveHttpRequest.Builder(
            HttpMethod.GET, "http://foo.com/")
            .cookies(
                    requestCookie("ABC01", "\"1\""),
                    requestCookie("ABC02", "1"),
                    requestCookie("guid", "a,b")
            )
            .build();
    assertThat(newHashSet(styxRequest.cookies()), is(newHashSet(expected.cookies())));
}
 
Example 14
Source Project: serve   Source File: ModelServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test(
        alwaysRun = true,
        dependsOnMethods = {"testDescribeModelNotFound"})
public void testRegisterModelMissingUrl() throws InterruptedException {
    Channel channel = TestUtils.connect(true, configManager);
    Assert.assertNotNull(channel);

    HttpRequest req =
            new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, "/models");
    channel.writeAndFlush(req).sync();
    channel.closeFuture().sync();

    ErrorResponse resp = JsonUtils.GSON.fromJson(TestUtils.getResult(), ErrorResponse.class);

    Assert.assertEquals(resp.getCode(), HttpResponseStatus.BAD_REQUEST.code());
    Assert.assertEquals(resp.getMessage(), "Parameter url is required.");
}
 
Example 15
Source Project: ambry   Source File: NettyResponseChannelTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Checks the headers in the response match those in the request.
 * @param request the {@link HttpRequest} with the original value of the headers.
 * @param response the {@link HttpResponse} that should have the same value for some headers in {@code request}.
 * @throws ParseException
 */
private void checkHeaders(HttpRequest request, HttpResponse response) throws ParseException {
  assertEquals("Unexpected response status", HttpResponseStatus.ACCEPTED, response.status());
  assertEquals(HttpHeaderNames.CONTENT_TYPE + " does not match", request.headers().get(HttpHeaderNames.CONTENT_TYPE),
      response.headers().get(HttpHeaderNames.CONTENT_TYPE));
  assertEquals(HttpHeaderNames.CONTENT_LENGTH + " does not match",
      request.headers().get(HttpHeaderNames.CONTENT_LENGTH), response.headers().get(HttpHeaderNames.CONTENT_LENGTH));
  assertEquals(HttpHeaderNames.LOCATION + " does not match", request.headers().get(HttpHeaderNames.LOCATION),
      response.headers().get(HttpHeaderNames.LOCATION));
  assertEquals(HttpHeaderNames.LAST_MODIFIED + " does not match",
      request.headers().getTimeMillis(HttpHeaderNames.LAST_MODIFIED),
      response.headers().getTimeMillis(HttpHeaderNames.LAST_MODIFIED));
  assertEquals(HttpHeaderNames.EXPIRES + " does not match", request.headers().getTimeMillis(HttpHeaderNames.EXPIRES),
      response.headers().getTimeMillis(HttpHeaderNames.EXPIRES));
  assertEquals(HttpHeaderNames.CACHE_CONTROL + " does not match",
      request.headers().get(HttpHeaderNames.CACHE_CONTROL), response.headers().get(HttpHeaderNames.CACHE_CONTROL));
  assertEquals(HttpHeaderNames.PRAGMA + " does not match", request.headers().get(HttpHeaderNames.PRAGMA),
      response.headers().get(HttpHeaderNames.PRAGMA));
  assertEquals(HttpHeaderNames.DATE + " does not match", request.headers().getTimeMillis(HttpHeaderNames.DATE),
      response.headers().getTimeMillis(HttpHeaderNames.DATE));
  assertEquals(MockNettyMessageProcessor.CUSTOM_HEADER_NAME + " does not match",
      request.headers().get(MockNettyMessageProcessor.CUSTOM_HEADER_NAME),
      response.headers().get(MockNettyMessageProcessor.CUSTOM_HEADER_NAME));
}
 
Example 16
@Test
public void alternate_constructor_creates_instance_using_specified_wingtips_strategy_and_adapter() {
    // given
    HttpTagAndSpanNamingStrategy<HttpRequest, HttpResponse> wingtipsStrategyMock =
        mock(HttpTagAndSpanNamingStrategy.class);
    HttpTagAndSpanNamingAdapter<HttpRequest, HttpResponse> wingtipsAdapterMock =
        mock(HttpTagAndSpanNamingAdapter.class);

    // when
    DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy instance =
        new DefaultRiposteProxyRouterSpanNamingAndTaggingStrategy(wingtipsStrategyMock, wingtipsAdapterMock);

    // then
    assertThat(instance.tagAndNamingStrategy).isSameAs(wingtipsStrategyMock);
    assertThat(instance.tagAndNamingAdapter).isSameAs(wingtipsAdapterMock);
}
 
Example 17
Source Project: CapturePacket   Source File: HttpsHostCaptureFilter.java    License: MIT License 6 votes vote down vote up
@Override
public HttpResponse clientToProxyRequest(HttpObject httpObject) {
    if (httpObject instanceof HttpRequest) {
        HttpRequest httpRequest = (HttpRequest) httpObject;

        if (ProxyUtils.isCONNECT(httpRequest)) {
            Attribute<String> hostname = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.HOST_ATTRIBUTE_NAME));
            String hostAndPort = httpRequest.getUri();

            // CONNECT requests contain the port, even when using the default port. a sensible default is to remove the
            // default port, since in most cases it is not explicitly specified and its presence (in a HAR file, for example)
            // would be unexpected.
            String hostNoDefaultPort = BrowserMobHttpUtil.removeMatchingPort(hostAndPort, 443);
            hostname.set(hostNoDefaultPort);
        }
    }

    return null;
}
 
Example 18
Source Project: hadoop   Source File: WebHdfsHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void channelRead0(final ChannelHandlerContext ctx,
                         final HttpRequest req) throws Exception {
  Preconditions.checkArgument(req.getUri().startsWith(WEBHDFS_PREFIX));
  QueryStringDecoder queryString = new QueryStringDecoder(req.getUri());
  params = new ParameterParser(queryString, conf);
  DataNodeUGIProvider ugiProvider = new DataNodeUGIProvider(params);
  ugi = ugiProvider.ugi();
  path = params.path();

  injectToken();
  ugi.doAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      handle(ctx, req);
      return null;
    }
  });
}
 
Example 19
Source Project: olingo-odata4   Source File: ODataNettyHandlerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Copy the headers part of Netty Request to OData Request
 * @param odRequest
 * @param req
 */
static void copyHeaders(ODataRequest odRequest, final HttpRequest req) {
 final Set<String> headers = req.headers().names();
 Iterator<String> headerNames = headers.iterator();
 while (headerNames.hasNext()) {
  final String headerName = headerNames.next();
  final List<String> headerValues = req.headers().getAll(headerName);
     odRequest.addHeader(headerName, headerValues);
 }
}
 
Example 20
Source Project: minnal   Source File: ApplicationMapping.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Resolves the request to an application by mapping the request url to the application path.
 * 
 * @param request
 * @return the application that this request resolves to
 */
public Application<ApplicationConfiguration> resolve(HttpRequest request) {
	String path = request.getUri();
	for (Entry<String, Application<ApplicationConfiguration>> entry : getSortedApplications().entrySet()) {
		if (path.startsWith(entry.getKey())) {
			return entry.getValue();
		}
	}
	return null;
}
 
Example 21
Source Project: riposte   Source File: ExceptionHandlingHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void getRequestInfo_creates_new_RequestInfo_based_on_msg_if_state_requestInfo_is_null_and_msg_is_a_HttpRequest() {
    // given
    assertThat(state.getRequestInfo(), nullValue());
    String expectedUri = "/some/uri/" + UUID.randomUUID().toString();
    HttpRequest httpRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, expectedUri);

    // when
    RequestInfo<?> result = handler.getRequestInfo(state, httpRequest);

    // then
    assertThat(result.getUri(), is(expectedUri));
}
 
Example 22
public ConnectionFlowProcessor(ChannelMediator channelMediator, HttpRequest httpRequest,
    List<ConnectionFlowStep> connectionFlow) {
  _channelMediator = channelMediator;
  _connectionFlow = connectionFlow;
  _complete = false;
  _startTime = System.currentTimeMillis();
  _remoteAddress = getRemoteAddress(httpRequest);
  LOG.debug(String.format("Start connection flow at: %d", _startTime));
}
 
Example 23
Source Project: multi-model-server   Source File: ModelServerTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testLoadModel(Channel channel) throws InterruptedException {
    result = null;
    latch = new CountDownLatch(1);
    HttpRequest req =
            new DefaultFullHttpRequest(
                    HttpVersion.HTTP_1_1,
                    HttpMethod.POST,
                    "/models?url=noop-v0.1&model_name=noop_v0.1&runtime=python&synchronous=false");
    channel.writeAndFlush(req);
    latch.await();

    StatusResponse resp = JsonUtils.GSON.fromJson(result, StatusResponse.class);
    Assert.assertEquals(resp.getStatus(), "Model \"noop_v0.1\" registered");
}
 
Example 24
Source Project: xio   Source File: Http1FilterConfig.java    License: Apache License 2.0 5 votes vote down vote up
public boolean denied(HttpRequest request) {
  for (Http1DeterministicRuleEngineConfig.Rule rule : blacklist) {
    if (rule.matches(request)) {
      return true;
    }
  }
  return false;
}
 
Example 25
Source Project: browserup-proxy   Source File: ImpersonatingMitmManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SSLEngine clientSslEngineFor(HttpRequest httpRequest, SSLSession sslSession) {
    String requestedHostname = HttpUtil.getHostFromRequest(httpRequest);

    try {
        SslContext ctx = getHostnameImpersonatingSslContext(requestedHostname, sslSession);

        return ctx.newEngine(ByteBufAllocator.DEFAULT);
    } catch (RuntimeException e) {
        throw new MitmException("Error creating SSLEngine for connection to client to impersonate upstream host: " + requestedHostname, e);
    }
}
 
Example 26
Source Project: browserup-proxy   Source File: HttpUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Gets the host and port from the specified request. Returns the host and port from the request URI if available,
 * otherwise retrieves the host and port from the Host header.
 *
 * @param httpRequest HTTP request
 * @return host and port of the request
 */
public static String getHostAndPortFromRequest(HttpRequest httpRequest) {
    if (startsWithHttpOrHttps(httpRequest.uri())) {
        try {
            return getHostAndPortFromUri(httpRequest.uri());
        } catch (URISyntaxException e) {
            // the URI could not be parsed, so return the host and port in the Host header
        }
    }

    return parseHostHeader(httpRequest, true);
}
 
Example 27
Source Project: netty-4.1.22   Source File: WebSocketRequestBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public static HttpRequest successful() {
    return new WebSocketRequestBuilder().httpVersion(HTTP_1_1)
            .method(HttpMethod.GET)
            .uri("/test")
            .host("server.example.com")
            .upgrade(HttpHeaderValues.WEBSOCKET)
            .key("dGhlIHNhbXBsZSBub25jZQ==")
            .origin("http://example.com")
            .version13()
            .build();
}
 
Example 28
Source Project: styx   Source File: NettyToStyxRequestDecoderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void callsTheEscaperForUnwiseChars() {
    UnwiseCharsEncoder encoder = mock(UnwiseCharsEncoder.class);
    NettyToStyxRequestDecoder decoder = new NettyToStyxRequestDecoder.Builder()
            .uniqueIdSupplier(uniqueIdSupplier)
            .unwiseCharEncoder(encoder)
            .build();

    HttpRequest request = newHttpRequest("/foo");
    when(encoder.encode("/foo")).thenReturn("/foo");
    request.headers().add(HOST, "example.com");
    handle(request, decoder);
    verify(encoder).encode("/foo");
}
 
Example 29
Source Project: netty-4.1.22   Source File: RtspEncoderTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test of a SETUP request, with no body.
 */
@Test
public void testSendSetupRequest() {
    String expected = "SETUP rtsp://172.10.20.30:554/d3abaaa7-65f2-42b4-"
                    + "8d6b-379f492fcf0f RTSP/1.0\r\n"
                    + "transport: MP2T/DVBC/UDP;unicast;client=01234567;"
                    + "source=172.10.20.30;"
                    + "destination=1.1.1.1;client_port=6922\r\n"
                    + "cseq: 1\r\n"
                    + "\r\n";

    HttpRequest request = new DefaultHttpRequest(RtspVersions.RTSP_1_0,
           RtspMethods.SETUP,
           "rtsp://172.10.20.30:554/d3abaaa7-65f2-42b4-8d6b-379f492fcf0f");
    request.headers().add(RtspHeaderNames.TRANSPORT,
           "MP2T/DVBC/UDP;unicast;client=01234567;source=172.10.20.30;" +
           "destination=1.1.1.1;client_port=6922");
    request.headers().add(RtspHeaderNames.CSEQ, "1");

    EmbeddedChannel ch = new EmbeddedChannel(new RtspEncoder());
    ch.writeOutbound(request);

    ByteBuf buf = ch.readOutbound();
    String actual = buf.toString(CharsetUtil.UTF_8);
    buf.release();
    assertEquals(expected, actual);
}
 
Example 30
Source Project: Dream-Catcher   Source File: HttpsOriginalHostCaptureFilter.java    License: MIT License 5 votes vote down vote up
public HttpsOriginalHostCaptureFilter(HttpRequest originalRequest, ChannelHandlerContext ctx) {
    super(originalRequest, ctx);

    // if this is an HTTP CONNECT, set the isHttps attribute on the ChannelHandlerConect and capture the hostname from the original request.
    // capturing the original host (and the remapped/modified host in clientToProxyRequest() below) guarantees that we will
    // have the "true" host, rather than relying on the Host header in subsequent requests (which may be absent or spoofed by malicious clients).
    if (ProxyUtils.isCONNECT(originalRequest)) {
        Attribute<String> originalHostAttr = ctx.attr(AttributeKey.<String>valueOf(HttpsAwareFiltersAdapter.ORIGINAL_HOST_ATTRIBUTE_NAME));
        String hostAndPort = originalRequest.getUri();
        originalHostAttr.set(hostAndPort);

        Attribute<Boolean> isHttpsAttr = ctx.attr(AttributeKey.<Boolean>valueOf(HttpsAwareFiltersAdapter.IS_HTTPS_ATTRIBUTE_NAME));
        isHttpsAttr.set(true);
    }
}