Java Code Examples for com.google.common.util.concurrent.SettableFuture.setException()

The following are Jave code examples for showing how to use setException() of the com.google.common.util.concurrent.SettableFuture class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: neoscada   File: Client.java   Source Code and License Vote up 6 votes
protected synchronized void handleOperationComplete ( final SettableFuture<Void> result, final ChannelFuture future )
{
    if ( this.connectFuture != result )
    {
        // this should never happen
        return;
    }

    this.connectFuture = null;

    try
    {
        future.get ();
        this.channel = future.channel ();

        fireConnected ( this.channel );
        result.set ( null );
    }
    catch ( final InterruptedException | ExecutionException e )
    {
        fireDisconnected ( e );
        result.setException ( e );
    }
}
 
Example 2
Project: graphouse   File: DirContentBatcher.java   Source Code and License Vote up 6 votes
@Override
public void run() {
    requestSemaphore.acquireUninterruptibly();
    try {
        currentBatch.getAndUpdate(batch -> (batch == this) ? null : batch); //Removing this batch from current
        Map<MetricDir, DirContent> dirsContent = metricSearch.loadDirsContent(requests.keySet());
        for (Map.Entry<MetricDir, DirContent> dirDirContentEntry : dirsContent.entrySet()) {
            requests.remove(dirDirContentEntry.getKey()).set(dirDirContentEntry.getValue());
        }
        if (!requests.isEmpty()) {
            log.error(requests.size() + " requests without data for dirs: " + requests.entrySet());
            throw new IllegalStateException("No data for dirs");
        }
    } catch (Exception e) {
        log.error("Failed to load content for dirs: " + requests.keySet(), e);

        for (SettableFuture<DirContent> settableFuture : requests.values()) {
            settableFuture.setException(e);
        }
    } finally {
        requestSemaphore.release();
    }
}
 
Example 3
Project: twister2   File: SharedFileSystemStateManager.java   Source Code and License Vote up 6 votes
@Override
@SuppressWarnings("unchecked")
protected <M extends Message> ListenableFuture<M> getNodeData(
    WatchCallback watcher, String path, Message.Builder builder) {
  final SettableFuture<M> future = SettableFuture.create();
  byte[] data = new byte[]{};
  if (FileUtils.isFileExists(path)) {
    data = FileUtils.readFromFile(path);
  }
  if (data.length == 0) {
    future.set(null);
    return future;
  }

  try {
    builder.mergeFrom(data);
    future.set((M) builder.build());
  } catch (InvalidProtocolBufferException e) {
    future.setException(new RuntimeException("Could not parse " + Message.Builder.class, e));
  }

  return future;
}
 
Example 4
Project: Elasticsearch   File: TableCreator.java   Source Code and License Vote up 6 votes
private void setException(SettableFuture<Long> result, Throwable e, CreateTableAnalyzedStatement statement) {
    e = Exceptions.unwrap(e);
    String message = e.getMessage();
    // sometimes message is empty
    if ("mapping [default]".equals(message) && e.getCause() != null) {
        // this is a generic mapping parse exception,
        // the cause has usually a better more detailed error message
        result.setException(e.getCause());
    } else if (statement.ifNotExists() &&
               (e instanceof IndexAlreadyExistsException
                || (e instanceof IndexTemplateAlreadyExistsException && statement.templateName() != null))) {
        result.set(null);
    } else {
        result.setException(e);
    }
}
 
Example 5
Project: Elasticsearch   File: ExecutionPhasesTask.java   Source Code and License Vote up 6 votes
@Override
public void start() {
    FluentIterable<NodeOperation> nodeOperations = FluentIterable.from(nodeOperationTrees)
        .transformAndConcat(new Function<NodeOperationTree, Iterable<? extends NodeOperation>>() {
            @Nullable
            @Override
            public Iterable<? extends NodeOperation> apply(NodeOperationTree input) {
                return input.nodeOperations();
            }
        });

    Map<String, Collection<NodeOperation>> operationByServer = NodeOperationGrouper.groupByServer(nodeOperations);
    InitializationTracker initializationTracker = new InitializationTracker(operationByServer.size());
    List<Tuple<ExecutionPhase, RowReceiver>> handlerPhases = createHandlerPhases(initializationTracker);
    try {
        setupContext(operationByServer, handlerPhases, initializationTracker);
    } catch (Throwable throwable) {
        for (SettableFuture<TaskResult> result : results) {
            result.setException(throwable);
        }
    }
}
 
Example 6
Project: Elasticsearch   File: ESJobContext.java   Source Code and License Vote up 5 votes
@Override
protected void innerClose(@Nullable Throwable t) {
    if (t != null) {
        for (SettableFuture<TaskResult> resultFuture : resultFutures) {
            if (!resultFuture.isDone()) {
                resultFuture.setException(t);
            }
        }
    }
}
 
Example 7
Project: Elasticsearch   File: UpsertByIdTask.java   Source Code and License Vote up 5 votes
private void executeUpsertRequest(final UpsertByIdNode.Item item, final SettableFuture<TaskResult> futureResult) {
    ShardId shardId;
    try {
        shardId = clusterService.operationRouting().indexShards(
                clusterService.state(),
                item.index(),
                Constants.DEFAULT_MAPPING_TYPE,
                item.id(),
                item.routing()
        ).shardId();
    } catch (IndexNotFoundException e) {
        if (PartitionName.isPartition(item.index())) {
            futureResult.set(TaskResult.ZERO);
            return;
        }
        throw e;
    }

    ShardUpsertRequest upsertRequest = new ShardUpsertRequest(
            shardId, node.updateColumns(), node.insertColumns(), item.routing(), jobId());
    upsertRequest.continueOnError(false);
    ShardUpsertRequest.Item requestItem = new ShardUpsertRequest.Item(
            item.id(), item.updateAssignments(), item.insertValues(), item.version());
    upsertRequest.add(0, requestItem);

    UpsertByIdContext upsertByIdContext = new UpsertByIdContext(
            node.executionPhaseId(), upsertRequest, item, futureResult, transportShardUpsertActionDelegate);
    createJobExecutionContext(upsertByIdContext);
    try {
        jobExecutionContext.start();
    } catch (Throwable throwable) {
        futureResult.setException(throwable);
    }
}
 
Example 8
Project: hashsdn-controller   File: NoOpTransactionContext.java   Source Code and License Vote up 5 votes
@Override
public <T> void executeRead(AbstractRead<T> readCmd, SettableFuture<T> proxyFuture) {
    LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
            readCmd.getPath());

    final Throwable t;
    if (failure instanceof NoShardLeaderException) {
        t = new DataStoreUnavailableException(failure.getMessage(), failure);
    } else {
        t = failure;
    }
    proxyFuture.setException(new ReadFailedException("Error executeRead " + readCmd.getClass().getSimpleName()
            + " for path " + readCmd.getPath(), t));
}
 
Example 9
Project: hashsdn-controller   File: RemoteTransactionContext.java   Source Code and License Vote up 5 votes
@Override
public <T> void executeRead(final AbstractRead<T> readCmd, final SettableFuture<T> returnFuture) {
    LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
            readCmd.getPath());

    // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
    // public API contract.

    acquireOperation();
    sendBatchedModifications();

    OnComplete<Object> onComplete = new OnComplete<Object>() {
        @Override
        public void onComplete(Throwable failure, Object response) throws Throwable {
            if (failure != null) {
                LOG.debug("Tx {} {} operation failed: {}", getIdentifier(), readCmd.getClass().getSimpleName(),
                        failure);

                returnFuture.setException(new ReadFailedException("Error checking "
                    + readCmd.getClass().getSimpleName() + " for path " + readCmd.getPath(), failure));
            } else {
                LOG.debug("Tx {} {} operation succeeded", getIdentifier(), readCmd.getClass().getSimpleName());
                readCmd.processResponse(response, returnFuture);
            }
        }
    };

    Future<Object> future = executeOperationAsync(readCmd.asVersion(getTransactionVersion()),
            actorContext.getOperationTimeout());

    future.onComplete(onComplete, actorContext.getClientDispatcher());
}
 
Example 10
Project: hashsdn-controller   File: ReadData.java   Source Code and License Vote up 5 votes
@Override
public void processResponse(Object readResponse, SettableFuture<Optional<NormalizedNode<?, ?>>> returnFuture) {
    if (ReadDataReply.isSerializedType(readResponse)) {
        ReadDataReply reply = ReadDataReply.fromSerializable(readResponse);
        returnFuture.set(Optional.<NormalizedNode<?, ?>>fromNullable(reply.getNormalizedNode()));
    } else {
        returnFuture.setException(new ReadFailedException("Invalid response reading data for path " + getPath()));
    }
}
 
Example 11
Project: hashsdn-controller   File: DataExists.java   Source Code and License Vote up 5 votes
@Override
public void processResponse(Object response, SettableFuture<Boolean> returnFuture) {
    if (DataExistsReply.isSerializedType(response)) {
        returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
    } else {
        returnFuture.setException(new ReadFailedException("Invalid response checking exists for path "
                + getPath()));
    }
}
 
Example 12
Project: TakinRPC   File: MajorityCollectorTest.java   Source Code and License Vote up 4 votes
@Test
public void testFireOnceMajorityFailed1() {

    SettableFuture<Boolean> f1 = SettableFuture.create();
    SettableFuture<Boolean> f2 = SettableFuture.create();

    List<ListenableFuture<Boolean>> responses = Lists.newArrayList(f1, f2, Futures.<Boolean> immediateFuture(Boolean.TRUE));

    ListenableFuture<Boolean> collector = majorityResponse(responses, Identity);

    f1.setException(new Exception());
    assertFalse(collector.isDone());

    f2.setException(new Exception());
    assertTrue(collector.isDone());

    assertFalse(Futures.getUnchecked(collector));

}
 
Example 13
Project: TakinRPC   File: MajorityCollectorTest.java   Source Code and License Vote up 4 votes
@Test
public void testFireOnceMajorityFailed() {

    SettableFuture<Boolean> f1 = SettableFuture.create();
    SettableFuture<Boolean> f2 = SettableFuture.create();
    SettableFuture<Boolean> f3 = SettableFuture.create();

    List<ListenableFuture<Boolean>> responses = Lists.newArrayList(f1, f2, f3, Futures.<Boolean> immediateFuture(Boolean.TRUE));

    ListenableFuture<Boolean> collector = majorityResponse(responses, Identity);

    f1.setException(new Exception());
    assertFalse(collector.isDone());

    f2.setException(new Exception());
    assertFalse(collector.isDone());

    f3.set(Boolean.TRUE);
    assertTrue(collector.isDone());

    assertTrue(Futures.getUnchecked(collector));

}
 
Example 14
Project: wall-t   File: ApiRequestController.java   Source Code and License Vote up 4 votes
@Override
public <T extends ApiResponse> ListenableFuture<T> sendRequest( final ApiVersion version, final String path, final Class<T> expectedType ) {
    final SettableFuture<T> apiResponseFuture = SettableFuture.create( );
    try {
        final ApiRequest request = ApiRequestBuilder.newRequest( )
                .to( _configuration.getServerUrl( ) )
                .forUser( _configuration.getCredentialsUser( ) )
                .withPassword( _configuration.getCredentialsPassword( ) )
                .request( path )
                .apiVersion( version )
                .build( );

        LOGGER.info( "<< REQUEST: to {}", request );

        final AsyncHttpClient.BoundRequestBuilder httpRequest = _httpClient
                .prepareGet( request.getURI( ) )
                .addHeader( HttpHeaders.ACCEPT, "application/json" );

        if ( !request.isGuestMode( ) ) {
            final Realm realm = new Realm.RealmBuilder( )
                    .setPrincipal( request.getUsername( ) )
                    .setPassword( request.getPassword( ) )
                    .setUsePreemptiveAuth( true )
                    .setScheme( Realm.AuthScheme.BASIC )
                    .build( );
            httpRequest.setRealm( realm );
        }

        if ( _configuration.isUseProxy( ) ) {
            // CODEREVIEW Let the user choose the protocol ?
            final ProxyServer proxyServer = new ProxyServer( ProxyServer.Protocol.HTTP, checkNotNull( _configuration.getProxyHost( ), "Proxy hostname is not defined" ), _configuration.getProxyPort( ), _configuration.getProxyCredentialsUser( ), _configuration.getProxyCredentialsPassword( ) );
            httpRequest.setProxyServer( proxyServer );
        }

        httpRequest.execute( new AsyncCompletionHandler<Void>( ) {
            @Override
            public void onThrowable( final Throwable t ) {
                super.onThrowable( t );
                apiResponseFuture.setException( t );
            }

            @Override
            public Void onCompleted( final Response response ) throws Exception {

                if ( response.getStatusCode( ) != 200 ) {
                    LOGGER.error( ">> RESPONSE: for {} has status code {}", request, response.getStatusCode( ) );
                    apiResponseFuture.setException( new ApiException( "Http status code is " + response.getStatusCode( ) + " when requesting uri: " + response.getUri( ) ) );
                    return null;
                }

                final String content = response.getResponseBody( Charsets.UTF_8.name( ) );
                LOGGER.debug( ">> RESPONSE: for {} has content: {}", request, content );

                final Gson gson = new GsonBuilder( ).create( );
                final T jsonResponse = gson.fromJson( content, expectedType );
                apiResponseFuture.set( jsonResponse );

                return null;
            }
        } );
    } catch ( Exception e ) {
        apiResponseFuture.setException( e );
    }

    return apiResponseFuture;
}
 
Example 15
Project: java-red   File: TestRedFuture.java   Source Code and License Vote up 4 votes
/**
 * Test the completion and callback invocation of {@link RedFutureHub}
 * optimistic union of adopted futures that later were failed
 */
@Test
public void testOptimisticAdoptPostResolveFailure() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    RedFutureHub hub = RedFuture.hub();
    OpenRedFuture future1 = RedFuture.future();
    OpenRedFuture future2 = RedFuture.future();
    OpenRedFuture future3 = RedFuture.future();
    OpenRedFutureOf<Object> futureOf1 = hub.provideFutureOf();
    OpenRedFutureOf<Object> futureOf2 = hub.provideFutureOf();
    SettableFuture<Object> settableFuture1 = SettableFuture.create();
    SettableFuture<Object> settableFuture2 = SettableFuture.create();
    SettableFuture<Object> settableFuture3 = SettableFuture.create();
    SettableFuture<Object> settableFuture4 = SettableFuture.create();
    SettableFuture<Object> settableFuture5 = SettableFuture.create();
    List<RedFuture> redFutureCollection = new LinkedList<>();
    redFutureCollection.add(future2);
    redFutureCollection.add(futureOf1);
    List<ListenableFuture> listenableFutureCollection = new LinkedList<>();
    listenableFutureCollection.add(settableFuture1);
    listenableFutureCollection.add(settableFuture2);
    hub.adoptFuture(future1);
    hub.adoptFutures(redFutureCollection);
    hub.adoptFutures(future3, futureOf2);
    hub.adoptListenableFuture(settableFuture3);
    hub.adoptListenableFutures(listenableFutureCollection);
    hub.adoptListenableFutures(settableFuture4, settableFuture5);
    RedFuture union = hub.uniteOptimistically();
    union.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    union.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    union.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    Assert.assertFalse(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
    settableFuture1.setException(new TestException());
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertTrue(reachedFailureBlock.get());
}
 
Example 16
Project: java-red   File: TestRedFuture.java   Source Code and License Vote up 4 votes
/**
 * Test the completion and callback invocation of {@link RedFutureHub}
 * optimistic union of provided and adopted futures that later were failed
 */
@Test
public void testOptimisticAdoptProvidePostResolveFailure() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    RedFutureHub hub = RedFuture.hub();
    OpenRedFuture future1 = RedFuture.future();
    OpenRedFuture future2 = RedFuture.future();
    OpenRedFuture future3 = RedFuture.future();
    hub.provideFuture();
    OpenRedFutureOf<Object> futureOf1 = hub.provideFutureOf();
    OpenRedFutureOf<Object> futureOf2 = hub.provideFutureOf();
    SettableFuture<Object> settableFuture1 = SettableFuture.create();
    SettableFuture<Object> settableFuture2 = SettableFuture.create();
    SettableFuture<Object> settableFuture3 = SettableFuture.create();
    SettableFuture<Object> settableFuture4 = SettableFuture.create();
    SettableFuture<Object> settableFuture5 = SettableFuture.create();
    List<RedFuture> redFutureCollection = new LinkedList<>();
    redFutureCollection.add(future2);
    redFutureCollection.add(futureOf1);
    List<ListenableFuture> listenableFutureCollection = new LinkedList<>();
    listenableFutureCollection.add(settableFuture1);
    listenableFutureCollection.add(settableFuture2);
    hub.adoptFuture(future1);
    hub.adoptFutures(redFutureCollection);
    hub.adoptFutures(future3, futureOf2);
    hub.adoptListenableFuture(settableFuture3);
    hub.adoptListenableFutures(listenableFutureCollection);
    hub.adoptListenableFutures(settableFuture4, settableFuture5);
    RedFuture union = hub.uniteOptimistically();
    union.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    union.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    union.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    Assert.assertFalse(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
    settableFuture1.setException(new TestException());
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertTrue(reachedFailureBlock.get());
}
 
Example 17
Project: java-red   File: TestRedFuture.java   Source Code and License Vote up 4 votes
/**
 * Test the completion and callback invocation of {@link RedFutureHub}
 * pessimistic union of provided and adopted futures that later were failed
 */
@Test
public void testPessimisticAdoptProvidePostResolveFailure() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    RedFutureHub hub = RedFuture.hub();
    OpenRedFuture future1 = RedFuture.future();
    OpenRedFuture future2 = RedFuture.future();
    OpenRedFuture future3 = RedFuture.future();
    OpenRedFuture future4 = hub.provideFuture();
    OpenRedFutureOf<Object> futureOf1 = hub.provideFutureOf();
    OpenRedFutureOf<Object> futureOf2 = hub.provideFutureOf();
    SettableFuture<Object> settableFuture1 = SettableFuture.create();
    SettableFuture<Object> settableFuture2 = SettableFuture.create();
    SettableFuture<Object> settableFuture3 = SettableFuture.create();
    SettableFuture<Object> settableFuture4 = SettableFuture.create();
    SettableFuture<Object> settableFuture5 = SettableFuture.create();
    List<RedFuture> redFutureCollection = new LinkedList<>();
    redFutureCollection.add(future2);
    redFutureCollection.add(futureOf1);
    List<ListenableFuture> listenableFutureCollection = new LinkedList<>();
    listenableFutureCollection.add(settableFuture1);
    listenableFutureCollection.add(settableFuture2);
    hub.adoptFuture(future1);
    hub.adoptFutures(redFutureCollection);
    hub.adoptFutures(future3, futureOf2);
    hub.adoptListenableFuture(settableFuture3);
    hub.adoptListenableFutures(listenableFutureCollection);
    hub.adoptListenableFutures(settableFuture4, settableFuture5);
    RedFuture union = hub.unitePessimistically();
    union.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    union.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    union.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    Assert.assertFalse(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
    future1.resolve();
    future2.resolve();
    future3.resolve();
    future4.resolve();
    futureOf1.resolve(new Object());
    futureOf2.resolve(new Object());
    settableFuture1.setException(new TestException());
    settableFuture2.set(new Object());
    settableFuture3.set(new Object());
    settableFuture4.set(new Object());
    settableFuture5.set(new Object());
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertTrue(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
}
 
Example 18
Project: hashsdn-controller   File: ThreePhaseCommitCohortProxy.java   Source Code and License Vote up 4 votes
private void finishCanCommit(final SettableFuture<Boolean> returnFuture) {
    LOG.debug("Tx {} finishCanCommit", transactionId);

    // For empty transactions return immediately
    if (cohorts.size() == 0) {
        LOG.debug("Tx {}: canCommit returning result true", transactionId);
        returnFuture.set(Boolean.TRUE);
        return;
    }

    commitOperationCallback = new TransactionRateLimitingCallback(actorContext);
    commitOperationCallback.run();

    final Iterator<CohortInfo> iterator = cohorts.iterator();

    final OnComplete<Object> onComplete = new OnComplete<Object>() {
        @Override
        public void onComplete(final Throwable failure, final Object response) {
            if (failure != null) {
                LOG.debug("Tx {}: a canCommit cohort Future failed", transactionId, failure);

                returnFuture.setException(failure);
                commitOperationCallback.failure();
                return;
            }

            // Only the first call to pause takes effect - subsequent calls before resume are no-ops. So
            // this means we'll only time the first transaction canCommit which should be fine.
            commitOperationCallback.pause();

            boolean result = true;
            if (CanCommitTransactionReply.isSerializedType(response)) {
                CanCommitTransactionReply reply = CanCommitTransactionReply.fromSerializable(response);

                LOG.debug("Tx {}: received {}", transactionId, response);

                if (!reply.getCanCommit()) {
                    result = false;
                }
            } else {
                LOG.error("Unexpected response type {}", response.getClass());
                returnFuture.setException(new IllegalArgumentException(
                        String.format("Unexpected response type %s", response.getClass())));
                return;
            }

            if (iterator.hasNext() && result) {
                sendCanCommitTransaction(iterator.next(), this);
            } else {
                LOG.debug("Tx {}: canCommit returning result: {}", transactionId, result);
                returnFuture.set(Boolean.valueOf(result));
            }

        }
    };

    sendCanCommitTransaction(iterator.next(), onComplete);
}
 
Example 19
Project: java-red   File: TestRedFuture.java   Source Code and License Vote up 4 votes
/**
 * Test the completion and callback invocation of {@link RedFutureHub}
 * cautious union of provided and adopted futures that later were failed
 */
@Test
public void testCautiousAdoptProvidePostResolveFailure() throws Throwable {
    AtomicBoolean reachedSuccessBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFailureBlock = new AtomicBoolean(false);
    AtomicBoolean reachedFinallyBlock = new AtomicBoolean(false);
    RedFutureHub hub = RedFuture.hub();
    OpenRedFuture future1 = RedFuture.future();
    OpenRedFuture future2 = RedFuture.future();
    OpenRedFuture future3 = RedFuture.future();
    OpenRedFuture future4 = hub.provideFuture();
    OpenRedFutureOf<Object> futureOf1 = hub.provideFutureOf();
    OpenRedFutureOf<Object> futureOf2 = hub.provideFutureOf();
    SettableFuture<Object> settableFuture1 = SettableFuture.create();
    SettableFuture<Object> settableFuture2 = SettableFuture.create();
    SettableFuture<Object> settableFuture3 = SettableFuture.create();
    SettableFuture<Object> settableFuture4 = SettableFuture.create();
    SettableFuture<Object> settableFuture5 = SettableFuture.create();
    List<RedFuture> redFutureCollection = new LinkedList<>();
    redFutureCollection.add(future2);
    redFutureCollection.add(futureOf1);
    List<ListenableFuture> listenableFutureCollection = new LinkedList<>();
    listenableFutureCollection.add(settableFuture1);
    listenableFutureCollection.add(settableFuture2);
    hub.adoptFuture(future1);
    hub.adoptFutures(redFutureCollection);
    hub.adoptFutures(future3, futureOf2);
    hub.adoptListenableFuture(settableFuture3);
    hub.adoptListenableFutures(listenableFutureCollection);
    hub.adoptListenableFutures(settableFuture4, settableFuture5);
    RedFuture union = hub.uniteCautiously();
    union.addSuccessCallback(() -> reachedSuccessBlock.set(true));
    union.addFailureCallback(throwable -> reachedFailureBlock.set(true));
    union.addFinallyCallback(() -> reachedFinallyBlock.set(true));
    future1.resolve();
    future2.resolve();
    future3.resolve();
    future4.resolve();
    futureOf1.resolve(new Object());
    futureOf2.resolve(new Object());
    settableFuture1.setException(new TestException());
    settableFuture2.set(new Object());
    settableFuture3.set(new Object());
    settableFuture4.set(new Object());
    Assert.assertFalse(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertFalse(reachedFailureBlock.get());
    settableFuture5.set(new Object());
    Assert.assertTrue(reachedFinallyBlock.get());
    Assert.assertFalse(reachedSuccessBlock.get());
    Assert.assertTrue(reachedFailureBlock.get());
}
 
Example 20
Project: hashsdn-controller   File: RemoteProxyTransaction.java   Source Code and License Vote up 4 votes
private void failFuture(final SettableFuture<?> future, final Response<?, ?> response) {
    future.setException(recordFailedResponse(response));
}