Example usage for android.support.v4.os CancellationSignal throwIfCanceled

List of usage examples for android.support.v4.os CancellationSignal throwIfCanceled

Introduction

In this page you can find the example usage for android.support.v4.os CancellationSignal throwIfCanceled.

Prototype

public void throwIfCanceled() 

Source Link

Document

Throws OperationCanceledException if the operation has been canceled.

Usage

From source file:io.requery.android.database.sqlite.SQLiteSession.java

/**
 * Performs special reinterpretation of certain SQL statements such as "BEGIN",
 * "COMMIT" and "ROLLBACK" to ensure that transaction state invariants are
 * maintained.//w w  w  .  j a  v  a2 s  . c o m
 *
 * This function is mainly used to support legacy apps that perform their
 * own transactions by executing raw SQL rather than calling {@link #beginTransaction}
 * and the like.
 *
 * @param sql The SQL statement to execute.
 * @param bindArgs The arguments to bind, or null if none.
 * @param connectionFlags The connection flags to use if a connection must be
 * acquired by this operation.  Refer to {@link SQLiteConnectionPool}.
 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
 * @return True if the statement was of a special form that was handled here,
 * false otherwise.
 *
 * @throws SQLiteException if an error occurs, such as a syntax error
 * or invalid number of bind arguments.
 * @throws OperationCanceledException if the operation was canceled.
 */
private boolean executeSpecial(String sql, Object[] bindArgs, int connectionFlags,
        CancellationSignal cancellationSignal) {
    if (cancellationSignal != null) {
        cancellationSignal.throwIfCanceled();
    }

    final int type = SQLiteStatementType.getSqlStatementType(sql);
    switch (type) {
    case SQLiteStatementType.STATEMENT_BEGIN:
        beginTransaction(TRANSACTION_MODE_EXCLUSIVE, null, connectionFlags, cancellationSignal);
        return true;

    case SQLiteStatementType.STATEMENT_COMMIT:
        setTransactionSuccessful();
        endTransaction(cancellationSignal);
        return true;

    case SQLiteStatementType.STATEMENT_ABORT:
        endTransaction(cancellationSignal);
        return true;
    }
    return false;
}

From source file:io.requery.android.database.sqlite.SQLiteSession.java

private boolean yieldTransactionUnchecked(long sleepAfterYieldDelayMillis,
        CancellationSignal cancellationSignal) {
    if (cancellationSignal != null) {
        cancellationSignal.throwIfCanceled();
    }/*from   w  w w .  j av a2s. com*/

    if (!mConnectionPool.shouldYieldConnection(mConnection, mConnectionFlags)) {
        return false;
    }

    final int transactionMode = mTransactionStack.mMode;
    final SQLiteTransactionListener listener = mTransactionStack.mListener;
    final int connectionFlags = mConnectionFlags;
    endTransactionUnchecked(cancellationSignal, true); // might throw

    if (sleepAfterYieldDelayMillis > 0) {
        try {
            Thread.sleep(sleepAfterYieldDelayMillis);
        } catch (InterruptedException ex) {
            // we have been interrupted, that's all we need to do
        }
    }

    beginTransactionUnchecked(transactionMode, listener, connectionFlags, cancellationSignal); // might throw
    return true;
}

From source file:io.requery.android.database.sqlite.SQLiteSession.java

private void beginTransactionUnchecked(int transactionMode, SQLiteTransactionListener transactionListener,
        int connectionFlags, CancellationSignal cancellationSignal) {
    if (cancellationSignal != null) {
        cancellationSignal.throwIfCanceled();
    }/* w w w.ja  v a2s.  co m*/

    if (mTransactionStack == null) {
        acquireConnection(null, connectionFlags, cancellationSignal); // might throw
    }
    try {
        // Set up the transaction such that we can back out safely
        // in case we fail part way.
        if (mTransactionStack == null) {
            // Execute SQL might throw a runtime exception.
            switch (transactionMode) {
            case TRANSACTION_MODE_IMMEDIATE:
                mConnection.execute("BEGIN IMMEDIATE;", null, cancellationSignal); // might throw
                break;
            case TRANSACTION_MODE_EXCLUSIVE:
                mConnection.execute("BEGIN EXCLUSIVE;", null, cancellationSignal); // might throw
                break;
            default:
                mConnection.execute("BEGIN;", null, cancellationSignal); // might throw
                break;
            }
        }

        // Listener might throw a runtime exception.
        if (transactionListener != null) {
            try {
                transactionListener.onBegin(); // might throw
            } catch (RuntimeException ex) {
                if (mTransactionStack == null) {
                    mConnection.execute("ROLLBACK;", null, cancellationSignal); // might throw
                }
                throw ex;
            }
        }

        // Bookkeeping can't throw, except an OOM, which is just too bad...
        Transaction transaction = obtainTransaction(transactionMode, transactionListener);
        transaction.mParent = mTransactionStack;
        mTransactionStack = transaction;
    } finally {
        if (mTransactionStack == null) {
            releaseConnection(); // might throw
        }
    }
}

From source file:io.requery.android.database.sqlite.SQLiteSession.java

private void endTransactionUnchecked(CancellationSignal cancellationSignal, boolean yielding) {
    if (cancellationSignal != null) {
        cancellationSignal.throwIfCanceled();
    }/*from w w  w. j  a  va 2s  . com*/

    final Transaction top = mTransactionStack;
    boolean successful = (top.mMarkedSuccessful || yielding) && !top.mChildFailed;

    RuntimeException listenerException = null;
    final SQLiteTransactionListener listener = top.mListener;
    if (listener != null) {
        try {
            if (successful) {
                listener.onCommit(); // might throw
            } else {
                listener.onRollback(); // might throw
            }
        } catch (RuntimeException ex) {
            listenerException = ex;
            successful = false;
        }
    }

    mTransactionStack = top.mParent;
    recycleTransaction(top);

    if (mTransactionStack != null) {
        if (!successful) {
            mTransactionStack.mChildFailed = true;
        }
    } else {
        try {
            if (successful) {
                mConnection.execute("COMMIT;", null, cancellationSignal); // might throw
            } else {
                mConnection.execute("ROLLBACK;", null, cancellationSignal); // might throw
            }
        } finally {
            releaseConnection(); // might throw
        }
    }

    if (listenerException != null) {
        throw listenerException;
    }
}

From source file:io.requery.android.database.sqlite.SQLiteSession.java

/**
 * Prepares a statement for execution but does not bind its parameters or execute it.
 * <p>/*from  w  ww.  j a v a2 s. c om*/
 * This method can be used to check for syntax errors during compilation
 * prior to execution of the statement.  If the {@code outStatementInfo} argument
 * is not null, the provided {@link SQLiteStatementInfo} object is populated
 * with information about the statement.
 * </p><p>
 * A prepared statement makes no reference to the arguments that may eventually
 * be bound to it, consequently it it possible to cache certain prepared statements
 * such as SELECT or INSERT/UPDATE statements.  If the statement is cacheable,
 * then it will be stored in the cache for later and reused if possible.
 * </p>
 *
 * @param sql The SQL statement to prepare.
 * @param connectionFlags The connection flags to use if a connection must be
 * acquired by this operation.  Refer to {@link SQLiteConnectionPool}.
 * @param cancellationSignal A signal to cancel the operation in progress, or null if none.
 * @param outStatementInfo The {@link SQLiteStatementInfo} object to populate
 * with information about the statement, or null if none.
 *
 * @throws SQLiteException if an error occurs, such as a syntax error.
 * @throws OperationCanceledException if the operation was canceled.
 */
public void prepare(String sql, int connectionFlags, CancellationSignal cancellationSignal,
        SQLiteStatementInfo outStatementInfo) {
    if (sql == null) {
        throw new IllegalArgumentException("sql must not be null.");
    }

    if (cancellationSignal != null) {
        cancellationSignal.throwIfCanceled();
    }

    acquireConnection(sql, connectionFlags, cancellationSignal); // might throw
    try {
        mConnection.prepare(sql, outStatementInfo); // might throw
    } finally {
        releaseConnection(); // might throw
    }
}

From source file:io.requery.android.database.sqlite.SQLiteConnectionPool.java

private SQLiteConnection waitForConnection(String sql, int connectionFlags,
        CancellationSignal cancellationSignal) {
    final boolean wantPrimaryConnection = (connectionFlags & CONNECTION_FLAG_PRIMARY_CONNECTION_AFFINITY) != 0;

    final ConnectionWaiter waiter;
    final int nonce;
    synchronized (mLock) {
        throwIfClosedLocked();/* w  ww.  j a v a  2  s.com*/

        // Abort if canceled.
        if (cancellationSignal != null) {
            cancellationSignal.throwIfCanceled();
        }

        // Try to acquire a connection.
        SQLiteConnection connection = null;
        if (!wantPrimaryConnection) {
            connection = tryAcquireNonPrimaryConnectionLocked(sql, connectionFlags); // might throw
        }
        if (connection == null) {
            connection = tryAcquirePrimaryConnectionLocked(connectionFlags); // might throw
        }
        if (connection != null) {
            return connection;
        }

        // No connections available.  Enqueue a waiter in priority order.
        final int priority = getPriority(connectionFlags);
        final long startTime = SystemClock.uptimeMillis();
        waiter = obtainConnectionWaiterLocked(Thread.currentThread(), startTime, priority,
                wantPrimaryConnection, sql, connectionFlags);
        ConnectionWaiter predecessor = null;
        ConnectionWaiter successor = mConnectionWaiterQueue;
        while (successor != null) {
            if (priority > successor.mPriority) {
                waiter.mNext = successor;
                break;
            }
            predecessor = successor;
            successor = successor.mNext;
        }
        if (predecessor != null) {
            predecessor.mNext = waiter;
        } else {
            mConnectionWaiterQueue = waiter;
        }

        nonce = waiter.mNonce;
    }

    // Set up the cancellation listener.
    if (cancellationSignal != null) {
        cancellationSignal.setOnCancelListener(new CancellationSignal.OnCancelListener() {
            @Override
            public void onCancel() {
                synchronized (mLock) {
                    if (waiter.mNonce == nonce) {
                        cancelConnectionWaiterLocked(waiter);
                    }
                }
            }
        });
    }
    try {
        // Park the thread until a connection is assigned or the pool is closed.
        // Rethrow an exception from the wait, if we got one.
        long busyTimeoutMillis = CONNECTION_POOL_BUSY_MILLIS;
        long nextBusyTimeoutTime = waiter.mStartTime + busyTimeoutMillis;
        for (;;) {
            // Detect and recover from connection leaks.
            if (mConnectionLeaked.compareAndSet(true, false)) {
                synchronized (mLock) {
                    wakeConnectionWaitersLocked();
                }
            }

            // Wait to be unparked (may already have happened), a timeout, or interruption.
            LockSupport.parkNanos(this, busyTimeoutMillis * 1000000L);

            // Clear the interrupted flag, just in case.
            Thread.interrupted();

            // Check whether we are done waiting yet.
            synchronized (mLock) {
                throwIfClosedLocked();

                final SQLiteConnection connection = waiter.mAssignedConnection;
                final RuntimeException ex = waiter.mException;
                if (connection != null || ex != null) {
                    recycleConnectionWaiterLocked(waiter);
                    if (connection != null) {
                        return connection;
                    }
                    throw ex; // rethrow!
                }

                final long now = SystemClock.uptimeMillis();
                if (now < nextBusyTimeoutTime) {
                    busyTimeoutMillis = now - nextBusyTimeoutTime;
                } else {
                    logConnectionPoolBusyLocked(now - waiter.mStartTime, connectionFlags);
                    busyTimeoutMillis = CONNECTION_POOL_BUSY_MILLIS;
                    nextBusyTimeoutTime = now + busyTimeoutMillis;
                }
            }
        }
    } finally {
        // Remove the cancellation listener.
        if (cancellationSignal != null) {
            cancellationSignal.setOnCancelListener(null);
        }
    }
}

From source file:io.requery.android.database.sqlite.SQLiteConnection.java

private void attachCancellationSignal(CancellationSignal cancellationSignal) {
    if (cancellationSignal != null) {
        cancellationSignal.throwIfCanceled();

        mCancellationSignalAttachCount += 1;
        if (mCancellationSignalAttachCount == 1) {
            // Reset cancellation flag before executing the statement.
            nativeResetCancel(mConnectionPtr, true /*cancelable*/);

            // After this point, onCancel() may be called concurrently.
            cancellationSignal.setOnCancelListener(this);
        }//w  ww. j a v  a 2  s . c o m
    }
}