io.vertx.core.http.CaseInsensitiveHeaders Java Examples

The following examples show how to use io.vertx.core.http.CaseInsensitiveHeaders. 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: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnPartialDebugInfoIfDebugEnabledAndGlobalTimeoutAlreadyExpired() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri1")
                    .body("requestBody1")
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    // when
    final BidderSeatBid bidderSeatBid =
            bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), expiredTimeout, true).result();

    // then
    assertThat(bidderSeatBid.getHttpCalls()).hasSize(1).containsOnly(
            ExtHttpCall.builder().uri("uri1").requestbody("requestBody1").build());
}
 
Example #2
Source File: RestClientOptions.java    From vertx-rest-client with Apache License 2.0 6 votes vote down vote up
public RestClientOptions(final JsonObject json) {
    super(json);
    final JsonObject jsonObjectGlobalRequestCacheOptions = json.getJsonObject("globalRequestCacheOptions");
    if (jsonObjectGlobalRequestCacheOptions != null) {
        final RequestCacheOptions requestCacheOptions = new RequestCacheOptions();
        final Integer ttlInMillis = jsonObjectGlobalRequestCacheOptions.getInteger("ttlInMillis");
        final Boolean evictBefore = jsonObjectGlobalRequestCacheOptions.getBoolean("evictBefore");
        if (jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes") != null) {
            final Set<Integer> cachedStatusCodes = jsonObjectGlobalRequestCacheOptions.getJsonArray("cachedStatusCodes")
                    .stream()
                    .map(e -> (Integer) e)
                    .collect(Collectors.toSet());
            requestCacheOptions.withCachedStatusCodes(cachedStatusCodes);
        }

        if (ttlInMillis != null) {
            requestCacheOptions.withExpiresAfterWriteMillis(ttlInMillis);
        }
        if (evictBefore != null) {
            requestCacheOptions.withEvictBefore(evictBefore);
        }
        globalRequestCacheOptions = requestCacheOptions;
    }
    globalHeaders = new CaseInsensitiveHeaders();
    globalRequestTimeoutInMillis = json.getLong("globalRequestTimeoutInMillis", DEFAULT_GLOBAL_REQUEST_TIMEOUT_IN_MILLIS);
}
 
Example #3
Source File: HttpUtils.java    From VX-API-Gateway with MIT License 6 votes vote down vote up
/**
 * 解码URI中的参数,既?后面的参数
 * 
 * @param uri
 *          uri参数
 * @param charset
 *          解码格式,如果该字段为空则默认为utf-8方式
 * @return 返回解码后的结果或者返回新的MultiMap,如果发生异常返回新的MultiMap
 */
public static MultiMap decoderUriParams(String uri, Charset charset) {
	try {
		if (charset == null) {
			charset = Charset.forName("UTF-8");
		}
		QueryStringDecoder decode = new QueryStringDecoder(uri, charset, false);
		Map<String, List<String>> paramMap = decode.parameters();
		MultiMap params = new CaseInsensitiveHeaders();
		if (!paramMap.isEmpty()) {
			for (Map.Entry<String, List<String>> entry : paramMap.entrySet()) {
				params.add(entry.getKey(), entry.getValue());
			}
		}
		return params;
	} catch (Exception e) {
		return new CaseInsensitiveHeaders();
	}
}
 
Example #4
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPassEmptyJsonResponseBodyToMakeBidsIfResponseStatusIs204() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    givenHttpClientReturnsResponse(204, EMPTY);

    // when
    bidderHttpConnector.requestBids(bidder, BidRequest.builder().test(1).build(), timeout, false);

    // then
    verify(bidder).makeBids(argThat(httpCall -> httpCall.getResponse().getBody().equals("{}")), any());
}
 
Example #5
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSendTimeoutNotificationIfTimeoutBidder() {
    // given
    given(timeoutBidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri1")
                    .body("requestBody1")
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    givenHttpClientProducesException(new TimeoutException("Timeout error"));

    // when
    bidderHttpConnector.requestBids(timeoutBidder, BidRequest.builder().build(), timeout, false);

    // then
    verify(timeoutBidder).makeTimeoutNotification(any());
}
 
Example #6
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTolerateAlreadyExpiredGlobalTimeout() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    // when
    final BidderSeatBid bidderSeatBid =
            bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), expiredTimeout, false).result();

    // then
    assertThat(bidderSeatBid.getErrors()).hasSize(1)
            .extracting(BidderError::getMessage)
            .containsOnly("Timeout has been exceeded");
    verifyZeroInteractions(httpClient);
}
 
Example #7
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnFullDebugInfoIfDebugEnabledAndErrorStatus() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri1")
                    .body("requestBody1")
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    givenHttpClientReturnsResponses(HttpClientResponse.of(500, null, "responseBody1"));

    // when
    final BidderSeatBid bidderSeatBid =
            bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), timeout, true).result();

    // then
    assertThat(bidderSeatBid.getHttpCalls()).hasSize(1).containsOnly(
            ExtHttpCall.builder().uri("uri1").requestbody("requestBody1").responsebody("responseBody1")
                    .status(500).build());
    assertThat(bidderSeatBid.getErrors()).hasSize(1)
            .extracting(BidderError::getMessage).containsOnly(
            "Unexpected status code: 500. Run with request.test = 1 for more info");
}
 
Example #8
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnPartialDebugInfoIfDebugEnabledAndHttpErrorOccurs() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri1")
                    .body("requestBody1")
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    givenHttpClientProducesException(new RuntimeException("Request exception"));

    // when
    final BidderSeatBid bidderSeatBid =
            bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), timeout, true).result();

    // then
    assertThat(bidderSeatBid.getHttpCalls()).hasSize(1).containsOnly(
            ExtHttpCall.builder().uri("uri1").requestbody("requestBody1").build());
}
 
Example #9
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldReturnBidsCreatedByBidder() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    givenHttpClientReturnsResponse(200, "responseBody");

    final List<BidderBid> bids = asList(BidderBid.of(null, null, null), BidderBid.of(null, null, null));
    given(bidder.makeBids(any(), any())).willReturn(Result.of(bids, emptyList()));

    // when
    final BidderSeatBid bidderSeatBid =
            bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), timeout, false).result();

    // then
    assertThat(bidderSeatBid.getBids()).containsOnlyElementsOf(bids);
}
 
Example #10
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSendMultipleRequests() {
    // given
    givenHttpClientReturnsResponse(200, null);

    given(bidder.makeHttpRequests(any())).willReturn(Result.of(asList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build(),
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    // when
    bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), timeout, false);

    // then
    verify(httpClient, times(2)).request(any(), anyString(), any(), any(), anyLong());
}
 
Example #11
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSendPopulatedPostRequest() {
    // given
    givenHttpClientReturnsResponse(200, null);

    final MultiMap headers = new CaseInsensitiveHeaders();
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(singletonList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri")
                    .body("requestBody")
                    .headers(headers)
                    .build()),
            emptyList()));
    headers.add("header1", "value1");
    headers.add("header2", "value2");

    // when
    bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), timeout, false);

    // then
    verify(httpClient).request(eq(HttpMethod.POST), eq("uri"), eq(headers), eq("requestBody"), eq(500L));
}
 
Example #12
Source File: VideoHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap());
    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());

    given(httpResponse.exceptionHandler(any())).willReturn(httpResponse);
    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);
    given(httpResponse.headers()).willReturn(new CaseInsensitiveHeaders());

    given(clock.millis()).willReturn(Instant.now().toEpochMilli());
    timeout = new TimeoutFactory(clock).create(2000L);

    given(exchangeService.holdAuction(any())).willReturn(Future.succeededFuture(BidResponse.builder().build()));

    videoHandler = new VideoHandler(videoRequestFactory, videoResponseFactory, exchangeService, analyticsReporter,
            metrics, clock, jacksonMapper);
}
 
Example #13
Source File: SetuidHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    final Map<Integer, PrivacyEnforcementAction> vendorIdToGdpr = singletonMap(null,
            PrivacyEnforcementAction.allowAll());
    given(tcfDefinerService.resultForVendorIds(anySet(), any(), any(), any(), any(), any()))
            .willReturn(Future.succeededFuture(TcfResponse.of(true, vendorIdToGdpr, null)));

    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpResponse.headers()).willReturn(new CaseInsensitiveHeaders());

    given(uidsCookieService.toCookie(any())).willReturn(Cookie.cookie("test", "test"));
    given(bidderCatalog.names()).willReturn(new HashSet<>(asList("rubicon", "audienceNetwork")));
    given(bidderCatalog.isActive(any())).willReturn(true);
    given(bidderCatalog.usersyncerByName(any())).willReturn(
            new Usersyncer(RUBICON, null, null, null, false));

    final Clock clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());
    final TimeoutFactory timeoutFactory = new TimeoutFactory(clock);
    setuidHandler = new SetuidHandler(2000, uidsCookieService, applicationSettings,
            bidderCatalog, tcfDefinerService, null, false, analyticsReporter, metrics, timeoutFactory);
}
 
Example #14
Source File: AuctionHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldTolerateDuplicateHeaderNames() {
    // given
    given(auctionRequestFactory.fromRequest(any(), anyLong()))
            .willReturn(Future.succeededFuture(givenAuctionContext(identity())));

    final CaseInsensitiveHeaders headers = new CaseInsensitiveHeaders();
    headers.add("header", "value1");
    headers.add("header", "value2");
    given(httpRequest.headers()).willReturn(headers);

    // when
    auctionHandler.handle(routingContext);

    // then
    final AuctionEvent auctionEvent = captureAuctionEvent();
    final Map<String, String> obtainedHeaders = auctionEvent.getHttpContext().getHeaders();
    assertThat(obtainedHeaders.entrySet()).containsOnly(entry("header", "value1"));
}
 
Example #15
Source File: AuctionHandlerTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {
    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap());
    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());

    given(httpResponse.exceptionHandler(any())).willReturn(httpResponse);
    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);
    given(httpResponse.headers()).willReturn(new CaseInsensitiveHeaders());

    given(clock.millis()).willReturn(Instant.now().toEpochMilli());
    timeout = new TimeoutFactory(clock).create(2000L);

    auctionHandler = new AuctionHandler(
            auctionRequestFactory, exchangeService, analyticsReporter, metrics, clock, adminManager, jacksonMapper);
}
 
Example #16
Source File: AuctionRequestFactoryTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    given(interstitialProcessor.process(any())).will(invocationOnMock -> invocationOnMock.getArgument(0));
    given(idGenerator.generateId()).willReturn(null);

    given(routingContext.request()).willReturn(httpRequest);
    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());

    given(timeoutResolver.resolve(any())).willReturn(2000L);
    given(timeoutResolver.adjustTimeout(anyLong())).willReturn(1900L);

    factory = new AuctionRequestFactory(
            Integer.MAX_VALUE,
            false,
            false,
            "USD",
            BLACKLISTED_APPS,
            BLACKLISTED_ACCOUNTS,
            storedRequestProcessor,
            paramsExtractor,
            uidsCookieService,
            bidderCatalog,
            requestValidator,
            interstitialProcessor,
            timeoutResolver,
            timeoutFactory,
            applicationSettings,
            idGenerator,
            jacksonMapper);
}
 
Example #17
Source File: BasicHttpClientTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    given(wrappedHttpClient.requestAbs(any(), any())).willReturn(httpClientRequest);

    given(httpClientRequest.setFollowRedirects(anyBoolean())).willReturn(httpClientRequest);
    given(httpClientRequest.handler(any())).willReturn(httpClientRequest);
    given(httpClientRequest.exceptionHandler(any())).willReturn(httpClientRequest);
    given(httpClientRequest.headers()).willReturn(new CaseInsensitiveHeaders());

    given(httpClientResponse.bodyHandler(any())).willReturn(httpClientResponse);
    given(httpClientResponse.exceptionHandler(any())).willReturn(httpClientResponse);

    httpClient = new BasicHttpClient(vertx, wrappedHttpClient);
}
 
Example #18
Source File: RestClientOptions.java    From vertx-rest-client with Apache License 2.0 5 votes vote down vote up
public RestClientOptions(final RestClientOptions other) {
    super(other);
    globalRequestCacheOptions = other.globalRequestCacheOptions;
    globalHeaders = new CaseInsensitiveHeaders().addAll(other.getGlobalHeaders());
    globalRequestTimeoutInMillis = other.getGlobalRequestTimeoutInMillis();

}
 
Example #19
Source File: ConsumerTest.java    From strimzi-kafka-bridge with Apache License 2.0 5 votes vote down vote up
@Test
void createConsumerWithMultipleForwardedHeaders(VertxTestContext context) throws InterruptedException, TimeoutException, ExecutionException {
    String forwarded = "host=my-api-gateway-host:443;proto=https";
    String forwarded2 = "host=my-api-another-gateway-host:886;proto=http";

    String baseUri = "https://my-api-gateway-host:443/consumers/" + groupId + "/instances/" + name;

    // we have to use MultiMap because of https://github.com/vert-x3/vertx-web/issues/1383
    MultiMap headers = new CaseInsensitiveHeaders();
    headers.add(FORWARDED, forwarded);
    headers.add(FORWARDED, forwarded2);

    CompletableFuture<Boolean> create = new CompletableFuture<>();
    consumerService().createConsumerRequest(groupId, consumerWithEarliestReset)
            .putHeaders(headers)
            .sendJsonObject(consumerWithEarliestReset, ar -> {
                context.verify(() -> {
                    assertThat(ar.succeeded(), is(true));
                    HttpResponse<JsonObject> response = ar.result();
                    assertThat(response.statusCode(), is(HttpResponseStatus.OK.code()));
                    JsonObject bridgeResponse = response.body();
                    String consumerInstanceId = bridgeResponse.getString("instance_id");
                    String consumerBaseUri = bridgeResponse.getString("base_uri");
                    assertThat(consumerInstanceId, is(name));
                    assertThat(consumerBaseUri, is(baseUri));
                });
                create.complete(true);
            });

    create.get(TEST_TIMEOUT, TimeUnit.SECONDS);
    consumerService()
        .deleteConsumer(context, groupId, name);
    context.completeNow();
    assertThat(context.awaitCompletion(TEST_TIMEOUT, TimeUnit.SECONDS), is(true));
}
 
Example #20
Source File: TestDefaultHttpClientFilter.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testAfterReceiveResponseNormal(@Mocked Invocation invocation,
    @Mocked HttpServletResponseEx responseEx,
    @Mocked Buffer bodyBuffer,
    @Mocked OperationMeta operationMeta,
    @Mocked RestOperationMeta swaggerRestOperation,
    @Mocked ProduceProcessor produceProcessor) throws Exception {
  MultiMap responseHeader = new CaseInsensitiveHeaders();
  responseHeader.add("b", "bValue");

  Object decodedResult = new Object();
  new Expectations() {
    {
      responseEx.getHeader(HttpHeaders.CONTENT_TYPE);
      result = "json";
      responseEx.getHeaderNames();
      result = Arrays.asList("a", "b");
      responseEx.getHeaders("b");
      result = responseHeader.getAll("b");
      swaggerRestOperation.findProduceProcessor("json");
      result = produceProcessor;
      produceProcessor.decodeResponse(bodyBuffer, (JavaType) any);
      result = decodedResult;

      invocation.getOperationMeta();
      result = operationMeta;
      operationMeta.getExtData(RestConst.SWAGGER_REST_OPERATION);
      result = swaggerRestOperation;

      responseEx.getStatusType();
      result = Status.OK;
    }
  };

  Response response = filter.afterReceiveResponse(invocation, responseEx);
  Assert.assertSame(decodedResult, response.getResult());
  Assert.assertEquals(1, response.getHeaders().getHeaderMap().size());
  Assert.assertEquals(response.getHeaders().getHeader("b"), Arrays.asList("bValue"));
}
 
Example #21
Source File: AmpHandlerTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap());
    given(httpRequest.getParam(anyString())).willReturn("tagId1");
    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());
    httpRequest.headers().add("Origin", "http://example.com");

    given(httpResponse.exceptionHandler(any())).willReturn(httpResponse);
    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);
    given(httpResponse.headers()).willReturn(new CaseInsensitiveHeaders());

    given(uidsCookie.hasLiveUids()).willReturn(true);

    given(clock.millis()).willReturn(Instant.now().toEpochMilli());
    timeout = new TimeoutFactory(clock).create(2000L);

    ampHandler = new AmpHandler(
            ampRequestFactory,
            exchangeService,
            analyticsReporter,
            metrics,
            clock,
            bidderCatalog,
            singleton("bidder1"),
            new AmpResponsePostProcessor.NoOpAmpResponsePostProcessor(),
            adminManager, jacksonMapper
    );
}
 
Example #22
Source File: Api.java    From xyz-hub with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the custom parsed query parameters.
 *
 * Temporary solution until https://github.com/vert-x3/issues/issues/380 is resolved.
 */
static MultiMap getQueryParameters(RoutingContext context) {
  MultiMap queryParams = context.get(QUERY_PARAMS);
  if (queryParams != null) {
    return queryParams;
  }
  final MultiMap map = new CaseInsensitiveHeaders();

  String query = context.request().query();
  if (query != null && query.length() > 0) {
    String[] paramStrings = query.split("&");
    for (String paramString : paramStrings) {
      int eqDelimiter = paramString.indexOf("=");
      if (eqDelimiter > 0) {
        String key = paramString.substring(0, eqDelimiter);
        String rawValue = paramString.substring(eqDelimiter + 1);
        if (rawValue.length() > 0) {
          String[] values = rawValue.split(",");
          Stream.of(values).forEach(v -> {
            try {
              map.add(key, URLDecoder.decode(v, Charset.defaultCharset().name()));
            } catch (UnsupportedEncodingException ignored) {
            }
          });
        }
      }
    }
  }
  context.put(QUERY_PARAMS, map);
  return map;
}
 
Example #23
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldReturnFullDebugInfoIfDebugEnabled() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(asList(
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri1")
                    .body("requestBody1")
                    .headers(new CaseInsensitiveHeaders())
                    .build(),
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri("uri2")
                    .body("requestBody2")
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            emptyList()));

    givenHttpClientReturnsResponses(
            HttpClientResponse.of(200, null, "responseBody1"),
            HttpClientResponse.of(200, null, "responseBody2"));

    given(bidder.makeBids(any(), any())).willReturn(Result.of(emptyList(), emptyList()));

    // when
    final BidderSeatBid bidderSeatBid =
            bidderHttpConnector.requestBids(bidder, BidRequest.builder().build(), timeout, true).result();

    // then
    assertThat(bidderSeatBid.getHttpCalls()).hasSize(2).containsOnly(
            ExtHttpCall.builder().uri("uri1").requestbody("requestBody1").responsebody("responseBody1")
                    .status(200).build(),
            ExtHttpCall.builder().uri("uri2").requestbody("requestBody2").responsebody("responseBody2")
                    .status(200).build());
}
 
Example #24
Source File: NotificationEventHandlerTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());
    given(httpRequest.params()).willReturn(MultiMap.caseInsensitiveMultiMap());

    given(httpResponse.putHeader(any(CharSequence.class), any(CharSequence.class))).willReturn(httpResponse);
    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);

    notificationHandler = new NotificationEventHandler(analyticsReporter, timeoutFactory, applicationSettings);
}
 
Example #25
Source File: ImplicitParametersExtractorTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    // minimal request
    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());

    extractor = new ImplicitParametersExtractor(psl);
}
 
Example #26
Source File: HttpBidderRequesterTest.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
@Test
public void shouldTolerateMultipleErrors() {
    // given
    given(bidder.makeHttpRequests(any())).willReturn(Result.of(asList(
            // this request will fail with response exception
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build(),
            // this request will fail with timeout
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build(),
            // this request will fail with 500 status
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build(),
            // this request will fail with 400 status
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build(),
            // this request will get 204 status
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build(),
            // finally this request will succeed
            HttpRequest.<BidRequest>builder()
                    .method(HttpMethod.POST)
                    .uri(EMPTY)
                    .body(EMPTY)
                    .headers(new CaseInsensitiveHeaders())
                    .build()),
            singletonList(BidderError.badInput("makeHttpRequestsError"))));

    given(httpClient.request(any(), anyString(), any(), any(), anyLong()))
            // simulate response error for the first request
            .willReturn(Future.failedFuture(new RuntimeException("Response exception")))
            // simulate timeout for the second request
            .willReturn(Future.failedFuture(new TimeoutException("Timeout exception")))
            // simulate 500 status
            .willReturn(Future.succeededFuture(HttpClientResponse.of(500, null, EMPTY)))
            // simulate 400 status
            .willReturn(Future.succeededFuture(HttpClientResponse.of(400, null, EMPTY)))
            // simulate 204 status
            .willReturn(Future.succeededFuture(HttpClientResponse.of(204, null, EMPTY)))
            // simulate 200 status
            .willReturn(Future.succeededFuture(HttpClientResponse.of(200, null, EMPTY)));

    given(bidder.makeBids(any(), any())).willReturn(
            Result.of(singletonList(BidderBid.of(null, null, null)),
                    singletonList(BidderError.badServerResponse("makeBidsError"))));

    // when
    final BidderSeatBid bidderSeatBid = bidderHttpConnector
            .requestBids(bidder, BidRequest.builder().test(1).build(), timeout, false)
            .result();

    // then
    // only two calls are expected (200 and 204) since other requests have failed with errors.
    verify(bidder, times(2)).makeBids(any(), any());
    assertThat(bidderSeatBid.getBids()).hasSize(2);
    assertThat(bidderSeatBid.getErrors()).containsOnly(
            BidderError.badInput("makeHttpRequestsError"),
            BidderError.generic("Response exception"),
            BidderError.timeout("Timeout exception"),
            BidderError.badServerResponse("Unexpected status code: 500. Run with request.test = 1 for more info"),
            BidderError.badInput("Unexpected status code: 400. Run with request.test = 1 for more info"),
            BidderError.badServerResponse("makeBidsError"));
}
 
Example #27
Source File: AuctionHandlerTest.java    From prebid-server-java with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() {
    given(applicationSettings.getAccountById(any(), any()))
            .willReturn(Future.succeededFuture(Account.builder().build()));

    given(bidderCatalog.isValidAdapterName(eq(RUBICON))).willReturn(true);
    given(bidderCatalog.isValidName(eq(RUBICON))).willReturn(true);
    given(bidderCatalog.isActive(eq(RUBICON))).willReturn(true);
    willReturn(rubiconAdapter).given(bidderCatalog).adapterByName(eq(RUBICON));
    given(bidderCatalog.bidderInfoByName(eq(RUBICON))).willReturn(givenBidderInfo(15));

    given(bidderCatalog.isValidAdapterName(eq(APPNEXUS))).willReturn(true);
    given(bidderCatalog.isValidName(eq(APPNEXUS))).willReturn(true);
    given(bidderCatalog.isActive(eq(APPNEXUS))).willReturn(true);
    willReturn(appnexusAdapter).given(bidderCatalog).adapterByName(eq(APPNEXUS));
    given(bidderCatalog.bidderInfoByName(eq(APPNEXUS))).willReturn(givenBidderInfo(20));

    given(routingContext.request()).willReturn(httpRequest);
    given(routingContext.response()).willReturn(httpResponse);

    given(httpRequest.headers()).willReturn(new CaseInsensitiveHeaders());

    given(httpResponse.exceptionHandler(any())).willReturn(httpResponse);
    given(httpResponse.setStatusCode(anyInt())).willReturn(httpResponse);
    given(httpResponse.putHeader(any(CharSequence.class), any(CharSequence.class))).willReturn(httpResponse);

    clock = Clock.fixed(Instant.now(), ZoneId.systemDefault());

    given(tcfDefinerService.resultForVendorIds(anySet(), any(), any(), any(), any(), any()))
            .willReturn(Future.succeededFuture(TcfResponse.of(true, emptyMap(), null)));

    privacyExtractor = new PrivacyExtractor(jacksonMapper);

    auctionHandler = new AuctionHandler(
            applicationSettings,
            bidderCatalog,
            preBidRequestContextFactory,
            cacheService,
            metrics,
            httpAdapterConnector,
            clock,
            tcfDefinerService,
            privacyExtractor,
            jacksonMapper,
            null,
            false);
}
 
Example #28
Source File: ConfigCenterClient.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public void doWatch(String configCenter)
    throws UnsupportedEncodingException, InterruptedException {
  CountDownLatch waiter = new CountDownLatch(1);
  IpPort ipPort = NetUtils.parseIpPortFromURI(configCenter);
  String url = uriConst.REFRESH_ITEMS + "?dimensionsInfo="
      + StringUtils.deleteWhitespace(URLEncoder.encode(serviceName, "UTF-8"));
  Map<String, String> headers = new HashMap<>();
  headers.put("x-domain-name", tenantName);
  if (ConfigCenterConfig.INSTANCE.getToken() != null) {
    headers.put("X-Auth-Token", ConfigCenterConfig.INSTANCE.getToken());
  }
  headers.put("x-environment", environment);

  HttpClientWithContext vertxHttpClient = HttpClients.getClient(ConfigCenterHttpClientOptionsSPI.CLIENT_NAME);

  vertxHttpClient.runOnContext(client -> {
    Map<String, String> authHeaders = new HashMap<>();
    authHeaderProviders.forEach(provider -> authHeaders.putAll(provider.getSignAuthHeaders(
        createSignRequest(null, configCenter + url, headers, null))));
    WebSocketConnectOptions options = new WebSocketConnectOptions();
    options.setHost(ipPort.getHostOrIp()).setPort(refreshPort).setURI(url)
        .setHeaders(new CaseInsensitiveHeaders().addAll(headers)
            .addAll(authHeaders));
    client.webSocket(options, asyncResult -> {
      if (asyncResult.failed()) {
        LOGGER.error(
            "watcher connect to config center {} refresh port {} failed. Error message is [{}]",
            configCenter,
            refreshPort,
            asyncResult.cause().getMessage());
        waiter.countDown();
      } else {
        {
          asyncResult.result().exceptionHandler(e -> {
            LOGGER.error("watch config read fail", e);
            stopHeartBeatThread();
            isWatching = false;
          });
          asyncResult.result().closeHandler(v -> {
            LOGGER.warn("watching config connection is closed accidentally");
            stopHeartBeatThread();
            isWatching = false;
          });

          asyncResult.result().pongHandler(pong -> {
            // ignore, just prevent NPE.
          });
          asyncResult.result().frameHandler(frame -> {
            Buffer action = frame.binaryData();
            LOGGER.info("watching config recieved {}", action);
            Map<String, Object> mAction = action.toJsonObject().getMap();
            if ("CREATE".equals(mAction.get("action"))) {
              //event loop can not be blocked,we just keep nothing changed in push mode
              refreshConfig(configCenter, false);
            } else if ("MEMBER_CHANGE".equals(mAction.get("action"))) {
              refreshMembers(memberdis);
            } else {
              parseConfigUtils.refreshConfigItemsIncremental(mAction);
            }
          });
          startHeartBeatThread(asyncResult.result());
          isWatching = true;
          waiter.countDown();
        }
      }
    });
  });
  waiter.await();
}
 
Example #29
Source File: WebsocketClientUtil.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public MultiMap getDefaultHeaders() {
  return new CaseInsensitiveHeaders().addAll(defaultHeaders());
}
 
Example #30
Source File: RestClientUtil.java    From servicecomb-java-chassis with Apache License 2.0 4 votes vote down vote up
public MultiMap getDefaultHeaders() {
  return new CaseInsensitiveHeaders().addAll(defaultHeaders());
}