com.ning.http.client.AsyncHttpClientConfig Java Examples

The following examples show how to use com.ning.http.client.AsyncHttpClientConfig. 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: 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 #2
Source File: MiosUnitConnector.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
private String getUri(boolean incremental) {
    MiosUnit unit = getMiosUnit();

    if (incremental) {
        AsyncHttpClientConfig c = getAsyncHttpClient().getConfig();

        // Use a timeout on the MiOS URL call that's about 2/3 of what
        // the connection timeout is.
        int t = Math.min(c.getIdleConnectionTimeoutInMs(), unit.getTimeout()) / 500 / 3;
        int d = unit.getMinimumDelay();

        return String.format(Locale.US, STATUS2_INCREMENTAL_URL, unit.getHostname(), unit.getPort(), loadTime,
                dataVersion, new Integer(t), new Integer(d));
    } else {
        return String.format(Locale.US, STATUS2_URL, unit.getHostname(), unit.getPort());
    }
}
 
Example #3
Source File: MiosUnitConnector.java    From openhab1-addons with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * @param unit
 *            The host to connect to. Give a reachable hostname or IP address, without protocol or port
 */
public MiosUnitConnector(MiosUnit unit, MiosBinding binding) {
    logger.debug("Constructor: unit '{}', binding '{}'", unit, binding);

    this.unit = unit;
    this.binding = binding;

    Builder builder = new AsyncHttpClientConfig.Builder();
    builder.setRequestTimeoutInMs(unit.getTimeout());

    // Use the JDK Provider for now, we're not looking for server-level
    // scalability, and we'd like to lighten the load for folks wanting to
    // run atop RPi units.
    this.client = new AsyncHttpClient(new JDKAsyncHttpProvider(builder.build()));

    pollCall = new LongPoll();
    pollThread = new Thread(pollCall);
}
 
Example #4
Source File: NingHttpResponseBuilder.java    From junit-servers with MIT License 6 votes vote down vote up
@Override
public Response build() {
	Uri uri = Uri.create("http://localhost:8080/");

	AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder().build();
	AsyncHttpProvider provider = new JDKAsyncHttpProvider(config);
	HttpURLConnection conn = createFakeUrlConnection();
	HttpResponseStatus status = new ResponseStatus(uri, config, conn);
	HttpResponseHeaders headers = new ResponseHeaders(uri, conn, provider);

	final List<HttpResponseBodyPart> bodyParts;
	if (body != null) {
		byte[] bodyBytes = body.getBytes(defaultCharset());
		HttpResponseBodyPart part = new ResponseBodyPart(bodyBytes, true);
		bodyParts = singletonList(part);
	}
	else {
		bodyParts = emptyList();
	}

	return new JDKResponse(status, headers, bodyParts);
}
 
Example #5
Source File: HttpClient.java    From ob1k with Apache License 2.0 6 votes vote down vote up
/**
 * Creates new HttpClient from the configuration set
 *
 * @return new HttpClient instance
 */
public HttpClient build() {

  final AsyncHttpClientConfig.Builder configBuilder = new AsyncHttpClientConfig.Builder().
    setConnectTimeout(connectionTimeout).
    setMaxRequestRetry(retries).
    setRequestTimeout(requestTimeout).
    setCompressionEnforced(compressionEnforced).
    setDisableUrlEncodingForBoundedRequests(disableUrlEncoding).
    setMaxConnectionsPerHost(maxConnectionsPerHost).
    setMaxConnections(maxTotalConnections).
    setAsyncHttpClientProviderConfig(NettyConfigHolder.INSTANCE).
    setFollowRedirect(followRedirect).
    setAcceptAnyCertificate(acceptAnySslCertificate);

  if (readTimeout != null) {
    configBuilder.setReadTimeout(readTimeout);
  }

  return new HttpClient(new AsyncHttpClient(configBuilder.build()), responseMaxSize, marshallingStrategy);
}
 
Example #6
Source File: DatastoreImpl.java    From async-datastore-client with Apache License 2.0 6 votes vote down vote up
DatastoreImpl(final DatastoreConfig config) {
  this.config = config;
  final AsyncHttpClientConfig httpConfig = new AsyncHttpClientConfig.Builder()
      .setConnectTimeout(config.getConnectTimeout())
      .setRequestTimeout(config.getRequestTimeout())
      .setMaxConnections(config.getMaxConnections())
      .setMaxRequestRetry(config.getRequestRetry())
      .setCompressionEnforced(true)
      .build();

  client = new AsyncHttpClient(httpConfig);
  prefixUri = String.format("%s/%s/projects/%s:", config.getHost(), config.getVersion(), config.getProject());

  executor = Executors.newSingleThreadScheduledExecutor();

  if (config.getCredential() != null) {
    // block while retrieving an access token for the first time
    refreshAccessToken();

    // wake up every 10 seconds to check if access token has expired
    executor.scheduleAtFixedRate(this::refreshAccessToken, 10, 10, TimeUnit.SECONDS);
  }
}
 
Example #7
Source File: AsyncHttpClientHelper.java    From riposte with Apache License 2.0 6 votes vote down vote up
/**
 * Constructor that gives you maximum control over configuration and behavior.
 *
 * @param builder
 *     The builder that will create the {@link #asyncHttpClient} and execute all the async downstream HTTP
 *     requests.
 * @param performSubSpanAroundDownstreamCalls
 *     Pass in true to have a distributed tracing subspan added to each downstream call to measure the time spent
 *     on the downstream call, false if you do not want subspans performed. The subspans can be used to determine
 *     how much time is spent processing in your app vs. waiting for downstream requests.
 */
public AsyncHttpClientHelper(AsyncHttpClientConfig.Builder builder, boolean performSubSpanAroundDownstreamCalls) {
    this.performSubSpanAroundDownstreamCalls = performSubSpanAroundDownstreamCalls;

    Map<String, String> mdcContextMap = MDC.getCopyOfContextMap();
    Deque<Span> distributedTraceStack = null;

    try {
        // We have to unlink tracing and MDC from the current thread before we setup the async http client library,
        //      otherwise all the internal threads it uses to do its job will be attached to the current thread's
        //      trace/MDC info forever and always.
        distributedTraceStack = Tracer.getInstance().unregisterFromThread();
        MDC.clear();
        AsyncHttpClientConfig cf = builder.build();
        asyncHttpClient = new AsyncHttpClient(cf);
    }
    finally {
        // Reattach the original tracing and MDC before we leave
        if (mdcContextMap == null)
            MDC.clear();
        else
            MDC.setContextMap(mdcContextMap);

        Tracer.getInstance().registerWithThread(distributedTraceStack);
    }
}
 
Example #8
Source File: GrizzlyClientCustomizer.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public AsyncHttpClientConfig.Builder customize(
    Client client, Configuration config, AsyncHttpClientConfig.Builder configBuilder
) {
  if (useProxy && !StringUtils.isEmpty(username)) {
    Realm realm = new Realm.RealmBuilder().setScheme(Realm.AuthScheme.BASIC)
        .setUsePreemptiveAuth(true)
        .setTargetProxy(true)
        .setPrincipal(username)
        .setPassword(password)
        .build();

    configBuilder.setRealm(realm);
  }
  return configBuilder;
}
 
Example #9
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 6 votes vote down vote up
@DataProvider(value = {
    "true",
    "false"
}, splitBy = "\\|")
@Test
public void kitchen_sink_constructor_sets_up_underlying_client_with_expected_config(boolean performSubspan) {
    // given
    int customRequestTimeoutVal = 4242;
    AsyncHttpClientConfig config =
        new AsyncHttpClientConfig.Builder().setRequestTimeout(customRequestTimeoutVal).build();
    AsyncHttpClientConfig.Builder builderMock = mock(AsyncHttpClientConfig.Builder.class);
    doReturn(config).when(builderMock).build();

    // when
    AsyncHttpClientHelper instance = new AsyncHttpClientHelper(builderMock, performSubspan);

    // then
    assertThat(instance.performSubSpanAroundDownstreamCalls).isEqualTo(performSubspan);
    assertThat(instance.asyncHttpClient.getConfig()).isSameAs(config);
    assertThat(instance.asyncHttpClient.getConfig().getRequestTimeout()).isEqualTo(customRequestTimeoutVal);
}
 
Example #10
Source File: SchedulerEventReceiver.java    From scheduling with GNU Affero General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("rawtypes")
private void openAndReceive(final SchedulerEventListener eventListener, boolean myEventsOnly,
        SchedulerEvent... events) throws IOException {
    Client client = ClientFactory.getDefault().newClient();
    AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
    if (insecure) {
        builder = builder.setAcceptAnyCertificate(true)
                         .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    }
    AsyncHttpClientConfig httpClientConfig = builder.build();
    AsyncHttpClient httpClient = new AsyncHttpClient(httpClientConfig);

    socket = client.create(client.newOptionsBuilder().runtime(httpClient).reconnect(false).build());
    EventNotificationHandler notificationHandler = new EventNotificationHandler(eventListener);
    socket.on(Event.MESSAGE, notificationHandler);
    socket.on(Event.CLOSE, new Function() {
        public void on(Object t) {
            SchedulerEventReceiver.logger.info("#### Websocket connection is closed ####");
            if (eventListener instanceof DisconnectionAwareSchedulerEventListener) {
                ((DisconnectionAwareSchedulerEventListener) eventListener).notifyDisconnection();
            }
        }
    });
    // initialize the connection
    RequestBuilder requestBuilder = client.newRequestBuilder();
    requestBuilder.method(Request.METHOD.GET);
    requestBuilder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
    // authentication header
    requestBuilder.header("sessionid", sessionId);
    requestBuilder.uri(eventingUrl(restServerUrl));
    requestBuilder.encoder(new EventSubscriptionEncoder());
    requestBuilder.decoder(new EventNotificationDecoder());
    requestBuilder.transport(Request.TRANSPORT.WEBSOCKET);
    socket.open(requestBuilder.build());
    // submit subscription request
    EventSubscription eventSubscription = new EventSubscription(myEventsOnly, asStringArray(events));
    socket.fire(EventCodecUtil.toJsonString(eventSubscription));
}
 
Example #11
Source File: BaragonServiceModule.java    From Baragon with Apache License 2.0 5 votes vote down vote up
@Provides
@Singleton
@Named(BARAGON_SERVICE_HTTP_CLIENT)
public AsyncHttpClient providesHttpClient(HttpClientConfiguration config) {
  AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();

  builder.setMaxRequestRetry(config.getMaxRequestRetry());
  builder.setRequestTimeout(config.getRequestTimeoutInMs());
  builder.setFollowRedirect(true);
  builder.setConnectTimeout(config.getConnectionTimeoutInMs());
  builder.setUserAgent(config.getUserAgent());

  return new AsyncHttpClient(builder.build());
}
 
Example #12
Source File: NingAsyncHttpClient.java    From junit-servers with MIT License 5 votes vote down vote up
/**
 * Create new http client using custom configuration.
 *
 * @param configuration Client configuration.
 * @param server Embedded server.
 * @return Http client.
 * @throws NullPointerException If {@code server} or {@code configuration} is {@code null}.
 */
public static NingAsyncHttpClient newAsyncHttpClient(HttpClientConfiguration configuration, EmbeddedServer<?> server) {
	AsyncHttpClientConfig config = new AsyncHttpClientConfig.Builder()
		.setFollowRedirect(configuration.isFollowRedirect())
		.build();

	AsyncHttpClient client = new AsyncHttpClient(config);
	return new NingAsyncHttpClient(configuration, server, client);
}
 
Example #13
Source File: HookGSpec.java    From bdt with Apache License 2.0 5 votes vote down vote up
@Before(order = ORDER_10, value = "@rest or @dcos")
public void restClientSetup() throws Exception {
    commonspec.getLogger().debug("Starting a REST client");

    commonspec.setClient(new AsyncHttpClient(new AsyncHttpClientConfig.Builder().setAcceptAnyCertificate(true).setAllowPoolingConnections(false)
            .build()));
}
 
Example #14
Source File: ApplyQueueServiceImpl.java    From qconfig with MIT License 5 votes vote down vote up
private AsyncHttpClient getHttpClient() {
    MapConfig config = MapConfig.get("config.properties");
    config.asMap();
    config.addListener(conf -> {
        REQUESTTIMEOUTMS = Numbers.toInt(conf.get("qtable.validate.timeoutMs"), DEFAULTTIMEOUT);
        logger.info("qtable validate timeout ms is [{}]", REQUESTTIMEOUTMS);
    });

    AsyncHttpClientConfig.Builder builder = new AsyncHttpClientConfig.Builder();
    builder.setConnectTimeout(CONNECTTIMEOUT);
    builder.setRequestTimeout(REQUESTTIMEOUT);
    return new AsyncHttpClient(builder.build());
}
 
Example #15
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
private final static <T> void executeRequest(final Channel channel,
                                             final AsyncHttpClientConfig config,
                                             final NettyResponseFuture<T> future,
                                             final HttpRequest nettyRequest) throws ConnectException {

	if (!channel.isConnected()){
		String url = channel.getRemoteAddress() != null ? channel.getRemoteAddress().toString() : null;
		if (url == null) {
			try {
				url = future.getURI().toString();
			} catch (MalformedURLException e) {
				log.debug(e);
			}
		}
		throw new ConnectException(String.format("Connection refused to %s", url));
	}

	channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(future);
	channel.write(nettyRequest);

	try{
		future.setReaperFuture(config.reaper().schedule(new Callable<Object>() {
			public Object call() {
				if (!future.isDone() && !future.isCancelled()) {
					future.abort(new TimeoutException());
					channel.getPipeline().getContext(NettyAsyncHttpProvider.class).setAttachment(ClosedEvent.class);
				}
				return null;
			}

		}, config.getRequestTimeoutInMs(), TimeUnit.MILLISECONDS));
	} catch (RejectedExecutionException ex){
		future.abort(ex);
	}
}
 
Example #16
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
private ConnectListener(AsyncHttpClientConfig config,
                        NettyResponseFuture<T> future,
                        HttpRequest nettyRequest) {
	this.config = config;
	this.future = future;
	this.nettyRequest = nettyRequest;
}
 
Example #17
Source File: NettyAsyncHttpProvider.java    From ck with Apache License 2.0 5 votes vote down vote up
public NettyAsyncHttpProvider(AsyncHttpClientConfig config) {
	super(new HashedWheelTimer(), 0, 0, config.getIdleConnectionTimeoutInMs(), TimeUnit.MILLISECONDS) ;
	socketChannelFactory = new NioClientSocketChannelFactory(
			Executors.newCachedThreadPool(),
			config.executorService());
	bootstrap = new ClientBootstrap(socketChannelFactory);
	this.config = config;
}
 
Example #18
Source File: ParsecAsyncHttpClient.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
/**
 * Private constructor.
 * @param ningClientConfigBuilder Ning client config builder
 * @param cacheExpireAfterWrite cache expire time
 * @param cacheMaximumSize cache maximum size
 */
private ParsecAsyncHttpClient(
    final AsyncHttpClientConfig.Builder ningClientConfigBuilder,
    int cacheRefreshAfterWrite,
    int cacheExpireAfterWrite,
    int cacheMaximumSize,
    boolean enableProfilingFilter,
    boolean recordCacheStats,
    Optional<Long> retryIntervalMillisOpt
) {
    ParsecAsyncHttpResponseLoadingCache.Builder cacheBuilder = new ParsecAsyncHttpResponseLoadingCache.Builder(this)
            .expireAfterWrite(cacheExpireAfterWrite, TimeUnit.SECONDS)
            .maximumSize(cacheMaximumSize);

    if(cacheRefreshAfterWrite > 0)
        cacheBuilder.refreshAfterWrite(cacheRefreshAfterWrite, TimeUnit.SECONDS);

    if (recordCacheStats) {
        cacheBuilder.recordStats();
    }

    responseLoadingCache = cacheBuilder.build();

    if (enableProfilingFilter) {
        //so that there's only one filter.
        ningClientConfigBuilder.removeRequestFilter(PROFILING_FILTER);
        ningClientConfigBuilder.addRequestFilter(PROFILING_FILTER);
        oldFashionProfiling = false;
    }

    this.ningClientConfig = ningClientConfigBuilder.build();

    executorService = (ThreadPoolExecutor) ningClientConfig.executorService();
    client = new AsyncHttpClient(ningClientConfig);

    this.retryIntervalMillisOpt = retryIntervalMillisOpt;
}
 
Example #19
Source File: AsyncHttpClientHelperTest.java    From riposte with Apache License 2.0 5 votes vote down vote up
private void verifyDefaultUnderlyingClientConfig(AsyncHttpClientHelper instance) {
    AsyncHttpClientConfig config = instance.asyncHttpClient.getConfig();
    assertThat(config.isAllowPoolingConnections()).isTrue();
    assertThat(config.getMaxRequestRetry()).isEqualTo(0);
    assertThat(config.getRequestTimeout()).isEqualTo(DEFAULT_REQUEST_TIMEOUT_MILLIS);
    assertThat(config.getConnectionTTL()).isEqualTo(DEFAULT_POOLED_DOWNSTREAM_CONNECTION_TTL_MILLIS);
    assertThat(Whitebox.getInternalState(instance.asyncHttpClient, "signatureCalculator")).isNull();
}
 
Example #20
Source File: AsyncHttpClientHelper.java    From riposte with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor that uses default settings for {@link #asyncHttpClient} but allows you to specify whether or not you
 * want subspans for each downstream request.
 *
 * @param performSubSpanAroundDownstreamCalls
 *     Pass in true to have a distributed tracing subspan added to each downstream call to measure the time spent
 *     on the downstream call, false if you do not want subspans performed. The subspans can be used to determine
 *     how much time is spent processing in your app vs. waiting for downstream requests.
 */
public AsyncHttpClientHelper(boolean performSubSpanAroundDownstreamCalls) {
    this(
        new AsyncHttpClientConfig.Builder()
            .setAllowPoolingConnections(true)
            .setMaxRequestRetry(0)
            .setRequestTimeout(DEFAULT_REQUEST_TIMEOUT_MILLIS)
            .setConnectionTTL(DEFAULT_POOLED_DOWNSTREAM_CONNECTION_TTL_MILLIS),
        performSubSpanAroundDownstreamCalls
    );
}
 
Example #21
Source File: ParsecAsyncHttpClientTest.java    From parsec-libraries with Apache License 2.0 5 votes vote down vote up
@Test
public void testSettingRetryIntervalWillAffectRetryBehavior() throws Exception {
    ThreadPoolExecutor executorService = mock(ThreadPoolExecutor.class);
    AsyncHttpClientConfig clientConfig = mock(AsyncHttpClientConfig.class);
    when(clientConfig.executorService()).thenReturn(executorService);
    AsyncHttpClientConfig.Builder configBuilder = mock(AsyncHttpClientConfig.Builder.class);
    when(configBuilder.build()).thenReturn(clientConfig);

    client = new ParsecAsyncHttpClient.Builder(configBuilder)
        .setRetryIntervalInMilliSeconds(100)
        .build();

    ParsecAsyncHttpRequest request = new ParsecAsyncHttpRequest.Builder()
        .setCriticalGet(true)
        .setUrl(baseUrl + "/sleep/25")
        .addRetryException(TimeoutException.class)
        .setRequestTimeout(10)
        .setMaxRetries(2)
        .build();

    CompletableFuture completableFuture = client.execute(request);
    assertNotNull(completableFuture);
    assertTrue(completableFuture instanceof ParsecCompletableFuture);

    ArgumentCaptor<ParsecHttpRequestRetryCallable> argumentCaptor = ArgumentCaptor.forClass(ParsecHttpRequestRetryCallable.class);
    verify(executorService, times(1)).submit(argumentCaptor.capture());
    ParsecHttpRequestRetryCallable retryCallable = argumentCaptor.getValue();
    assertEquals(100, retryCallable.getRetryDelayer().getRetryIntervalMillis());
}
 
Example #22
Source File: Pubsub.java    From async-google-pubsub-client with Apache License 2.0 4 votes vote down vote up
private Pubsub(final Builder builder) {
  final AsyncHttpClientConfig config = builder.clientConfig.build();

  log.debug("creating new pubsub client with config:");
  log.debug("uri: {}", builder.uri);
  log.debug("connect timeout: {}", config.getConnectTimeout());
  log.debug("read timeout: {}", config.getReadTimeout());
  log.debug("request timeout: {}", config.getRequestTimeout());
  log.debug("max connections: {}", config.getMaxConnections());
  log.debug("max connections per host: {}", config.getMaxConnectionsPerHost());
  log.debug("enabled cipher suites: {}", Arrays.toString(config.getEnabledCipherSuites()));
  log.debug("response compression enforced: {}", config.isCompressionEnforced());
  log.debug("request compression level: {}", builder.compressionLevel);
  log.debug("accept any certificate: {}", config.isAcceptAnyCertificate());
  log.debug("follows redirect: {}", config.isFollowRedirect());
  log.debug("pooled connection TTL: {}", config.getConnectionTTL());
  log.debug("pooled connection idle timeout: {}", config.getPooledConnectionIdleTimeout());
  log.debug("pooling connections: {}", config.isAllowPoolingConnections());
  log.debug("pooling SSL connections: {}", config.isAllowPoolingSslConnections());
  log.debug("user agent: {}", config.getUserAgent());
  log.debug("max request retry: {}", config.getMaxRequestRetry());

  final SSLSocketFactory sslSocketFactory =
      new ConfigurableSSLSocketFactory(config.getEnabledCipherSuites(),
          (SSLSocketFactory) SSLSocketFactory.getDefault());

  this.transport = new NetHttpTransport.Builder()
      .setSslSocketFactory(sslSocketFactory)
      .build();

  this.client = new AsyncHttpClient(config);

  this.compressionLevel = builder.compressionLevel;

  if (builder.credential == null) {
    this.credential = scoped(defaultCredential());
  } else {
    this.credential = scoped(builder.credential);
  }

  this.baseUri = builder.uri.toString();

  // Get initial access token
  refreshAccessToken();
  if (accessToken == null) {
    throw new RuntimeException("Failed to get access token");
  }

  // Wake up every 10 seconds to check if access token has expired
  scheduler.scheduleAtFixedRate(this::refreshAccessToken, 10, 10, SECONDS);
}
 
Example #23
Source File: AsyncHttpClientAgentIntercept.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
public static void exit(final @Advice.This Object thiz) {
  ((AsyncHttpClientConfig.Builder)thiz).addRequestFilter(new TracingRequestFilter(GlobalTracer.get()));
}
 
Example #24
Source File: AsyncHttpClientTest.java    From vw-webservice with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void doTest(Request request) throws InterruptedException, ExecutionException, IOException {
	final PipedOutputStream pipedOutputStream = new PipedOutputStream();
	final PipedInputStream pipedInputStream = new PipedInputStream(pipedOutputStream);

	AsyncHandler<Response> asyncHandler = new AsyncHandler<Response>() {
		private final Response.ResponseBuilder builder = new Response.ResponseBuilder();

		@Override
		public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
			content.writeTo(pipedOutputStream);
			return STATE.CONTINUE;
		}

		@Override
		public STATE onStatusReceived(final HttpResponseStatus status) throws Exception {
			builder.accumulate(status);
			return STATE.CONTINUE;
		}

		@Override
		public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {
			builder.accumulate(headers);
			return STATE.CONTINUE;
		}

		@Override
		public Response onCompleted() throws Exception {

			LOGGER.info("On complete called!");

			pipedOutputStream.flush();
			pipedOutputStream.close();

			return builder.build();

		}

		@Override
		public void onThrowable(Throwable arg0) {
			// TODO Auto-generated method stub
			LOGGER.error("Error: {}", arg0);
			onTestFailed();
		}

	};

	Future<Void> readingThreadFuture = Executors.newCachedThreadPool().submit(new Callable<Void>() {

		@Override
		public Void call() throws Exception {
			BufferedReader reader = new BufferedReader(new InputStreamReader(pipedInputStream));

			String readPrediction;

			int numPredictionsRead = 0;

			while ((readPrediction = reader.readLine()) != null) {
				//LOGGER.info("Got prediction: {}", readPrediction);
				numPredictionsRead++;
			}

			LOGGER.info("Read a total of {} predictions", numPredictionsRead);
			Assert.assertEquals(roundsOfDataToSubmit * 272274, numPredictionsRead);

			return null;
		}
	});

	Builder config = new AsyncHttpClientConfig.Builder();

	config.setRequestTimeoutInMs(-1); //need to set this to -1, to indicate wait forever. setting to 0 actually means a 0 ms timeout!

	AsyncHttpClient client = new AsyncHttpClient(config.build());

	client.executeRequest(request, asyncHandler).get();

	readingThreadFuture.get(); //verify no exceptions occurred when reading predictions

	client.close();

	Assert.assertFalse(getTestFailed());
}
 
Example #25
Source File: PlexConnector.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
private AsyncHttpClientConfig createAsyncHttpClientConfig() {
    Builder builder = new AsyncHttpClientConfig.Builder();
    builder.setRequestTimeoutInMs(REQUEST_TIMEOUT_MS);
    return builder.build();
}
 
Example #26
Source File: XbmcConnector.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
private AsyncHttpClientConfig createAsyncHttpClientConfig() {
    Builder builder = new AsyncHttpClientConfig.Builder();
    builder.setRealm(createRealm());
    builder.setRequestTimeoutInMs(REQUEST_TIMEOUT_MS);
    return builder.build();
}
 
Example #27
Source File: DenonConnector.java    From openhab1-addons with Eclipse Public License 2.0 4 votes vote down vote up
private AsyncHttpClientConfig createAsyncHttpClientConfig() {
    Builder builder = new AsyncHttpClientConfig.Builder();
    builder.setRequestTimeoutInMs(REQUEST_TIMEOUT_MS);
    builder.setUseRawUrl(true);
    return builder.build();
}
 
Example #28
Source File: ParsecAsyncHttpClient.java    From parsec-libraries with Apache License 2.0 4 votes vote down vote up
/**
 * Constructor.
 */
public Builder() {
    this(new AsyncHttpClientConfig.Builder());
}
 
Example #29
Source File: SingularityExecutorModule.java    From Singularity with Apache License 2.0 4 votes vote down vote up
@Provides
@Singleton
public LocalDownloadServiceFetcher provideDownloadFetcher(
  SingularityS3Configuration s3Configuration,
  SingularityExecutorConfiguration executorConfiguration,
  ObjectMapper objectMapper
) {
  if (s3Configuration.getLocalDownloadSocket().isPresent()) {
    HttpClient httpClient = new HttpClient(
      new HttpClientTransportOverUnixSockets(
        s3Configuration.getLocalDownloadSocket().get()
      ),
      null
    );
    return new UnixLocalDownloadServiceFetcher(
      httpClient,
      objectMapper,
      executorConfiguration,
      s3Configuration
    );
  } else {
    AsyncHttpClientConfig.Builder configBldr = new AsyncHttpClientConfig.Builder();
    configBldr.setRequestTimeout(
      (int) executorConfiguration.getLocalDownloadServiceTimeoutMillis()
    );
    configBldr.setPooledConnectionIdleTimeout(
      (int) executorConfiguration.getLocalDownloadServiceTimeoutMillis()
    );
    configBldr.addRequestFilter(
      new ThrottleRequestFilter(
        executorConfiguration.getLocalDownloadServiceMaxConnections()
      )
    );
    return new HttpLocalDownloadServiceFetcher(
      new AsyncHttpClient(configBldr.build()),
      objectMapper,
      executorConfiguration,
      s3Configuration
    );
  }
}
 
Example #30
Source File: SingularityAsyncHttpClient.java    From Singularity with Apache License 2.0 4 votes vote down vote up
public SingularityAsyncHttpClient(AsyncHttpClientConfig clientConfig) {
  super(clientConfig);
}