io.netty.handler.codec.http.DefaultHttpHeaders Java Examples

The following examples show how to use io.netty.handler.codec.http.DefaultHttpHeaders. 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: HttpUtilsTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void extractCookies_works_if_cookies_defined_in_trailing_headers() {
    // given
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    HttpHeaders trailingHeaders = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));

    FullHttpRequest nettyRequestMock = mock(FullHttpRequest.class);
    doReturn(new DefaultHttpHeaders()).when(nettyRequestMock).headers();
    doReturn(trailingHeaders).when(nettyRequestMock).trailingHeaders();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
}
 
Example #2
Source File: Http2ServerUpgradeCodecTest.java    From netty-4.1.22 with Apache License 2.0 6 votes vote down vote up
private static void testUpgrade(Http2ConnectionHandler handler) {
    FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.OPTIONS, "*");
    request.headers().set(HttpHeaderNames.HOST, "netty.io");
    request.headers().set(HttpHeaderNames.CONNECTION, "Upgrade, HTTP2-Settings");
    request.headers().set(HttpHeaderNames.UPGRADE, "h2c");
    request.headers().set("HTTP2-Settings", "AAMAAABkAAQAAP__");

    EmbeddedChannel channel = new EmbeddedChannel(new ChannelInboundHandlerAdapter());
    ChannelHandlerContext ctx = channel.pipeline().firstContext();
    Http2ServerUpgradeCodec codec = new Http2ServerUpgradeCodec("connectionHandler", handler);
    assertTrue(codec.prepareUpgradeResponse(ctx, request, new DefaultHttpHeaders()));
    codec.upgradeTo(ctx, request);
    // Flush the channel to ensure we write out all buffered data
    channel.flush();

    assertSame(handler, channel.pipeline().remove("connectionHandler"));
    assertNull(channel.pipeline().get(handler.getClass()));
    assertTrue(channel.finish());

    // Check that the preface was send (a.k.a the settings frame)
    ByteBuf settingsBuffer = channel.readOutbound();
    assertNotNull(settingsBuffer);
    settingsBuffer.release();

    assertNull(channel.readOutbound());
}
 
Example #3
Source File: NettyResponseChannelTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Asks the server to write more data than the set Content-Length and checks behavior.
 * @param chunkCount the number of chunks of {@link MockNettyMessageProcessor#CHUNK} to use to set Content-Length.
 * @throws Exception
 */
private void doWriteMoreThanContentLengthTest(int chunkCount) throws Exception {
  EmbeddedChannel channel = createEmbeddedChannel();
  MockNettyMessageProcessor processor = channel.pipeline().get(MockNettyMessageProcessor.class);
  HttpHeaders httpHeaders = new DefaultHttpHeaders();
  httpHeaders.set(MockNettyMessageProcessor.CHUNK_COUNT_HEADER_NAME, chunkCount);
  HttpRequest httpRequest =
      RestTestUtils.createRequest(HttpMethod.POST, TestingUri.WriteMoreThanContentLength.toString(), httpHeaders);
  HttpUtil.setKeepAlive(httpRequest, true);
  channel.writeInbound(httpRequest);

  try {
    verifyCallbacks(processor);
    fail("One of the callbacks should have failed because the data written was more than Content-Length");
  } catch (IllegalStateException e) {
    // expected. Nothing to do.
  }

  // It doesn't matter what the response is - because it may either fail or succeed depending on certain race
  // conditions. What matters is that the programming error is caught appropriately by NettyResponseChannel and it
  // makes a callback with the right exception.
  while (channel.readOutbound() != null) {
  }
  channel.close();
}
 
Example #4
Source File: RequestInfoSetterHandlerTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void doChannelRead_uses_existing_RequestInfo_on_state_if_available_and_does_not_recreate_it() {
    // given
    HttpRequest msgMock = mock(HttpRequest.class);
    String uri = "/some/url";
    HttpHeaders headers = new DefaultHttpHeaders();
    doReturn(uri).when(msgMock).uri();
    doReturn(headers).when(msgMock).headers();
    doReturn(HttpVersion.HTTP_1_1).when(msgMock).protocolVersion();
    doReturn(requestInfo).when(stateMock).getRequestInfo();

    // when
    PipelineContinuationBehavior result = handler.doChannelRead(ctxMock, msgMock);

    // then
    verify(stateMock, never()).setRequestInfo(any(RequestInfo.class));
    assertThat(result).isEqualTo(PipelineContinuationBehavior.CONTINUE);
}
 
Example #5
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
void outboundCookiesMustBeMergedForHttp1() {
    final HttpHeaders in = HttpHeaders.builder()
                                      .add(HttpHeaderNames.COOKIE, "a=b; c=d")
                                      .add(HttpHeaderNames.COOKIE, "e=f;g=h")
                                      .addObject(HttpHeaderNames.CONTENT_TYPE, MediaType.PLAIN_TEXT_UTF_8)
                                      .add(HttpHeaderNames.COOKIE, "i=j")
                                      .add(HttpHeaderNames.COOKIE, "k=l;")
                                      .build();

    final io.netty.handler.codec.http.HttpHeaders out =
            new DefaultHttpHeaders();

    toNettyHttp1ClientHeader(in, out);
    assertThat(out.getAll(HttpHeaderNames.COOKIE))
            .containsExactly("a=b; c=d; e=f; g=h; i=j; k=l");
}
 
Example #6
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void extractCookies_handles_cookie_values_leniently() {
    // given
    //these are cookie values seen in the wild...
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), "2094%3Az%7C2021%3Ab");
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), "geoloc=cc=US,rc=OR,tp=vhigh,tz=PST,la=45.4978,lo=-122.6937,bw=5000");
    Cookie cookie3 = new DefaultCookie(UUID.randomUUID().toString(), "\"dm=n.com&si=27431295-a282-4745-8cd5-542e7fce" +
            "429e&ss=1477551008358&sl=76&tt=437632&obo=12&sh=1477552753923%3D76%3A12%3A437632%2C1477552698670%3D75%3" +
            "A12%3A429879%2C1477552677137%3D74%3A12%3A426596%2C1477552672564%3D73%3A12%3A425585%2C1477552669893%3D72" +
            "%3A12%3A423456&bcn=%2F%2F3408178b.mpstat.us%2F&ld=1477552753923&r=http%3A%2F%2Fwww.nike.com%2Fbe%2Fde_de%" +
            "2F&ul=1477552756811\"");
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2, cookie3));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
    assertThat(extractedCookies.contains(cookie3), is(true));
}
 
Example #7
Source File: VerifyProxyRouterTracingBehaviorComponentTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Override
public @NotNull CompletableFuture<ResponseInfo<String>> execute(
    @NotNull RequestInfo<Void> request,
    @NotNull Executor longRunningTaskExecutor,
    @NotNull ChannelHandlerContext ctx
) {
    HttpHeaders reqHeaders = request.getHeaders();
    return CompletableFuture.completedFuture(
        ResponseInfo.newBuilder(RESPONSE_PAYLOAD)
                    .withHeaders(
                        new DefaultHttpHeaders()
                            .set(RECEIVED_TRACE_ID_HEADER_KEY, String.valueOf(reqHeaders.get(TraceHeaders.TRACE_ID)))
                            .set(RECEIVED_SPAN_ID_HEADER_KEY, String.valueOf(reqHeaders.get(TraceHeaders.SPAN_ID)))
                            .set(RECEIVED_PARENT_SPAN_ID_HEADER_KEY, String.valueOf(reqHeaders.get(TraceHeaders.PARENT_SPAN_ID)))
                            .set(RECEIVED_SAMPLED_HEADER_KEY, String.valueOf(reqHeaders.get(TraceHeaders.TRACE_SAMPLED)))
                    )
                    .build()
    );
}
 
Example #8
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Tests multipart POST and verifies it via GET operations.
 * @throws Exception
 */
@Test
public void multipartPostGetHeadUpdateDeleteUndeleteTest() throws Exception {
  Account refAccount = ACCOUNT_SERVICE.createAndAddRandomAccount();
  Container refContainer = refAccount.getContainerById(Container.DEFAULT_PUBLIC_CONTAINER_ID);
  doPostGetHeadUpdateDeleteUndeleteTest(0, refAccount, refContainer, refAccount.getName(),
      !refContainer.isCacheable(), refAccount.getName(), refContainer.getName(), true);
  doPostGetHeadUpdateDeleteUndeleteTest(FRONTEND_CONFIG.chunkedGetResponseThresholdInBytes * 3, refAccount,
      refContainer, refAccount.getName(), !refContainer.isCacheable(), refAccount.getName(), refContainer.getName(),
      true);

  // failure case
  // size of content being POSTed is higher than what is allowed via multipart/form-data
  long maxAllowedSizeBytes = new NettyConfig(FRONTEND_VERIFIABLE_PROPS).nettyMultipartPostMaxSizeBytes;
  ByteBuffer content = ByteBuffer.wrap(TestUtils.getRandomBytes((int) maxAllowedSizeBytes + 1));
  HttpHeaders headers = new DefaultHttpHeaders();
  setAmbryHeadersForPut(headers, TTL_SECS, !refContainer.isCacheable(), refAccount.getName(),
      "application/octet-stream", null, refAccount.getName(), refContainer.getName());
  HttpRequest httpRequest = RestTestUtils.createRequest(HttpMethod.POST, "/", headers);
  HttpPostRequestEncoder encoder = createEncoder(httpRequest, content, ByteBuffer.allocate(0));
  ResponseParts responseParts = nettyClient.sendRequest(encoder.finalizeRequest(), encoder, null).get();
  HttpResponse response = getHttpResponse(responseParts);
  assertEquals("Unexpected response status", HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
  assertTrue("No Date header", response.headers().getTimeMillis(HttpHeaderNames.DATE, -1) != -1);
  assertFalse("Channel should not be active", HttpUtil.isKeepAlive(response));
}
 
Example #9
Source File: TestBindClientContextHandler.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@Test
public void testBindUnknownSession() throws Exception {
   EasyMock
      .expect(sessionDao.readSession("test"))
      .andThrow(new UnknownSessionException());
   replay();

   DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "http://localhost/client");
   DefaultHttpHeaders.addHeader(request, "Cookie", "irisAuthToken=test;");
   handler.channelRead(context, request);
   
   
   // an authenticated Client should have been bound
   ClientFactory factory = ServiceLocator.getInstance(ClientFactory.class);
   Client client = factory.get(channel);
   assertNotNull(client);
   assertFalse(client.isAuthenticated());
   assertEquals(null, client.getSessionId());

   verify();
}
 
Example #10
Source File: RouterTest.java    From minnal with Apache License 2.0 6 votes vote down vote up
@BeforeMethod
public void setup() {
	applicationMapping = mock(ApplicationMapping.class);
	request = mock(FullHttpRequest.class);
	response = mock(FullHttpResponse.class);
	when(request.getMethod()).thenReturn(HttpMethod.GET);
	when(request.getUri()).thenReturn("/test");
	when(request.headers()).thenReturn(new DefaultHttpHeaders());
	when(request.content()).thenReturn(mock(ByteBuf.class));
	when(request.getProtocolVersion()).thenReturn(HttpVersion.HTTP_1_1);
	when(response.getStatus()).thenReturn(HttpResponseStatus.PROCESSING);
	application = mock(Application.class);
	context = mock(MessageContext.class);
	router = spy(new Router(applicationMapping));
	doReturn(new ApplicationHandler()).when(router).getApplicationHandler(application);
	when(application.getPath()).thenReturn(URI.create("/app"));
	when(context.getRequest()).thenReturn(request);
	when(context.getResponse()).thenReturn(response);
	when(context.getApplication()).thenReturn(application);
	when(context.getBaseUri()).thenReturn(URI.create("http://localhost:8080"));
	when(applicationMapping.resolve(request)).thenReturn(application);
}
 
Example #11
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 6 votes vote down vote up
/**
 * Call the {@code GET /accounts} API and deserialize the response.
 * @param accountName if non-null, fetch a single account by name instead of all accounts.
 * @param accountId if non-null, fetch a single account by ID instead of all accounts.
 * @return the accounts fetched.
 */
private Set<Account> getAccounts(String accountName, Short accountId) throws Exception {
  HttpHeaders headers = new DefaultHttpHeaders();
  if (accountName != null) {
    headers.add(RestUtils.Headers.TARGET_ACCOUNT_NAME, accountName);
  } else if (accountId != null) {
    headers.add(RestUtils.Headers.TARGET_ACCOUNT_ID, accountId);
  }
  FullHttpRequest request = buildRequest(HttpMethod.GET, Operations.ACCOUNTS, headers, null);
  ResponseParts responseParts = nettyClient.sendRequest(request, null, null).get();
  HttpResponse response = getHttpResponse(responseParts);
  assertEquals("Unexpected response status", HttpResponseStatus.OK, response.status());
  verifyTrackingHeaders(response);
  ByteBuffer content = getContent(responseParts.queue, HttpUtil.getContentLength(response));
  return new HashSet<>(
      AccountCollectionSerde.fromJson(new JSONObject(new String(content.array(), StandardCharsets.UTF_8))));
}
 
Example #12
Source File: BaseResponseInfoTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void uber_constructor_for_full_response_sets_fields_as_expected() {
    // given
    int httpStatusCode = 200;
    HttpHeaders headers = new DefaultHttpHeaders();
    String mimeType = "text/text";
    Charset contentCharset = CharsetUtil.UTF_8;
    Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2"));
    boolean preventCompressedResponse = true;

    // when
    BaseResponseInfo<?> responseInfo = createNewBaseResponseInfoForTesting(httpStatusCode, headers, mimeType, contentCharset, cookies, preventCompressedResponse);

    // then
    assertThat(responseInfo.getHttpStatusCode(), is(httpStatusCode));
    assertThat(responseInfo.getHeaders(), is(headers));
    assertThat(responseInfo.getDesiredContentWriterMimeType(), is(mimeType));
    assertThat(responseInfo.getDesiredContentWriterEncoding(), is(contentCharset));
    assertThat(responseInfo.getCookies(), is(cookies));
    assertThat(responseInfo.getUncompressedRawContentLength(), nullValue());
    assertThat(responseInfo.isPreventCompressedOutput(), is(preventCompressedResponse));
    assertThat(responseInfo.isResponseSendingStarted(), is(false));
    assertThat(responseInfo.isResponseSendingLastChunkSent(), is(false));
}
 
Example #13
Source File: CookieIntercept.java    From proxyee-down with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeRequest(Channel clientChannel, HttpRequest httpRequest, HttpProxyInterceptPipeline pipeline) throws Exception {
  String acceptValue = httpRequest.headers().get(HttpHeaderNames.ACCEPT);
  if (acceptValue != null && acceptValue.contains("application/x-sniff-cookie")) {
    HttpResponse httpResponse = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, new DefaultHttpHeaders());
    httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, 0);
    //https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Access-Control-Expose-Headers
    AsciiString customHeadKey = AsciiString.cached("X-Sniff-Cookie");
    String cookie = pipeline.getHttpRequest().headers().get(HttpHeaderNames.COOKIE);
    httpResponse.headers().set(customHeadKey, cookie == null ? "" : cookie);
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_EXPOSE_HEADERS, customHeadKey);
    String origin = httpRequest.headers().get(HttpHeaderNames.ORIGIN);
    if (StringUtil.isNullOrEmpty(origin)) {
      String referer = httpRequest.headers().get(HttpHeaderNames.REFERER);
      URL url = new URL(referer);
      origin = url.getHost();
    }
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    httpResponse.headers().set(HttpHeaderNames.ACCESS_CONTROL_ALLOW_CREDENTIALS, true);
    clientChannel.writeAndFlush(httpResponse);
    clientChannel.writeAndFlush(new DefaultLastHttpContent());
    clientChannel.close();
  } else {
    super.beforeRequest(clientChannel, httpRequest, pipeline);
  }
}
 
Example #14
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
@DataProvider(value = {
        "text/text charset=US-ASCII |   UTF-8   | US-ASCII",
        "text/text charset=us-ascii |   UTF-8   | US-ASCII",
        "text/text                  |   UTF-8   | UTF-8",
        "                           |   UTF-8   | UTF-8",
        "null                       |   UTF-8   | UTF-8",
}, splitBy = "\\|")
public void determineCharsetFromContentType_works(String contentTypeHeader, String defaultCharsetString, String expectedCharsetString) {
    // given
    Charset defaultCharset = Charset.forName(defaultCharsetString);
    Charset expectedCharset = Charset.forName(expectedCharsetString);
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.CONTENT_TYPE, String.valueOf(contentTypeHeader));

    // when
    Charset actualCharset = HttpUtils.determineCharsetFromContentType(headers, defaultCharset);

    // then
    assertThat(actualCharset, is(expectedCharset));
}
 
Example #15
Source File: HttpUtilsTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@Test
public void extractCookies_works_if_cookies_defined_in_headers() {
    // given
    Cookie cookie1 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    Cookie cookie2 = new DefaultCookie(UUID.randomUUID().toString(), UUID.randomUUID().toString());
    HttpHeaders headers = new DefaultHttpHeaders().add(HttpHeaders.Names.COOKIE, ClientCookieEncoder.LAX.encode(cookie1, cookie2));

    HttpRequest nettyRequestMock = mock(HttpRequest.class);
    doReturn(headers).when(nettyRequestMock).headers();

    // when
    Set<Cookie> extractedCookies = HttpUtils.extractCookies(nettyRequestMock);

    // then
    assertThat(extractedCookies.contains(cookie1), is(true));
    assertThat(extractedCookies.contains(cookie2), is(true));
}
 
Example #16
Source File: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Does a test for the request handling flow with transfer encoding chunked
 */
private void doRequestHandleWithChunkedResponse(boolean useSSL) throws Exception {
  EmbeddedChannel channel = createChannel(useSSL);
  HttpHeaders headers = new DefaultHttpHeaders();
  headers.add(EchoMethodHandler.IS_CHUNKED, "true");
  HttpRequest request = RestTestUtils.createRequest(HttpMethod.POST, "POST", headers);
  HttpUtil.setKeepAlive(request, true);
  sendRequestCheckResponse(channel, request, "POST", headers, false, true, useSSL);
  Assert.assertTrue("Channel should not be closed ", channel.isOpen());
  channel.close();
}
 
Example #17
Source File: HttpServletRequestWrapperForRequestInfoTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeMethod() {
    headers = new DefaultHttpHeaders();
    attributes = new HashMap<>();
    requestInfoMock = mock(RequestInfo.class);
    doReturn(headers).when(requestInfoMock).getHeaders();
    doReturn(attributes).when(requestInfoMock).getRequestAttributes();
    isSsl = false;
    wrapper = new HttpServletRequestWrapperForRequestInfo<>(requestInfoMock, isSsl);
}
 
Example #18
Source File: PublicAccessLogHandlerTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Does a test to see that two consecutive requests without sending last http content for first request fails
 * @param httpMethod the {@link HttpMethod} for the request.
 * @param uri Uri to be used during the request
 * @param useSSL {@code true} to test SSL logging.
 * @throws Exception
 */
private void doRequestHandleWithMultipleRequest(HttpMethod httpMethod, String uri, boolean useSSL) throws Exception {
  EmbeddedChannel channel = createChannel(useSSL);
  // contains one logged request header
  HttpHeaders headers1 = new DefaultHttpHeaders();
  headers1.add(HttpHeaderNames.CONTENT_LENGTH, new Random().nextLong());

  HttpRequest request = RestTestUtils.createRequest(httpMethod, uri, headers1);
  HttpUtil.setKeepAlive(request, true);
  channel.writeInbound(request);

  // contains one logged and not logged header
  HttpHeaders headers2 = new DefaultHttpHeaders();
  headers2.add(NOT_LOGGED_HEADER_KEY + "1", "headerValue1");
  headers2.add(HttpHeaderNames.CONTENT_LENGTH, new Random().nextLong());
  // sending another request w/o sending last http content
  request = RestTestUtils.createRequest(httpMethod, uri, headers2);
  HttpUtil.setKeepAlive(request, true);
  sendRequestCheckResponse(channel, request, uri, headers2, false, false, useSSL);
  Assert.assertTrue("Channel should not be closed ", channel.isOpen());

  // verify that headers from first request is not found in public access log
  String lastLogEntry = publicAccessLogger.getLastPublicAccessLogEntry();
  // verify request headers
  verifyPublicAccessLogEntryForRequestHeaders(lastLogEntry, headers1, request.method(), false);

  channel.close();
}
 
Example #19
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void stripTEHeadersAccountsForOWS() {
    final io.netty.handler.codec.http.HttpHeaders in = new DefaultHttpHeaders();
    in.add(HttpHeaderNames.TE, " " + HttpHeaderValues.TRAILERS + ' ');
    final HttpHeadersBuilder out = HttpHeaders.builder();
    toArmeria(in, out);
    assertThat(out.get(HttpHeaderNames.TE)).isEqualTo(HttpHeaderValues.TRAILERS.toString());
}
 
Example #20
Source File: RequestInfoImpl.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new RequestInfo that represents unknown requests. Usually only needed in error situations. The URI,
 * query params, and headers will be tagged with {@link #NONE_OR_UNKNOWN_TAG} to indicate that the request was
 * unknown.
 */
public static RequestInfoImpl<?> dummyInstanceForUnknownRequests() {
    HttpHeaders headers = new DefaultHttpHeaders().set(NONE_OR_UNKNOWN_TAG, "true");
    QueryStringDecoder queryParams = new QueryStringDecoder("/?" + NONE_OR_UNKNOWN_TAG + "=true");

    return new RequestInfoImpl<>(
        NONE_OR_UNKNOWN_TAG, null, headers, null, queryParams, null, null, null, null, false, true, false
    );
}
 
Example #21
Source File: BaseResponseInfoBuilderTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void builder_stores_values_as_expected() {
    // given
    String content = UUID.randomUUID().toString();
    int httpStatusCode = 200;
    HttpHeaders headers = new DefaultHttpHeaders();
    String mimeType = "text/text";
    Charset contentCharset = CharsetUtil.ISO_8859_1;
    Set<Cookie> cookies = Sets.newHashSet(new DefaultCookie("key1", "val1"), new DefaultCookie("key2", "val2"));
    boolean preventCompressedOutput = true;

    // when
    BaseResponseInfoBuilder<String> responseInfoBuilder = new BaseResponseInfoBuilder<String>(){}
            .withHttpStatusCode(httpStatusCode)
            .withHeaders(headers)
            .withDesiredContentWriterMimeType(mimeType)
            .withDesiredContentWriterEncoding(contentCharset).withCookies(cookies)
            .withPreventCompressedOutput(preventCompressedOutput);

    // then
    assertThat(responseInfoBuilder.getHttpStatusCode(), is(httpStatusCode));
    assertThat(responseInfoBuilder.getHeaders(), is(headers));
    assertThat(responseInfoBuilder.getDesiredContentWriterMimeType(), is(mimeType));
    assertThat(responseInfoBuilder.getDesiredContentWriterEncoding(), is(contentCharset));
    assertThat(responseInfoBuilder.getCookies(), is(cookies));
    assertThat(responseInfoBuilder.isPreventCompressedOutput(), is(preventCompressedOutput));
}
 
Example #22
Source File: WebSocketIT.java    From qonduit with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.getCache().put(sessionId, token);
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(HttpHeaderNames.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
 
Example #23
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void stripConnectionNomineesWithCsv() {
    final io.netty.handler.codec.http.HttpHeaders in = new DefaultHttpHeaders();
    in.add(HttpHeaderNames.CONNECTION, "foo,  bar");
    in.add("foo", "baz");
    in.add("bar", "qux");
    in.add("hello", "world");
    final HttpHeadersBuilder out = HttpHeaders.builder();
    toArmeria(in, out);
    assertThat(out).hasSize(1);
    assertThat(out.get(HttpHeaderNames.of("hello"))).isEqualTo("world");
}
 
Example #24
Source File: VerifyAutoPayloadDecompressionComponentTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
private static HttpHeaders generateDefaultResponseHeaders(RequestInfo<?> request) {
    String base64EncodedPayload = base64Encode(request.getRawContentBytes());

    return new DefaultHttpHeaders()
        .set(RECEIVED_PAYLOAD_BYTES_AS_BASE64_RESPONSE_HEADER_KEY, base64EncodedPayload)
        .set(RECEIVED_CONTENT_ENCODING_HEADER, String.valueOf(request.getHeaders().get(CONTENT_ENCODING)))
        .set(RECEIVED_CONTENT_LENGTH_HEADER, String.valueOf(request.getHeaders().get(CONTENT_LENGTH)))
        .set(RECEIVED_TRANSFER_ENCODING_HEADER, String.valueOf(request.getHeaders().get(TRANSFER_ENCODING)));
    
}
 
Example #25
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Test when the undelete is disabled.
 */
@Test
public void disableUndeleteTest() throws Exception {
  assumeTrue(!enableUndeleteTested);
  enableUndeleteTested = true;
  File trustStoreFile = File.createTempFile("truststore", ".jks");
  trustStoreFile.deleteOnExit();
  VerifiableProperties vprop = buildFrontendVProps(trustStoreFile, false, PLAINTEXT_SERVER_PORT + 100, SSL_SERVER_PORT + 100);

  RestServer ambryRestServer = new RestServer(vprop, CLUSTER_MAP, new LoggingNotificationSystem(),
      SSLFactory.getNewInstance(new SSLConfig(vprop)));
  ambryRestServer.start();
  NettyClient plaintextNettyClient = new NettyClient("localhost", PLAINTEXT_SERVER_PORT + 100, null);
  NettyClient sslNettyClient = new NettyClient("localhost", SSL_SERVER_PORT + 100,
      SSLFactory.getNewInstance(new SSLConfig(SSL_CLIENT_VERIFIABLE_PROPS)));
  NettyClient nettyClient = useSSL ? sslNettyClient : plaintextNettyClient;

  String blobId = "randomblobid";
  HttpHeaders headers = new DefaultHttpHeaders();
  headers.set(RestUtils.Headers.BLOB_ID, addClusterPrefix ? "/" + CLUSTER_NAME + blobId : blobId);
  headers.set(RestUtils.Headers.SERVICE_ID, "updateBlobTtlAndVerify");
  FullHttpRequest httpRequest = buildRequest(HttpMethod.PUT, "/" + Operations.UNDELETE, headers, null);
  ResponseParts responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
  HttpResponse response = getHttpResponse(responseParts);
  assertEquals("Unexpected response status", HttpResponseStatus.BAD_REQUEST, response.status());

  plaintextNettyClient.close();
  sslNettyClient.close();
  ambryRestServer.shutdown();
}
 
Example #26
Source File: WebsocketChannelInitializer.java    From SynchronizeFX with GNU Lesser General Public License v3.0 5 votes vote down vote up
private HttpHeaders createHttpHeaders(final Map<String, Object> headerParams) {
    if (headerParams == null || headerParams.isEmpty()) {
        return null;
    }
    HttpHeaders headers = new DefaultHttpHeaders();
    for (Map.Entry<String, Object> headerEntry : headerParams.entrySet()) {
        headers.add(headerEntry.getKey(), headerEntry.getValue());
    }
    return headers;
}
 
Example #27
Source File: ArmeriaHttpUtilTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Test
void stripTEHeadersCsvSeparatedExcludingTrailers() {
    final io.netty.handler.codec.http.HttpHeaders in = new DefaultHttpHeaders();
    in.add(HttpHeaderNames.TE, HttpHeaderValues.GZIP + "," + HttpHeaderValues.TRAILERS);
    final HttpHeadersBuilder out = HttpHeaders.builder();
    toArmeria(in, out);
    assertThat(out.get(HttpHeaderNames.TE)).isEqualTo(HttpHeaderValues.TRAILERS.toString());
}
 
Example #28
Source File: FrontendIntegrationTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Undelete given {@code blobId} and verifies it by doing a BlobInfo.
 * @param blobId the blob ID of the blob to update and verify.
 * @param getExpectedHeaders the expected headers in the getBlobInfo response after the TTL update.
 * @param isPrivate {@code true} if the blob is expected to be private
 * @param accountName the expected account name in the response.
 * @param containerName the expected container name in response.
 * @param usermetadata if non-null, this is expected to come as the body.
 * @throws ExecutionException
 * @throws InterruptedException
 */
private void undeleteBlobAndVerify(String blobId, HttpHeaders getExpectedHeaders, boolean isPrivate,
    String accountName, String containerName, byte[] usermetadata) throws ExecutionException, InterruptedException {
  HttpHeaders headers = new DefaultHttpHeaders();
  headers.set(RestUtils.Headers.BLOB_ID, addClusterPrefix ? "/" + CLUSTER_NAME + blobId : blobId);
  headers.set(RestUtils.Headers.SERVICE_ID, "updateBlobTtlAndVerify");
  FullHttpRequest httpRequest = buildRequest(HttpMethod.PUT, "/" + Operations.UNDELETE, headers, null);
  ResponseParts responseParts = nettyClient.sendRequest(httpRequest, null, null).get();
  verifyUndeleteBlobResponse(responseParts);
  getBlobInfoAndVerify(blobId, GetOption.None, getExpectedHeaders, isPrivate, accountName, containerName,
      usermetadata);
}
 
Example #29
Source File: WebSocketIT.java    From timely with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
    s = new Server(conf);
    s.run();

    Connector con = mac.getConnector("root", "secret");
    con.securityOperations().changeUserAuthorizations("root", new Authorizations("A", "B", "C", "D", "E", "F"));

    this.sessionId = UUID.randomUUID().toString();
    AuthCache.put(sessionId, TimelyPrincipal.anonymousPrincipal());
    group = new NioEventLoopGroup();
    SslContext ssl = SslContextBuilder.forClient().trustManager(InsecureTrustManagerFactory.INSTANCE).build();

    String cookieVal = ClientCookieEncoder.STRICT.encode(Constants.COOKIE_NAME, sessionId);
    HttpHeaders headers = new DefaultHttpHeaders();
    headers.add(HttpHeaderNames.COOKIE, cookieVal);

    WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(LOCATION,
            WebSocketVersion.V13, (String) null, false, headers);
    handler = new ClientHandler(handshaker);
    Bootstrap boot = new Bootstrap();
    boot.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ch.pipeline().addLast("ssl", ssl.newHandler(ch.alloc(), "127.0.0.1", WS_PORT));
            ch.pipeline().addLast(new HttpClientCodec());
            ch.pipeline().addLast(new HttpObjectAggregator(8192));
            ch.pipeline().addLast(handler);
        }
    });
    ch = boot.connect("127.0.0.1", WS_PORT).sync().channel();
    // Wait until handshake is complete
    while (!handshaker.isHandshakeComplete()) {
        sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
        LOG.debug("Waiting for Handshake to complete");
    }
}
 
Example #30
Source File: HttpClientConfig.java    From reactor-netty with Apache License 2.0 5 votes vote down vote up
HttpClientConfig(ConnectionProvider connectionProvider, Map<ChannelOption<?>, ?> options,
		Supplier<? extends SocketAddress> remoteAddress) {
	super(connectionProvider, options, remoteAddress);
	this.acceptGzip = false;
	this.cookieDecoder = ClientCookieDecoder.STRICT;
	this.cookieEncoder = ClientCookieEncoder.STRICT;
	this.decoder = new HttpResponseDecoderSpec();
	this.headers = new DefaultHttpHeaders();
	this.method = HttpMethod.GET;
	this.protocols = new HttpProtocol[]{HttpProtocol.HTTP11};
	this._protocols = h11;
	this.retryDisabled = false;
}