Java Code Examples for com.google.common.util.concurrent.FutureCallback

The following are top voted examples for showing how to use com.google.common.util.concurrent.FutureCallback. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: hashsdn-controller   File: BindingDOMTransactionChainAdapter.java   Source Code and License 7 votes vote down vote up
private CheckedFuture<Void, TransactionCommitFailedException> listenForFailure(
        final WriteTransaction tx, final CheckedFuture<Void, TransactionCommitFailedException> future) {
    Futures.addCallback(future, new FutureCallback<Void>() {
        @Override
        public void onFailure(final Throwable t) {
            failTransactionChain(tx,t);
        }

        @Override
        public void onSuccess(final Void result) {
            // Intentionally NOOP
        }
    });

    return future;
}
 
Example 2
Project: hashsdn-controller   File: DOMDataBrokerTransactionChainImpl.java   Source Code and License 7 votes vote down vote up
@Override
public CheckedFuture<Void, TransactionCommitFailedException> submit(
        final DOMDataWriteTransaction transaction, final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {
    checkNotFailed();
    checkNotClosed();

    final CheckedFuture<Void, TransactionCommitFailedException> ret = broker.submit(transaction, cohorts);

    COUNTER_UPDATER.incrementAndGet(this);
    Futures.addCallback(ret, new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            transactionCompleted();
        }

        @Override
        public void onFailure(final Throwable t) {
            transactionFailed(transaction, t);
        }
    });

    return ret;
}
 
Example 3
Project: hashsdn-controller   File: SimpleShardDataTreeCohortTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testPreCommitWithReportedFailure() throws Exception {
    canCommitSuccess();

    final Exception cause = new IllegalArgumentException("mock");
    cohort.reportFailure(cause);

    @SuppressWarnings("unchecked")
    final FutureCallback<DataTreeCandidate> callback = mock(FutureCallback.class);
    cohort.preCommit(callback);

    verify(callback).onFailure(cause);
    verifyNoMoreInteractions(callback);

    verify(mockShardDataTree, never()).startPreCommit(cohort);
}
 
Example 4
Project: azure-documentdb-rxjava   File: SyncBulkInsertBenchmark.java   Source Code and License 6 votes vote down vote up
@Override
protected void createDocument(Document docToInsert, CallBack<ResourceResponse<Document>> onSuccess,
        CallBack<Throwable> onFailure) {

    Callable<ResourceResponse<Document>> documentCreateCallable = new Callable<ResourceResponse<Document>>() {

        @Override
        public ResourceResponse<Document> call() throws Exception {
            return documentClient.createDocument(collection.getSelfLink(), docToInsert, null, true);
        }
    };
    ListenableFuture<ResourceResponse<Document>> listenableFuture = this.executor.submit(documentCreateCallable);

    Futures.addCallback(listenableFuture, new FutureCallback<ResourceResponse<Document>>() {

        @Override
        public void onFailure(Throwable t) {
            onFailure.invoke(t);
        }

        @Override
        public void onSuccess(ResourceResponse<Document> resourceResponse) {
            onSuccess.invoke(resourceResponse);
        }
    } );
}
 
Example 5
Project: TakinRPC   File: Leader.java   Source Code and License 6 votes vote down vote up
/**
 * Notify the {@link ReplicaManager} to send an update the next possible time it can
 *
 * @return futures with the result of the update
 */
@Nonnull
@VisibleForTesting
List<ListenableFuture<AppendEntriesResponse>> sendRequests(final RaftStateContext ctx) {
    List<ListenableFuture<AppendEntriesResponse>> responses = newArrayList();
    for (ReplicaManager replicaManager : managers.values()) {
        ListenableFuture<AppendEntriesResponse> response = replicaManager.requestUpdate();
        responses.add(response);
        Futures.addCallback(response, new FutureCallback<AppendEntriesResponse>() {
            @Override
            public void onSuccess(@Nullable AppendEntriesResponse result) {
                updateCommitted();
                checkTermOnResponse(ctx, result);
            }

            @Override
            public void onFailure(Throwable t) {
            }

        });

    }
    return responses;
}
 
Example 6
Project: hashsdn-controller   File: ShardProxyTransaction.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<Boolean> validate() {
    LOG.debug("Validating transaction for shard {}", shardRoot);

    checkTransactionReadied();
    final List<ListenableFuture<Boolean>> futures =
            cohorts.stream().map(DOMStoreThreePhaseCommitCohort::canCommit).collect(Collectors.toList());
    final SettableFuture<Boolean> ret = SettableFuture.create();

    Futures.addCallback(Futures.allAsList(futures), new FutureCallback<List<Boolean>>() {
        @Override
        public void onSuccess(final List<Boolean> result) {
            ret.set(true);
        }

        @Override
        public void onFailure(final Throwable throwable) {
            ret.setException(throwable);
        }
    }, MoreExecutors.directExecutor());

    return ret;
}
 
Example 7
Project: TakinRPC   File: Candidate.java   Source Code and License 6 votes vote down vote up
@VisibleForTesting
List<ListenableFuture<RequestVoteResponse>> sendRequests(final RaftStateContext ctx) {

    RequestVote request = RequestVote.newBuilder().setTerm(log.currentTerm()).setCandidateId(log.self().toString()).setLastLogIndex(log.lastLogIndex()).setLastLogTerm(log.lastLogTerm()).build();

    List<ListenableFuture<RequestVoteResponse>> responses = Lists.newArrayList();
    for (Replica replica : log.members()) {
        ListenableFuture<RequestVoteResponse> response = client.requestVote(replica, request);
        Futures.addCallback(response, new FutureCallback<RequestVoteResponse>() {
            @Override
            public void onSuccess(@Nullable RequestVoteResponse result) {
                checkTermOnResponse(ctx, result);
            }

            @Override
            public void onFailure(Throwable t) {
            }
        });
        responses.add(response);
    }

    return responses;
}
 
Example 8
Project: drift   File: DriftInvocationHandler.java   Source Code and License 6 votes vote down vote up
private static ListenableFuture<Object> unwrapUserException(ListenableFuture<Object> future)
{
    SettableFuture<Object> result = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<Object>()
    {
        @Override
        public void onSuccess(Object value)
        {
            result.set(value);
        }

        @Override
        public void onFailure(Throwable t)
        {
            result.setException(unwrapUserException(t));
        }
    });
    return result;
}
 
Example 9
Project: hashsdn-controller   File: SimpleShardDataTreeCohortTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testPreCommitWithIllegalArgumentEx() throws Exception {
    canCommitSuccess();

    final Exception cause = new IllegalArgumentException("mock");
    doAnswer(invocation -> {
        invocation.getArgumentAt(0, SimpleShardDataTreeCohort.class).failedPreCommit(cause);
        return null;
    }).when(mockShardDataTree).startPreCommit(cohort);

    @SuppressWarnings("unchecked")
    final FutureCallback<DataTreeCandidate> callback = mock(FutureCallback.class);
    cohort.preCommit(callback);

    verify(callback).onFailure(cause);
    verifyNoMoreInteractions(callback);

    verify(mockUserCohorts).abort();
}
 
Example 10
Project: hashsdn-controller   File: EventSourceTopology.java   Source Code and License 6 votes vote down vote up
private <T extends DataObject>  void deleteData(final LogicalDatastoreType store, final InstanceIdentifier<T> path){
    final WriteTransaction tx = getDataBroker().newWriteOnlyTransaction();
    tx.delete(OPERATIONAL, path);
    Futures.addCallback( tx.submit(), new FutureCallback<Void>(){

        @Override
        public void onSuccess(final Void result) {
            LOG.trace("Data has deleted from datastore {} {}", store, path);
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.error("Can not delete data from datastore [store: {}] [path: {}] [exception: {}]",store,path, t);
        }

    });
}
 
Example 11
Project: wall-t   File: ApiController.java   Source Code and License 6 votes vote down vote up
private FutureCallback<Build> registerBuildStatus( final BuildTypeData buildType, final int buildId ) {
    return new FutureCallback<Build>( ) {
        @Override
        public void onSuccess( final Build result ) {
            buildType.registerBuild( _buildProvider.get( getApiVersion( ) ).apply( result ) );
            _eventBus.post( buildType );

            final Optional<ProjectData> project = _projectManager.getProject( buildType.getProjectId( ) );
            if ( project.isPresent( ) ) {
                _eventBus.post( project.get( ) );
            }
        }

        @Override
        public void onFailure( final Throwable t ) {
            LOGGER.error( "Error during loading full information for build with id " + buildId + ", build type: " + buildType.getId( ), t );

            final Integer errorCount = _buildRequestErrorCounter.getIfPresent( buildId );
            final int newErrorCount = errorCount == null ? 1 : errorCount + 1;
            _buildRequestErrorCounter.put( buildId, newErrorCount );
            if ( newErrorCount >= ERROR_COUNT_BEFORE_IGNORING )
                LOGGER.info( "Build {} is now temporary ignored for about {} minutes due to {} failures.", buildId, IGNORING_TIME_IN_MINUTES, ERROR_COUNT_BEFORE_IGNORING );
        }
    };
}
 
Example 12
Project: iotplatform   File: CassandraBaseTimeseriesDao.java   Source Code and License 6 votes vote down vote up
private ListenableFuture<List<TsKvEntry>> findAllAsyncWithLimit(EntityId entityId, TsKvQuery query) {
    long minPartition = toPartitionTs(query.getStartTs());
    long maxPartition = toPartitionTs(query.getEndTs());

    ResultSetFuture partitionsFuture = fetchPartitions(entityId, query.getKey(), minPartition, maxPartition);

    final SimpleListenableFuture<List<TsKvEntry>> resultFuture = new SimpleListenableFuture<>();
    final ListenableFuture<List<Long>> partitionsListFuture = Futures.transform(partitionsFuture, getPartitionsArrayFunction(), readResultsProcessingExecutor);

    Futures.addCallback(partitionsListFuture, new FutureCallback<List<Long>>() {
        @Override
        public void onSuccess(@Nullable List<Long> partitions) {
            TsKvQueryCursor cursor = new TsKvQueryCursor(entityId.getEntityType().name(), entityId.getId(), query, partitions);
            findAllAsyncSequentiallyWithLimit(cursor, resultFuture);
        }

        @Override
        public void onFailure(Throwable t) {
            log.error("[{}][{}] Failed to fetch partitions for interval {}-{}", entityId.getEntityType().name(), entityId.getId(), minPartition, maxPartition, t);
        }
    }, readResultsProcessingExecutor);

    return resultFuture;
}
 
Example 13
Project: Elasticsearch   File: CountContext.java   Source Code and License 6 votes vote down vote up
@Override
public void innerStart() {
    try {
        countFuture = countOperation.count(indexShardMap, whereClause);
    } catch (IOException | InterruptedException e) {
        throw Throwables.propagate(e);
    }
    Futures.addCallback(countFuture, new FutureCallback<Long>() {
        @Override
        public void onSuccess(@Nullable Long result) {
            rowReceiver.setNextRow(new Row1(result));
            close();
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            close(t);
        }
    });
}
 
Example 14
Project: Elasticsearch   File: AbstractChainedTask.java   Source Code and License 6 votes vote down vote up
@Override
public void start() {
    if (!this.upstreamResult.isEmpty()) {
        Futures.addCallback(Futures.allAsList(this.upstreamResult), new FutureCallback<List<TaskResult>>() {
            @Override
            public void onSuccess(@Nullable List<TaskResult> result) {
                doStart(result);
            }

            @Override
            public void onFailure(@Nonnull Throwable t) {
                result.setException(t);
            }
        });
    } else {
        doStart(ImmutableList.<TaskResult>of());
    }
}
 
Example 15
Project: Elasticsearch   File: DDLTask.java   Source Code and License 6 votes vote down vote up
@Override
public void start() {
    ListenableFuture<Long> future = ddlStatementDispatcher.dispatch(analyzedStatement, jobId(), this);
    Futures.addCallback(future, new FutureCallback<Long>() {
        @Override
        public void onSuccess(Long rowCount) {
            if (rowCount == null) {
                result.set(TaskResult.ROW_COUNT_UNKNOWN);
            } else {
                result.set(new RowCountResult(rowCount));
            }
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            result.setException(t);
        }
    });
}
 
Example 16
Project: hadoop   File: QuorumCall.java   Source Code and License 6 votes vote down vote up
static <KEY, RESULT> QuorumCall<KEY, RESULT> create(
    Map<KEY, ? extends ListenableFuture<RESULT>> calls) {
  final QuorumCall<KEY, RESULT> qr = new QuorumCall<KEY, RESULT>();
  for (final Entry<KEY, ? extends ListenableFuture<RESULT>> e : calls.entrySet()) {
    Preconditions.checkArgument(e.getValue() != null,
        "null future for key: " + e.getKey());
    Futures.addCallback(e.getValue(), new FutureCallback<RESULT>() {
      @Override
      public void onFailure(Throwable t) {
        qr.addException(e.getKey(), t);
      }

      @Override
      public void onSuccess(RESULT res) {
        qr.addResult(e.getKey(), res);
      }
    });
  }
  return qr;
}
 
Example 17
Project: grpc-java-contrib   File: GuavaLFReturnValueHandler.java   Source Code and License 6 votes vote down vote up
@Override
public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer,
                              NativeWebRequest webRequest) throws Exception {
    if (returnValue == null) {
        mavContainer.setRequestHandled(true);
        return;
    }

    final DeferredResult<Object> deferredResult = new DeferredResult<>();
    @SuppressWarnings("unchecked")
    ListenableFuture<Object> futureValue = (ListenableFuture<Object>) returnValue;
    Futures.addCallback(futureValue, new FutureCallback<Object>() {
        @Override
        public void onSuccess(@Nullable Object result) {
            deferredResult.setResult(result);
        }

        @Override
        public void onFailure(Throwable ex) {
            deferredResult.setErrorResult(ex);
        }
    });

    startDeferredResultProcessing(mavContainer, webRequest, deferredResult);
}
 
Example 18
Project: hashsdn-controller   File: EventSourceTopology.java   Source Code and License 6 votes vote down vote up
private <T extends DataObject>  void putData(final LogicalDatastoreType store,
                                             final InstanceIdentifier<T> path,
                                             final T data){

    final WriteTransaction tx = getDataBroker().newWriteOnlyTransaction();
    tx.put(store, path, data, true);
    Futures.addCallback( tx.submit(), new FutureCallback<Void>(){

        @Override
        public void onSuccess(final Void result) {
            LOG.trace("Data has put into datastore {} {}", store, path);
        }

        @Override
        public void onFailure(final Throwable t) {
            LOG.error("Can not put data into datastore [store: {}] [path: {}] [exception: {}]",store,path, t);
        }
    });

}
 
Example 19
Project: okwallet   File: PaymentChannelClientState.java   Source Code and License 6 votes vote down vote up
protected void watchCloseConfirmations() {
    // When we see the close transaction get enough confirmations, we can just delete the record
    // of this channel along with the refund tx from the wallet, because we're not going to need
    // any of that any more.
    final TransactionConfidence confidence = storedChannel.close.getConfidence();
    int numConfirms = Context.get().getEventHorizon();
    ListenableFuture<TransactionConfidence> future = confidence.getDepthFuture(numConfirms, Threading.SAME_THREAD);
    Futures.addCallback(future, new FutureCallback<TransactionConfidence>() {
        @Override
        public void onSuccess(TransactionConfidence result) {
            deleteChannelFromWallet();
        }

        @Override
        public void onFailure(Throwable t) {
            Throwables.propagate(t);
        }
    });
}
 
Example 20
Project: okwallet   File: Peer.java   Source Code and License 6 votes vote down vote up
/**
 * <p>Returns a future that wraps a list of all transactions that the given transaction depends on, recursively.
 * Only transactions in peers memory pools are included; the recursion stops at transactions that are in the
 * current best chain. So it doesn't make much sense to provide a tx that was already in the best chain and
 * a precondition checks this.</p>
 *
 * <p>For example, if tx has 2 inputs that connect to transactions A and B, and transaction B is unconfirmed and
 * has one input connecting to transaction C that is unconfirmed, and transaction C connects to transaction D
 * that is in the chain, then this method will return either {B, C} or {C, B}. No ordering is guaranteed.</p>
 *
 * <p>This method is useful for apps that want to learn about how long an unconfirmed transaction might take
 * to confirm, by checking for unexpectedly time locked transactions, unusually deep dependency trees or fee-paying
 * transactions that depend on unconfirmed free transactions.</p>
 *
 * <p>Note that dependencies downloaded this way will not trigger the onTransaction method of event listeners.</p>
 */
public ListenableFuture<List<Transaction>> downloadDependencies(Transaction tx) {
    TransactionConfidence.ConfidenceType txConfidence = tx.getConfidence().getConfidenceType();
    Preconditions.checkArgument(txConfidence != TransactionConfidence.ConfidenceType.BUILDING);
    log.info("{}: Downloading dependencies of {}", getAddress(), tx.getHashAsString());
    final LinkedList<Transaction> results = new LinkedList<>();
    // future will be invoked when the entire dependency tree has been walked and the results compiled.
    final ListenableFuture<Object> future = downloadDependenciesInternal(vDownloadTxDependencyDepth, 0, tx,
            new Object(), results);
    final SettableFuture<List<Transaction>> resultFuture = SettableFuture.create();
    Futures.addCallback(future, new FutureCallback<Object>() {
        @Override
        public void onSuccess(Object ignored) {
            resultFuture.set(results);
        }

        @Override
        public void onFailure(Throwable throwable) {
            resultFuture.setException(throwable);
        }
    });
    return resultFuture;
}
 
Example 21
Project: java-red   File: BaseOpenRedFuture.java   Source Code and License 6 votes vote down vote up
/**
 * Generates a guava {@link FutureCallback} to attach to a {@link ListenableFuture} with given
 * success and failure callbacks. Wraps the invocations such that if an uncaught runtime exception
 * is thrown from a callback invocation, a warning is logged. Such a case must be seriously considered
 * in an asynchronous system, as it can cause the system to freeze if some pending propagation has not
 * reached before the exception was thrown.
 * @param onSuccess callback on be invoked on success, or null to skip success event.
 * @param onFailure callback on be invoked on failure, or null to skip failure event.
 * @param <K>       type of the returned {@link FutureCallback}
 * @return a guava {@link FutureCallback} to attach to a {@link ListenableFuture}
 */
@SuppressWarnings("WeakerAccess")
protected <K> FutureCallback<K> safeCallback(Callback<K> onSuccess, Callback<Throwable> onFailure) {
    return new FutureCallback<K>() {

        @Override
        public void onSuccess(K t) {
            call(onSuccess, t);
        }

        @Override
        public void onFailure(Throwable throwable) {
            call(onFailure, throwable);
        }

    };
}
 
Example 22
Project: yadaframework   File: YadaJobScheduler.java   Source Code and License 6 votes vote down vote up
/**
 * Run the job now.
 * The job must set its own state to DISABLED or PAUSED when failed, otherwise it is set to ACTIVE.
 * @param yadaJob
 * @return
 */
public void runJob(Long yadaJobId) {
	log.debug("Running job id {}", yadaJobId);
	YadaJob toRun = yadaJobRepository.findOne(yadaJobId);
	if (toRun==null) {
		log.info("Job not found when trying to run it, id={}", toRun);
		return;
	}
	yadaJobRepository.internalSetRunning(yadaJobId, YadaJobState.RUNNING.toId(), YadaJobState.ACTIVE.toId());
	final YadaJob wiredYadaJob = (YadaJob) yadaUtil.autowire(toRun); // YadaJob instances can have @Autowire fields
	ListenableFuture<Void> jobHandle = jobScheduler.submit(wiredYadaJob);
	jobHandles.put(yadaJobId, jobHandle);
	Futures.addCallback(jobHandle, new FutureCallback<Void>() {
		// The callback is run in executor
		public void onSuccess(Void result) {
			// result is always null
			jobHandles.remove(yadaJobId);
			yadaJobSchedulerDao.internalJobSuccessful(wiredYadaJob);
		}
		public void onFailure(Throwable thrown) {
			jobHandles.remove(yadaJobId);
			yadaJobSchedulerDao.internalJobFailed(wiredYadaJob, thrown);
		}
	},  MoreExecutors.directExecutor());
}
 
Example 23
Project: hashsdn-controller   File: ShardedDOMDataBrokerDelegatingReadWriteTransaction.java   Source Code and License 6 votes vote down vote up
@Override
public CheckedFuture<Optional<NormalizedNode<?, ?>>, ReadFailedException> read(final LogicalDatastoreType store,
                                                                               final YangInstanceIdentifier path) {
    checkState(root != null, "A modify operation (put, merge or delete) must be performed prior to a read operation");
    final SettableFuture<Optional<NormalizedNode<?, ?>>> readResult = SettableFuture.create();
    final Queue<Modification> currentHistory = Lists.newLinkedList(modificationHistoryMap.get(store));
    Futures.addCallback(initialReadMap.get(store), new FutureCallback<Optional<NormalizedNode<?, ?>>>() {
        @Override
        public void onSuccess(@Nullable final Optional<NormalizedNode<?, ?>> result) {
            final DataTreeModification mod = snapshotMap.get(store).newModification();
            if (result.isPresent()) {
                mod.write(path, result.get());
            }
            applyModificationHistoryToSnapshot(mod, currentHistory);
            readResult.set(mod.readNode(path));
        }

        @Override
        public void onFailure(final Throwable t) {
            readResult.setException(t);
        }
    }, MoreExecutors.directExecutor());

    return Futures.makeChecked(readResult, ReadFailedException.MAPPER);
}
 
Example 24
Project: hashsdn-controller   File: PingPongTransactionChain.java   Source Code and License 6 votes vote down vote up
/**
 * Process a ready transaction. The caller needs to ensure that
 * each transaction is seen only once by this method.
 *
 * @param tx Transaction which needs processing.
 */
@GuardedBy("this")
private void processTransaction(@Nonnull final PingPongTransaction tx) {
    if (failed) {
        LOG.debug("Cancelling transaction {}", tx);
        tx.getTransaction().cancel();
        return;
    }

    LOG.debug("Submitting transaction {}", tx);
    if (!INFLIGHT_UPDATER.compareAndSet(this, null, tx)) {
        LOG.warn("Submitting transaction {} while {} is still running", tx, inflightTx);
    }

    Futures.addCallback(tx.getTransaction().submit(), new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            transactionSuccessful(tx, result);
        }

        @Override
        public void onFailure(final Throwable t) {
            transactionFailed(tx, t);
        }
    }, MoreExecutors.directExecutor());
}
 
Example 25
Project: hashsdn-controller   File: ShardCommitCoordinator.java   Source Code and License 6 votes vote down vote up
private void handleCanCommit(final CohortEntry cohortEntry) {
    cohortEntry.canCommit(new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void result) {
            log.debug("{}: canCommit for {}: success", name, cohortEntry.getTransactionId());

            if (cohortEntry.isDoImmediateCommit()) {
                doCommit(cohortEntry);
            } else {
                cohortEntry.getReplySender().tell(
                    CanCommitTransactionReply.yes(cohortEntry.getClientVersion()).toSerializable(),
                    cohortEntry.getShard().self());
            }
        }

        @Override
        public void onFailure(final Throwable failure) {
            log.debug("{}: An exception occurred during canCommit for {}: {}", name,
                    cohortEntry.getTransactionId(), failure);

            cohortCache.remove(cohortEntry.getTransactionId());
            cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
        }
    });
}
 
Example 26
Project: hashsdn-controller   File: ShardCommitCoordinator.java   Source Code and License 6 votes vote down vote up
void doCommit(final CohortEntry cohortEntry) {
    log.debug("{}: Committing transaction {}", name, cohortEntry.getTransactionId());

    // We perform the preCommit phase here atomically with the commit phase. This is an
    // optimization to eliminate the overhead of an extra preCommit message. We lose front-end
    // coordination of preCommit across shards in case of failure but preCommit should not
    // normally fail since we ensure only one concurrent 3-phase commit.
    cohortEntry.preCommit(new FutureCallback<DataTreeCandidate>() {
        @Override
        public void onSuccess(final DataTreeCandidate candidate) {
            finishCommit(cohortEntry.getReplySender(), cohortEntry);
        }

        @Override
        public void onFailure(final Throwable failure) {
            log.error("{} An exception occurred while preCommitting transaction {}", name,
                    cohortEntry.getTransactionId(), failure);

            cohortCache.remove(cohortEntry.getTransactionId());
            cohortEntry.getReplySender().tell(new Failure(failure), cohortEntry.getShard().self());
        }
    });
}
 
Example 27
Project: hashsdn-controller   File: ChainedCommitCohort.java   Source Code and License 6 votes vote down vote up
@Override
public void commit(final FutureCallback<UnsignedLong> callback) {
    delegate.commit(new FutureCallback<UnsignedLong>() {
        @Override
        public void onSuccess(final UnsignedLong result) {
            chain.clearTransaction(transaction);
            LOG.debug("Committed transaction {}", transaction);
            callback.onSuccess(result);
        }

        @Override
        public void onFailure(final Throwable failure) {
            LOG.error("Transaction {} commit failed, cannot recover", transaction, failure);
            callback.onFailure(failure);
        }
    });
}
 
Example 28
Project: hashsdn-controller   File: FrontendReadWriteTransaction.java   Source Code and License 6 votes vote down vote up
void successfulDirectCanCommit(final RequestEnvelope envelope, final long startTime) {
    if (state instanceof Retired) {
        LOG.debug("{}: Suppressing direct canCommit of retired transaction {}", persistenceId(), getIdentifier());
        return;
    }

    final Ready ready = checkReady();
    ready.stage = CommitStage.PRE_COMMIT_PENDING;
    LOG.debug("{}: Transaction {} initiating direct preCommit", persistenceId(), getIdentifier());
    ready.readyCohort.preCommit(new FutureCallback<DataTreeCandidate>() {
        @Override
        public void onSuccess(final DataTreeCandidate result) {
            successfulDirectPreCommit(envelope, startTime);
        }

        @Override
        public void onFailure(final Throwable failure) {
            failTransaction(envelope, startTime, new RuntimeRequestException("PreCommit failed", failure));
        }
    });
}
 
Example 29
Project: hashsdn-controller   File: FrontendReadWriteTransaction.java   Source Code and License 6 votes vote down vote up
void successfulDirectPreCommit(final RequestEnvelope envelope, final long startTime) {
    if (state instanceof Retired) {
        LOG.debug("{}: Suppressing direct commit of retired transaction {}", persistenceId(), getIdentifier());
        return;
    }

    final Ready ready = checkReady();
    ready.stage = CommitStage.COMMIT_PENDING;
    LOG.debug("{}: Transaction {} initiating direct commit", persistenceId(), getIdentifier());
    ready.readyCohort.commit(new FutureCallback<UnsignedLong>() {
        @Override
        public void onSuccess(final UnsignedLong result) {
            successfulCommit(envelope, startTime);
        }

        @Override
        public void onFailure(final Throwable failure) {
            failTransaction(envelope, startTime, new RuntimeRequestException("DoCommit failed", failure));
        }
    });
}
 
Example 30
Project: hashsdn-controller   File: ThreePhaseCommitCohortProxy.java   Source Code and License 6 votes vote down vote up
@Override
public ListenableFuture<Boolean> canCommit() {
    LOG.debug("Tx {} canCommit", transactionId);

    final SettableFuture<Boolean> returnFuture = SettableFuture.create();

    // The first phase of canCommit is to gather the list of cohort actor paths that will
    // participate in the commit. buildCohortPathsList combines the cohort path Futures into
    // one Future which we wait on asynchronously here. The cohort actor paths are
    // extracted from ReadyTransactionReply messages by the Futures that were obtained earlier
    // and passed to us from upstream processing. If any one fails then  we'll fail canCommit.

    Futures.addCallback(resolveCohorts(), new FutureCallback<Void>() {
        @Override
        public void onSuccess(final Void notUsed) {
            finishCanCommit(returnFuture);
        }

        @Override
        public void onFailure(final Throwable failure) {
            returnFuture.setException(failure);
        }
    }, MoreExecutors.directExecutor());

    return returnFuture;
}
 
Example 31
Project: minebox   File: EncyptionKeyProvider.java   Source Code and License 5 votes vote down vote up
default void onLoadKey(Runnable runnable) {
    Futures.addCallback(getMasterPassword(), new FutureCallback<String>() {
        @Override
        public void onSuccess(@Nullable String result) {
            runnable.run();
        }

        @Override
        public void onFailure(Throwable t) {
            LOGGER.error("failed to run callback " + runnable.toString() + " due to unexpected error while waiting for keyfile: ", t);
        }
    });
}
 
Example 32
Project: xrpc   File: Call.java   Source Code and License 5 votes vote down vote up
public ListenableFuture<FullHttpResponse> execute() throws URISyntaxException {
  Preconditions.checkState(request != null);
  final SettableFuture<FullHttpResponse> error = SettableFuture.create();
  final SettableFuture<FullHttpResponse> response = SettableFuture.create();
  final ListenableFuture<ChannelFuture> connectFuture =
      connect(XUrl.getInetSocket(uri), client.getBootstrap(), buildRetryLoop());

  Futures.addCallback(
      connectFuture,
      new FutureCallback<ChannelFuture>() {
        @Override
        public void onSuccess(ChannelFuture result) {
          try {
            Channel channel = result.await().channel();
            channel.writeAndFlush(request);

            HttpResponseHandler responseHandler =
                (HttpResponseHandler) channel.pipeline().get("responseHandler");
            response.setFuture(responseHandler.getResponse());
          } catch (InterruptedException e) {
            response.cancel(true);
            error.setException(e);
          }
        }

        @Override
        public void onFailure(Throwable t) {
          response.cancel(true);
          error.setException(t);
        }
      });

  if (response.isCancelled()) {
    return error;
  } else {
    return response;
  }
}
 
Example 33
Project: ForgeHax   File: ScoreboardListenerService.java   Source Code and License 5 votes vote down vote up
@SubscribeEvent
public void onScoreboardEvent(PacketEvent.Incoming.Pre event) {
    if(event.getPacket() instanceof SPacketPlayerListItem
            && getWorld() != null
            && System.currentTimeMillis() > waitTime) {
        final SPacketPlayerListItem packet = (SPacketPlayerListItem) event.getPacket();
        packet.getEntries().stream()
                .filter(Objects::nonNull)
                .filter(data -> data.getProfile() != null)
                .filter(data -> !Strings.isNullOrEmpty(data.getProfile().getName()))
                .forEach(data -> {
                    final String name = data.getProfile().getName();
                    PlayerInfoHelper.invokeEfficiently(name, new FutureCallback<PlayerInfo>() {
                        @Override
                        public void onSuccess(@Nullable PlayerInfo result) {
                            if(result != null) fireEvents(packet.getAction(), result, data.getProfile());
                        }

                        @Override
                        public void onFailure(Throwable t) {

                        }
                    });
                });
    }
}
 
Example 34
Project: ProjectAres   File: UserFinder.java   Source Code and License 5 votes vote down vote up
public ListenableFuture<PlayerSearchResponse> findPlayer(CommandSender sender, @Nullable String name, Scope scope, Default def) {
    try {
        final Player player = getLocalPlayer(sender, name);
        if(player != null) {
            return Futures.immediateFuture(localPlayerResponse(sender, player));
        }

        if(scope.noGreaterThan(Scope.LOCAL)) {
            throw new TranslatableCommandException("command.playerNotFound");
        }

        final SettableFuture<PlayerSearchResponse> playerResult = SettableFuture.create();
        mainThreadExecutor.callback(
            findUser(sender, name, scope, def),
            new FutureCallback<UserSearchResponse>() {
                @Override
                public void onSuccess(@Nullable UserSearchResponse userResult) {
                    playerResult.set(new PlayerSearchResponse(userResult, onlinePlayers.find(userResult.user)));
                }

                @Override
                public void onFailure(Throwable t) {
                    playerResult.setException(t);
                }
            }
        );

        return playerResult;
    } catch(CommandException e) {
        return Futures.immediateFailedFuture(e);
    }
}
 
Example 35
Project: wall-t   File: ApiController.java   Source Code and License 5 votes vote down vote up
@Override
public ListenableFuture<Void> loadBuildTypeList( ) {
    if ( !getApiVersion( ).isSupported( ApiFeature.BUILD_TYPE_STATUS ) )
        return Futures.immediateFuture( null );

    final SettableFuture<Void> ackFuture = SettableFuture.create( );

    runInWorkerThread( ( ) -> {
        final ListenableFuture<BuildTypeList> buildListFuture = _apiRequestController.sendRequest( getApiVersion( ), "buildTypes", BuildTypeList.class );
        addCallback( buildListFuture, new FutureCallback<BuildTypeList>( ) {
            @Override
            public void onSuccess( final BuildTypeList result ) {
                final List<BuildTypeData> buildTypes = result.getBuildTypes( ).stream( )
                        .map( ( btype ) -> _buildTypeProvider.get( getApiVersion( ) ).apply( btype ) )
                        .collect( Collectors.toList( ) );
                _buildManager.registerBuildTypes( buildTypes );
                _eventBus.post( _buildManager );

                for ( final BuildTypeData buildType : _buildManager.getBuildTypes( ) ) {
                    final Optional<ProjectData> project = _projectManager.getProject( buildType.getProjectId( ) );
                    if ( project.isPresent( ) ) {
                        project.get( ).registerBuildType( buildType );
                        _eventBus.post( project.get( ) );
                    }
                    LOGGER.info( "Discovering build type " + buildType.getId( ) + " (" + buildType.getName( ) + ") on project " + buildType.getProjectId( ) + " (" + buildType.getProjectName( ) + ")" );
                }

                ackFuture.set( null );
            }

            @Override
            public void onFailure( final Throwable t ) {
                LOGGER.error( "Error during loading build type list:", t );
                ackFuture.setException( t );
            }
        } );
    } );

    return ackFuture;
}
 
Example 36
Project: hashsdn-controller   File: ShardDataTreeMocking.java   Source Code and License 5 votes vote down vote up
public static FutureCallback<DataTreeCandidate> coordinatedPreCommit(final ShardDataTreeCohort cohort) {
    final FutureCallback<DataTreeCandidate> callback = mockCallback();
    doNothing().when(callback).onSuccess(any(DataTreeCandidate.class));
    doNothing().when(callback).onFailure(any(Throwable.class));
    cohort.preCommit(callback);
    return callback;
}
 
Example 37
Project: hashsdn-controller   File: ShardDataTreeMocking.java   Source Code and License 5 votes vote down vote up
public static ShardDataTreeCohort immediateCommit(final ShardDataTreeCohort cohort) {
    final FutureCallback<UnsignedLong> callback = mockCallback();
    doNothing().when(callback).onSuccess(any(UnsignedLong.class));
    cohort.commit(callback);

    verify(callback, timeout(5000)).onSuccess(any(UnsignedLong.class));
    verifyNoMoreInteractions(callback);
    return cohort;
}
 
Example 38
Project: Elasticsearch   File: JobCollectContext.java   Source Code and License 5 votes vote down vote up
public JobCollectContext(final CollectPhase collectPhase,
                         MapSideDataCollectOperation collectOperation,
                         String localNodeId,
                         RamAccountingContext queryPhaseRamAccountingContext,
                         final RowReceiver rowReceiver,
                         SharedShardContexts sharedShardContexts) {
    super(collectPhase.executionPhaseId(), LOGGER);
    this.collectPhase = collectPhase;
    this.collectOperation = collectOperation;
    this.queryPhaseRamAccountingContext = queryPhaseRamAccountingContext;
    this.sharedShardContexts = sharedShardContexts;

    listenableRowReceiver = RowReceivers.listenableRowReceiver(rowReceiver);
    Futures.addCallback(listenableRowReceiver.finishFuture(), new FutureCallback<Void>() {
        @Override
        public void onSuccess(@Nullable Void result) {
            close();
        }

        @Override
        public void onFailure(@Nonnull Throwable t) {
            closeDueToFailure(t);
        }
    });
    this.rowReceiver = listenableRowReceiver;
    this.threadPoolName = threadPoolName(collectPhase, localNodeId);
}
 
Example 39
Project: Elasticsearch   File: RejectionAwareExecutor.java   Source Code and License 5 votes vote down vote up
/**
 * returns an Executor that will either execute the command given the Executor delegate or
 * call the callback.onFailure if it receives a (Es)RejectedExecutionException
 */
public static Executor wrapExecutor(Executor delegate, FutureCallback<?> callback) {
    if (delegate == MoreExecutors.directExecutor()) {
        // directExecutor won't reject anything...
        return delegate;
    }

    return new RejectionAwareExecutor(delegate, callback);
}
 
Example 40
Project: hashsdn-controller   File: ConcurrentDOMDataBroker.java   Source Code and License 5 votes vote down vote up
private void doCanCommit(final AsyncNotifyingSettableFuture clientSubmitFuture,
        final DOMDataWriteTransaction transaction,
        final Collection<DOMStoreThreePhaseCommitCohort> cohorts) {

    final long startTime = System.nanoTime();

    final Iterator<DOMStoreThreePhaseCommitCohort> cohortIterator = cohorts.iterator();

    // Not using Futures.allAsList here to avoid its internal overhead.
    FutureCallback<Boolean> futureCallback = new FutureCallback<Boolean>() {
        @Override
        public void onSuccess(final Boolean result) {
            if (result == null || !result) {
                handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER,
                        new TransactionCommitFailedException("Can Commit failed, no detailed cause available."));
            } else if (!cohortIterator.hasNext()) {
                // All cohorts completed successfully - we can move on to the preCommit phase
                doPreCommit(startTime, clientSubmitFuture, transaction, cohorts);
            } else {
                Futures.addCallback(cohortIterator.next().canCommit(), this, MoreExecutors.directExecutor());
            }
        }

        @Override
        public void onFailure(final Throwable failure) {
            handleException(clientSubmitFuture, transaction, cohorts, CAN_COMMIT, CAN_COMMIT_ERROR_MAPPER, failure);
        }
    };

    ListenableFuture<Boolean> canCommitFuture = cohortIterator.next().canCommit();
    Futures.addCallback(canCommitFuture, futureCallback, MoreExecutors.directExecutor());
}