Search in sources :

Example 1 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project bazel by bazelbuild.

the class GlobCache method getGlobUnsorted.

@VisibleForTesting
protected List<String> getGlobUnsorted(String pattern, boolean excludeDirs) throws IOException, BadGlobException, InterruptedException {
    Future<List<Path>> futureResult = getGlobUnsortedAsync(pattern, excludeDirs);
    List<Path> globPaths = fromFuture(futureResult);
    // garbage collection of the GlobFuture and GlobVisitor objects.
    if (!(futureResult instanceof SettableFuture<?>)) {
        SettableFuture<List<Path>> completedFuture = SettableFuture.create();
        completedFuture.set(globPaths);
        globCache.put(Pair.of(pattern, excludeDirs), completedFuture);
    }
    List<String> result = Lists.newArrayListWithCapacity(globPaths.size());
    for (Path path : globPaths) {
        String relative = path.relativeTo(packageDirectory).getPathString();
        // really want to name the package directory.
        if (!relative.isEmpty()) {
            result.add(relative);
        }
    }
    return result;
}
Also used : Path(com.google.devtools.build.lib.vfs.Path) SettableFuture(com.google.common.util.concurrent.SettableFuture) ArrayList(java.util.ArrayList) List(java.util.List) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 2 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project apollo by ctripcorp.

the class ReleaseMessageScannerTest method testScanMessageAndNotifyMessageListener.

@Test
public void testScanMessageAndNotifyMessageListener() throws Exception {
    SettableFuture<ReleaseMessage> someListenerFuture = SettableFuture.create();
    ReleaseMessageListener someListener = (message, channel) -> someListenerFuture.set(message);
    releaseMessageScanner.addMessageListener(someListener);
    String someMessage = "someMessage";
    long someId = 100;
    ReleaseMessage someReleaseMessage = assembleReleaseMessage(someId, someMessage);
    when(releaseMessageRepository.findFirst500ByIdGreaterThanOrderByIdAsc(0L)).thenReturn(Lists.newArrayList(someReleaseMessage));
    ReleaseMessage someListenerMessage = someListenerFuture.get(5000, TimeUnit.MILLISECONDS);
    assertEquals(someMessage, someListenerMessage.getMessage());
    assertEquals(someId, someListenerMessage.getId());
    SettableFuture<ReleaseMessage> anotherListenerFuture = SettableFuture.create();
    ReleaseMessageListener anotherListener = (message, channel) -> anotherListenerFuture.set(message);
    releaseMessageScanner.addMessageListener(anotherListener);
    String anotherMessage = "anotherMessage";
    long anotherId = someId + 1;
    ReleaseMessage anotherReleaseMessage = assembleReleaseMessage(anotherId, anotherMessage);
    when(releaseMessageRepository.findFirst500ByIdGreaterThanOrderByIdAsc(someId)).thenReturn(Lists.newArrayList(anotherReleaseMessage));
    ReleaseMessage anotherListenerMessage = anotherListenerFuture.get(5000, TimeUnit.MILLISECONDS);
    assertEquals(anotherMessage, anotherListenerMessage.getMessage());
    assertEquals(anotherId, anotherListenerMessage.getId());
}
Also used : ReleaseMessageRepository(com.ctrip.framework.apollo.biz.repository.ReleaseMessageRepository) Mock(org.mockito.Mock) ReleaseMessage(com.ctrip.framework.apollo.biz.entity.ReleaseMessage) ReflectionTestUtils(org.springframework.test.util.ReflectionTestUtils) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) SettableFuture(com.google.common.util.concurrent.SettableFuture) TimeUnit(java.util.concurrent.TimeUnit) BizConfig(com.ctrip.framework.apollo.biz.config.BizConfig) Lists(com.google.common.collect.Lists) Environment(org.springframework.core.env.Environment) AbstractUnitTest(com.ctrip.framework.apollo.biz.AbstractUnitTest) Assert.assertEquals(org.junit.Assert.assertEquals) Before(org.junit.Before) ReleaseMessage(com.ctrip.framework.apollo.biz.entity.ReleaseMessage) Test(org.junit.Test) AbstractUnitTest(com.ctrip.framework.apollo.biz.AbstractUnitTest)

Example 3 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project bitsquare by bitsquare.

the class RequestDataHandler method requestData.

///////////////////////////////////////////////////////////////////////////////////////////
// API
///////////////////////////////////////////////////////////////////////////////////////////
public void requestData(NodeAddress nodeAddress, boolean isPreliminaryDataRequest) {
    Log.traceCall("nodeAddress=" + nodeAddress);
    peersNodeAddress = nodeAddress;
    if (!stopped) {
        GetDataRequest getDataRequest;
        // We collect the keys of the PersistedStoragePayload items so we exclude them in our request.
        // PersistedStoragePayload items don't get removed, so we don't have an issue with the case that
        // an object gets removed in between PreliminaryGetDataRequest and the GetUpdatedDataRequest and we would 
        // miss that event if we do not load the full set or use some delta handling.
        Set<byte[]> excludedKeys = dataStorage.getMap().entrySet().stream().filter(e -> e.getValue().getStoragePayload() instanceof PersistedStoragePayload).map(e -> e.getKey().bytes).collect(Collectors.toSet());
        if (isPreliminaryDataRequest)
            getDataRequest = new PreliminaryGetDataRequest(nonce, excludedKeys);
        else
            getDataRequest = new GetUpdatedDataRequest(networkNode.getNodeAddress(), nonce, excludedKeys);
        if (timeoutTimer == null) {
            timeoutTimer = UserThread.runAfter(() -> {
                // setup before sending to avoid race conditions
                if (!stopped) {
                    String errorMessage = "A timeout occurred at sending getDataRequest:" + getDataRequest + " on nodeAddress:" + nodeAddress;
                    log.debug(errorMessage + " / RequestDataHandler=" + RequestDataHandler.this);
                    handleFault(errorMessage, nodeAddress, CloseConnectionReason.SEND_MSG_TIMEOUT);
                } else {
                    log.trace("We have stopped already. We ignore that timeoutTimer.run call. " + "Might be caused by an previous networkNode.sendMessage.onFailure.");
                }
            }, TIME_OUT_SEC);
        }
        log.debug("We send a {} to peer {}. ", getDataRequest.getClass().getSimpleName(), nodeAddress);
        networkNode.addMessageListener(this);
        SettableFuture<Connection> future = networkNode.sendMessage(nodeAddress, getDataRequest);
        Futures.addCallback(future, new FutureCallback<Connection>() {

            @Override
            public void onSuccess(Connection connection) {
                if (!stopped) {
                    RequestDataHandler.this.connection = connection;
                    log.trace("Send " + getDataRequest + " to " + nodeAddress + " succeeded.");
                } else {
                    log.trace("We have stopped already. We ignore that networkNode.sendMessage.onSuccess call." + "Might be caused by an previous timeout.");
                }
            }

            @Override
            public void onFailure(@NotNull Throwable throwable) {
                if (!stopped) {
                    String errorMessage = "Sending getDataRequest to " + nodeAddress + " failed. That is expected if the peer is offline.\n\t" + "getDataRequest=" + getDataRequest + "." + "\n\tException=" + throwable.getMessage();
                    log.debug(errorMessage);
                    handleFault(errorMessage, nodeAddress, CloseConnectionReason.SEND_MSG_FAILURE);
                } else {
                    log.trace("We have stopped already. We ignore that networkNode.sendMessage.onFailure call. " + "Might be caused by an previous timeout.");
                }
            }
        });
    } else {
        log.warn("We have stopped already. We ignore that requestData call.");
    }
}
Also used : java.util(java.util) ProtectedStorageEntry(io.bitsquare.p2p.storage.storageentry.ProtectedStorageEntry) LoggerFactory(org.slf4j.LoggerFactory) Connection(io.bitsquare.p2p.network.Connection) Timer(io.bitsquare.common.Timer) SettableFuture(com.google.common.util.concurrent.SettableFuture) GetDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetDataRequest) PreliminaryGetDataRequest(io.bitsquare.p2p.peers.getdata.messages.PreliminaryGetDataRequest) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) PersistedStoragePayload(io.bitsquare.p2p.storage.payload.PersistedStoragePayload) PeerManager(io.bitsquare.p2p.peers.PeerManager) Log(io.bitsquare.app.Log) P2PDataStorage(io.bitsquare.p2p.storage.P2PDataStorage) GetUpdatedDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetUpdatedDataRequest) Logger(org.slf4j.Logger) GetDataResponse(io.bitsquare.p2p.peers.getdata.messages.GetDataResponse) UserThread(io.bitsquare.common.UserThread) Message(io.bitsquare.p2p.Message) NodeAddress(io.bitsquare.p2p.NodeAddress) StoragePayload(io.bitsquare.p2p.storage.payload.StoragePayload) Collectors(java.util.stream.Collectors) FutureCallback(com.google.common.util.concurrent.FutureCallback) TimeUnit(java.util.concurrent.TimeUnit) Nullable(org.jetbrains.annotations.Nullable) Futures(com.google.common.util.concurrent.Futures) LazyProcessedStoragePayload(io.bitsquare.p2p.storage.payload.LazyProcessedStoragePayload) MessageListener(io.bitsquare.p2p.network.MessageListener) CloseConnectionReason(io.bitsquare.p2p.network.CloseConnectionReason) NotNull(org.jetbrains.annotations.NotNull) NetworkNode(io.bitsquare.p2p.network.NetworkNode) PreliminaryGetDataRequest(io.bitsquare.p2p.peers.getdata.messages.PreliminaryGetDataRequest) PersistedStoragePayload(io.bitsquare.p2p.storage.payload.PersistedStoragePayload) Connection(io.bitsquare.p2p.network.Connection) GetDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetDataRequest) PreliminaryGetDataRequest(io.bitsquare.p2p.peers.getdata.messages.PreliminaryGetDataRequest) GetUpdatedDataRequest(io.bitsquare.p2p.peers.getdata.messages.GetUpdatedDataRequest)

Example 4 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project jackrabbit-oak by apache.

the class CacheTest method testRefresh.

@Test
public void testRefresh() throws ExecutionException {
    CacheLIRS<Integer, String> cache = new CacheLIRS.Builder<Integer, String>().maximumWeight(100).weigher(new Weigher<Integer, String>() {

        @Override
        public int weigh(Integer key, String value) {
            return key + value.length();
        }
    }).build(new CacheLoader<Integer, String>() {

        @Override
        public String load(Integer key) throws Exception {
            if (key < 0 || key >= 100) {
                throw new Exception("Out of range");
            }
            return "n" + key;
        }

        @Override
        public ListenableFuture<String> reload(Integer key, String oldValue) {
            assertTrue(oldValue != null);
            SettableFuture<String> f = SettableFuture.create();
            f.set(oldValue);
            return f;
        }
    });
    assertEquals("n1", cache.get(1));
    cache.refresh(1);
    cache.refresh(2);
    try {
        cache.get(-1);
        fail();
    } catch (Exception e) {
    // expected
    }
    // expected to log a warning, but not fail
    cache.refresh(-1);
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) Weigher(com.google.common.cache.Weigher) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) ExecutionException(java.util.concurrent.ExecutionException) Test(org.junit.Test)

Example 5 with SettableFuture

use of com.google.common.util.concurrent.SettableFuture in project jackrabbit-oak by apache.

the class UploadStagingCacheTest method testPutMoveFileError.

/**
 * Error in putting file to stage.
 * @throws Exception
 */
@Test
public void testPutMoveFileError() throws Exception {
    File empty = new File(folder.getRoot(), String.valueOf(System.currentTimeMillis()));
    assertFalse(empty.exists());
    Optional<SettableFuture<Integer>> future = stagingCache.put(ID_PREFIX + 0, empty);
    // assert no file
    assertFalse(future.isPresent());
    assertEquals(1, stagingCache.getStats().getMissCount());
    assertCacheStats(stagingCache, 0, 0, 0, 1);
}
Also used : SettableFuture(com.google.common.util.concurrent.SettableFuture) File(java.io.File) Test(org.junit.Test)

Aggregations

SettableFuture (com.google.common.util.concurrent.SettableFuture)43 Test (org.junit.Test)23 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)14 List (java.util.List)14 ArrayList (java.util.ArrayList)13 File (java.io.File)12 Futures (com.google.common.util.concurrent.Futures)9 IOException (java.io.IOException)9 ImmutableMap (com.google.common.collect.ImmutableMap)8 TimeUnit (java.util.concurrent.TimeUnit)8 FutureCallback (com.google.common.util.concurrent.FutureCallback)7 ExecutionException (java.util.concurrent.ExecutionException)7 CountDownLatch (java.util.concurrent.CountDownLatch)6 Throwables (com.google.common.base.Throwables)5 ImmutableList (com.google.common.collect.ImmutableList)5 Before (org.junit.Before)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 Collections (java.util.Collections)4 Executors (java.util.concurrent.Executors)4