io.vertx.core.http.impl.headers.VertxHttpHeaders Java Examples

The following examples show how to use io.vertx.core.http.impl.headers.VertxHttpHeaders. 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: ClientBasicAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotAuthenticateClient_badClientSecret() throws Exception {
    Client client = mock(Client.class);
    when(client.getClientId()).thenReturn("my-client-id");
    when(client.getClientSecret()).thenReturn("my-client-secret");

    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    VertxHttpHeaders vertxHttpHeaders = new VertxHttpHeaders();
    vertxHttpHeaders.add(HttpHeaders.AUTHORIZATION, "Basic bXktY2xpZW50LWlkOm15LW90aGVyLWNsaWVudC1zZWNyZXQ=");
    when(httpServerRequest.headers()).thenReturn(MultiMap.newInstance(vertxHttpHeaders));

    CountDownLatch latch = new CountDownLatch(1);
    authProvider.handle(client, httpServerRequest, userAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(userAsyncResult);
        Assert.assertTrue(userAsyncResult.failed());
        Assert.assertTrue(userAsyncResult.cause() instanceof InvalidClientException);
    });

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #2
Source File: ClientBasicAuthProviderTest.java    From graviteeio-access-management with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldAuthenticateClient() throws Exception {
    Client client = mock(Client.class);
    when(client.getClientId()).thenReturn("my-client-id");
    when(client.getClientSecret()).thenReturn("my-client-secret");

    HttpServerRequest httpServerRequest = mock(HttpServerRequest.class);
    VertxHttpHeaders vertxHttpHeaders = new VertxHttpHeaders();
    vertxHttpHeaders.add(HttpHeaders.AUTHORIZATION, "Basic bXktY2xpZW50LWlkOm15LWNsaWVudC1zZWNyZXQ=");
    when(httpServerRequest.headers()).thenReturn(MultiMap.newInstance(vertxHttpHeaders));

    CountDownLatch latch = new CountDownLatch(1);
    authProvider.handle(client, httpServerRequest, clientAsyncResult -> {
        latch.countDown();
        Assert.assertNotNull(clientAsyncResult);
        Assert.assertNotNull(clientAsyncResult.result());
    });

    assertTrue(latch.await(10, TimeUnit.SECONDS));
}
 
Example #3
Source File: AbstractVertxRespositoryTest.java    From symbol-sdk-java with Apache License 2.0 6 votes vote down vote up
/**
 * Mocks the api client telling that the next time there is remote call, an error should be
 * returned.
 *
 * @param statusCode the status code of the response (404 for example)
 * @param errorResponse the raw response, it may or may not be a json string.
 */
protected void mockErrorCodeRawResponse(int statusCode, String errorResponse) {
    String reasonPhrase = HttpStatus.valueOf(statusCode).getReasonPhrase();
    VertxHttpHeaders headers = new VertxHttpHeaders();
    ApiException exception = new ApiException(reasonPhrase, statusCode, headers,
        errorResponse);

    Mockito.doAnswer((Answer<Void>) invocationOnMock -> {

        Handler<AsyncResult<Object>> resultHandler = (Handler<AsyncResult<Object>>) invocationOnMock
            .getArguments()[invocationOnMock.getArguments().length - 1];
        resultHandler.handle(Future.failedFuture(exception));

        return null;
    }).when(apiClientMock)
        .invokeAPI(Mockito.anyString(), Mockito.anyString(), Mockito.anyList(), Mockito.any(),
            Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
            Mockito.any(), Mockito.any(), Mockito.any());
}
 
Example #4
Source File: VertxWebSocketClientTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldAdaptHeaders() {
    HttpHeaders originalHeaders = new HttpHeaders();
    originalHeaders.put("key1", Arrays.asList("value1", "value2"));
    originalHeaders.add("key2", "value3");

    webSocketClient.execute(TEST_URI, originalHeaders, session -> Mono.empty())
        .subscribe();

    ArgumentCaptor<VertxHttpHeaders> headersCaptor = ArgumentCaptor.forClass(VertxHttpHeaders.class);
    verify(mockHttpClient).websocket(anyInt(), anyString(), anyString(), headersCaptor.capture(),
        any(Handler.class), any(Handler.class));

    VertxHttpHeaders actualHeaders = headersCaptor.getValue();
    assertThat(actualHeaders.getAll("key1")).isEqualTo(originalHeaders.get("key1"));
    assertThat(actualHeaders.getAll("key2")).isEqualTo(originalHeaders.get("key2"));
}
 
Example #5
Source File: VertxClientHttpResponseTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetHeaders() {
    MultiMap originalHeaders = new VertxHttpHeaders()
        .add("key1", "value1")
        .add("key1", "value2")
        .add("key2", "value3");
    given(mockDelegate.headers()).willReturn(originalHeaders);

    HttpHeaders expectedHeaders = new HttpHeaders();
    expectedHeaders.add("key1", "value1");
    expectedHeaders.add("key1", "value2");
    expectedHeaders.add("key2", "value3");

    VertxClientHttpResponse response = new VertxClientHttpResponse(mockDelegate, Flux.empty());
    HttpHeaders actualHeaders = response.getHeaders();

    assertThat(actualHeaders).isEqualTo(expectedHeaders);
}
 
Example #6
Source File: VertxServerHttpResponseTest.java    From vertx-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldInitHeaders() {
    MultiMap originalHeaders = new VertxHttpHeaders()
        .add("key1", "value1")
        .add("key1", "value2")
        .add("key2", "value3");
    given(mockHttpServerResponse.headers()).willReturn(originalHeaders);

    response = new VertxServerHttpResponse(mockRoutingContext, bufferConverter);

    HttpHeaders expectedHeaders = new HttpHeaders();
    expectedHeaders.add("key1", "value1");
    expectedHeaders.add("key1", "value2");
    expectedHeaders.add("key2", "value3");

    assertThat(response.getHeaders()).isEqualTo(expectedHeaders);
}
 
Example #7
Source File: VertxServerHttpRequestTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    given(mockRoutingContext.request()).willReturn(mockHttpServerRequest);
    given(mockHttpServerRequest.absoluteURI()).willReturn("http://localhost:8080");
    given(mockHttpServerRequest.headers()).willReturn(new VertxHttpHeaders());

    bufferConverter = new BufferConverter();
    vertxServerHttpRequest = new VertxServerHttpRequest(mockRoutingContext, bufferConverter);
}
 
Example #8
Source File: ResponseHeaderItemTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void serverFormattedElementOnNotFound() {
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String headerValue = "headerValue";
  headers.add("anotherHeader", headerValue);
  when(routingContext.response()).thenReturn(serverResponse);
  when(serverResponse.headers()).thenReturn(headers);

  ELEMENT.appendServerFormattedItem(accessLogEvent, strBuilder);
  assertEquals("-", strBuilder.toString());
}
 
Example #9
Source File: ResponseHeaderItemTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void serverFormattedElement() {
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String headerValue = "headerValue";
  headers.add(VAR_NAME, headerValue);
  when(routingContext.response()).thenReturn(serverResponse);
  when(serverResponse.headers()).thenReturn(headers);

  ELEMENT.appendServerFormattedItem(accessLogEvent, strBuilder);
  assertEquals(headerValue, strBuilder.toString());
  assertEquals(ELEMENT.getVarName(), VAR_NAME);
}
 
Example #10
Source File: RequestHeaderItemTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void serverFormattedElementIfNotFound() {
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String testValue = "testValue";
  headers.add("anotherKey", testValue);
  when(routingContext.request()).thenReturn(serverRequest);
  when(serverRequest.headers()).thenReturn(headers);

  ELEMENT.appendServerFormattedItem(accessLogEvent, strBuilder);
  assertEquals("-", strBuilder.toString());
}
 
Example #11
Source File: RequestHeaderItemTest.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void serverFormattedElement() {
  VertxHttpHeaders headers = new VertxHttpHeaders();
  String testValue = "testValue";
  headers.add(VAR_NAME, testValue);
  when(routingContext.request()).thenReturn(serverRequest);
  when(serverRequest.headers()).thenReturn(headers);

  ELEMENT.appendServerFormattedItem(accessLogEvent, strBuilder);
  assertEquals(testValue, strBuilder.toString());
  assertEquals(ELEMENT.getVarName(), VAR_NAME);
}
 
Example #12
Source File: VertxServerHttpResponseTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    given(mockRoutingContext.response()).willReturn(mockHttpServerResponse);
    given(mockHttpServerResponse.headers()).willReturn(new VertxHttpHeaders());

    bufferConverter = new BufferConverter();
    response = new VertxServerHttpResponse(mockRoutingContext, bufferConverter);
}
 
Example #13
Source File: VertxRequestTransmitter.java    From ethsigner with Apache License 2.0 5 votes vote down vote up
private MultiMap createHeaders(final MultiMap headers) {
  final MultiMap requestHeaders = new VertxHttpHeaders();
  requestHeaders.addAll(headers);
  requestHeaders.remove(HttpHeaders.CONTENT_LENGTH);
  requestHeaders.remove(HttpHeaders.ORIGIN);
  renameHeader(requestHeaders, HttpHeaders.HOST, HttpHeaders.X_FORWARDED_HOST);
  return requestHeaders;
}
 
Example #14
Source File: VertxWebSocketClientTest.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void shouldInitializeEmptyHeaders() {
    webSocketClient.execute(TEST_URI, session -> Mono.empty())
        .subscribe();

    ArgumentCaptor<VertxHttpHeaders> headersCaptor = ArgumentCaptor.forClass(VertxHttpHeaders.class);
    verify(mockHttpClient).websocket(anyInt(), anyString(), anyString(), headersCaptor.capture(),
        any(Handler.class), any(Handler.class));

    assertThat(headersCaptor.getValue()).isEmpty();
}
 
Example #15
Source File: VertxWebSocketClient.java    From vertx-spring-boot with Apache License 2.0 5 votes vote down vote up
private void connect(URI uri, VertxHttpHeaders headers, WebSocketHandler handler, MonoSink<Void> callback) {
    HttpClient client = vertx.createHttpClient(clientOptions);
    client.websocket(uri.getPort(), uri.getHost(), uri.getPath(), headers,
        socket -> handler.handle(initSession(uri, socket))
            .doOnSuccess(callback::success)
            .doOnError(callback::error)
            .doFinally(ignore -> client.close())
            .subscribe(),
        callback::error
    );
}
 
Example #16
Source File: VertxHttpExchange.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
public void pushResource(String path, String method, Map<String, List<String>> requestHeaders) {
    MultiMap map = new VertxHttpHeaders();
    for (Map.Entry<String, List<String>> entry : requestHeaders.entrySet()) {
        map.add(entry.getKey(), entry.getValue());
    }
    response.push(HttpMethod.valueOf(method), path, map, new Handler<AsyncResult<HttpServerResponse>>() {
        @Override
        public void handle(AsyncResult<HttpServerResponse> event) {
            //we don't actually care about the result
        }
    });
}
 
Example #17
Source File: WebSocketServiceLoginTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void websocketServiceWithGoodHeaderAuthenticationToken(final TestContext context) {
  final Async async = context.async();

  final JWTOptions jwtOptions = new JWTOptions().setExpiresInMinutes(5).setAlgorithm("RS256");
  final JsonObject jwtContents =
      new JsonObject().put("permissions", Lists.newArrayList("eth:*")).put("username", "user");
  final String goodToken = jwtAuth.generateToken(jwtContents, jwtOptions);

  final String requestSub =
      "{\"id\": 1, \"method\": \"eth_subscribe\", \"params\": [\"syncing\"]}";
  final String expectedResponse = "{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":\"0x1\"}";

  RequestOptions options = new RequestOptions();
  options.setURI("/");
  options.setHost(websocketConfiguration.getHost());
  options.setPort(websocketConfiguration.getPort());
  final MultiMap headers = new VertxHttpHeaders();
  if (goodToken != null) {
    headers.add("Authorization", "Bearer " + goodToken);
  }
  httpClient.websocket(
      options,
      headers,
      webSocket -> {
        webSocket.writeTextMessage(requestSub);

        webSocket.handler(
            buffer -> {
              context.assertEquals(expectedResponse, buffer.toString());
              async.complete();
            });
      });

  async.awaitSuccess(VERTX_AWAIT_TIMEOUT_MILLIS);
}
 
Example #18
Source File: WebSocketServiceLoginTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void websocketServiceWithBadHeaderAuthenticationToken(final TestContext context) {
  final Async async = context.async();

  final String request = "{\"id\": 1, \"method\": \"eth_subscribe\", \"params\": [\"syncing\"]}";
  final String expectedResponse =
      "{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-40100,\"message\":\"Unauthorized\"}}";

  RequestOptions options = new RequestOptions();
  options.setURI("/");
  options.setHost(websocketConfiguration.getHost());
  options.setPort(websocketConfiguration.getPort());
  final MultiMap headers = new VertxHttpHeaders();
  String badtoken = "badtoken";
  if (badtoken != null) {
    headers.add("Authorization", "Bearer " + badtoken);
  }
  httpClient.websocket(
      options,
      headers,
      webSocket -> {
        webSocket.writeTextMessage(request);

        webSocket.handler(
            buffer -> {
              context.assertEquals(expectedResponse, buffer.toString());
              async.complete();
            });
      });

  async.awaitSuccess(VERTX_AWAIT_TIMEOUT_MILLIS);
}
 
Example #19
Source File: TestBodyProcessor.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
  headers = new VertxHttpHeaders();
}
 
Example #20
Source File: VertxWebSocketClient.java    From vertx-spring-boot with Apache License 2.0 4 votes vote down vote up
private VertxHttpHeaders convertHeaders(HttpHeaders headers) {
    VertxHttpHeaders vertxHeaders = new VertxHttpHeaders();
    headers.forEach(vertxHeaders::add);

    return vertxHeaders;
}
 
Example #21
Source File: VertxWebSocketClient.java    From vertx-spring-boot with Apache License 2.0 4 votes vote down vote up
@Override
public Mono<Void> execute(URI uri, HttpHeaders headers, WebSocketHandler handler) {
    VertxHttpHeaders vertxHeaders = convertHeaders(headers);

    return Mono.create(sink -> connect(uri, vertxHeaders, handler, sink));
}