org.asynchttpclient.AsyncHttpClient Java Examples

The following examples show how to use org.asynchttpclient.AsyncHttpClient. 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: CloneWorkFlowTest.java    From blynk-server with GNU General Public License v3.0 7 votes vote down vote up
@Test
public void getProjectByCloneCodeViaHttp() throws Exception {
    clientPair.appClient.send("getCloneCode 1");
    String token = clientPair.appClient.getBody();
    assertNotNull(token);
    assertEquals(32, token.length());

    AsyncHttpClient httpclient = new DefaultAsyncHttpClient(
            new DefaultAsyncHttpClientConfig.Builder()
                    .setUserAgent(null)
                    .setKeepAlive(true)
                    .build()
    );

    Future<Response> f = httpclient.prepareGet("http://localhost:" + properties.getHttpPort() + "/" + token + "/clone").execute();
    Response response = f.get();
    assertEquals(200, response.getStatusCode());
    String responseBody = response.getResponseBody();
    assertNotNull(responseBody);
    DashBoard dashBoard = JsonParser.parseDashboard(responseBody, 0);
    assertEquals("My Dashboard", dashBoard.name);
    httpclient.close();
}
 
Example #2
Source File: AzureAsyncReader.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public AzureAsyncReader(final String accountName,
                        final Path path,
                        final AzureAuthTokenProvider authProvider,
                        final String version,
                        final boolean isSecure,
                        final AsyncHttpClient asyncHttpClient) {
  this.authProvider = authProvider;
  this.path = path;
  this.version = AzureAsyncHttpClientUtils.toHttpDateFormat(Long.parseLong(version));
  this.asyncHttpClient = asyncHttpClient;
  final String baseURL = AzureAsyncHttpClientUtils.getBaseEndpointURL(accountName, isSecure);
  final String container = ContainerFileSystem.getContainerName(path);
  final String subPath = removeLeadingSlash(ContainerFileSystem.pathWithoutContainer(path).toString());
  this.url = String.format("%s/%s/%s", baseURL, container, AzureAsyncHttpClientUtils.encodeUrl(subPath));
  this.threadName = Thread.currentThread().getName();
}
 
Example #3
Source File: HttpClientTest.java    From tac with MIT License 6 votes vote down vote up
@Test
public void test() throws InterruptedException, ExecutionException, TimeoutException {

    JSONObject data = new JSONObject();
    data.put("name", "ljinshuan");

    AsyncHttpClient asyncHttpClient = asyncHttpClient();

    ListenableFuture<Response> execute = asyncHttpClient.preparePost("http://localhost:8001/api/tac/execute/shuan")
        .addHeader("Content-Type", "application/json;charset=UTF-8").setBody(data.toJSONString()).execute();
    Response response = execute.get(10, TimeUnit.SECONDS);

    if (response.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
        TacResult tacResult = JSONObject.parseObject(response.getResponseBody(), TacResult.class);

        System.out.println(tacResult);
    }
    System.out.println(response);
}
 
Example #4
Source File: TacPublishTestService.java    From tac with MIT License 6 votes vote down vote up
/**
 * test with http .
 *
 * @param instId
 * @param msCode
 * @param params
 * @return
 */
private TacResult<?> onlinePublishTestHttp(Long instId, String msCode, Map<String, Object> params) {

    AsyncHttpClient asyncHttpClient = asyncHttpClient();

    ListenableFuture<Response> execute = asyncHttpClient.preparePost(containerWebApi + "/" + msCode)
        .addHeader("Content-Type", "application/json;charset=UTF-8").setBody(JSONObject.toJSONString(params))
        .execute();
    Response response;
    try {
        response = execute.get(10, TimeUnit.SECONDS);
        if (response.getStatusCode() == HttpConstants.ResponseStatusCodes.OK_200) {
            TacResult tacResult = JSONObject.parseObject(response.getResponseBody(), TacResult.class);
            return tacResult;
        }
        log.error("onlinePublishTestHttp msCode:{} params:{} {}", msCode, params, response);
        throw new IllegalStateException("request engine error " + msCode);
    } catch (Exception e) {
        throw new IllegalStateException(e.getMessage(), e);
    }

}
 
Example #5
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 6 votes vote down vote up
private Zendesk(AsyncHttpClient client, String url, String username, String password, Map<String, String> headers) {
    this.logger = LoggerFactory.getLogger(Zendesk.class);
    this.closeClient = client == null;
    this.oauthToken = null;
    this.client = client == null ? new DefaultAsyncHttpClient() : client;
    this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2";
    if (username != null) {
        this.realm = new Realm.Builder(username, password)
                .setScheme(Realm.AuthScheme.BASIC)
                .setUsePreemptiveAuth(true)
                .build();
    } else {
        if (password != null) {
            throw new IllegalStateException("Cannot specify token or password without specifying username");
        }
        this.realm = null;
    }
    this.headers = Collections.unmodifiableMap(headers);
    this.mapper = createMapper();
}
 
Example #6
Source File: WebhookModule.java    From attic-aurora with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure() {
  if (webhookConfig.isPresent()) {
    WebhookInfo webhookInfo = parseWebhookConfig(webhookConfig.get());
    DefaultAsyncHttpClientConfig config = new DefaultAsyncHttpClientConfig.Builder()
        .setThreadPoolName("WebHook-AsyncHttpClient")
        .setConnectTimeout(webhookInfo.getConnectonTimeoutMsec())
        .setHandshakeTimeout(webhookInfo.getConnectonTimeoutMsec())
        .setSslSessionTimeout(webhookInfo.getConnectonTimeoutMsec())
        .setReadTimeout(webhookInfo.getConnectonTimeoutMsec())
        .setRequestTimeout(webhookInfo.getConnectonTimeoutMsec())
        .setKeepAliveStrategy(new DefaultKeepAliveStrategy())
        .build();
    AsyncHttpClient httpClient = asyncHttpClient(config);

    bind(WebhookInfo.class).toInstance(webhookInfo);
    bind(AsyncHttpClient.class).toInstance(httpClient);
    PubsubEventModule.bindSubscriber(binder(), Webhook.class);
    bind(Webhook.class).in(Singleton.class);

    SchedulerServicesModule.addSchedulerActiveServiceBinding(binder())
        .to(Webhook.class);
  }
}
 
Example #7
Source File: AsyncHttpClientITest.java    From java-specialagent with Apache License 2.0 6 votes vote down vote up
public static void main(final String[] args) throws Exception {
  try (final AsyncHttpClient client = new DefaultAsyncHttpClient()) {
    final Request request = new RequestBuilder(HttpConstants.Methods.GET).setUrl("http://www.google.com").build();
    final int statusCode = client.executeRequest(request, new AsyncCompletionHandler<Response>() {
      @Override
      public Response onCompleted(final Response response) {
        TestUtil.checkActiveSpan();
        return response;
      }
    }).get(10, TimeUnit.SECONDS).getStatusCode();

    if (200 != statusCode)
      throw new AssertionError("ERROR: response: " + statusCode);

    TestUtil.checkSpan(true, new ComponentSpanCount("java-asynchttpclient", 1), new ComponentSpanCount("netty", 1));
  }
}
 
Example #8
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 6 votes vote down vote up
@Test(timeOut = 5000L)
public void testReadingOkResponse() throws Exception {
    PubSubMessage expected = new PubSubMessage("foo", "response");

    CompletableFuture<Response> response = getOkFuture(getOkResponse(expected.asJSON()));
    AsyncHttpClient mockClient = mockClientWith(response);
    pubscriber.setClient(mockClient);

    pubscriber.send(new PubSubMessage("foo", "bar"));
    // This is async (but practically still very fast since we mocked the response), so need a timeout.
    PubSubMessage actual = fetchAsync().get();

    Assert.assertNotNull(actual);
    Assert.assertEquals(actual.getId(), expected.getId());
    Assert.assertEquals(actual.getContent(), expected.getContent());
}
 
Example #9
Source File: TestAzureAsyncReader.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncHttpClientClosedError() {
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  when(client.isClosed()).thenReturn(true);
  LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2);

  AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader(
    "account", new Path("container/directory/file_00.parquet"),
    getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()),
    false, client
  ));

  try {
    azureAsyncReader.readFully(0, Unpooled.buffer(1), 0, 1);
    fail("Operation shouldn't proceed if client is closed");
  } catch (RuntimeException e) {
    assertEquals("AsyncHttpClient is closed", e.getMessage());
  }
}
 
Example #10
Source File: BrokerServiceLookupTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private AsyncHttpClient getHttpClient(String version) {
    DefaultAsyncHttpClientConfig.Builder confBuilder = new DefaultAsyncHttpClientConfig.Builder();
    confBuilder.setFollowRedirect(true);
    confBuilder.setUserAgent(version);
    confBuilder.setKeepAliveStrategy(new DefaultKeepAliveStrategy() {
        @Override
        public boolean keepAlive(InetSocketAddress remoteAddress, Request ahcRequest,
                                 HttpRequest request, HttpResponse response) {
            // Close connection upon a server error or per HTTP spec
            return (response.status().code() / 100 != 5)
                   && super.keepAlive(remoteAddress, ahcRequest, request, response);
        }
    });
    AsyncHttpClientConfig config = confBuilder.build();
    return new DefaultAsyncHttpClient(config);
}
 
Example #11
Source File: TestAzureStorageFileSystem.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testResourceClosures() throws IOException {
  AsyncHttpClient asyncHttpClient = mock(AsyncHttpClient.class);
  PowerMockito.mockStatic(AzureAsyncHttpClientUtils.class);
  AtomicReference<HashedWheelTimer> timerInstance = new AtomicReference<>();
  when(AzureAsyncHttpClientUtils.newClient(eq(ACCOUNT), eq(true), any(HashedWheelTimer.class))).then(invocationOnMock -> {
    timerInstance.set(invocationOnMock.getArgument(2, HashedWheelTimer.class));
    return asyncHttpClient;
  });

  AzureStorageFileSystem azureStorageFileSystem = new AzureStorageFileSystem();
  azureStorageFileSystem.setup(getMockHadoopConf());

  // Close
  azureStorageFileSystem.close();

  verify(asyncHttpClient, times(1)).close();
  try {
    timerInstance.get().start();
    fail("Timer cannot be started if it was stopped properly at resource closure");
  } catch (IllegalStateException e) {
    assertEquals("cannot be started once stopped", e.getMessage());
  }
}
 
Example #12
Source File: TestAzureAsyncContainerProvider.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Test
public void testDoesContainerExists() throws ExecutionException, InterruptedException {
  AzureStorageFileSystem parentClass = mock(AzureStorageFileSystem.class);
  AzureAuthTokenProvider authTokenProvider = getMockAuthTokenProvider();
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  when(response.getHeader(any(String.class))).thenReturn("");
  when(response.getStatusCode()).thenReturn(200);
  ListenableFuture<Response> future = mock(ListenableFuture.class);
  when(future.get()).thenReturn(response);
  when(client.executeRequest(any(Request.class))).thenReturn(future);

  AzureAsyncContainerProvider containerProvider = new AzureAsyncContainerProvider(
    client, "azurestoragev2hier", authTokenProvider, parentClass, true);
  assertTrue(containerProvider.doesContainerExists("container"));
}
 
Example #13
Source File: AzureAsyncHttpClientUtils.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
public static AsyncHttpClient newClient(final String accountName,
                                        final boolean isSecure,
                                        final HashedWheelTimer poolTimer) {
  final DefaultAsyncHttpClientConfig.Builder configBuilder = config()
    // TODO: Confirm a new thread pool is not getting created everytime
    .setThreadPoolName(accountName + "-azurestorage-async-client")
    .setChannelPool(new DefaultChannelPool(DEFAULT_IDLE_TIME, -1, poolTimer, DEFAULT_CLEANER_PERIOD))
    .setRequestTimeout(DEFAULT_REQUEST_TIMEOUT)
    .setResponseBodyPartFactory(AsyncHttpClientConfig.ResponseBodyPartFactory.LAZY)
    .setMaxRequestRetry(MAX_RETRIES);

  try {
    if (isSecure) {
      configBuilder.setSslContext(SslContextBuilder.forClient().build());
    }
  } catch (SSLException e) {
    logger.error("Error while setting ssl context in Async Client", e);
  }

  poolTimer.start();
  return asyncHttpClient(configBuilder.build());
}
 
Example #14
Source File: NettyWebSocket.java    From selenium with Apache License 2.0 6 votes vote down vote up
static BiFunction<HttpRequest, Listener, WebSocket> create(ClientConfig config, AsyncHttpClient client) {
  Filter filter = config.filter();

  Function<HttpRequest, HttpRequest> filterRequest = req -> {
    AtomicReference<HttpRequest> ref = new AtomicReference<>();
    filter.andFinally(in -> {
      ref.set(in);
      return new HttpResponse();
    }).execute(req);
    return ref.get();
  };

  return (req, listener) -> {
    HttpRequest filtered = filterRequest.apply(req);

    org.asynchttpclient.Request nettyReq = NettyMessages.toNettyRequest(config.baseUri(), filtered);

    return new NettyWebSocket(client, nettyReq, listener);
  };
}
 
Example #15
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 5000L)
public void testReadingNullResponse() throws Exception {
    CompletableFuture<Response> response = getOkFuture(null);
    AsyncHttpClient mockClient = mockClientWith(response);
    pubscriber.setClient(mockClient);

    pubscriber.send(new PubSubMessage("foo", "bar"));
    // This is async (but practically still very fast since we mocked the response), so need a timeout.
    PubSubMessage actual = fetchAsync().get();

    Assert.assertNotNull(actual);
    Assert.assertEquals(actual.getId(), "foo");
    Assert.assertEquals(actual.getContent(), CANNOT_REACH_DRPC.asJSONClip());
}
 
Example #16
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
@Test
public void testClosingWithException() throws Exception {
    AsyncHttpClient mockClient = mock(AsyncHttpClient.class);
    doThrow(new IOException()).when(mockClient).close();

    pubscriber.setClient(mockClient);
    pubscriber.close();
    verify(mockClient, times(1)).close();
}
 
Example #17
Source File: GCMWrapper.java    From blynk-server with GNU General Public License v3.0 5 votes vote down vote up
public GCMWrapper(GCMProperties props, AsyncHttpClient httpclient, String productName) {
    this.apiKey = "key=" + props.getGCMApiKey();
    this.httpclient = httpclient;
    this.gcmURI = props.getGCMServer();

    String title = props.getNotificationTitle();
    this.title = title.replace(Placeholders.PRODUCT_NAME, productName);
}
 
Example #18
Source File: AhcIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncHttpClient() throws Exception {

    try (AsyncHttpClient client = new DefaultAsyncHttpClient()) {
        Future<Response> f = client.prepareGet(HTTP_URL).execute();
        Response res = f.get();
        Assert.assertEquals(200, res.getStatusCode());
        final String body = res.getResponseBody();
        Assert.assertTrue("Got body " + body, body.contains("Welcome to WildFly"));
    }
}
 
Example #19
Source File: OAuthPublicKeyTestConfiguration.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@Bean
@Profile("test")
public AsyncHttpClient asyncHttpClient() {
    final AsyncHttpClientConfig httpClientConfig = new DefaultAsyncHttpClientConfig.Builder()
            .setRequestTimeout(1000)
            .setReadTimeout(1000)
            .build();
    return new DefaultAsyncHttpClient(httpClientConfig);
}
 
Example #20
Source File: AsyncHttpRegistryClient.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@Autowired
public AsyncHttpRegistryClient(final ApplicationInfo applicationInfo,
                               final AsyncHttpClient httpClient,
                               final ServiceRegistryProperties serviceRegistryProperties,
                               final EdisonApplicationProperties edisonApplicationProperties) {
    this.applicationInfo = applicationInfo;
    this.httpClient = httpClient;
    this.serviceRegistryProperties = serviceRegistryProperties;
    this.edisonApplicationProperties = edisonApplicationProperties;
}
 
Example #21
Source File: OAuthPublicKeyStore.java    From edison-microservice with Apache License 2.0 5 votes vote down vote up
@Autowired
public OAuthPublicKeyStore(@Value("${edison.oauth.public-key.url}") final String publicKeyUrl,
                           final AsyncHttpClient asyncHttpClient,
                           final OAuthPublicKeyRepository oAuthPublicKeyRepository) {
    this.publicKeyUrl = publicKeyUrl;
    this.oAuthPublicKeyRepository = oAuthPublicKeyRepository;
    this.asyncHttpClient = asyncHttpClient;

    this.objectMapper = createObjectMapper();
}
 
Example #22
Source File: Zendesk.java    From zendesk-java-client with Apache License 2.0 5 votes vote down vote up
private Zendesk(AsyncHttpClient client, String url, String oauthToken, Map<String, String> headers) {
    this.logger = LoggerFactory.getLogger(Zendesk.class);
    this.closeClient = client == null;
    this.realm = null;
    this.client = client == null ? new DefaultAsyncHttpClient() : client;
    this.url = url.endsWith("/") ? url + "api/v2" : url + "/api/v2";
    if (oauthToken != null) {
        this.oauthToken = oauthToken;
    } else {
        throw new IllegalStateException("Cannot specify token or password without specifying username");
    }
    this.headers = Collections.unmodifiableMap(headers);

    this.mapper = createMapper();
}
 
Example #23
Source File: AsyncHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    int statusCode =
            asyncHttpClient.prepareGet("http://localhost:" + getPort() + "/hello1/")
                    .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #24
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
@Test(timeOut = 5000L)
public void testReadingNotOkResponse() throws Exception {
    CompletableFuture<Response> response = getOkFuture(getNotOkResponse(500));
    AsyncHttpClient mockClient = mockClientWith(response);
    pubscriber.setClient(mockClient);

    pubscriber.send(new PubSubMessage("foo", "bar"));
    // This is async (but practically still very fast since we mocked the response), so need a timeout.
    PubSubMessage actual = fetchAsync().get();

    Assert.assertNotNull(actual);
    Assert.assertEquals(actual.getId(), "foo");
    Assert.assertEquals(actual.getContent(), CANNOT_REACH_DRPC.asJSONClip());
}
 
Example #25
Source File: AsyncHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    int statusCode =
            asyncHttpClient.preparePost("http://localhost:" + getPort() + "/hello2")
                    .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #26
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
private AsyncHttpClient mockClientWith(CompletableFuture<Response> future) {
    ListenableFuture<Response> mockListenable = (ListenableFuture<Response>) mock(ListenableFuture.class);
    doReturn(future).when(mockListenable).toCompletableFuture();

    BoundRequestBuilder mockBuilder = mock(BoundRequestBuilder.class);
    doReturn(mockListenable).when(mockBuilder).execute();
    // Return itself
    doReturn(mockBuilder).when(mockBuilder).setBody(anyString());

    AsyncHttpClient mockClient = mock(AsyncHttpClient.class);
    doReturn(mockBuilder).when(mockClient).preparePost(anyString());
    return mockClient;
}
 
Example #27
Source File: TestAzureAsyncReader.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
private AzureAsyncReader prepareAsyncReader(final String responseBody, final int responseCode) {
  // Prepare response
  AsyncHttpClient client = mock(AsyncHttpClient.class);
  Response response = mock(Response.class);
  HttpResponseStatus status = mock(HttpResponseStatus.class);
  when(status.getStatusCode()).thenReturn(responseCode);
  when(response.getResponseBody()).thenReturn(responseBody);

  CompletableFuture<Response> future = new CompletableFuture<>(); //CompletableFuture.completedFuture(response);
  ListenableFuture<Response> resFuture = mock(ListenableFuture.class);
  when(resFuture.toCompletableFuture()).thenReturn(future);
  LocalDateTime versionDate = LocalDateTime.now(ZoneId.of("GMT")).minusDays(2);

  when(client.executeRequest(any(Request.class), any(AsyncCompletionHandler.class))).then(invocationOnMock -> {
    AsyncCompletionHandler<Response> responseHandler = invocationOnMock.getArgument(1, AsyncCompletionHandler.class);
    assertEquals(responseHandler.getClass(), BufferBasedCompletionHandler.class);
    responseHandler.onStatusReceived(status);
    try {
      responseHandler.onCompleted(response);
    } catch (Exception e) {
      future.completeExceptionally(e);
    }
    return resFuture;
  });

  AzureAsyncReader azureAsyncReader = spy(new AzureAsyncReader(
    "account", new Path("container/directory/file_00.parquet"),
    getMockAuthTokenProvider(), String.valueOf(versionDate.atZone(ZoneId.of("GMT")).toInstant().toEpochMilli()),
    true, client
  ));
  return azureAsyncReader;

}
 
Example #28
Source File: AsyncHttpClientPluginIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void transactionMarker() throws Exception {
    AsyncHttpClient asyncHttpClient = new DefaultAsyncHttpClient();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger statusCode = new AtomicInteger();
    asyncHttpClient.prepareGet("http://localhost:" + getPort() + "/hello3/")
            .execute(new AsyncCompletionHandler<Response>() {
                @Override
                public Response onCompleted(Response response) throws Exception {
                    latch.countDown();
                    return null;
                }
                @Override
                public State onStatusReceived(HttpResponseStatus status) {
                    statusCode.set(status.getStatusCode());
                    return null;
                }
                @Override
                public void onThrowable(Throwable t) {
                    t.printStackTrace();
                }
            });
    latch.await();
    asyncHttpClient.close();
    if (statusCode.get() != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #29
Source File: Webhook.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
@Inject
Webhook(AsyncHttpClient httpClient, WebhookInfo webhookInfo, StatsProvider statsProvider) {
  this.webhookInfo = requireNonNull(webhookInfo);
  this.httpClient = requireNonNull(httpClient);
  this.attemptsCounter = statsProvider.makeCounter(ATTEMPTS_STAT_NAME);
  this.successCounter = statsProvider.makeCounter(SUCCESS_STAT_NAME);
  this.errorsCounter = statsProvider.makeCounter(ERRORS_STAT_NAME);
  this.userErrorsCounter = statsProvider.makeCounter(USER_ERRORS_STAT_NAME);
  this.isWhitelisted = status -> !webhookInfo.getWhitelistedStatuses().isPresent()
      || webhookInfo.getWhitelistedStatuses().get().contains(status);
  LOG.info("Webhook enabled with info" + this.webhookInfo);
}
 
Example #30
Source File: DRPCQueryResultPubscriberTest.java    From bullet-storm with Apache License 2.0 5 votes vote down vote up
@Test
public void testClosing() throws Exception {
    AsyncHttpClient mockClient = mock(AsyncHttpClient.class);
    pubscriber.setClient(mockClient);
    pubscriber.close();
    verify(mockClient, times(1)).close();
}