com.google.common.util.concurrent.MoreExecutors Java Examples

The following examples show how to use com.google.common.util.concurrent.MoreExecutors. 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: CacheBuilderGwtTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
public void testAsMapKeySet_contains() {
  Cache<Integer, Integer> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
      .expireAfterWrite(1000, TimeUnit.MILLISECONDS)
      .executor(MoreExecutors.directExecutor())
      .ticker(fakeTicker::read));

  cache.put(10, 20);
  fakeTicker.advance(500, TimeUnit.MILLISECONDS);
  cache.put(20, 22);
  cache.put(5, 10);

  fakeTicker.advance(501, TimeUnit.MILLISECONDS);

  assertTrue(cache.asMap().keySet().contains(20));
  assertTrue(cache.asMap().keySet().contains(5));
  assertFalse(cache.asMap().keySet().contains(10));
}
 
Example #2
Source File: ProcessRuntime.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<InstanceCommunication.MetricsData> getMetrics(int instanceId) {
    CompletableFuture<InstanceCommunication.MetricsData> retval = new CompletableFuture<>();
    if (stub == null) {
        retval.completeExceptionally(new RuntimeException("Not alive"));
        return retval;
    }
    ListenableFuture<InstanceCommunication.MetricsData> response = stub.withDeadlineAfter(GRPC_TIMEOUT_SECS, TimeUnit.SECONDS).getMetrics(Empty.newBuilder().build());
    Futures.addCallback(response, new FutureCallback<InstanceCommunication.MetricsData>() {
        @Override
        public void onFailure(Throwable throwable) {
            retval.completeExceptionally(throwable);
        }

        @Override
        public void onSuccess(InstanceCommunication.MetricsData t) {
            retval.complete(t);
        }
    }, MoreExecutors.directExecutor());
    return retval;
}
 
Example #3
Source File: GoogleAdsFieldServiceClient.java    From google-ads-java with Apache License 2.0 6 votes vote down vote up
public static ApiFuture<SearchGoogleAdsFieldsPagedResponse> createAsync(
    PageContext<SearchGoogleAdsFieldsRequest, SearchGoogleAdsFieldsResponse, GoogleAdsField>
        context,
    ApiFuture<SearchGoogleAdsFieldsResponse> futureResponse) {
  ApiFuture<SearchGoogleAdsFieldsPage> futurePage =
      SearchGoogleAdsFieldsPage.createEmptyPage().createPageAsync(context, futureResponse);
  return ApiFutures.transform(
      futurePage,
      new ApiFunction<SearchGoogleAdsFieldsPage, SearchGoogleAdsFieldsPagedResponse>() {
        @Override
        public SearchGoogleAdsFieldsPagedResponse apply(SearchGoogleAdsFieldsPage input) {
          return new SearchGoogleAdsFieldsPagedResponse(input);
        }
      },
      MoreExecutors.directExecutor());
}
 
Example #4
Source File: StreamingCallSubscriberTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void cancel() throws Exception {
    when(armeriaCall.tryFinish()).thenReturn(false);
    when(armeriaCall.isCanceled()).thenReturn(false, false, true);

    final ManualMockCallback callback = new ManualMockCallback();
    final StreamingCallSubscriber subscriber = new StreamingCallSubscriber(
            armeriaCall, callback, new Request.Builder().url("http://foo.com").build(),
            MoreExecutors.directExecutor());
    subscriber.onSubscribe(subscription);
    subscriber.onNext(ResponseHeaders.of(200));
    subscriber.onNext(HttpData.ofUtf8("{\"name\":\"foo\"}"));
    subscriber.onComplete();

    verify(subscription, times(2)).request(1L);

    await().untilAsserted(() -> assertThat(callback.callbackCallingCount).isEqualTo(1));
    await().untilAsserted(() -> assertThat(callback.exception.getMessage()).isEqualTo("cancelled"));
}
 
Example #5
Source File: ServerSentEventsTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Override
protected void configure(ServerBuilder sb) throws Exception {
    sb.service("/sse/publisher", (ctx, req) -> ServerSentEvents.fromPublisher(
            Flux.just(ServerSentEvent.ofData("foo"), ServerSentEvent.ofData("bar"))));
    sb.service("/sse/stream", (ctx, req) -> ServerSentEvents.fromStream(
            Stream.of(ServerSentEvent.ofData("foo"), ServerSentEvent.ofData("bar")),
            MoreExecutors.directExecutor()));

    sb.service("/converter/publisher", (ctx, req) -> ServerSentEvents.fromPublisher(
            Flux.just("foo", "bar"), ServerSentEvent::ofComment));
    sb.service("/converter/stream", (ctx, req) -> ServerSentEvents.fromStream(
            Stream.of("foo", "bar"), MoreExecutors.directExecutor(), ServerSentEvent::ofComment));

    sb.service("/single/sse", (ctx, req) -> ServerSentEvents.fromEvent(
            ServerSentEvent.ofEvent("add")));
}
 
Example #6
Source File: MobileServiceTable.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Executes a query to retrieve all the table rows
 *
 * @param callback Callback to invoke when the operation is completed
 * @throws com.microsoft.windowsazure.mobileservices.MobileServiceException
 * @deprecated use {@link #execute()} instead
 */
public void execute(final TableQueryCallback<E> callback) throws MobileServiceException {

    ListenableFuture<MobileServiceList<E>> executeFuture = execute();

    Futures.addCallback(executeFuture, new FutureCallback<MobileServiceList<E>>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onCompleted(null, 0, (Exception) exception, MobileServiceException.getServiceResponse(exception));
            } else {
                callback.onCompleted(null, 0, new Exception(exception), MobileServiceException.getServiceResponse(exception));
            }
        }

        @Override
        public void onSuccess(MobileServiceList<E> result) {
            callback.onCompleted(result, result.getTotalCount(), null, null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example #7
Source File: MessagingPerfApp.java    From onos with Apache License 2.0 6 votes vote down vote up
@Activate
public void activate(ComponentContext context) {
    configService.registerProperties(getClass());
    setupCodecs();
    messageReceivingExecutor = receiveOnIOLoopThread
            ? MoreExecutors.directExecutor()
            : Executors.newFixedThreadPool(
                    totalReceiverThreads,
                    groupedThreads("onos/net-perf-test", "receiver-%d"));
    registerMessageHandlers();
    startTest();
    reporter.scheduleWithFixedDelay(this::reportPerformance,
            reportIntervalSeconds,
            reportIntervalSeconds,
            TimeUnit.SECONDS);
    logConfig("Started");
}
 
Example #8
Source File: MobileServiceClient.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes a custom API
 *
 * @param apiName        The API name
 * @param content        The byte array to send as the request body
 * @param httpMethod     The HTTP Method used to invoke the API
 * @param requestHeaders The extra headers to send in the request
 * @param parameters     The query string parameters sent in the request
 * @param callback       The callback to invoke after the API execution
 */
public void invokeApi(String apiName, byte[] content, String httpMethod, List<Pair<String, String>> requestHeaders, List<Pair<String, String>> parameters,
                      final ServiceFilterResponseCallback callback) {

    ListenableFuture<ServiceFilterResponse> invokeApiFuture = invokeApi(apiName, content, httpMethod, requestHeaders, parameters);

    Futures.addCallback(invokeApiFuture, new FutureCallback<ServiceFilterResponse>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onResponse(MobileServiceException.getServiceResponse(exception), (Exception) exception);
            } else {
                callback.onResponse(MobileServiceException.getServiceResponse(exception), new Exception(exception));
            }
        }

        @Override
        public void onSuccess(ServiceFilterResponse result) {
            callback.onResponse(result, null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example #9
Source File: ProcessEventProcessor.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
@Override
public void processResponseStream(StreamContext<ProcessEvent> context) {
    Consumer<ProcessEvent> watcher = context.getWatcher();
    InputStream response = context.getStream();
    SettableFuture<Boolean> interrupter = context.getInterrupter();
    interrupter.addListener(() -> Thread.currentThread().interrupt(), MoreExecutors.directExecutor());
    try (FrameReader frameReader = new FrameReader(response)) {

        Frame frame = frameReader.readFrame();
        while (frame != null && !interrupter.isDone()) {
            try {
                ProcessEvent.watchRaw(watcher, frame.getMessage(), false);
            } catch (Exception e) {
                log.error("Cannot read body", e);
            } finally {
                frame = frameReader.readFrame();
            }
        }
    } catch (Exception t) {
        log.error("Cannot close reader", t);
    }

}
 
Example #10
Source File: DatabaseBackupTest.java    From Plan with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Test
default void testBackupAndRestoreH2() throws Exception {
    File tempFile = Files.createTempFile(system().getPlanFiles().getDataFolder().toPath(), "backup-", ".db").toFile();
    tempFile.deleteOnExit();
    H2DB backup = system().getDatabaseSystem().getH2Factory().usingFile(tempFile);
    backup.setTransactionExecutorServiceProvider(MoreExecutors::newDirectExecutorService);
    try {
        backup.init();

        saveDataForBackup();

        backup.executeTransaction(new BackupCopyTransaction(db(), backup));

        assertQueryResultIsEqual(db(), backup, BaseUserQueries.fetchAllBaseUsers());
        assertQueryResultIsEqual(db(), backup, UserInfoQueries.fetchAllUserInformation());
        assertQueryResultIsEqual(db(), backup, NicknameQueries.fetchAllNicknameData());
        assertQueryResultIsEqual(db(), backup, GeoInfoQueries.fetchAllGeoInformation());
        assertQueryResultIsEqual(db(), backup, SessionQueries.fetchAllSessions());
        assertQueryResultIsEqual(db(), backup, LargeFetchQueries.fetchAllWorldNames());
        assertQueryResultIsEqual(db(), backup, LargeFetchQueries.fetchAllTPSData());
        assertQueryResultIsEqual(db(), backup, ServerQueries.fetchPlanServerInformation());
        assertQueryResultIsEqual(db(), backup, WebUserQueries.fetchAllUsers());
    } finally {
        backup.close();
    }
}
 
Example #11
Source File: MobileServiceClient.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Invokes a custom API
 *
 * @param apiName    The API name
 * @param body       The json element to send as the request body
 * @param httpMethod The HTTP Method used to invoke the API
 * @param parameters The query string parameters sent in the request
 * @param callback   The callback to invoke after the API execution
 * @deprecated use {@link #invokeApi(String apiName, com.google.gson.JsonElement body, String httpMethod, List parameters)} instead
 */
public void invokeApi(String apiName, JsonElement body, String httpMethod, List<Pair<String, String>> parameters, final ApiJsonOperationCallback callback) {

    ListenableFuture<JsonElement> invokeApiFuture = invokeApi(apiName, body, httpMethod, parameters);

    Futures.addCallback(invokeApiFuture, new FutureCallback<JsonElement>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onCompleted(null, (Exception) exception, MobileServiceException.getServiceResponse(exception));
            } else {
                callback.onCompleted(null, new Exception(exception), MobileServiceException.getServiceResponse(exception));
            }
        }

        @Override
        public void onSuccess(JsonElement result) {
            callback.onCompleted(result, null, null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example #12
Source File: FileTransport.java    From bazel with Apache License 2.0 6 votes vote down vote up
ListenableFuture<Void> close() {
  if (isClosed.getAndSet(true)) {
    return closeFuture;
  } else if (closeFuture.isDone()) {
    return closeFuture;
  }

  // Close abruptly if the closing future is cancelled.
  closeFuture.addListener(
      () -> {
        if (closeFuture.isCancelled()) {
          closeNow();
        }
      },
      MoreExecutors.directExecutor());

  try {
    pendingWrites.put(CLOSE_EVENT_FUTURE);
  } catch (InterruptedException e) {
    closeNow();
    logger.atSevere().withCause(e).log("Failed to close the sequential writer.");
    closeFuture.set(null);
  }
  return closeFuture;
}
 
Example #13
Source File: CPSPublisherTask.java    From pubsub with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Void> publish(
    int clientId, int sequenceNumber, long publishTimestampMillis) {
  SettableFuture<Void> done = SettableFuture.create();
  ApiFutures.addCallback(
      publisher.publish(
          PubsubMessage.newBuilder()
              .setData(payload)
              .putAttributes("sendTime", Long.toString(publishTimestampMillis))
              .putAttributes("clientId", Integer.toString(clientId))
              .putAttributes("sequenceNumber", Integer.toString(sequenceNumber))
              .build()),
      new ApiFutureCallback<String>() {
        @Override
        public void onSuccess(String messageId) {
          done.set(null);
        }

        @Override
        public void onFailure(Throwable t) {
          done.setException(t);
        }
      },
      MoreExecutors.directExecutor());
  return done;
}
 
Example #14
Source File: StreamingCallSubscriberTest.java    From armeria with Apache License 2.0 6 votes vote down vote up
@Test
public void completeOnlyHeaders() throws Exception {
    when(armeriaCall.tryFinish()).thenReturn(true);

    final ManualMockCallback callback = new ManualMockCallback();
    final StreamingCallSubscriber subscriber = new StreamingCallSubscriber(
            armeriaCall, callback, new Request.Builder().url("http://foo.com").build(),
            MoreExecutors.directExecutor());
    subscriber.onSubscribe(subscription);
    subscriber.onNext(ResponseHeaders.of(HttpStatus.OK, CONTENT_LENGTH, 0));
    subscriber.onComplete();

    verify(subscription, times(2)).request(1L);
    await().untilAsserted(() -> assertThat(callback.callbackCallingCount).isEqualTo(1));
    await().untilAsserted(
            () -> assertThat(callback.response.header(CONTENT_LENGTH.toString())).isEqualTo("0"));
    await().untilAsserted(() -> assertThat(callback.response.body().string()).isEmpty());
}
 
Example #15
Source File: MobileServiceJsonTable.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Inserts a JsonObject into a Mobile Service Table
 *
 * @param element    The JsonObject to insert
 * @param parameters A list of user-defined parameters and values to include in the
 *                   request URI query string
 * @param callback   Callback to invoke when the operation is completed
 * @throws IllegalArgumentException if the element has an id property set with a numeric value
 *                                  other than default (0), or an invalid string value
 * @deprecated use {@link #insert(JsonObject element, List parameters)} instead
 */
public void insert(final JsonObject element, List<Pair<String, String>> parameters, final TableJsonOperationCallback callback) {
    ListenableFuture<JsonObject> insertFuture = insert(element, parameters);

    Futures.addCallback(insertFuture, new FutureCallback<JsonObject>() {
        @Override
        public void onFailure(Throwable exception) {
            if (exception instanceof Exception) {
                callback.onCompleted(null, (Exception) exception, MobileServiceException.getServiceResponse(exception));
            } else {
                callback.onCompleted(null, new Exception(exception), MobileServiceException.getServiceResponse(exception));
            }
        }

        @Override
        public void onSuccess(JsonObject result) {
            callback.onCompleted(result, null, null);
        }
    }, MoreExecutors.directExecutor());
}
 
Example #16
Source File: TestHelper.java    From bitfinex-v2-wss-api-java with Apache License 2.0 6 votes vote down vote up
/**
 * Build a mocked bitfinex connection
 * @return
 */
public static BitfinexWebsocketClient buildMockedBitfinexConnection() {

	final ExecutorService executorService = MoreExecutors.newDirectExecutorService();
	final BitfinexWebsocketClient bitfinexApiBroker = Mockito.mock(SimpleBitfinexApiBroker.class);
	final BitfinexWebsocketConfiguration config = Mockito.mock(BitfinexWebsocketConfiguration.class);

	Mockito.when(bitfinexApiBroker.getConfiguration()).thenReturn(config);
	Mockito.when(config.getApiKey()).thenReturn(API_KEY);
	Mockito.when(bitfinexApiBroker.isAuthenticated()).thenReturn(true);
	Mockito.when(bitfinexApiBroker.getApiKeyPermissions()).thenReturn(BitfinexApiKeyPermissions.ALL_PERMISSIONS);
	Mockito.when(bitfinexApiBroker.getCallbacks()).thenReturn(new BitfinexApiCallbackRegistry());

	final OrderManager orderManager = new OrderManager(bitfinexApiBroker, executorService);
	final TradeManager tradeManager = new TradeManager(bitfinexApiBroker, executorService);
	Mockito.when(bitfinexApiBroker.getOrderManager()).thenReturn(orderManager);
	Mockito.when(bitfinexApiBroker.getTradeManager()).thenReturn(tradeManager);

	return bitfinexApiBroker;
}
 
Example #17
Source File: ThrottledAsyncChecker.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * Register a callback to cache the result of a check.
 * @param target
 * @param lf
 */
private void addResultCachingCallback(
    Checkable<K, V> target, ListenableFuture<V> lf) {
  Futures.addCallback(lf, new FutureCallback<V>() {
    @Override
    public void onSuccess(@Nullable V result) {
      synchronized (ThrottledAsyncChecker.this) {
        checksInProgress.remove(target);
        completedChecks.put(target, new LastCheckResult<>(
            result, timer.monotonicNow()));
      }
    }

    @Override
    public void onFailure(@Nonnull Throwable t) {
      synchronized (ThrottledAsyncChecker.this) {
        checksInProgress.remove(target);
        completedChecks.put(target, new LastCheckResult<>(
            t, timer.monotonicNow()));
      }
    }
  }, MoreExecutors.directExecutor());
}
 
Example #18
Source File: NodeExecutionFallbackTest.java    From trickle with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  //noinspection unchecked
  graphBuilder = mock(GraphBuilder.class);
  when(graphBuilder.getFallback())
      .thenReturn(Optional.<AsyncFunction<Throwable, String>>absent());

  Map<Input<?>, Object> emptyMap = Collections.emptyMap();
  traverseState = new TraverseState(emptyMap, MoreExecutors.sameThreadExecutor(), true);

  List<? extends NodeInfo> currentNodeParameters = ImmutableList.of();

  currentNodeInfo = new FakeNodeInfo("the node", currentNodeParameters);
  List<ListenableFuture<?>> currentNodeValues = ImmutableList.of();

  currentCall = new TraverseState.FutureCallInformation(currentNodeInfo, currentNodeValues);
  currentCallInfo = new CallInfo(currentNodeInfo, NO_PARAMS);

  fallback = new NodeExecutionFallback<String>(graphBuilder, currentCall, traverseState);
}
 
Example #19
Source File: ClientCallImplTest.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@Test
public void advertisedEncodingsAreSent() {
  ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>(
      method,
      MoreExecutors.directExecutor(),
      baseCallOptions,
      provider,
      deadlineCancellationExecutor,
      channelCallTracer,
      false /* retryEnabled */)
          .setDecompressorRegistry(decompressorRegistry);

  call.start(callListener, new Metadata());

  ArgumentCaptor<Metadata> metadataCaptor = ArgumentCaptor.forClass(Metadata.class);
  verify(transport).newStream(eq(method), metadataCaptor.capture(), same(baseCallOptions));
  Metadata actual = metadataCaptor.getValue();

  // there should only be one.
  Set<String> acceptedEncodings = ImmutableSet.of(
      new String(actual.get(GrpcUtil.MESSAGE_ACCEPT_ENCODING_KEY), GrpcUtil.US_ASCII));
  assertEquals(decompressorRegistry.getAdvertisedMessageEncodings(), acceptedEncodings);
}
 
Example #20
Source File: WebRTCWrapper.java    From Conversations with GNU General Public License v3.0 6 votes vote down vote up
ListenableFuture<Void> setLocalDescription(final SessionDescription sessionDescription) {
    Log.d(EXTENDED_LOGGING_TAG, "setting local description:");
    for (final String line : sessionDescription.description.split(eu.siacs.conversations.xmpp.jingle.SessionDescription.LINE_DIVIDER)) {
        Log.d(EXTENDED_LOGGING_TAG, line);
    }
    return Futures.transformAsync(getPeerConnectionFuture(), peerConnection -> {
        final SettableFuture<Void> future = SettableFuture.create();
        peerConnection.setLocalDescription(new SetSdpObserver() {
            @Override
            public void onSetSuccess() {
                future.set(null);
            }

            @Override
            public void onSetFailure(final String s) {
                future.setException(new IllegalArgumentException("unable to set local session description: " + s));

            }
        }, sessionDescription);
        return future;
    }, MoreExecutors.directExecutor());
}
 
Example #21
Source File: BmpRibInWriter.java    From bgpcep with Eclipse Public License 1.0 6 votes vote down vote up
private synchronized void addRoutes(final MpReachNlri nlri, final org.opendaylight.yang.gen.v1.urn.opendaylight
        .params.xml.ns.yang.bgp.message.rev200120.path.attributes.Attributes attributes) {
    final TablesKey key = new TablesKey(nlri.getAfi(), nlri.getSafi());
    final TableContext ctx = this.tables.get(key);

    if (ctx == null) {
        LOG.debug("No table for {}, not accepting NLRI {}", key, nlri);
        return;
    }

    final DOMDataTreeWriteTransaction tx = this.chain.newWriteOnlyTransaction();
    ctx.writeRoutes(tx, nlri, attributes);
    LOG.trace("Write routes {}", nlri);
    tx.commit().addCallback(new FutureCallback<CommitInfo>() {
        @Override
        public void onSuccess(final CommitInfo result) {
            LOG.trace("Successful commit");
        }

        @Override
        public void onFailure(final Throwable trw) {
            LOG.error("Failed commit", trw);
        }
    }, MoreExecutors.directExecutor());
}
 
Example #22
Source File: CacheLoadingTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
public void testBulkLoadInterruptedException() {
  Exception e = new InterruptedException();
  CacheLoader<Object, Object> loader = exceptionLoader(e);
  LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
      .recordStats().executor(MoreExecutors.directExecutor()), bulkLoader(loader));
  CacheStats stats = cache.stats();
  assertEquals(0, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(0, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());

  try {
    cache.getAll(asList(new Object()));
    fail();
  } catch (ExecutionException expected) {
    assertSame(e, expected.getCause());
  }
  assertTrue(Thread.interrupted());
  stats = cache.stats();
  assertEquals(1, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(1, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());
}
 
Example #23
Source File: MobileServicePush.java    From azure-mobile-apps-android-client with Apache License 2.0 6 votes vote down vote up
/**
 * Registers the client for push notification using device {@link Installation}
 *
 * @param installation device installation in Azure Notification Hub (https://msdn.microsoft.com/en-us/library/azure/mt621153.aspx)
 * @return Future with registration information
 */
public ListenableFuture<Void> register(Installation installation) {
    final SettableFuture<Void> resultFuture = SettableFuture.create();

    ListenableFuture<Void> registerInternalFuture = createOrUpdateInstallation(installation);

    Futures.addCallback(registerInternalFuture, new FutureCallback<Void>() {
        @Override
        public void onFailure(Throwable exception) {
            resultFuture.setException(exception);
        }

        @Override
        public void onSuccess(Void v) {
            resultFuture.set(v);
        }
    }, MoreExecutors.directExecutor());

    return resultFuture;
}
 
Example #24
Source File: NullCacheTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
public void testGet() {
  Object computed = new Object();
  LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
      .executor(MoreExecutors.directExecutor())
      .maximumSize(0)
      .removalListener(listener),
      constantLoader(computed));

  Object key = new Object();
  assertSame(computed, cache.getUnchecked(key));
  RemovalNotification<Object, Object> notification = listener.remove();
  assertSame(key, notification.getKey());
  assertSame(computed, notification.getValue());
  assertSame(RemovalCause.SIZE, notification.getCause());
  assertTrue(listener.isEmpty());
  checkEmpty(cache);
}
 
Example #25
Source File: DefaultAgentConnectionStore.java    From bistoury with GNU General Public License v3.0 6 votes vote down vote up
@Override
public AgentConnection register(String agentId, int agentVersion, Channel channel) {
    DefaultAgentConnection agentConnection = new DefaultAgentConnection(agentId, agentVersion, channel);
    AgentConnection oldConnection = connections.get(agentId);
    if (!Objects.equals(oldConnection, agentConnection)) {
        oldConnection = connections.put(agentId, agentConnection);
        agentConnection.init();
        agentConnection.closeFuture().addListener(() -> connections.remove(agentId, agentConnection), MoreExecutors.directExecutor());
        if (oldConnection != null && !Objects.equals(oldConnection, agentConnection)) {
            oldConnection.close();
        }
        return agentConnection;
    } else {
        return oldConnection;
    }
}
 
Example #26
Source File: PathWatcherServiceImpl.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
WatchedDirectory(Path dir) throws IOException {
    logger.fine(() -> "Watching new directory " + dir);

    this.dir = dir;

    // Watch ourselves, unless we are the root dir
    if(dir.getParent() != null) {
        watch(dir, MoreExecutors.sameThreadExecutor(), this);
    }
}
 
Example #27
Source File: TargetGraphHashing.java    From buck with Apache License 2.0 5 votes vote down vote up
/**
 * @return the {@link HashCode} of all the node's dependencies as as a {@link ListenableFuture}
 *     of a list of {@link BuildTarget} and {@link HashCode} pairs.
 */
private ListenableFuture<List<Pair<BuildTarget, HashCode>>> getDepPairsFuture(
    TargetNode<?> node) {
  return Futures.allAsList(
      node.getParseDeps().stream()
          .map(
              dep ->
                  Futures.transform(
                      getHash(targetGraph.get(dep)),
                      depHash -> new Pair<>(dep, depHash),
                      MoreExecutors.directExecutor()))
          .collect(Collectors.toList()));
}
 
Example #28
Source File: OpenstackRouterManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    osRouterStore = new DistributedOpenstackRouterStore();
    TestUtils.setField(osRouterStore, "coreService", new TestCoreService());
    TestUtils.setField(osRouterStore, "storageService", new TestStorageService());
    TestUtils.setField(osRouterStore, "eventExecutor", MoreExecutors.newDirectExecutorService());
    osRouterStore.activate();

    target = new OpenstackRouterManager();
    target.coreService = new TestCoreService();
    target.osRouterStore = osRouterStore;
    target.addListener(testListener);
    target.activate();
}
 
Example #29
Source File: ClientCallImplTest.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
@Test
public void getAttributes() {
  ClientCallImpl<Void, Void> call = new ClientCallImpl<>(
      method, MoreExecutors.directExecutor(), baseCallOptions, provider,
      deadlineCancellationExecutor, channelCallTracer, /* retryEnabled= */ false);
  Attributes attrs =
      Attributes.newBuilder().set(Key.<String>create("fake key"), "fake value").build();
  when(stream.getAttributes()).thenReturn(attrs);

  assertNotEquals(attrs, call.getAttributes());

  call.start(callListener, new Metadata());

  assertEquals(attrs, call.getAttributes());
}
 
Example #30
Source File: DxToolchainFactory.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<DxToolchain> createToolchain(
    ToolchainProvider toolchainProvider,
    ToolchainCreationContext context,
    TargetConfiguration toolchainTargetConfiguration) {

  JavaBuckConfig javaConfig = context.getBuckConfig().getView(JavaBuckConfig.class);

  if (javaConfig.getDxThreadCount().isPresent()) {
    LOG.warn("java.dx_threads has been deprecated. Use dx.threads instead");
  }

  DxConfig dxConfig = new DxConfig(context.getBuckConfig());

  ListeningExecutorService dxExecutorService =
      MoreExecutors.listeningDecorator(
          Executors.newFixedThreadPool(
              Math.min(
                  dxConfig
                      .getDxThreadCount()
                      .orElse(
                          javaConfig
                              .getDxThreadCount()
                              .orElse(SmartDexingStep.determineOptimalThreadCount())),
                  dxConfig.getDxMaxThreadCount().orElse(Integer.MAX_VALUE)),
              new CommandThreadFactory(
                  "SmartDexing", GlobalStateManager.singleton().getThreadToCommandRegister())));

  return Optional.of(DxToolchain.of(dxExecutorService));
}