Search in sources :

Example 56 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project openflowplugin by opendaylight.

the class MultiLayerExperimenterMultipartService method handleAndReply.

@Override
@SuppressWarnings("unchecked")
public Future<RpcResult<SendExperimenterMpRequestOutput>> handleAndReply(SendExperimenterMpRequestInput input) {
    final ListenableFuture<RpcResult<List<MultipartReply>>> multipartFuture = handleServiceCall(input);
    final SettableFuture<RpcResult<SendExperimenterMpRequestOutput>> finalFuture = SettableFuture.create();
    class CallBackImpl implements FutureCallback<RpcResult<List<MultipartReply>>> {

        @Override
        public void onSuccess(@Nonnull final RpcResult<List<MultipartReply>> result) {
            if (result.isSuccessful()) {
                final List<MultipartReply> multipartReplies = result.getResult();
                if (multipartReplies.isEmpty()) {
                    LOG.warn("Multipart reply to Experimenter-Mp request shouldn't be empty list.");
                    finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed().withError(ErrorType.RPC, "Multipart reply list is empty.").build());
                } else {
                    LOG.debug("OnSuccess, rpc result successful," + " multipart response for rpc sendExperimenterMpRequest with xid {} obtained.", multipartReplies.get(0).getXid());
                    final SendExperimenterMpRequestOutputBuilder sendExpMpReqOutputBuilder = new SendExperimenterMpRequestOutputBuilder();
                    final List<ExperimenterCoreMessageItem> expCoreMessageItem = new ArrayList<>();
                    for (MultipartReply multipartReply : multipartReplies) {
                        final MultipartReplyExperimenterCase caseBody = (MultipartReplyExperimenterCase) multipartReply.getMultipartReplyBody();
                        final MultipartReplyExperimenter replyBody = caseBody.getMultipartReplyExperimenter();
                        final ExperimenterDataOfChoice vendorData = replyBody.getExperimenterDataOfChoice();
                        final MessageTypeKey<? extends ExperimenterDataOfChoice> key = new MessageTypeKey<>(getVersion(), (Class<? extends ExperimenterDataOfChoice>) vendorData.getImplementedInterface());
                        final ConvertorMessageFromOFJava<ExperimenterDataOfChoice, MessagePath> messageConverter = getExtensionConverterProvider().getMessageConverter(key);
                        if (messageConverter == null) {
                            LOG.warn("Custom converter for {}[OF:{}] not found", vendorData.getImplementedInterface(), getVersion());
                            finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed().withError(ErrorType.RPC, "Custom converter not found.").build());
                            return;
                        }
                        try {
                            final ExperimenterMessageOfChoice messageOfChoice = messageConverter.convert(vendorData, MessagePath.MPMESSAGE_RPC_OUTPUT);
                            final ExperimenterCoreMessageItemBuilder expCoreMessageItemBuilder = new ExperimenterCoreMessageItemBuilder();
                            expCoreMessageItemBuilder.setExperimenterMessageOfChoice(messageOfChoice);
                            expCoreMessageItem.add(expCoreMessageItemBuilder.build());
                        } catch (final ConversionException e) {
                            LOG.error("Conversion of experimenter message reply failed. Exception: {}", e);
                            finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed().withError(ErrorType.RPC, "Conversion of experimenter rpc output failed.").build());
                            return;
                        }
                    }
                    sendExpMpReqOutputBuilder.setExperimenterCoreMessageItem(expCoreMessageItem);
                    finalFuture.set(RpcResultBuilder.success(sendExpMpReqOutputBuilder.build()).build());
                }
            } else {
                LOG.warn("OnSuccess, rpc result unsuccessful," + " multipart response for rpc sendExperimenterMpRequest was unsuccessful.");
                finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed().withRpcErrors(result.getErrors()).build());
            }
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.warn("Failure multipart response for Experimenter-Mp request. Exception: {}", throwable);
            finalFuture.set(RpcResultBuilder.<SendExperimenterMpRequestOutput>failed().withError(ErrorType.RPC, "Future error", throwable).build());
        }
    }
    Futures.addCallback(multipartFuture, new CallBackImpl(), MoreExecutors.directExecutor());
    return finalFuture;
}
Also used : MultipartReply(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply) ArrayList(java.util.ArrayList) MultipartReplyExperimenter(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.experimenter._case.MultipartReplyExperimenter) ExperimenterMessageOfChoice(org.opendaylight.yang.gen.v1.urn.opendaylight.openflowplugin.experimenter.types.rev151020.experimenter.core.message.ExperimenterMessageOfChoice) ExperimenterDataOfChoice(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.experimenter.core.ExperimenterDataOfChoice) ArrayList(java.util.ArrayList) List(java.util.List) MessageTypeKey(org.opendaylight.openflowjava.protocol.api.keys.MessageTypeKey) FutureCallback(com.google.common.util.concurrent.FutureCallback) MultipartReplyExperimenterCase(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyExperimenterCase) ConversionException(org.opendaylight.openflowplugin.extension.api.exception.ConversionException) ExperimenterCoreMessageItemBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.mp.message.service.rev151020.send.experimenter.mp.request.output.ExperimenterCoreMessageItemBuilder) Nonnull(javax.annotation.Nonnull) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) MessagePath(org.opendaylight.openflowplugin.extension.api.path.MessagePath) SendExperimenterMpRequestOutputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.mp.message.service.rev151020.SendExperimenterMpRequestOutputBuilder) ExperimenterCoreMessageItem(org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.mp.message.service.rev151020.send.experimenter.mp.request.output.ExperimenterCoreMessageItem) SendExperimenterMpRequestOutput(org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.mp.message.service.rev151020.SendExperimenterMpRequestOutput)

Example 57 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project openflowplugin by opendaylight.

the class MultiLayerTableMultipartService method handleAndReply.

@Override
public Future<RpcResult<UpdateTableOutput>> handleAndReply(UpdateTableInput input) {
    final ListenableFuture<RpcResult<List<MultipartReply>>> multipartFuture = handleServiceCall(input);
    final SettableFuture<RpcResult<UpdateTableOutput>> finalFuture = SettableFuture.create();
    class CallBackImpl implements FutureCallback<RpcResult<List<MultipartReply>>> {

        @Override
        @SuppressWarnings("checkstyle:IllegalCatch")
        public void onSuccess(@Nonnull final RpcResult<List<MultipartReply>> result) {
            if (result.isSuccessful()) {
                final List<MultipartReply> multipartReplies = result.getResult();
                if (multipartReplies.isEmpty()) {
                    LOG.debug("Multipart reply to table features request shouldn't be empty list.");
                    finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed().withError(ErrorType.RPC, "Multipart reply list is empty.").build());
                } else {
                    final Long xid = multipartReplies.get(0).getXid();
                    LOG.debug("OnSuccess, rpc result successful," + " multipart response for rpc update-table with xid {} obtained.", xid);
                    final UpdateTableOutputBuilder updateTableOutputBuilder = new UpdateTableOutputBuilder();
                    updateTableOutputBuilder.setTransactionId(new TransactionId(BigInteger.valueOf(xid)));
                    finalFuture.set(RpcResultBuilder.success(updateTableOutputBuilder.build()).build());
                    try {
                        storeStatistics(convertToSalTableFeatures(multipartReplies));
                    } catch (Exception e) {
                        LOG.warn("Not able to write to operational datastore: {}", e.getMessage());
                    }
                }
            } else {
                LOG.debug("OnSuccess, rpc result unsuccessful," + " multipart response for rpc update-table was unsuccessful.");
                finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed().withRpcErrors(result.getErrors()).build());
            }
        }

        @Override
        public void onFailure(final Throwable throwable) {
            LOG.error("Failure multipart response for table features request. Exception: {}", throwable);
            finalFuture.set(RpcResultBuilder.<UpdateTableOutput>failed().withError(ErrorType.RPC, "Future error", throwable).build());
        }
    }
    Futures.addCallback(multipartFuture, new CallBackImpl(), MoreExecutors.directExecutor());
    return finalFuture;
}
Also used : Nonnull(javax.annotation.Nonnull) MultipartReply(org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply) RpcResult(org.opendaylight.yangtools.yang.common.RpcResult) ServiceException(org.opendaylight.openflowplugin.impl.services.util.ServiceException) TransactionId(org.opendaylight.yang.gen.v1.urn.opendaylight.flow.transaction.rev150304.TransactionId) ArrayList(java.util.ArrayList) List(java.util.List) UpdateTableOutputBuilder(org.opendaylight.yang.gen.v1.urn.opendaylight.table.service.rev131026.UpdateTableOutputBuilder) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 58 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project bisq-core by bisq-network.

the class CreateTakerFeeTx method run.

@Override
protected void run() {
    try {
        runInterceptHook();
        User user = processModel.getUser();
        NodeAddress selectedArbitratorNodeAddress = ArbitratorSelectionRule.select(user.getAcceptedArbitratorAddresses(), processModel.getOffer());
        log.debug("selectedArbitratorAddress " + selectedArbitratorNodeAddress);
        Arbitrator selectedArbitrator = user.getAcceptedArbitratorByAddress(selectedArbitratorNodeAddress);
        checkNotNull(selectedArbitrator, "selectedArbitrator must not be null at CreateTakeOfferFeeTx");
        BtcWalletService walletService = processModel.getBtcWalletService();
        String id = processModel.getOffer().getId();
        AddressEntry addressEntry = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.OFFER_FUNDING);
        AddressEntry reservedForTradeAddressEntry = walletService.getOrCreateAddressEntry(id, AddressEntry.Context.RESERVED_FOR_TRADE);
        AddressEntry changeAddressEntry = walletService.getOrCreateAddressEntry(AddressEntry.Context.AVAILABLE);
        Address fundingAddress = addressEntry.getAddress();
        Address reservedForTradeAddress = reservedForTradeAddressEntry.getAddress();
        Address changeAddress = changeAddressEntry.getAddress();
        final TradeWalletService tradeWalletService = processModel.getTradeWalletService();
        if (trade.isCurrencyForTakerFeeBtc()) {
            tradeFeeTx = tradeWalletService.createBtcTradingFeeTx(fundingAddress, reservedForTradeAddress, changeAddress, processModel.getFundsNeededForTradeAsLong(), processModel.isUseSavingsWallet(), trade.getTakerFee(), trade.getTxFee(), selectedArbitrator.getBtcAddress(), new FutureCallback<Transaction>() {

                @Override
                public void onSuccess(Transaction transaction) {
                    // we delay one render frame to be sure we don't get called before the method call has
                    // returned (tradeFeeTx would be null in that case)
                    UserThread.execute(() -> {
                        if (!completed) {
                            processModel.setTakeOfferFeeTx(tradeFeeTx);
                            trade.setTakerFeeTxId(tradeFeeTx.getHashAsString());
                            walletService.swapTradeEntryToAvailableEntry(id, AddressEntry.Context.OFFER_FUNDING);
                            trade.setState(Trade.State.TAKER_PUBLISHED_TAKER_FEE_TX);
                            complete();
                        } else {
                            log.warn("We got the onSuccess callback called after the timeout has been triggered a complete().");
                        }
                    });
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    if (!completed) {
                        failed(t);
                    } else {
                        log.warn("We got the onFailure callback called after the timeout has been triggered a complete().");
                    }
                }
            });
        } else {
            final BsqWalletService bsqWalletService = processModel.getBsqWalletService();
            Transaction preparedBurnFeeTx = processModel.getBsqWalletService().getPreparedBurnFeeTx(trade.getTakerFee());
            Transaction txWithBsqFee = tradeWalletService.completeBsqTradingFeeTx(preparedBurnFeeTx, fundingAddress, reservedForTradeAddress, changeAddress, processModel.getFundsNeededForTradeAsLong(), processModel.isUseSavingsWallet(), trade.getTxFee());
            Transaction signedTx = processModel.getBsqWalletService().signTx(txWithBsqFee);
            WalletService.checkAllScriptSignaturesForTx(signedTx);
            bsqWalletService.commitTx(signedTx);
            // We need to create another instance, otherwise the tx would trigger an invalid state exception
            // if it gets committed 2 times
            tradeWalletService.commitTx(tradeWalletService.getClonedTransaction(signedTx));
            bsqWalletService.broadcastTx(signedTx, new FutureCallback<Transaction>() {

                @Override
                public void onSuccess(@Nullable Transaction transaction) {
                    if (!completed) {
                        if (transaction != null) {
                            log.debug("Successfully sent tx with id " + transaction.getHashAsString());
                            trade.setTakerFeeTxId(transaction.getHashAsString());
                            processModel.setTakeOfferFeeTx(transaction);
                            walletService.swapTradeEntryToAvailableEntry(id, AddressEntry.Context.OFFER_FUNDING);
                            trade.setState(Trade.State.TAKER_PUBLISHED_TAKER_FEE_TX);
                            complete();
                        }
                    } else {
                        log.warn("We got the onSuccess callback called after the timeout has been triggered a complete().");
                    }
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    if (!completed) {
                        log.error(t.toString());
                        t.printStackTrace();
                        trade.setErrorMessage("An error occurred.\n" + "Error message:\n" + t.getMessage());
                        failed(t);
                    } else {
                        log.warn("We got the onFailure callback called after the timeout has been triggered a complete().");
                    }
                }
            });
        }
    } catch (Throwable t) {
        failed(t);
    }
}
Also used : User(bisq.core.user.User) NodeAddress(bisq.network.p2p.NodeAddress) Address(org.bitcoinj.core.Address) AddressEntry(bisq.core.btc.AddressEntry) TradeWalletService(bisq.core.btc.wallet.TradeWalletService) Arbitrator(bisq.core.arbitration.Arbitrator) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) NotNull(org.jetbrains.annotations.NotNull) Transaction(org.bitcoinj.core.Transaction) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) NodeAddress(bisq.network.p2p.NodeAddress) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Example 59 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project bisq-api by mrosseel.

the class BisqProxy method withdrawFunds.

public void withdrawFunds(Set<String> sourceAddresses, Coin amountAsCoin, boolean feeExcluded, String targetAddress) throws AddressEntryException, InsufficientFundsException, AmountTooLowException {
    // get all address entries
    final List<AddressEntry> sourceAddressEntries = sourceAddresses.stream().filter(address -> null != address).map(address -> btcWalletService.getAddressEntryListAsImmutableList().stream().filter(addressEntry -> address.equals(addressEntry.getAddressString())).findFirst().orElse(null)).filter(item -> null != item).collect(Collectors.toList());
    // this filter matches all unauthorized address types
    Predicate<AddressEntry> filterNotAllowedAddressEntries = addressEntry -> !(AddressEntry.Context.AVAILABLE.equals(addressEntry.getContext()) || AddressEntry.Context.TRADE_PAYOUT.equals(addressEntry.getContext()));
    // check if there are any unauthorized address types
    if (sourceAddressEntries.stream().anyMatch(filterNotAllowedAddressEntries)) {
        throw new ValidationException("Funds can be withdrawn only from addresses with context AVAILABLE and TRADE_PAYOUT");
    }
    Coin sendersAmount;
    // We do not know sendersAmount if senderPaysFee is true. We repeat fee calculation after first attempt if senderPaysFee is true.
    Transaction feeEstimationTransaction;
    try {
        feeEstimationTransaction = btcWalletService.getFeeEstimationTransactionForMultipleAddresses(sourceAddresses, amountAsCoin);
    } catch (IllegalArgumentException e) {
        if (e.getMessage().contains("dust limit")) {
            throw new AmountTooLowException(e.getMessage());
        }
        throw e;
    }
    if (feeExcluded && feeEstimationTransaction != null) {
        sendersAmount = amountAsCoin.add(feeEstimationTransaction.getFee());
        feeEstimationTransaction = btcWalletService.getFeeEstimationTransactionForMultipleAddresses(sourceAddresses, sendersAmount);
    }
    checkNotNull(feeEstimationTransaction, "feeEstimationTransaction must not be null");
    Coin fee = feeEstimationTransaction.getFee();
    sendersAmount = feeExcluded ? amountAsCoin.add(fee) : amountAsCoin;
    Coin receiverAmount = feeExcluded ? amountAsCoin : amountAsCoin.subtract(fee);
    final Coin totalAvailableAmountOfSelectedItems = sourceAddressEntries.stream().map(address -> btcWalletService.getBalanceForAddress(address.getAddress())).reduce(Coin.ZERO, Coin::add);
    if (!sendersAmount.isPositive())
        throw new ValidationException("Senders amount must be positive");
    if (!new BtcAddressValidator().validate(targetAddress).isValid)
        throw new ValidationException("Invalid target address");
    if (sourceAddresses.isEmpty())
        throw new ValidationException("List of source addresses must not be empty");
    if (sendersAmount.compareTo(totalAvailableAmountOfSelectedItems) > 0)
        throw new InsufficientFundsException("Not enough funds in selected addresses");
    if (receiverAmount.isPositive()) {
        try {
            // TODO return completable future
            btcWalletService.sendFundsForMultipleAddresses(sourceAddresses, targetAddress, amountAsCoin, fee, null, null, new FutureCallback<Transaction>() {

                @Override
                public void onSuccess(@javax.annotation.Nullable Transaction transaction) {
                    if (transaction != null) {
                        log.debug("onWithdraw onSuccess tx ID:" + transaction.getHashAsString());
                    } else {
                        log.error("onWithdraw transaction is null");
                    }
                    List<Trade> trades = new ArrayList<>(tradeManager.getTradableList());
                    trades.stream().filter(Trade::isPayoutPublished).forEach(trade -> btcWalletService.getAddressEntry(trade.getId(), AddressEntry.Context.TRADE_PAYOUT).ifPresent(addressEntry -> {
                        if (btcWalletService.getBalanceForAddress(addressEntry.getAddress()).isZero())
                            tradeManager.addTradeToClosedTrades(trade);
                    }));
                }

                @Override
                public void onFailure(@NotNull Throwable t) {
                    log.error("onWithdraw onFailure");
                }
            });
        } catch (org.bitcoinj.core.InsufficientMoneyException e) {
            throw new InsufficientFundsException(e.getMessage());
        }
    } else {
        throw new AmountTooLowException(Res.get("portfolio.pending.step5_buyer.amountTooLow"));
    }
}
Also used : Arrays(java.util.Arrays) OpenOffer(bisq.core.offer.OpenOffer) User(bisq.core.user.User) PriceFeed(network.bisq.api.model.PriceFeed) Statistic(bisq.network.p2p.network.Statistic) ZoneOffset(java.time.ZoneOffset) KeyParameter(org.spongycastle.crypto.params.KeyParameter) ClosedTradableDetails(network.bisq.api.model.ClosedTradableDetails) CurrencyList(network.bisq.api.model.CurrencyList) WalletAddress(network.bisq.api.model.WalletAddress) AddressEntryException(bisq.core.btc.AddressEntryException) Offer(bisq.core.offer.Offer) ClosedTradableManager(bisq.core.trade.closed.ClosedTradableManager) SellerAsMakerProtocol(bisq.core.trade.protocol.SellerAsMakerProtocol) WalletTransactionList(network.bisq.api.model.WalletTransactionList) InsufficientFundsException(bisq.core.btc.InsufficientFundsException) Set(java.util.Set) TokenRegistry(network.bisq.api.service.TokenRegistry) BlockChainExplorer(bisq.core.user.BlockChainExplorer) TradeProtocol(bisq.core.trade.protocol.TradeProtocol) ZoneId(java.time.ZoneId) ECKey(org.bitcoinj.core.ECKey) Slf4j(lombok.extern.slf4j.Slf4j) Stream(java.util.stream.Stream) AddressEntry(bisq.core.btc.AddressEntry) WalletsSetup(bisq.core.btc.wallet.WalletsSetup) CryptoCurrency(bisq.core.locale.CryptoCurrency) Currency(network.bisq.api.model.Currency) TradeManager(bisq.core.trade.TradeManager) NodeAddress(bisq.network.p2p.NodeAddress) SellerAsTakerProtocol(bisq.core.trade.protocol.SellerAsTakerProtocol) CountryUtil(bisq.core.locale.CountryUtil) BuyerAsTakerProtocol(bisq.core.trade.protocol.BuyerAsTakerProtocol) TransactionOutput(org.bitcoinj.core.TransactionOutput) FeeService(bisq.core.provider.fee.FeeService) ObservableList(javafx.collections.ObservableList) PaymentAccountHelper(network.bisq.api.model.payment.PaymentAccountHelper) Restrictions(bisq.core.btc.Restrictions) Arbitrator(bisq.core.arbitration.Arbitrator) TransactionConfidence(org.bitcoinj.core.TransactionConfidence) Wallet(org.bitcoinj.wallet.Wallet) Peer(org.bitcoinj.core.Peer) ArrayList(java.util.ArrayList) ClosedTradableConverter(network.bisq.api.model.ClosedTradableConverter) OfferPayload(bisq.core.offer.OfferPayload) Country(bisq.core.locale.Country) BitcoinNetworkStatus(network.bisq.api.model.BitcoinNetworkStatus) WalletDetails(network.bisq.api.model.WalletDetails) Nullable(javax.annotation.Nullable) IOException(java.io.IOException) OfferBookService(bisq.core.offer.OfferBookService) Names(com.google.inject.name.Names) BisqEnvironment(bisq.core.app.BisqEnvironment) SeedWords(network.bisq.api.model.SeedWords) FutureCallback(com.google.common.util.concurrent.FutureCallback) File(java.io.File) OpenOfferManager(bisq.core.offer.OpenOfferManager) InputValidator(bisq.core.util.validation.InputValidator) PriceFeedService(bisq.core.provider.price.PriceFeedService) PaymentAccountList(network.bisq.api.model.PaymentAccountList) KeyRing(bisq.common.crypto.KeyRing) PreferencesAvailableValues(network.bisq.api.model.PreferencesAvailableValues) Transaction(org.bitcoinj.core.Transaction) Preferences(network.bisq.api.model.Preferences) Date(java.util.Date) Coin(org.bitcoinj.core.Coin) Key(com.google.inject.Key) AltCoinAddressValidator(bisq.core.payment.validation.AltCoinAddressValidator) VersionDetails(network.bisq.api.model.VersionDetails) Res(bisq.core.locale.Res) ErrorMessageHandler(bisq.common.handlers.ErrorMessageHandler) KeyCrypterScrypt(org.bitcoinj.crypto.KeyCrypterScrypt) PaymentAccountUtil.isPaymentAccountValidForOffer(bisq.core.payment.PaymentAccountUtil.isPaymentAccountValidForOffer) OfferUtil(bisq.core.offer.OfferUtil) P2PService(bisq.network.p2p.P2PService) Predicate(java.util.function.Predicate) ArbitratorManager(bisq.core.arbitration.ArbitratorManager) Collection(java.util.Collection) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) FileNotFoundException(java.io.FileNotFoundException) BsqWalletService(bisq.core.btc.wallet.BsqWalletService) AccountAgeWitnessService(bisq.core.payment.AccountAgeWitnessService) FileUtil(bisq.common.storage.FileUtil) List(java.util.List) PaymentAccount(bisq.core.payment.PaymentAccount) DeterministicSeed(org.bitcoinj.wallet.DeterministicSeed) DevEnv(bisq.common.app.DevEnv) MarketList(network.bisq.api.model.MarketList) AppOptionKeys(bisq.core.app.AppOptionKeys) LocalDate(java.time.LocalDate) Optional(java.util.Optional) Address(org.bitcoinj.core.Address) NotNull(org.jetbrains.annotations.NotNull) MarketPrice(bisq.core.provider.price.MarketPrice) BtcWalletService(bisq.core.btc.wallet.BtcWalletService) TradeCurrency(bisq.core.locale.TradeCurrency) SellerAsMakerTrade(bisq.core.trade.SellerAsMakerTrade) Getter(lombok.Getter) WalletService(bisq.core.btc.wallet.WalletService) CompletableFuture(java.util.concurrent.CompletableFuture) FiatCurrency(bisq.core.locale.FiatCurrency) WalletsManager(bisq.core.btc.wallet.WalletsManager) Tuple2(bisq.common.util.Tuple2) BuyerAsMakerProtocol(bisq.core.trade.protocol.BuyerAsMakerProtocol) P2PNetworkStatus(network.bisq.api.model.P2PNetworkStatus) Market(network.bisq.api.model.Market) CurrencyUtil(bisq.core.locale.CurrencyUtil) BitcoinNodes(bisq.core.btc.BitcoinNodes) Version(bisq.common.app.Version) CryptoCurrencyAccount(bisq.core.payment.CryptoCurrencyAccount) P2PNetworkConnection(network.bisq.api.model.P2PNetworkConnection) BuyerAsMakerTrade(bisq.core.trade.BuyerAsMakerTrade) Trade(bisq.core.trade.Trade) WalletAddressList(network.bisq.api.model.WalletAddressList) ResultHandler(bisq.common.handlers.ResultHandler) FailedTradesManager(bisq.core.trade.failed.FailedTradesManager) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) FileInputStream(java.io.FileInputStream) WalletTransaction(network.bisq.api.model.WalletTransaction) Injector(com.google.inject.Injector) Collectors.toList(java.util.stream.Collectors.toList) AuthResult(network.bisq.api.model.AuthResult) ValidationException(javax.validation.ValidationException) Storage(bisq.common.storage.Storage) Comparator(java.util.Comparator) Collections(java.util.Collections) CoinUtil(bisq.core.util.CoinUtil) InputStream(java.io.InputStream) ValidationException(javax.validation.ValidationException) AddressEntry(bisq.core.btc.AddressEntry) Coin(org.bitcoinj.core.Coin) SellerAsMakerTrade(bisq.core.trade.SellerAsMakerTrade) BuyerAsMakerTrade(bisq.core.trade.BuyerAsMakerTrade) Trade(bisq.core.trade.Trade) Transaction(org.bitcoinj.core.Transaction) WalletTransaction(network.bisq.api.model.WalletTransaction) InsufficientFundsException(bisq.core.btc.InsufficientFundsException) CurrencyList(network.bisq.api.model.CurrencyList) WalletTransactionList(network.bisq.api.model.WalletTransactionList) ObservableList(javafx.collections.ObservableList) ArrayList(java.util.ArrayList) PaymentAccountList(network.bisq.api.model.PaymentAccountList) List(java.util.List) MarketList(network.bisq.api.model.MarketList) WalletAddressList(network.bisq.api.model.WalletAddressList) Collectors.toList(java.util.stream.Collectors.toList)

Example 60 with FutureCallback

use of com.google.common.util.concurrent.FutureCallback in project qpid-broker-j by apache.

the class AbstractVirtualHost method doRestart.

private ListenableFuture<Void> doRestart() {
    createHousekeepingExecutor();
    final VirtualHostStoreUpgraderAndRecoverer virtualHostStoreUpgraderAndRecoverer = new VirtualHostStoreUpgraderAndRecoverer((VirtualHostNode<?>) getParent());
    virtualHostStoreUpgraderAndRecoverer.reloadAndRecoverVirtualHost(getDurableConfigurationStore());
    final Collection<VirtualHostAccessControlProvider> accessControlProviders = getChildren(VirtualHostAccessControlProvider.class);
    if (!accessControlProviders.isEmpty()) {
        accessControlProviders.forEach(child -> child.addChangeListener(_accessControlProviderListener));
    }
    final List<ListenableFuture<Void>> childOpenFutures = new ArrayList<>();
    Subject.doAs(getSubjectWithAddedSystemRights(), (PrivilegedAction<Object>) () -> {
        applyToChildren(child -> {
            final ListenableFuture<Void> childOpenFuture = child.openAsync();
            childOpenFutures.add(childOpenFuture);
            addFutureCallback(childOpenFuture, new FutureCallback<Void>() {

                @Override
                public void onSuccess(final Void result) {
                }

                @Override
                public void onFailure(final Throwable t) {
                    LOGGER.error("Exception occurred while opening {} : {}", child.getClass().getSimpleName(), child.getName(), t);
                    onRestartFailure();
                }
            }, getTaskExecutor());
        });
        return null;
    });
    ListenableFuture<List<Void>> combinedFuture = Futures.allAsList(childOpenFutures);
    return Futures.transformAsync(combinedFuture, input -> onActivate(), MoreExecutors.directExecutor());
}
Also used : AccessControlContext(java.security.AccessControlContext) Arrays(java.util.Arrays) BufferedInputStream(java.io.BufferedInputStream) ManagedAttributeField(org.apache.qpid.server.model.ManagedAttributeField) BrokerModel(org.apache.qpid.server.model.BrokerModel) MessageStoreSerializer(org.apache.qpid.server.store.serializer.MessageStoreSerializer) Future(java.util.concurrent.Future) NetworkConnectionScheduler(org.apache.qpid.server.transport.NetworkConnectionScheduler) Map(java.util.Map) QueueEntryIterator(org.apache.qpid.server.queue.QueueEntryIterator) NotFoundException(org.apache.qpid.server.model.NotFoundException) UserPreferences(org.apache.qpid.server.model.preferences.UserPreferences) EnumSet(java.util.EnumSet) AutoCommitTransaction(org.apache.qpid.server.txn.AutoCommitTransaction) Binding(org.apache.qpid.server.model.Binding) Set(java.util.Set) AMQPConnection(org.apache.qpid.server.transport.AMQPConnection) InstanceProperties(org.apache.qpid.server.message.InstanceProperties) Iterators.cycle(com.google.common.collect.Iterators.cycle) StandardCharsets(java.nio.charset.StandardCharsets) HousekeepingExecutor(org.apache.qpid.server.util.HousekeepingExecutor) Serializable(java.io.Serializable) MessageStoreMessages(org.apache.qpid.server.logging.messages.MessageStoreMessages) Operation(org.apache.qpid.server.security.access.Operation) PreferenceRecord(org.apache.qpid.server.store.preferences.PreferenceRecord) StateTransition(org.apache.qpid.server.model.StateTransition) QpidServiceLoader(org.apache.qpid.server.plugin.QpidServiceLoader) SystemConfig(org.apache.qpid.server.model.SystemConfig) CompoundAccessControl(org.apache.qpid.server.security.CompoundAccessControl) TaskExecutor(org.apache.qpid.server.configuration.updater.TaskExecutor) UUIDGenerator(org.apache.qpid.server.model.UUIDGenerator) CustomRestHeaders(org.apache.qpid.server.model.CustomRestHeaders) Queue(org.apache.qpid.server.model.Queue) PreferencesRoot(org.apache.qpid.server.store.preferences.PreferencesRoot) Callable(java.util.concurrent.Callable) ServerMessage(org.apache.qpid.server.message.ServerMessage) ArrayList(java.util.ArrayList) ResultCalculator(org.apache.qpid.server.security.SubjectFixedResultAccessControl.ResultCalculator) PreferenceStoreUpdaterImpl(org.apache.qpid.server.store.preferences.PreferenceStoreUpdaterImpl) ManageableMessage(org.apache.qpid.server.model.ManageableMessage) AbstractConfiguredObject(org.apache.qpid.server.model.AbstractConfiguredObject) UserPreferencesImpl(org.apache.qpid.server.model.preferences.UserPreferencesImpl) QueueEntry(org.apache.qpid.server.queue.QueueEntry) MessageHandler(org.apache.qpid.server.store.handler.MessageHandler) SubjectFixedResultAccessControl(org.apache.qpid.server.security.SubjectFixedResultAccessControl) PreferenceStore(org.apache.qpid.server.store.preferences.PreferenceStore) StoredMessage(org.apache.qpid.server.store.StoredMessage) NoFactoryForTypeException(org.apache.qpid.server.model.NoFactoryForTypeException) MessageDeletedException(org.apache.qpid.server.message.MessageDeletedException) DtxRegistry(org.apache.qpid.server.txn.DtxRegistry) MessageInstanceHandler(org.apache.qpid.server.store.handler.MessageInstanceHandler) IOException(java.io.IOException) PreferencesRecoverer(org.apache.qpid.server.store.preferences.PreferencesRecoverer) Connection(org.apache.qpid.server.model.Connection) File(java.io.File) FutureCallback(com.google.common.util.concurrent.FutureCallback) DurableConfigurationStore(org.apache.qpid.server.store.DurableConfigurationStore) Strings(org.apache.qpid.server.util.Strings) AtomicLong(java.util.concurrent.atomic.AtomicLong) Futures(com.google.common.util.concurrent.Futures) Result(org.apache.qpid.server.security.Result) SuppressingInheritedAccessControlContextThreadFactory(org.apache.qpid.server.pool.SuppressingInheritedAccessControlContextThreadFactory) QpidByteBuffer(org.apache.qpid.server.bytebuffer.QpidByteBuffer) ScheduledFuture(java.util.concurrent.ScheduledFuture) MessageReference(org.apache.qpid.server.message.MessageReference) URL(java.net.URL) Date(java.util.Date) Outcome(org.apache.qpid.server.logging.Outcome) DistributedTransactionHandler(org.apache.qpid.server.store.handler.DistributedTransactionHandler) LoggerFactory(org.slf4j.LoggerFactory) DefaultDestination(org.apache.qpid.server.exchange.DefaultDestination) TaskExecutorImpl(org.apache.qpid.server.configuration.updater.TaskExecutorImpl) SettableFuture(com.google.common.util.concurrent.SettableFuture) MessageStore(org.apache.qpid.server.store.MessageStore) ExchangeDefaults(org.apache.qpid.server.exchange.ExchangeDefaults) VirtualHostAccessControlProvider(org.apache.qpid.server.model.VirtualHostAccessControlProvider) AmqpPort(org.apache.qpid.server.model.port.AmqpPort) StoreException(org.apache.qpid.server.store.StoreException) MessageEnqueueRecord(org.apache.qpid.server.store.MessageEnqueueRecord) PatternSyntaxException(java.util.regex.PatternSyntaxException) LocalTransaction(org.apache.qpid.server.txn.LocalTransaction) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) LinkModel(org.apache.qpid.server.protocol.LinkModel) ScheduledThreadPoolExecutor(java.util.concurrent.ScheduledThreadPoolExecutor) UUID(java.util.UUID) PrivilegedAction(java.security.PrivilegedAction) RoutingResult(org.apache.qpid.server.message.RoutingResult) ConfigurationExtractor(org.apache.qpid.server.model.ConfigurationExtractor) VirtualHostLogger(org.apache.qpid.server.model.VirtualHostLogger) ConnectionValidator(org.apache.qpid.server.plugin.ConnectionValidator) MessageStoreLogSubject(org.apache.qpid.server.logging.subjects.MessageStoreLogSubject) List(java.util.List) Principal(java.security.Principal) AMQMessageHeader(org.apache.qpid.server.message.AMQMessageHeader) VirtualHost(org.apache.qpid.server.model.VirtualHost) MessageDestination(org.apache.qpid.server.message.MessageDestination) MessageSource(org.apache.qpid.server.message.MessageSource) Pattern(java.util.regex.Pattern) CacheBuilder(com.google.common.cache.CacheBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) DataInputStream(java.io.DataInputStream) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) InternalMessage(org.apache.qpid.server.message.internal.InternalMessage) AccessControl(org.apache.qpid.server.security.AccessControl) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) JdkFutureAdapters(com.google.common.util.concurrent.JdkFutureAdapters) EventLogger(org.apache.qpid.server.logging.EventLogger) ConcurrentMap(java.util.concurrent.ConcurrentMap) HashSet(java.util.HashSet) ConfigurationChangeListener(org.apache.qpid.server.model.ConfigurationChangeListener) Collections.newSetFromMap(java.util.Collections.newSetFromMap) RejectedExecutionException(java.util.concurrent.RejectedExecutionException) ExclusivityPolicy(org.apache.qpid.server.model.ExclusivityPolicy) Preference(org.apache.qpid.server.model.preferences.Preference) AuthenticatedPrincipal(org.apache.qpid.server.security.auth.AuthenticatedPrincipal) SystemNodeCreator(org.apache.qpid.server.plugin.SystemNodeCreator) AbstractConfigurationChangeListener(org.apache.qpid.server.model.AbstractConfigurationChangeListener) ConfiguredObjectRecord(org.apache.qpid.server.store.ConfiguredObjectRecord) Task(org.apache.qpid.server.configuration.updater.Task) Param(org.apache.qpid.server.model.Param) OutputStream(java.io.OutputStream) PreferenceStoreUpdater(org.apache.qpid.server.store.preferences.PreferenceStoreUpdater) ServerTransaction(org.apache.qpid.server.txn.ServerTransaction) Logger(org.slf4j.Logger) VirtualHostMessages(org.apache.qpid.server.logging.messages.VirtualHostMessages) Iterator(java.util.Iterator) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) SocketConnectionMetaData(org.apache.qpid.server.security.auth.SocketConnectionMetaData) MalformedURLException(java.net.MalformedURLException) Exchange(org.apache.qpid.server.model.Exchange) Content(org.apache.qpid.server.model.Content) Broker(org.apache.qpid.server.model.Broker) State(org.apache.qpid.server.model.State) Subject(javax.security.auth.Subject) TimeUnit(java.util.concurrent.TimeUnit) ConfiguredObjectRecordHandler(org.apache.qpid.server.store.handler.ConfiguredObjectRecordHandler) VirtualHostStoreUpgraderAndRecoverer(org.apache.qpid.server.store.VirtualHostStoreUpgraderAndRecoverer) URLEncoder(java.net.URLEncoder) AMQInvalidArgumentException(org.apache.qpid.server.filter.AMQInvalidArgumentException) Event(org.apache.qpid.server.store.Event) MessageStoreProvider(org.apache.qpid.server.store.MessageStoreProvider) MessageNode(org.apache.qpid.server.message.MessageNode) DoOnConfigThread(org.apache.qpid.server.model.DoOnConfigThread) Cache(com.google.common.cache.Cache) RestContentHeader(org.apache.qpid.server.model.RestContentHeader) Collections(java.util.Collections) VirtualHostNode(org.apache.qpid.server.model.VirtualHostNode) StatisticsReportingTask(org.apache.qpid.server.stats.StatisticsReportingTask) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) VirtualHostAccessControlProvider(org.apache.qpid.server.model.VirtualHostAccessControlProvider) VirtualHostStoreUpgraderAndRecoverer(org.apache.qpid.server.store.VirtualHostStoreUpgraderAndRecoverer) ListenableFuture(com.google.common.util.concurrent.ListenableFuture) AbstractConfiguredObject(org.apache.qpid.server.model.AbstractConfiguredObject) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) ArrayList(java.util.ArrayList) List(java.util.List) FutureCallback(com.google.common.util.concurrent.FutureCallback)

Aggregations

FutureCallback (com.google.common.util.concurrent.FutureCallback)70 ListenableFuture (com.google.common.util.concurrent.ListenableFuture)33 List (java.util.List)33 ArrayList (java.util.ArrayList)27 Futures (com.google.common.util.concurrent.Futures)24 Logger (org.slf4j.Logger)19 LoggerFactory (org.slf4j.LoggerFactory)19 MoreExecutors (com.google.common.util.concurrent.MoreExecutors)18 IOException (java.io.IOException)18 Set (java.util.Set)17 Collections (java.util.Collections)16 Map (java.util.Map)16 TimeUnit (java.util.concurrent.TimeUnit)16 Optional (com.google.common.base.Optional)15 ExecutionException (java.util.concurrent.ExecutionException)15 Nonnull (javax.annotation.Nonnull)15 Nullable (javax.annotation.Nullable)15 Collection (java.util.Collection)13 Future (java.util.concurrent.Future)13 Collectors (java.util.stream.Collectors)12