Search in sources :

Example 21 with AnyThread

use of androidx.annotation.AnyThread in project Signal-Android by WhisperSystems.

the class LiveRecipientCache method warmUp.

@AnyThread
public void warmUp() {
    if (warmedUp.getAndSet(true)) {
        return;
    }
    Stopwatch stopwatch = new Stopwatch("recipient-warm-up");
    SignalExecutors.BOUNDED.execute(() -> {
        ThreadDatabase threadDatabase = SignalDatabase.threads();
        List<Recipient> recipients = new ArrayList<>();
        try (ThreadDatabase.Reader reader = threadDatabase.readerFor(threadDatabase.getRecentConversationList(THREAD_CACHE_WARM_MAX, false, false))) {
            int i = 0;
            ThreadRecord record = null;
            while ((record = reader.getNext()) != null && i < THREAD_CACHE_WARM_MAX) {
                recipients.add(record.getRecipient());
                i++;
            }
        }
        Log.d(TAG, "Warming up " + recipients.size() + " thread recipients.");
        addToCache(recipients);
        stopwatch.split("thread");
        if (SignalStore.registrationValues().isRegistrationComplete() && SignalStore.account().getAci() != null) {
            try (Cursor cursor = SignalDatabase.recipients().getNonGroupContacts(false)) {
                int count = 0;
                while (cursor != null && cursor.moveToNext() && count < CONTACT_CACHE_WARM_MAX) {
                    RecipientId id = RecipientId.from(CursorUtil.requireLong(cursor, RecipientDatabase.ID));
                    Recipient.resolved(id);
                    count++;
                }
                Log.d(TAG, "Warmed up " + count + " contact recipient.");
                stopwatch.split("contact");
            }
        }
        stopwatch.stop(TAG);
    });
}
Also used : Stopwatch(org.thoughtcrime.securesms.util.Stopwatch) ArrayList(java.util.ArrayList) ThreadRecord(org.thoughtcrime.securesms.database.model.ThreadRecord) ThreadDatabase(org.thoughtcrime.securesms.database.ThreadDatabase) Cursor(android.database.Cursor) SuppressLint(android.annotation.SuppressLint) AnyThread(androidx.annotation.AnyThread)

Example 22 with AnyThread

use of androidx.annotation.AnyThread in project bitcoin-wallet by bitcoin-wallet.

the class WalletApplication method getWalletAsync.

@AnyThread
public void getWalletAsync(final OnWalletLoadedListener listener) {
    getWalletExecutor.execute(new Runnable() {

        @Override
        public void run() {
            org.bitcoinj.core.Context.propagate(Constants.CONTEXT);
            synchronized (getWalletLock) {
                initMnemonicCode();
                if (walletFiles == null)
                    loadWalletFromProtobuf();
            }
            listener.onWalletLoaded(walletFiles.getWallet());
        }

        @WorkerThread
        private void loadWalletFromProtobuf() {
            Wallet wallet;
            if (walletFile.exists()) {
                try (final FileInputStream walletStream = new FileInputStream(walletFile)) {
                    final Stopwatch watch = Stopwatch.createStarted();
                    wallet = new WalletProtobufSerializer().readWallet(walletStream);
                    watch.stop();
                    if (!wallet.getParams().equals(Constants.NETWORK_PARAMETERS))
                        throw new UnreadableWalletException("bad wallet network parameters: " + wallet.getParams().getId());
                    log.info("wallet loaded from: '{}', took {}", walletFile, watch);
                } catch (final IOException | UnreadableWalletException x) {
                    log.warn("problem loading wallet, auto-restoring: " + walletFile, x);
                    wallet = WalletUtils.restoreWalletFromAutoBackup(WalletApplication.this);
                    if (wallet != null)
                        new Toast(WalletApplication.this).postLongToast(R.string.toast_wallet_reset);
                }
                if (!wallet.isConsistent()) {
                    log.warn("inconsistent wallet, auto-restoring: " + walletFile);
                    wallet = WalletUtils.restoreWalletFromAutoBackup(WalletApplication.this);
                    if (wallet != null)
                        new Toast(WalletApplication.this).postLongToast(R.string.toast_wallet_reset);
                }
                if (!wallet.getParams().equals(Constants.NETWORK_PARAMETERS))
                    throw new Error("bad wallet network parameters: " + wallet.getParams().getId());
                wallet.cleanup();
                walletFiles = wallet.autosaveToFile(walletFile, Constants.Files.WALLET_AUTOSAVE_DELAY_MS, TimeUnit.MILLISECONDS, null);
            } else {
                final Stopwatch watch = Stopwatch.createStarted();
                wallet = Wallet.createDeterministic(Constants.NETWORK_PARAMETERS, Constants.DEFAULT_OUTPUT_SCRIPT_TYPE);
                walletFiles = wallet.autosaveToFile(walletFile, Constants.Files.WALLET_AUTOSAVE_DELAY_MS, TimeUnit.MILLISECONDS, null);
                // persist...
                autosaveWalletNow();
                // ...and backup asap
                WalletUtils.autoBackupWallet(WalletApplication.this, wallet);
                watch.stop();
                log.info("fresh {} wallet created, took {}", Constants.DEFAULT_OUTPUT_SCRIPT_TYPE, watch);
                config.armBackupReminder();
            }
        }

        private void initMnemonicCode() {
            if (MnemonicCode.INSTANCE == null) {
                try {
                    final Stopwatch watch = Stopwatch.createStarted();
                    MnemonicCode.INSTANCE = new MnemonicCode(getAssets().open(BIP39_WORDLIST_FILENAME), null);
                    watch.stop();
                    log.info("BIP39 wordlist loaded from: '{}', took {}", BIP39_WORDLIST_FILENAME, watch);
                } catch (final IOException x) {
                    throw new Error(x);
                }
            }
        }
    });
}
Also used : WorkerThread(androidx.annotation.WorkerThread) UnreadableWalletException(org.bitcoinj.wallet.UnreadableWalletException) Toast(de.schildbach.wallet.util.Toast) Wallet(org.bitcoinj.wallet.Wallet) Stopwatch(com.google.common.base.Stopwatch) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) WalletProtobufSerializer(org.bitcoinj.wallet.WalletProtobufSerializer) MnemonicCode(org.bitcoinj.crypto.MnemonicCode) AnyThread(androidx.annotation.AnyThread)

Example 23 with AnyThread

use of androidx.annotation.AnyThread in project Signal-Android by signalapp.

the class KeyValueStore method blockUntilAllWritesFinished.

/**
 * Ensures that any pending writes (such as those made via {@link Writer#apply()}) are finished.
 */
@AnyThread
synchronized void blockUntilAllWritesFinished() {
    CountDownLatch latch = new CountDownLatch(1);
    executor.execute(latch::countDown);
    try {
        latch.await();
    } catch (InterruptedException e) {
        Log.w(TAG, "Failed to wait for all writes.");
    }
}
Also used : CountDownLatch(java.util.concurrent.CountDownLatch) AnyThread(androidx.annotation.AnyThread)

Example 24 with AnyThread

use of androidx.annotation.AnyThread in project Signal-Android by signalapp.

the class ConfirmPaymentRepository method confirmPayment.

@AnyThread
void confirmPayment(@NonNull ConfirmPaymentState state, @NonNull Consumer<ConfirmPaymentResult> consumer) {
    Log.i(TAG, "confirmPayment");
    SignalExecutors.BOUNDED.execute(() -> {
        Balance balance = wallet.getCachedBalance();
        if (state.getTotal().requireMobileCoin().greaterThan(balance.getFullAmount().requireMobileCoin())) {
            Log.w(TAG, "The total was greater than the wallet's balance");
            consumer.accept(new ConfirmPaymentResult.Error());
            return;
        }
        Payee payee = state.getPayee();
        RecipientId recipientId;
        MobileCoinPublicAddress mobileCoinPublicAddress;
        if (payee.hasRecipientId()) {
            recipientId = payee.requireRecipientId();
            try {
                mobileCoinPublicAddress = ProfileUtil.getAddressForRecipient(Recipient.resolved(recipientId));
            } catch (IOException e) {
                Log.w(TAG, "Failed to get address for recipient " + recipientId);
                consumer.accept(new ConfirmPaymentResult.Error());
                return;
            } catch (PaymentsAddressException e) {
                Log.w(TAG, "Failed to get address for recipient " + recipientId);
                consumer.accept(new ConfirmPaymentResult.Error(e.getCode()));
                return;
            }
        } else if (payee.hasPublicAddress()) {
            recipientId = null;
            mobileCoinPublicAddress = payee.requirePublicAddress();
        } else
            throw new AssertionError();
        UUID paymentUuid = PaymentSendJob.enqueuePayment(recipientId, mobileCoinPublicAddress, Util.emptyIfNull(state.getNote()), state.getAmount().requireMobileCoin(), state.getFee().requireMobileCoin());
        Log.i(TAG, "confirmPayment: PaymentSendJob enqueued");
        consumer.accept(new ConfirmPaymentResult.Success(paymentUuid));
    });
}
Also used : RecipientId(org.thoughtcrime.securesms.recipients.RecipientId) IOException(java.io.IOException) PaymentsAddressException(org.thoughtcrime.securesms.payments.PaymentsAddressException) UUID(java.util.UUID) Balance(org.thoughtcrime.securesms.payments.Balance) Payee(org.thoughtcrime.securesms.payments.Payee) MobileCoinPublicAddress(org.thoughtcrime.securesms.payments.MobileCoinPublicAddress) AnyThread(androidx.annotation.AnyThread)

Example 25 with AnyThread

use of androidx.annotation.AnyThread in project Signal-Android by signalapp.

the class MegaphoneRepository method markFinished.

@AnyThread
public void markFinished(@NonNull Event event, @Nullable Runnable onComplete) {
    executor.execute(() -> {
        MegaphoneRecord record = databaseCache.get(event);
        if (record != null && record.isFinished()) {
            return;
        }
        database.markFinished(event);
        resetDatabaseCache();
        if (onComplete != null) {
            onComplete.run();
        }
    });
}
Also used : MegaphoneRecord(org.thoughtcrime.securesms.database.model.MegaphoneRecord) AnyThread(androidx.annotation.AnyThread)

Aggregations

AnyThread (androidx.annotation.AnyThread)27 IOException (java.io.IOException)5 Cursor (android.database.Cursor)4 NonNull (androidx.annotation.NonNull)4 UUID (java.util.UUID)4 MegaphoneRecord (org.thoughtcrime.securesms.database.model.MegaphoneRecord)4 SuppressLint (android.annotation.SuppressLint)2 Paint (android.graphics.Paint)2 Point (android.graphics.Point)2 Uri (android.net.Uri)2 AlertDialog (androidx.appcompat.app.AlertDialog)2 ExifInterface (androidx.exifinterface.media.ExifInterface)2 ByteString (com.google.protobuf.ByteString)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 CountDownLatch (java.util.concurrent.CountDownLatch)2 AtomicLong (java.util.concurrent.atomic.AtomicLong)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Attachment (org.thoughtcrime.securesms.attachments.Attachment)2 DatabaseAttachment (org.thoughtcrime.securesms.attachments.DatabaseAttachment)2