Example usage for android.support.v4.util LongSparseArray indexOfKey

List of usage examples for android.support.v4.util LongSparseArray indexOfKey

Introduction

In this page you can find the example usage for android.support.v4.util LongSparseArray indexOfKey.

Prototype

public int indexOfKey(long j) 

Source Link

Usage

From source file:de.vanita5.twittnuker.util.LongSparseArrayUtils.java

public static <E> boolean hasKey(final LongSparseArray<E> array, final long key) {
    return array.indexOfKey(key) >= 0;
}

From source file:nz.ac.otago.psyanlab.common.model.util.ModelUtils.java

public static Long findUnusedKey(LongSparseArray<?> map) {
    Long currKey = 0l;/*from   w  ww.java2 s  .  c  o m*/
    while (true) {
        if (map.indexOfKey(currKey) < 0) {
            break;
        }
        currKey++;
    }
    return currKey;
}

From source file:com.ruesga.timelinechart.TimelineChartView.java

private float computeOffsetForTimestamp(long timestamp) {
    final LongSparseArray<Pair<double[], int[]>> data;
    synchronized (mLock) {
        data = mData;/*from w w  w  .  j av a2 s. c o m*/
    }
    final int index = data.indexOfKey(timestamp);
    if (index >= 0) {
        final int size = data.size();
        return (mBarWidth * (size - index - 1));
    }
    return -1;
}

From source file:org.sufficientlysecure.keychain.provider.ProviderHelper.java

/**
 * Saves PGPPublicKeyRing with its keys and userIds in DB
 *//*w  w  w  . j a  v a  2  s  .c  om*/
@SuppressWarnings("unchecked")
public void savePublicKeyRing(UncachedKeyRing keyRing) throws IOException {
    if (keyRing.isSecret()) {
        throw new RuntimeException(
                "Tried to save secret keyring as public! " + "This is a bug, please file a bug report.");
    }

    UncachedPublicKey masterKey = keyRing.getPublicKey();
    long masterKeyId = masterKey.getKeyId();

    // IF there is a secret key, preserve it!
    UncachedKeyRing secretRing = null;
    try {
        secretRing = getWrappedSecretKeyRing(masterKeyId).getUncached();
    } catch (NotFoundException e) {
        Log.e(Constants.TAG, "key not found!");
    }

    // delete old version of this keyRing, which also deletes all keys and userIds on cascade
    try {
        mContentResolver.delete(KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId)), null, null);
    } catch (UnsupportedOperationException e) {
        Log.e(Constants.TAG, "Key could not be deleted! Maybe we are creating a new one!", e);
    }

    // insert new version of this keyRing
    ContentValues values = new ContentValues();
    values.put(KeyRingData.MASTER_KEY_ID, masterKeyId);
    values.put(KeyRingData.KEY_RING_DATA, keyRing.getEncoded());
    Uri uri = KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId));
    mContentResolver.insert(uri, values);

    // save all keys and userIds included in keyRing object in database
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    int rank = 0;
    for (UncachedPublicKey key : new IterableIterator<UncachedPublicKey>(keyRing.getPublicKeys())) {
        operations.add(buildPublicKeyOperations(masterKeyId, key, rank));
        ++rank;
    }

    // get a list of owned secret keys, for verification filtering
    LongSparseArray<UncachedPublicKey> allKeyRings = getUncachedMasterKeys(KeyRingData.buildSecretKeyRingUri());
    // special case: available secret keys verify themselves!
    if (secretRing != null) {
        allKeyRings.put(secretRing.getMasterKeyId(), secretRing.getPublicKey());
    }

    // classify and order user ids. primary are moved to the front, revoked to the back,
    // otherwise the order in the keyfile is preserved.
    List<UserIdItem> uids = new ArrayList<UserIdItem>();

    for (String userId : new IterableIterator<String>(masterKey.getUnorderedUserIds().iterator())) {
        UserIdItem item = new UserIdItem();
        uids.add(item);
        item.userId = userId;

        // look through signatures for this specific key
        for (WrappedSignature cert : new IterableIterator<WrappedSignature>(
                masterKey.getSignaturesForId(userId))) {
            long certId = cert.getKeyId();
            try {
                // self signature
                if (certId == masterKeyId) {
                    cert.init(masterKey);
                    if (!cert.verifySignature(masterKey, userId)) {
                        // not verified?! dang! TODO notify user? this is kinda serious...
                        Log.e(Constants.TAG, "Could not verify self signature for " + userId + "!");
                        continue;
                    }
                    // is this the first, or a more recent certificate?
                    if (item.selfCert == null
                            || item.selfCert.getCreationTime().before(cert.getCreationTime())) {
                        item.selfCert = cert;
                        item.isPrimary = cert.isPrimaryUserId();
                        item.isRevoked = cert.isRevocation();
                    }
                }
                // verify signatures from known private keys
                if (allKeyRings.indexOfKey(certId) >= 0) {
                    cert.init(allKeyRings.get(certId));
                    if (cert.verifySignature(masterKey, userId)) {
                        item.trustedCerts.add(cert);
                    }
                }
            } catch (PgpGeneralException e) {
                Log.e(Constants.TAG,
                        "Signature verification failed! " + PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyId())
                                + " from " + PgpKeyHelper.convertKeyIdToHex(cert.getKeyId()),
                        e);
            }
        }
    }

    // primary before regular before revoked (see UserIdItem.compareTo)
    // this is a stable sort, so the order of keys is otherwise preserved.
    Collections.sort(uids);
    // iterate and put into db
    for (int userIdRank = 0; userIdRank < uids.size(); userIdRank++) {
        UserIdItem item = uids.get(userIdRank);
        operations.add(buildUserIdOperations(masterKeyId, item, userIdRank));
        // no self cert is bad, but allowed by the rfc...
        if (item.selfCert != null) {
            operations.add(buildCertOperations(masterKeyId, userIdRank, item.selfCert, Certs.VERIFIED_SELF));
        }
        // don't bother with trusted certs if the uid is revoked, anyways
        if (item.isRevoked) {
            continue;
        }
        for (int i = 0; i < item.trustedCerts.size(); i++) {
            operations.add(buildCertOperations(masterKeyId, userIdRank, item.trustedCerts.get(i),
                    Certs.VERIFIED_SECRET));
        }
    }

    try {
        mContentResolver.applyBatch(KeychainContract.CONTENT_AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.e(Constants.TAG, "applyBatch failed!", e);
    } catch (OperationApplicationException e) {
        Log.e(Constants.TAG, "applyBatch failed!", e);
    }

    // Save the saved keyring (if any)
    if (secretRing != null) {
        saveSecretKeyRing(secretRing);
    }

}

From source file:org.thialfihar.android.apg.provider.ProviderHelper.java

/**
 * Saves PGPPublicKeyRing with its keys and userIds in DB
 *///from   w w w .  ja  v a2  s . com
@SuppressWarnings("unchecked")
public void saveKeyRing(PGPPublicKeyRing keyRing) throws IOException {
    PGPPublicKey masterKey = keyRing.getPublicKey();
    long masterKeyId = masterKey.getKeyID();

    // IF there is a secret key, preserve it!
    PGPSecretKeyRing secretRing = null;
    try {
        secretRing = getPGPSecretKeyRing(masterKeyId);
    } catch (NotFoundException e) {
        Log.e(Constants.TAG, "key not found!");
    }

    // delete old version of this keyRing, which also deletes all keys and userIds on cascade
    try {
        mContentResolver.delete(KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId)), null, null);
    } catch (UnsupportedOperationException e) {
        Log.e(Constants.TAG, "Key could not be deleted! Maybe we are creating a new one!", e);
    }

    // insert new version of this keyRing
    ContentValues values = new ContentValues();
    values.put(KeyRingData.MASTER_KEY_ID, masterKeyId);
    values.put(KeyRingData.KEY_RING_DATA, keyRing.getEncoded());
    Uri uri = KeyRingData.buildPublicKeyRingUri(Long.toString(masterKeyId));
    mContentResolver.insert(uri, values);

    // save all keys and userIds included in keyRing object in database
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();

    int rank = 0;
    for (PGPPublicKey key : new IterableIterator<PGPPublicKey>(keyRing.getPublicKeys())) {
        operations.add(buildPublicKeyOperations(masterKeyId, key, rank));
        ++rank;
    }

    // get a list of owned secret keys, for verification filtering
    LongSparseArray<PGPKeyRing> allKeyRings = getPGPKeyRings(KeyRingData.buildSecretKeyRingUri());
    // special case: available secret keys verify themselves!
    if (secretRing != null)
        allKeyRings.put(secretRing.getSecretKey().getKeyID(), secretRing);

    // classify and order user ids. primary are moved to the front, revoked to the back,
    // otherwise the order in the keyfile is preserved.
    List<UserIdItem> uids = new ArrayList<UserIdItem>();

    for (String userId : new IterableIterator<String>(masterKey.getUserIDs())) {
        UserIdItem item = new UserIdItem();
        uids.add(item);
        item.userId = userId;

        // look through signatures for this specific key
        for (PGPSignature cert : new IterableIterator<PGPSignature>(masterKey.getSignaturesForID(userId))) {
            long certId = cert.getKeyID();
            try {
                // self signature
                if (certId == masterKeyId) {
                    cert.init(new JcaPGPContentVerifierBuilderProvider()
                            .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME), masterKey);
                    if (!cert.verifyCertification(userId, masterKey)) {
                        // not verified?! dang! TODO notify user? this is kinda serious...
                        Log.e(Constants.TAG, "Could not verify self signature for " + userId + "!");
                        continue;
                    }
                    // is this the first, or a more recent certificate?
                    if (item.selfCert == null
                            || item.selfCert.getCreationTime().before(cert.getCreationTime())) {
                        item.selfCert = cert;
                        item.isPrimary = cert.getHashedSubPackets().isPrimaryUserID();
                        item.isRevoked = cert.getSignatureType() == PGPSignature.CERTIFICATION_REVOCATION;
                    }
                }
                // verify signatures from known private keys
                if (allKeyRings.indexOfKey(certId) >= 0) {
                    // mark them as verified
                    cert.init(
                            new JcaPGPContentVerifierBuilderProvider()
                                    .setProvider(Constants.BOUNCY_CASTLE_PROVIDER_NAME),
                            allKeyRings.get(certId).getPublicKey());
                    if (cert.verifyCertification(userId, masterKey)) {
                        item.trustedCerts.add(cert);
                    }
                }
            } catch (SignatureException e) {
                Log.e(Constants.TAG,
                        "Signature verification failed! " + PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID())
                                + " from " + PgpKeyHelper.convertKeyIdToHex(cert.getKeyID()),
                        e);
            } catch (PGPException e) {
                Log.e(Constants.TAG,
                        "Signature verification failed! " + PgpKeyHelper.convertKeyIdToHex(masterKey.getKeyID())
                                + " from " + PgpKeyHelper.convertKeyIdToHex(cert.getKeyID()),
                        e);
            }
        }
    }

    // primary before regular before revoked (see UserIdItem.compareTo)
    // this is a stable sort, so the order of keys is otherwise preserved.
    Collections.sort(uids);
    // iterate and put into db
    for (int userIdRank = 0; userIdRank < uids.size(); userIdRank++) {
        UserIdItem item = uids.get(userIdRank);
        operations.add(buildUserIdOperations(masterKeyId, item, userIdRank));
        // no self cert is bad, but allowed by the rfc...
        if (item.selfCert != null) {
            operations.add(buildCertOperations(masterKeyId, userIdRank, item.selfCert, Certs.VERIFIED_SELF));
        }
        // don't bother with trusted certs if the uid is revoked, anyways
        if (item.isRevoked) {
            continue;
        }
        for (int i = 0; i < item.trustedCerts.size(); i++) {
            operations.add(buildCertOperations(masterKeyId, userIdRank, item.trustedCerts.get(i),
                    Certs.VERIFIED_SECRET));
        }
    }

    try {
        mContentResolver.applyBatch(ApgContract.CONTENT_AUTHORITY, operations);
    } catch (RemoteException e) {
        Log.e(Constants.TAG, "applyBatch failed!", e);
    } catch (OperationApplicationException e) {
        Log.e(Constants.TAG, "applyBatch failed!", e);
    }

    // Save the saved keyring (if any)
    if (secretRing != null) {
        saveKeyRing(secretRing);
    }

}

From source file:org.sufficientlysecure.keychain.provider.KeyWritableRepository.java

/**
 * Saves an UncachedKeyRing of the public variant into the db.
 * <p/>//from ww  w .  jav  a2 s  . c o m
 * This method will not delete all previous data for this masterKeyId from the database prior
 * to inserting. All public data is effectively re-inserted, secret keyrings are left deleted
 * and need to be saved externally to be preserved past the operation.
 */
@SuppressWarnings("unchecked")
private int saveCanonicalizedPublicKeyRing(CanonicalizedPublicKeyRing keyRing, boolean selfCertsAreTrusted) {

    // start with ok result
    int result = SaveKeyringResult.SAVED_PUBLIC;

    long masterKeyId = keyRing.getMasterKeyId();
    UncachedPublicKey masterKey = keyRing.getPublicKey();

    ArrayList<ContentProviderOperation> operations;
    try {

        log(LogType.MSG_IP_PREPARE);
        mIndent += 1;

        // save all keys and userIds included in keyRing object in database
        operations = new ArrayList<>();

        log(LogType.MSG_IP_INSERT_KEYRING);
        try {
            writePublicKeyRing(keyRing, masterKeyId, operations);
        } catch (IOException e) {
            log(LogType.MSG_IP_ENCODE_FAIL);
            return SaveKeyringResult.RESULT_ERROR;
        }

        log(LogType.MSG_IP_INSERT_SUBKEYS);
        mIndent += 1;
        { // insert subkeys
            Uri uri = Keys.buildKeysUri(masterKeyId);
            int rank = 0;
            for (CanonicalizedPublicKey key : keyRing.publicKeyIterator()) {
                long keyId = key.getKeyId();
                log(keyId == masterKeyId ? LogType.MSG_IP_MASTER : LogType.MSG_IP_SUBKEY,
                        KeyFormattingUtils.convertKeyIdToHex(keyId));
                mIndent += 1;

                ContentValues values = new ContentValues();
                values.put(Keys.MASTER_KEY_ID, masterKeyId);
                values.put(Keys.RANK, rank);

                values.put(Keys.KEY_ID, key.getKeyId());
                values.put(Keys.KEY_SIZE, key.getBitStrength());
                values.put(Keys.KEY_CURVE_OID, key.getCurveOid());
                values.put(Keys.ALGORITHM, key.getAlgorithm());
                values.put(Keys.FINGERPRINT, key.getFingerprint());

                boolean c = key.canCertify(), e = key.canEncrypt(), s = key.canSign(),
                        a = key.canAuthenticate();
                values.put(Keys.CAN_CERTIFY, c);
                values.put(Keys.CAN_ENCRYPT, e);
                values.put(Keys.CAN_SIGN, s);
                values.put(Keys.CAN_AUTHENTICATE, a);
                values.put(Keys.IS_REVOKED, key.isRevoked());
                values.put(Keys.IS_SECURE, key.isSecure());

                // see above
                if (masterKeyId == keyId) {
                    if (key.getKeyUsage() == null) {
                        log(LogType.MSG_IP_MASTER_FLAGS_UNSPECIFIED);
                    } else {
                        log(LOG_TYPES_FLAG_MASTER[(c ? 1 : 0) + (e ? 2 : 0) + (s ? 4 : 0) + (a ? 8 : 0)]);
                    }
                } else {
                    if (key.getKeyUsage() == null) {
                        log(LogType.MSG_IP_SUBKEY_FLAGS_UNSPECIFIED);
                    } else {
                        log(LOG_TYPES_FLAG_SUBKEY[(c ? 1 : 0) + (e ? 2 : 0) + (s ? 4 : 0) + (a ? 8 : 0)]);
                    }
                }

                Date creation = key.getCreationTime();
                values.put(Keys.CREATION, creation.getTime() / 1000);
                Date expiryDate = key.getExpiryTime();
                if (expiryDate != null) {
                    values.put(Keys.EXPIRY, expiryDate.getTime() / 1000);
                    if (key.isExpired()) {
                        log(keyId == masterKeyId ? LogType.MSG_IP_MASTER_EXPIRED
                                : LogType.MSG_IP_SUBKEY_EXPIRED, expiryDate.toString());
                    } else {
                        log(keyId == masterKeyId ? LogType.MSG_IP_MASTER_EXPIRES
                                : LogType.MSG_IP_SUBKEY_EXPIRES, expiryDate.toString());
                    }
                }

                operations.add(ContentProviderOperation.newInsert(uri).withValues(values).build());
                ++rank;
                mIndent -= 1;
            }
        }
        mIndent -= 1;

        // get a list of owned secret keys, for verification filtering
        LongSparseArray<CanonicalizedPublicKey> trustedKeys = getTrustedMasterKeys();

        // classify and order user ids. primary are moved to the front, revoked to the back,
        // otherwise the order in the keyfile is preserved.
        List<UserPacketItem> uids = new ArrayList<>();

        List<Long> signerKeyIds = new ArrayList<>();

        if (trustedKeys.size() == 0) {
            log(LogType.MSG_IP_UID_CLASSIFYING_ZERO);
        } else {
            log(LogType.MSG_IP_UID_CLASSIFYING, trustedKeys.size());
        }
        mIndent += 1;
        for (byte[] rawUserId : masterKey.getUnorderedRawUserIds()) {
            String userId = Utf8Util.fromUTF8ByteArrayReplaceBadEncoding(rawUserId);
            UserPacketItem item = new UserPacketItem();
            uids.add(item);
            OpenPgpUtils.UserId splitUserId = KeyRing.splitUserId(userId);
            item.userId = userId;
            item.name = splitUserId.name;
            item.email = splitUserId.email;
            item.comment = splitUserId.comment;
            int unknownCerts = 0;

            log(LogType.MSG_IP_UID_PROCESSING, userId);
            mIndent += 1;
            // look through signatures for this specific key
            for (WrappedSignature cert : new IterableIterator<>(masterKey.getSignaturesForRawId(rawUserId))) {
                long certId = cert.getKeyId();
                // self signature
                if (certId == masterKeyId) {

                    // NOTE self-certificates are already verified during canonicalization,
                    // AND we know there is at most one cert plus at most one revocation
                    if (!cert.isRevocation()) {
                        item.selfCert = cert;
                        item.isPrimary = cert.isPrimaryUserId();
                    } else {
                        item.selfRevocation = cert;
                        log(LogType.MSG_IP_UID_REVOKED);
                    }
                    continue;

                }

                // do we have a trusted key for this?
                if (trustedKeys.indexOfKey(certId) < 0) {
                    if (!signerKeyIds.contains(certId)) {
                        operations.add(ContentProviderOperation.newInsert(KeySignatures.CONTENT_URI)
                                .withValue(KeySignatures.MASTER_KEY_ID, masterKeyId)
                                .withValue(KeySignatures.SIGNER_KEY_ID, certId).build());
                        signerKeyIds.add(certId);
                    }
                    unknownCerts += 1;
                    continue;
                }

                // verify signatures from known private keys
                CanonicalizedPublicKey trustedKey = trustedKeys.get(certId);

                try {
                    cert.init(trustedKey);
                    // if it doesn't certify, leave a note and skip
                    if (!cert.verifySignature(masterKey, rawUserId)) {
                        log(LogType.MSG_IP_UID_CERT_BAD);
                        continue;
                    }

                    log(cert.isRevocation() ? LogType.MSG_IP_UID_CERT_GOOD_REVOKE
                            : LogType.MSG_IP_UID_CERT_GOOD,
                            KeyFormattingUtils.convertKeyIdToHexShort(trustedKey.getKeyId()));

                    // check if there is a previous certificate
                    WrappedSignature prev = item.trustedCerts.get(cert.getKeyId());
                    if (prev != null) {
                        // if it's newer, skip this one
                        if (prev.getCreationTime().after(cert.getCreationTime())) {
                            log(LogType.MSG_IP_UID_CERT_OLD);
                            continue;
                        }
                        // if the previous one was a non-revokable certification, no need to look further
                        if (!prev.isRevocation() && !prev.isRevokable()) {
                            log(LogType.MSG_IP_UID_CERT_NONREVOKE);
                            continue;
                        }
                        log(LogType.MSG_IP_UID_CERT_NEW);
                    }
                    item.trustedCerts.put(cert.getKeyId(), cert);

                } catch (PgpGeneralException e) {
                    log(LogType.MSG_IP_UID_CERT_ERROR, KeyFormattingUtils.convertKeyIdToHex(cert.getKeyId()));
                }

            }

            if (unknownCerts > 0) {
                log(LogType.MSG_IP_UID_CERTS_UNKNOWN, unknownCerts);
            }
            mIndent -= 1;

        }
        mIndent -= 1;

        ArrayList<WrappedUserAttribute> userAttributes = masterKey.getUnorderedUserAttributes();
        // Don't spam the log if there aren't even any attributes
        if (!userAttributes.isEmpty()) {
            log(LogType.MSG_IP_UAT_CLASSIFYING);
        }

        mIndent += 1;
        for (WrappedUserAttribute userAttribute : userAttributes) {

            UserPacketItem item = new UserPacketItem();
            uids.add(item);
            item.type = userAttribute.getType();
            item.attributeData = userAttribute.getEncoded();

            int unknownCerts = 0;

            switch (item.type) {
            case WrappedUserAttribute.UAT_IMAGE:
                log(LogType.MSG_IP_UAT_PROCESSING_IMAGE);
                break;
            default:
                log(LogType.MSG_IP_UAT_PROCESSING_UNKNOWN);
                break;
            }
            mIndent += 1;
            // look through signatures for this specific key
            for (WrappedSignature cert : new IterableIterator<>(
                    masterKey.getSignaturesForUserAttribute(userAttribute))) {
                long certId = cert.getKeyId();
                // self signature
                if (certId == masterKeyId) {

                    // NOTE self-certificates are already verified during canonicalization,
                    // AND we know there is at most one cert plus at most one revocation
                    // AND the revocation only exists if there is no newer certification
                    if (!cert.isRevocation()) {
                        item.selfCert = cert;
                    } else {
                        item.selfRevocation = cert;
                        log(LogType.MSG_IP_UAT_REVOKED);
                    }
                    continue;

                }

                // do we have a trusted key for this?
                if (trustedKeys.indexOfKey(certId) < 0) {
                    unknownCerts += 1;
                    continue;
                }

                // verify signatures from known private keys
                CanonicalizedPublicKey trustedKey = trustedKeys.get(certId);

                try {
                    cert.init(trustedKey);
                    // if it doesn't certify, leave a note and skip
                    if (!cert.verifySignature(masterKey, userAttribute)) {
                        log(LogType.MSG_IP_UAT_CERT_BAD);
                        continue;
                    }

                    log(cert.isRevocation() ? LogType.MSG_IP_UAT_CERT_GOOD_REVOKE
                            : LogType.MSG_IP_UAT_CERT_GOOD,
                            KeyFormattingUtils.convertKeyIdToHexShort(trustedKey.getKeyId()));

                    // check if there is a previous certificate
                    WrappedSignature prev = item.trustedCerts.get(cert.getKeyId());
                    if (prev != null) {
                        // if it's newer, skip this one
                        if (prev.getCreationTime().after(cert.getCreationTime())) {
                            log(LogType.MSG_IP_UAT_CERT_OLD);
                            continue;
                        }
                        // if the previous one was a non-revokable certification, no need to look further
                        if (!prev.isRevocation() && !prev.isRevokable()) {
                            log(LogType.MSG_IP_UAT_CERT_NONREVOKE);
                            continue;
                        }
                        log(LogType.MSG_IP_UAT_CERT_NEW);
                    }
                    item.trustedCerts.put(cert.getKeyId(), cert);

                } catch (PgpGeneralException e) {
                    log(LogType.MSG_IP_UAT_CERT_ERROR, KeyFormattingUtils.convertKeyIdToHex(cert.getKeyId()));
                }

            }

            if (unknownCerts > 0) {
                log(LogType.MSG_IP_UAT_CERTS_UNKNOWN, unknownCerts);
            }
            mIndent -= 1;

        }
        mIndent -= 1;

        log(LogType.MSG_IP_UID_REORDER);
        // primary before regular before revoked (see UserIdItem.compareTo)
        // this is a stable sort, so the order of keys is otherwise preserved.
        Collections.sort(uids);
        // iterate and put into db
        for (int userIdRank = 0; userIdRank < uids.size(); userIdRank++) {
            UserPacketItem item = uids.get(userIdRank);
            operations.add(buildUserIdOperations(masterKeyId, item, userIdRank));

            if (item.selfRevocation != null) {
                operations.add(
                        buildCertOperations(masterKeyId, userIdRank, item.selfRevocation, Certs.VERIFIED_SELF));
                // don't bother with trusted certs if the uid is revoked, anyways
                continue;
            }

            if (item.selfCert == null) {
                throw new AssertionError("User ids MUST be self-certified at this point!!");
            }

            operations.add(buildCertOperations(masterKeyId, userIdRank, item.selfCert,
                    selfCertsAreTrusted ? Certs.VERIFIED_SECRET : Certs.VERIFIED_SELF));

            // iterate over signatures
            for (int i = 0; i < item.trustedCerts.size(); i++) {
                WrappedSignature sig = item.trustedCerts.valueAt(i);
                // if it's a revocation
                if (sig.isRevocation()) {
                    // don't further process it
                    continue;
                }
                // otherwise, build database operation
                operations.add(buildCertOperations(masterKeyId, userIdRank, sig, Certs.VERIFIED_SECRET));
            }
        }

    } catch (IOException e) {
        log(LogType.MSG_IP_ERROR_IO_EXC);
        Log.e(Constants.TAG, "IOException during import", e);
        return SaveKeyringResult.RESULT_ERROR;
    } finally {
        mIndent -= 1;
    }

    ContentProviderOperation lastUpdateReinsertOp = getLastUpdatedReinsertOperationByMasterKeyId(masterKeyId);
    if (lastUpdateReinsertOp != null) {
        operations.add(lastUpdateReinsertOp);
    }

    try {
        // delete old version of this keyRing (from database only!), which also deletes all keys and userIds on cascade
        int deleted = mContentResolver.delete(KeyRingData.buildPublicKeyRingUri(masterKeyId), null, null);
        if (deleted > 0) {
            log(LogType.MSG_IP_DELETE_OLD_OK);
            result |= SaveKeyringResult.UPDATED;
        } else {
            log(LogType.MSG_IP_DELETE_OLD_FAIL);
        }

        log(LogType.MSG_IP_APPLY_BATCH);
        mContentResolver.applyBatch(KeychainContract.CONTENT_AUTHORITY, operations);

        log(LogType.MSG_IP_SUCCESS);
        return result;

    } catch (RemoteException e) {
        log(LogType.MSG_IP_ERROR_REMOTE_EX);
        Log.e(Constants.TAG, "RemoteException during import", e);
        return SaveKeyringResult.RESULT_ERROR;
    } catch (OperationApplicationException e) {
        log(LogType.MSG_IP_ERROR_OP_EXC);
        Log.e(Constants.TAG, "OperationApplicationException during import", e);
        return SaveKeyringResult.RESULT_ERROR;
    }

}

From source file:nz.ac.otago.psyanlab.common.designer.ExperimentDesignerActivity.java

private void updateReferencesToDataChannel(long id) {
    DataChannel dataChannel = mExperiment.dataChannels.get(id);
    ArrayList<Long> calls = findAffectedCallIds(ExperimentObject.KIND_CHANNEL, id);

    for (Long callId : calls) {
        CallValue call = (CallValue) mExperiment.operands.get(callId);

        if (call == null) {
            // It is possible we might be trying to update a call we have
            // already obliterated due to removing a parent operand, so we
            // just skip the missing operand and continue processing the
            // list.
            continue;
        }//www  .ja v a 2  s .  c om

        if (dataChannel == null) {
            // The prop was actually deleted so we just need to remove the
            // reference.
            StubOperand replacement = new StubOperand(call.getName());
            replacement.type = call.type;
            replacement.tag = call.tag;
            deleteOperand(callId);
            putOperand(callId, replacement);
            continue;
        }

        // Separate the parameters that will be retained from those that
        // will be discarded.
        LongSparseArray<Long> retainedParameterIds = new LongSparseArray<Long>();
        ArrayList<Long> discardedParameterIds = new ArrayList<Long>();
        for (Long parameterId : call.parameters) {
            Operand parameter = mExperiment.operands.get(parameterId);
            Field matchedField = null;
            for (Field field : dataChannel.fields) {
                if (parameter.tag == field.id) {
                    matchedField = field;
                    break;
                }
            }
            if (matchedField != null) {
                retainedParameterIds.put(matchedField.id, parameterId);
            } else {
                discardedParameterIds.add(parameterId);
            }
        }

        // Delete discarded parameters.
        for (Long discardedId : discardedParameterIds) {
            deleteOperandData(mExperiment.operands.remove(discardedId));
        }

        // Update parameters and rebuild the order to match that of the
        // fields in the data channel.
        call.parameters = new ArrayList<Long>();
        for (Field field : dataChannel.fields) {
            // Create a new stub, or attempt to update parameters to match
            // field, otherwise replace the parameter with a stub.
            Operand parameter;
            long parameterId;
            if (retainedParameterIds.indexOfKey(field.id) < 0) {
                parameter = new StubOperand(field.name);
                parameter.tag = field.id;
                parameterId = addOperand(parameter);
            } else {
                parameterId = retainedParameterIds.get(field.id);
                parameter = mExperiment.operands.get(parameterId);
                parameter.name = field.name;
            }
            // Dictate type, if that fails replace the operand with a stub
            // and force the new type.
            if (!parameter.attemptRestrictType(field.type)) {
                deleteOperandData(parameter);
                StubOperand replacement = new StubOperand(field.name);
                replacement.type = field.type;
                replacement.tag = field.id;
                putOperand(parameterId, replacement);
            }
            call.parameters.add(parameterId);
        }
    }
}