com.ning.http.client.AsyncHttpClient Java Examples

The following examples show how to use com.ning.http.client.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: StatusManager.java    From Baragon with Apache License 2.0 6 votes vote down vote up
@Inject
public StatusManager(BaragonRequestDatastore requestDatastore,
                     ObjectMapper objectMapper,
                     @Named(BaragonDataModule.BARAGON_SERVICE_LEADER_LATCH) LeaderLatch leaderLatch,
                     @Named(BaragonDataModule.BARAGON_SERVICE_WORKER_LAST_START) AtomicLong workerLastStart,
                     @Named(BaragonDataModule.BARAGON_ELB_WORKER_LAST_START) AtomicLong elbWorkerLastStart,
                     @Named(BaragonDataModule.BARAGON_ZK_CONNECTION_STATE) AtomicReference<ConnectionState> connectionState,
                     @Named(BaragonServiceModule.BARAGON_SERVICE_HTTP_CLIENT)AsyncHttpClient httpClient) {
  this.requestDatastore = requestDatastore;
  this.leaderLatch = leaderLatch;
  this.workerLastStart = workerLastStart;
  this.elbWorkerLastStart = elbWorkerLastStart;
  this.connectionState = connectionState;
  this.httpClient = httpClient;
  this.objectMapper = objectMapper;
}
 
Example #2
Source File: SandboxResource.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Inject
public SandboxResource(
  AsyncHttpClient httpClient,
  LeaderLatch leaderLatch,
  @Singularity ObjectMapper objectMapper,
  HistoryManager historyManager,
  TaskManager taskManager,
  SandboxManager sandboxManager,
  DeployManager deployManager,
  SingularityMesosExecutorInfoSupport logSupport,
  SingularityConfiguration configuration,
  SingularityAuthorizer authorizationHelper
) {
  super(
    httpClient,
    leaderLatch,
    objectMapper,
    historyManager,
    taskManager,
    deployManager,
    authorizationHelper
  );
  this.configuration = configuration;
  this.sandboxManager = sandboxManager;
  this.logSupport = logSupport;
}
 
Example #3
Source File: Configs.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private static ProxyConfig getProxyConfig(String bistouryHost) {
    String url = "http://" + bistouryHost + PROXY_URI;
    try {
        AsyncHttpClient client = AsyncHttpClientHolder.getInstance();
        AsyncHttpClient.BoundRequestBuilder builder = client.prepareGet(url);
        builder.setHeader("content-type", "application/json;charset=utf-8");
        Response response = client.executeRequest(builder.build()).get();
        if (response.getStatusCode() != 200) {
            logger.error("get proxy config error, http code [{}], url [{}]", response.getStatusCode(), url);
            return null;
        }

        JsonResult<ProxyConfig> result = JacksonSerializer.deSerialize(response.getResponseBody("utf8"), PROXY_REFERENCE);
        if (!result.isOK()) {
            logger.error("get proxy config error, status code [{}], url [{}]", result.getStatus(), url);
            return null;
        }

        return result.getData();
    } catch (Throwable e) {
        logger.error("get proxy config error, url [{}]", url, e);
        return null;
    }
}
 
Example #4
Source File: HttpRequestClient.java    From qconfig with MIT License 6 votes vote down vote up
public <R> JsonV2<R> get(String url, Map<String, String> params, TypeReference<JsonV2<R>> typeReference) {
    AsyncHttpClient.BoundRequestBuilder prepareGet = httpClient.prepareGet(url);
    prepareGet.setHeader("Accept", "application/json");
    prepareGet.setHeader("Content-Type", "application/json; charset=utf-8");
    if (!CollectionUtils.isEmpty(params)) {
        for (Map.Entry<String, String> param : params.entrySet()) {
            prepareGet.addQueryParam(param.getKey(), param.getValue());
        }
    }
    Request request = prepareGet.build();
    try {
        Response response = httpClient.executeRequest(request).get(TIMEOUT_MS, TimeUnit.MILLISECONDS);
        int statusCode = response.getStatusCode();
        if (statusCode != Constants.OK_STATUS) {
            throw new RuntimeException(String.format("http request error,url:%s,status code:%d",url,statusCode));
        }
        return mapper.readValue(response.getResponseBody(DEFAULT_CHARSET), typeReference);
    }  catch (Exception e) {
        logger.error("request failOf, url [{}], params {}", url, params, e);
        throw new RuntimeException(e);
    }
}
 
Example #5
Source File: DruidRestUtils.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
/**
 * Query Druid with Post.
 *
 * @param url     <Broker>:<Port, default: 8082>
 * @param json    query json
 * @param timeOut the timeout of http connection, default unit is millisecond
 * @param charset charset
 * @return the result of query
 */
public static String post(String url, String json, Long timeOut, TimeUnit timeUnit, String charset) {
    Future<Response> f = null;
    try (AsyncHttpClient asyncHttpClient = new AsyncHttpClient()) {
        AsyncHttpClient.BoundRequestBuilder builder = asyncHttpClient.preparePost(url);
        builder.setBodyEncoding(StandardCharsets.UTF_8.name()).setBody(json);
        return (f = builder.execute()).get(timeOut == null ? DEFEAT_TIMEOUT : timeOut,
                timeUnit == null ? DEFEAT_UNIT : timeUnit)
                .getResponseBody(charset == null ? StandardCharsets.UTF_8.name() : charset);
    } catch (Exception e) {
        _log.error(ExceptionUtils.errorInfo(e));
        throw new RuntimeException(e);
    } finally {
        if (f != null) f.cancel(true);
    }
}
 
Example #6
Source File: ProxyServiceImpl.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
private boolean existAgent(String url, @RequestParam String agentIp) {
    try {
        AsyncHttpClient.BoundRequestBuilder builder = httpClient.prepareGet(url);
        builder.addQueryParam("ip", agentIp);
        Response response = httpClient.executeRequest(builder.build()).get();
        if (response.getStatusCode() == 200) {
            ApiResult<AgentInfo> result = JacksonSerializer.deSerialize(response.getResponseBody("utf8"), AGENT_TYPE_REFERENCE);
            if (result.getStatus() == 0) {
                return true;
            }
        }
    } catch (Exception e) {
        logger.error("query exist agent error, agent ip [{}], url [{}]", agentIp, url, e);
    }
    return false;
}
 
Example #7
Source File: SingularityLifecycleManaged.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Inject
public SingularityLifecycleManaged(
  SingularityManagedThreadPoolFactory cachedThreadPoolFactory,
  SingularityManagedScheduledExecutorServiceFactory scheduledExecutorServiceFactory,
  AsyncHttpClient asyncHttpClient,
  CuratorFramework curatorFramework,
  SingularityLeaderController leaderController,
  LeaderLatch leaderLatch,
  SingularityMesosExecutorInfoSupport executorInfoSupport,
  SingularityGraphiteReporter graphiteReporter,
  ExecutorIdGenerator executorIdGenerator,
  Set<SingularityLeaderOnlyPoller> leaderOnlyPollers
) {
  this.cachedThreadPoolFactory = cachedThreadPoolFactory;
  this.scheduledExecutorServiceFactory = scheduledExecutorServiceFactory;
  this.asyncHttpClient = asyncHttpClient;
  this.curatorFramework = curatorFramework;
  this.leaderController = leaderController;
  this.leaderLatch = leaderLatch;
  this.executorInfoSupport = executorInfoSupport;
  this.graphiteReporter = graphiteReporter;
  this.executorIdGenerator = executorIdGenerator;
  this.leaderOnlyPollers = leaderOnlyPollers;
}
 
Example #8
Source File: DeployResource.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Inject
public DeployResource(
  RequestManager requestManager,
  DeployManager deployManager,
  SingularityValidator validator,
  SingularityAuthorizer authorizationHelper,
  SingularityConfiguration configuration,
  TaskManager taskManager,
  LeaderLatch leaderLatch,
  AsyncHttpClient httpClient,
  @Singularity ObjectMapper objectMapper,
  RequestHelper requestHelper
) {
  super(
    requestManager,
    deployManager,
    validator,
    authorizationHelper,
    httpClient,
    leaderLatch,
    objectMapper,
    requestHelper
  );
  this.configuration = configuration;
  this.taskManager = taskManager;
}
 
Example #9
Source File: NotifyServiceImpl.java    From qconfig with MIT License 6 votes vote down vote up
@Override
public void notifyFixedVersion(final ConfigMeta meta, final String ip, final long version) {
    List<String> serverUrls = getServerUrls();
    if (CollectionUtils.isEmpty(serverUrls)) {
        logger.warn("notify fixedVersionConsumer server, meta:{}, ip:{}, version: {}, but no server", meta, ip, version);
        return;
    }
    String uri = this.notifyFixedVersionUrl;
    logger.info("notify fixedVersionConsumer server, meta:{}, ip:{}, version: {}, servers:{}", meta, ip, version, serverUrls);
    doNotify(serverUrls, uri, "fixedVersion", new Function<String, Request>() {
        @Override
        public Request apply(String url) {
            AsyncHttpClient.BoundRequestBuilder builder = httpClient.preparePost(url);
            builder.addQueryParam(Constants.GROUP_NAME, meta.getGroup())
                    .addQueryParam(Constants.PROFILE_NAME, meta.getProfile())
                    .addQueryParam(Constants.DATAID_NAME, meta.getDataId())
                    .addQueryParam(Constants.VERSION_NAME, String.valueOf(version))
                    .addQueryParam("ip", ip)
                    .addHeader(Constants.TOKEN_NAME, ServerManager.getInstance().getAppServerConfig().getToken());
            return builder.build();
        }
    });
}
 
Example #10
Source File: SingularityLifecycleManagedTest.java    From Singularity with Apache License 2.0 6 votes vote down vote up
@Inject
public SingularityLifecycleManagedTest(
  SingularityManagedThreadPoolFactory cachedThreadPoolFactory,
  SingularityManagedScheduledExecutorServiceFactory scheduledExecutorServiceFactory,
  AsyncHttpClient asyncHttpClient,
  CuratorFramework curatorFramework,
  SingularityLeaderController leaderController,
  LeaderLatch leaderLatch,
  SingularityMesosExecutorInfoSupport executorInfoSupport,
  SingularityGraphiteReporter graphiteReporter,
  ExecutorIdGenerator executorIdGenerator,
  Set<SingularityLeaderOnlyPoller> leaderOnlyPollers
) {
  super(
    cachedThreadPoolFactory,
    scheduledExecutorServiceFactory,
    asyncHttpClient,
    curatorFramework,
    leaderController,
    leaderLatch,
    executorInfoSupport,
    graphiteReporter,
    executorIdGenerator,
    leaderOnlyPollers
  );
}
 
Example #11
Source File: InvokeJaxrsResourceInTomcat.java    From glowroot with Apache License 2.0 6 votes vote down vote up
public void executeApp(String webapp, String contextPath, String url) throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context = tomcat.addWebapp(contextPath,
            new File("src/test/resources/" + webapp).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(InvokeJaxrsResourceInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode = asyncHttpClient.prepareGet("http://localhost:" + port + contextPath + url)
            .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }

    tomcat.stop();
    tomcat.destroy();
}
 
Example #12
Source File: AsyncUtil.java    From httpsig-java with The Unlicense 6 votes vote down vote up
/**
 * Executes and replays a login request until one is found which satisfies the
 * {@link net.adamcin.httpsig.api.Challenge} being returned by the server, or until there are no more keys in the
 * keychain.
 *
 * @since 1.0.4
 *
 * @param client the {@link AsyncHttpClient} to which the {@link Signer} will be attached
 * @param signer the {@link Signer} used for login and subsequent signature authentication
 * @param loginRequest the login {@link Request} to be executed and replayed while rotating the keychain
 * @param responseHandler an {@link AsyncCompletionHandler} of type {@code T}
 * @param calcBefore provide another {@link SignatureCalculator} to call (such as a Content-MD5 generator) prior to
 *                   generating the signature for authentication.
 * @param <T> type parameter for completion handler
 * @return a {@link Future} of type {@code T}
 * @throws IOException if thrown by a login request
 */
public static <T> Future<T> login(final AsyncHttpClient client,
                         final Signer signer,
                         final Request loginRequest,
                         final AsyncCompletionHandler<T> responseHandler,
                         final SignatureCalculator calcBefore) throws IOException {

    final AsyncHttpClientConfig.Builder configBuilder = new AsyncHttpClientConfig.Builder(client.getConfig());
    configBuilder.addResponseFilter(new RotateAndReplayResponseFilter(signer));
    AsyncHttpClient loginClient = new AsyncHttpClient(configBuilder.build());

    enableAuth(loginClient, signer, calcBefore);
    Future<T> response = loginClient.executeRequest(loginClient
                                                            .prepareRequest(loginRequest)
                                                            .setUrl(loginRequest.getUrl()).build(),
                                                    responseHandler);
    enableAuth(client, signer, calcBefore);
    return response;
}
 
Example #13
Source File: TestServerFixture.java    From fixd with Apache License 2.0 6 votes vote down vote up
@Test
public void testSplatPathParametersOccurringMultipleTimes() throws Exception {
    
    server.handle(Method.GET, "/say/*/to/*")
          .with(200, "text/plain", "[request.path]");

    AsyncHttpClient client1 = new AsyncHttpClient();
    AsyncHttpClient client2 = new AsyncHttpClient();
    AsyncHttpClient client3 = new AsyncHttpClient();

    try {
        Response resp = client1.prepareGet("http://localhost:8080/hello").execute().get();
        assertEquals(404, resp.getStatusCode());

        resp = client2.prepareGet("http://localhost:8080/say/hello/to/world").execute().get();
        assertEquals("/say/hello/to/world", resp.getResponseBody().trim());

        resp = client3.prepareGet("http://localhost:8080/say/bye/to/Tim").execute().get();
        assertEquals("/say/bye/to/Tim", resp.getResponseBody().trim());
    } finally {
        client1.close();
        client2.close();
        client3.close();
    }
}
 
Example #14
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testSplatPathParamsWithVariousPathParams() throws Exception {
    
    server.handle(Method.GET, "/say/*/to/:name/:times<[0-9]+>/*")
          .with(200, "text/plain", "[request.path] :name :times");

    AsyncHttpClient client1 = new AsyncHttpClient();
    AsyncHttpClient client2 = new AsyncHttpClient();
    AsyncHttpClient client3 = new AsyncHttpClient();
    AsyncHttpClient client4 = new AsyncHttpClient();

    try {
        Response resp = client1.prepareGet("http://localhost:8080/hello").execute().get();
        assertEquals(404, resp.getStatusCode());

        resp = client2.prepareGet("http://localhost:8080/say/hello/to/John").execute().get();
        assertEquals(404, resp.getStatusCode());

        resp = client3.prepareGet("http://localhost:8080/say/hello/to/John/1/").execute().get();
        assertEquals("/say/hello/to/John/1/ John 1", resp.getResponseBody().trim());

        resp = client4.prepareGet("http://localhost:8080/say/hello/to/Tim/1/time").execute().get();
        assertEquals("/say/hello/to/Tim/1/time Tim 1", resp.getResponseBody().trim());
    } finally {
        client1.close();
        client2.close();
        client3.close();
        client4.close();
    }
}
 
Example #15
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void getCircuitBreaker_returns_empty_if_disableCircuitBreaker_is_true() {
    // given
    RequestBuilderWrapper rbw = new RequestBuilderWrapper(
        "foo", "bar", mock(AsyncHttpClient.BoundRequestBuilder.class), Optional.of(mock(CircuitBreaker.class)),
        true);

    // when
    Optional<CircuitBreaker<Response>> result = helperSpy.getCircuitBreaker(rbw);

    // then
    assertThat(result).isEmpty();
}
 
Example #16
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void recordsRequestsOnSameURL() throws Exception {
    
    server.handle(Method.GET, "/say-hello/:name")
          .with(200, "text/plain", "Hello :name!");
    
    assertEquals(0, server.capturedRequests().size());

    AsyncHttpClient client1 = new AsyncHttpClient();
    AsyncHttpClient client2 = new AsyncHttpClient();

    try {
        client1.prepareGet("http://localhost:8080/say-hello/John")
                .execute().get();

        client2.prepareGet("http://localhost:8080/say-hello/Tim")
                .execute().get();

        assertEquals(2, server.capturedRequests().size());

        CapturedRequest firstRequest = server.request();
        assertNotNull(firstRequest);
        assertEquals("GET /say-hello/John HTTP/1.1", firstRequest.getRequestLine());

        CapturedRequest secondRequest = server.request();
        assertNotNull(secondRequest);
        assertEquals("GET /say-hello/Tim HTTP/1.1", secondRequest.getRequestLine());
    } finally {
        client1.close();
        client2.close();
    }
}
 
Example #17
Source File: TaskResource.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Inject
public TaskResource(
  TaskRequestManager taskRequestManager,
  TaskManager taskManager,
  SlaveManager slaveManager,
  MesosClient mesosClient,
  SingularityTaskMetadataConfiguration taskMetadataConfiguration,
  SingularityAuthorizer authorizationHelper,
  RequestManager requestManager,
  SingularityValidator validator,
  DisasterManager disasterManager,
  AsyncHttpClient httpClient,
  LeaderLatch leaderLatch,
  @Singularity ObjectMapper objectMapper,
  RequestHelper requestHelper,
  MesosConfiguration configuration,
  SingularityMesosSchedulerClient mesosSchedulerClient
) {
  super(httpClient, leaderLatch, objectMapper);
  this.taskManager = taskManager;
  this.taskRequestManager = taskRequestManager;
  this.taskMetadataConfiguration = taskMetadataConfiguration;
  this.slaveManager = slaveManager;
  this.mesosClient = mesosClient;
  this.requestManager = requestManager;
  this.authorizationHelper = authorizationHelper;
  this.validator = validator;
  this.disasterManager = disasterManager;
  this.requestHelper = requestHelper;
  this.httpClient = httpClient;
  this.configuration = configuration;
  this.fileTypeMap = new MimetypesFileTypeMap();
  this.mesosSchedulerClient = mesosSchedulerClient;
}
 
Example #18
Source File: AsyncServletIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
protected void doTest(int port) throws Exception {
    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode =
            asyncHttpClient.prepareGet("http://localhost:" + port + contextPath + "/async")
                    .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #19
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 AsyncHttpClient();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicInteger statusCode = new AtomicInteger();
    asyncHttpClient.prepareGet("http://localhost:" + getPort() + "/hello3/")
            .execute(new AsyncHandler<Response>() {
                @Override
                public STATE onBodyPartReceived(HttpResponseBodyPart part) {
                    return null;
                }
                @Override
                public Response onCompleted() throws Exception {
                    latch.countDown();
                    return null;
                }
                @Override
                public STATE onHeadersReceived(HttpResponseHeaders headers) {
                    return null;
                }
                @Override
                public STATE onStatusReceived(HttpResponseStatus status) {
                    statusCode.set(status.getStatusCode());
                    return null;
                }
                @Override
                public void onThrowable(Throwable t) {}
            });
    latch.await();
    asyncHttpClient.close();
    if (statusCode.get() != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }
}
 
Example #20
Source File: CommonGTest.java    From bdt with Apache License 2.0 5 votes vote down vote up
@Test
public void testPOSTRequest() throws Exception {
    ThreadProperty.set("class", this.getClass().getCanonicalName());
    CommonG commong = new CommonG();

    commong.setClient(new AsyncHttpClient());
    commong.setRestHost("jenkins.int.stratio.com");
    commong.setRestPort(":80");
    String data = "{j_username=user&j_password=pass";

    Future<Response> response = commong.generateRequest("POST", false, "bdt", "bdt", "/j_acegi_security_check", data, "");

    assertThat(401).as("GET Request with exit code status 401").isEqualTo(response.get().getStatusCode());
}
 
Example #21
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpon() throws Exception {
    
    server.handle(Method.GET, "/subscribe")
          .with(200, "text/plain", "message: :message")
          .upon(Method.GET, "/broadcast/:message");
    
    final List<String> broadcasts = new ArrayList<String>();
    ListenableFuture<Integer> f = client.prepareGet("http://localhost:8080/subscribe")
          .execute(new AddToListOnBodyPartReceivedHandler(broadcasts));
    
    /* need some time for the above request to complete
     * before the broadcast requests can start */
    Thread.sleep(200);
    
    for (int i = 0; i < 2; i++) {

        AsyncHttpClient otherClient = new AsyncHttpClient();
        try {
            otherClient.prepareGet("http://localhost:8080/broadcast/hello" + i).execute().get();

            /* sometimes the last broadcast request is not
             * finished before f.done() is called */
            Thread.sleep(200);
        } finally {
            otherClient.close();
        }
    }
    
    f.done(null);
    assertEquals("[message: hello0, message: hello1]", broadcasts.toString());
}
 
Example #22
Source File: BaseClient.java    From bdt with Apache License 2.0 5 votes vote down vote up
protected Response post(String endpoint, String data) throws Exception {
    AsyncHttpClient.BoundRequestBuilder request = this.httpClient.preparePost(endpoint);
    request = request.setBody(data);
    request = request.setCookies(cookies);
    Response response = request.execute().get();
    this.log.debug("PUT to " + response.getUri() + ":" + response.getResponseBody());
    return response;
}
 
Example #23
Source File: RabbitTestUtils.java    From rxrabbit with MIT License 5 votes vote down vote up
public static int countConsumers(AsyncHttpClient httpClient, String rabbitAdminPort) throws Exception {
    final Response response = httpClient
            .prepareGet("http://localhost:" + rabbitAdminPort + "/api/channels")
            .setRealm(realm)
            .execute().get();
    ObjectMapper mapper = new ObjectMapper();
    int consumers = 0;
    final List<Map<String,Object>> list = mapper.readValue(response.getResponseBody(), List.class);
    for(Map<String,Object> entry : list){
        consumers+= (Integer)entry.get("consumer_count");
    }
    return consumers;
}
 
Example #24
Source File: StrutsTwoIT.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Override
public void executeApp() throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    String subdir;
    try {
        Class.forName("org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter");
        subdir = "struts2.5";
    } catch (ClassNotFoundException e) {
        subdir = "struts2";
    }
    Context context = tomcat.addWebapp("",
            new File("src/test/resources/" + subdir).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(ExecuteActionInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
    int statusCode =
            asyncHttpClient.prepareGet("http://localhost:" + port + "/hello.action")
                    .execute().get().getStatusCode();
    asyncHttpClient.close();
    if (statusCode != 200) {
        throw new IllegalStateException("Unexpected status code: " + statusCode);
    }

    tomcat.stop();
    tomcat.destroy();
}
 
Example #25
Source File: TestServerFixture.java    From fixd with Apache License 2.0 5 votes vote down vote up
@Before
public void beforeEachTest() throws Exception {
    /*
     * Instantiate the server fixture before each test.
     * It could also have been initialized as part of the
     * server field declaration above, as JUnit will 
     * instantiate this Test class for each of its tests.
     */
    server = new ServerFixture(8080);
    server.start();
    client = new AsyncHttpClient();
}
 
Example #26
Source File: RequestBuilderWrapperTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    url = "http://localhost.com";
    httpMethod = HttpMethod.GET.name();
    requestBuilder = mock(AsyncHttpClient.BoundRequestBuilder.class);
    customCircuitBreaker = Optional.of(new CircuitBreakerImpl<Response>());
    disableCircuitBreaker = true;
}
 
Example #27
Source File: SingularityHealthchecker.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Inject
public SingularityHealthchecker(
  SingularityManagedScheduledExecutorServiceFactory executorServiceFactory,
  AsyncHttpClient http,
  OkHttpClient http2,
  SingularityConfiguration configuration,
  SingularityNewTaskChecker newTaskChecker,
  TaskManager taskManager,
  SingularityAbort abort,
  SingularityExceptionNotifier exceptionNotifier,
  DisasterManager disasterManager,
  MesosProtosUtils mesosProtosUtils
) {
  this.http = http;
  this.http2 = http2;
  this.configuration = configuration;
  this.newTaskChecker = newTaskChecker;
  this.taskManager = taskManager;
  this.abort = abort;
  this.exceptionNotifier = exceptionNotifier;

  this.taskIdToHealthcheck = Maps.newConcurrentMap();

  this.executorService =
    executorServiceFactory.get(
      "health-checker",
      configuration.getHealthcheckStartThreads()
    );
  this.disasterManager = disasterManager;
  this.mesosProtosUtils = mesosProtosUtils;
}
 
Example #28
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
@Test
public void getCircuitBreaker_returns_custom_circuit_breaker_if_disableCircuitBreaker_is_false_and_customCircuitBreaker_exists() {
    // given
    Optional<CircuitBreaker<Response>> customCb = Optional.of(mock(CircuitBreaker.class));
    RequestBuilderWrapper rbw = new RequestBuilderWrapper(
        "foo", "bar", mock(AsyncHttpClient.BoundRequestBuilder.class), customCb, false);

    // when
    Optional<CircuitBreaker<Response>> result = helperSpy.getCircuitBreaker(rbw);

    // then
    assertThat(result).isSameAs(customCb);
}
 
Example #29
Source File: XbmcConnector.java    From openhab1-addons with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param xbmc
 *            The host to connect to. Give a reachable hostname or ip
 *            address, without protocol or port
 * @param eventPublisher
 *            EventPublisher to push out state updates
 */
public XbmcConnector(XbmcHost xbmc, EventPublisher eventPublisher) {
    this.xbmc = xbmc;
    this.eventPublisher = eventPublisher;

    this.httpUri = String.format("http://%s:%d/jsonrpc", xbmc.getHostname(), xbmc.getPort());
    this.wsUri = String.format("ws://%s:%d/jsonrpc", xbmc.getHostname(), xbmc.getWSPort());

    this.client = new AsyncHttpClient(new NettyAsyncHttpProvider(createAsyncHttpClientConfig()));
    this.handler = createWebSocketHandler();
}
 
Example #30
Source File: S3LogResource.java    From Singularity with Apache License 2.0 5 votes vote down vote up
@Inject
public S3LogResource(
  AsyncHttpClient httpClient,
  LeaderLatch leaderLatch,
  @Singularity ObjectMapper objectMapper,
  RequestManager requestManager,
  HistoryManager historyManager,
  RequestHistoryHelper requestHistoryHelper,
  TaskManager taskManager,
  DeployManager deployManager,
  Optional<S3Configuration> configuration,
  SingularityAuthorizer authorizationHelper,
  SingularityS3Services s3Services
) {
  super(
    httpClient,
    leaderLatch,
    objectMapper,
    historyManager,
    taskManager,
    deployManager,
    authorizationHelper
  );
  this.requestManager = requestManager;
  this.configuration = configuration;
  this.requestHistoryHelper = requestHistoryHelper;
  this.s3Services = s3Services;
}