Search in sources :

Example 81 with Savepoint

use of java.sql.Savepoint in project CloudStack-archive by CloudStack-extras.

the class Transaction method setSavepoint.

public Savepoint setSavepoint(final String name) throws SQLException {
    _txn = true;
    StackElement st = new StackElement(START_TXN, null);
    _stack.push(st);
    final Connection conn = getConnection();
    final Savepoint sp = conn.setSavepoint(name);
    st.ref = sp;
    return sp;
}
Also used : Connection(java.sql.Connection) Savepoint(java.sql.Savepoint)

Example 82 with Savepoint

use of java.sql.Savepoint in project CloudStack-archive by CloudStack-extras.

the class Merovingian method doAcquire.

protected boolean doAcquire(String key) {
    Connection conn = getConnection(key, true);
    PreparedStatement pstmt = null;
    Savepoint sp = null;
    try {
        sp = conn.setSavepoint(key);
    } catch (SQLException e) {
        s_logger.warn("Unable to set save point " + key);
        return false;
    }
    try {
        long startTime = InaccurateClock.getTime();
        try {
            pstmt = conn.prepareStatement(ACQUIRE_SQL);
            pstmt.setString(1, key);
            pstmt.setString(2, s_macAddress);
            pstmt.setString(3, s_ipAddress);
            pstmt.setString(4, Thread.currentThread().getName());
            String exceptionMessage = null;
            int rows = pstmt.executeUpdate();
            if (rows == 1) {
                if (s_logger.isTraceEnabled()) {
                    s_logger.trace("Lock: lock acquired for " + key);
                }
                Ternary<Savepoint, Integer, Long> lock = new Ternary<Savepoint, Integer, Long>(sp, 1, InaccurateClock.getTime());
                _locks.put(key, lock);
                return true;
            }
        } catch (SQLException e) {
            s_logger.warn("Lock: Retrying lock " + key + ".  Waited " + (InaccurateClock.getTime() - startTime), e);
        }
        conn.rollback(sp);
        s_logger.trace("Lock: Unable to acquire DB lock " + key);
    } catch (SQLException e) {
        s_logger.warn("Lock: Unable to acquire db connection for locking " + key, e);
    } finally {
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
            }
        }
    }
    return false;
}
Also used : SQLException(java.sql.SQLException) Ternary(com.cloud.utils.Ternary) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Savepoint(java.sql.Savepoint) Savepoint(java.sql.Savepoint)

Example 83 with Savepoint

use of java.sql.Savepoint in project CloudStack-archive by CloudStack-extras.

the class Merovingian method acquire.

public boolean acquire(String key, int timeInSeconds) {
    Pair<Lock, Integer> memLock = null;
    boolean acquiredDbLock = false;
    boolean acquiredMemLock = false;
    try {
        synchronized (s_memLocks) {
            memLock = s_memLocks.get(key);
            if (memLock == null) {
                Lock l = new ReentrantLock(true);
                memLock = new Pair<Lock, Integer>(l, 0);
                s_memLocks.put(key, memLock);
            }
            memLock.second(memLock.second() + 1);
        }
        if (!memLock.first().tryLock(timeInSeconds, TimeUnit.SECONDS)) {
            return false;
        }
        acquiredMemLock = true;
        Ternary<Savepoint, Integer, Long> lock = _locks.get(key);
        if (lock != null) {
            lock.second(lock.second() + 1);
            if (s_logger.isTraceEnabled()) {
                s_logger.trace("Lock: Reacquiring " + key + " Count: " + lock.second());
            }
            acquiredDbLock = true;
            return true;
        }
        long startTime = InaccurateClock.getTime();
        while ((InaccurateClock.getTime() - startTime) < (timeInSeconds * 1000)) {
            if (isLocked(key)) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                }
            } else {
                acquiredDbLock = doAcquire(key);
                if (acquiredDbLock) {
                    return true;
                }
            }
        }
        if (s_logger.isTraceEnabled()) {
            s_logger.trace("Lock: Timed out on acquiring lock " + key);
        }
        return false;
    } catch (InterruptedException e) {
        s_logger.debug("Interrupted while trying to acquire " + key);
        return false;
    } finally {
        if (!acquiredMemLock || !acquiredDbLock) {
            synchronized (s_memLocks) {
                if (memLock.second(memLock.second() - 1) <= 0) {
                    s_memLocks.remove(key);
                }
            }
        }
        if (acquiredMemLock && !acquiredDbLock) {
            memLock.first().unlock();
        }
    }
}
Also used : ReentrantLock(java.util.concurrent.locks.ReentrantLock) Savepoint(java.sql.Savepoint) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Lock(java.util.concurrent.locks.Lock)

Example 84 with Savepoint

use of java.sql.Savepoint in project adempiere by adempiere.

the class PO method save.

//	is_new
/*
	 * Classes which override save() method:
	 * org.compiere.process.DocActionTemplate
	 * org.compiere.model.MClient
	 * org.compiere.model.MClientInfo
	 * org.compiere.model.MSystem
	 */
/**************************************************************************
	 *  Update Value or create new record.
	 * 	To reload call load() - not updated
	 *  @return true if saved
	 */
public boolean save() {
    CLogger.resetLast();
    //	save locally as load resets
    boolean newRecord = is_new();
    if (!newRecord && !is_Changed()) {
        log.fine("Nothing changed - " + p_info.getTableName());
        return true;
    }
    //	Organization Check
    if (getAD_Org_ID() == 0 && (get_AccessLevel() == ACCESSLEVEL_ORG || (get_AccessLevel() == ACCESSLEVEL_CLIENTORG && MClientShare.isOrgLevelOnly(getAD_Client_ID(), get_Table_ID())))) {
        log.saveError("FillMandatory", Msg.getElement(getCtx(), "AD_Org_ID"));
        return false;
    }
    //	Should be Org 0
    if (getAD_Org_ID() != 0) {
        boolean reset = get_AccessLevel() == ACCESSLEVEL_SYSTEM;
        if (!reset && MClientShare.isClientLevelOnly(getAD_Client_ID(), get_Table_ID())) {
            reset = get_AccessLevel() == ACCESSLEVEL_CLIENT || get_AccessLevel() == ACCESSLEVEL_SYSTEMCLIENT || get_AccessLevel() == ACCESSLEVEL_ALL || get_AccessLevel() == ACCESSLEVEL_CLIENTORG;
        }
        if (reset) {
            log.warning("Set Org to 0");
            setAD_Org_ID(0);
        }
    }
    Trx localTrx = null;
    Trx trx = null;
    Savepoint savepoint = null;
    if (m_trxName == null) {
        m_trxName = Trx.createTrxName("POSave");
        localTrx = Trx.get(m_trxName, true);
    } else {
        trx = Trx.get(m_trxName, false);
        if (trx == null) {
            // Using a trx that was previously closed or never opened
            // Creating and starting the transaction right here, but please note
            // that this is not a good practice
            trx = Trx.get(m_trxName, true);
            log.severe("Transaction closed or never opened (" + m_trxName + ") => starting now --> " + toString());
        }
    }
    //	Before Save
    try {
        // If not a localTrx we need to set a savepoint for rollback
        if (localTrx == null)
            savepoint = trx.setSavepoint(null);
        if (!beforeSave(newRecord)) {
            log.warning("beforeSave failed - " + toString());
            if (localTrx != null) {
                localTrx.rollback();
                localTrx.close();
                m_trxName = null;
            } else {
                trx.rollback(savepoint);
                savepoint = null;
            }
            return false;
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "beforeSave - " + toString(), e);
        log.saveError("Error", e, false);
        if (localTrx != null) {
            localTrx.rollback();
            localTrx.close();
            m_trxName = null;
        } else if (savepoint != null) {
            try {
                trx.rollback(savepoint);
            } catch (SQLException e1) {
            }
            savepoint = null;
        }
        return false;
    }
    try {
        // Call ModelValidators TYPE_NEW/TYPE_CHANGE
        String errorMsg = ModelValidationEngine.get().fireModelChange(this, newRecord ? ModelValidator.TYPE_NEW : ModelValidator.TYPE_CHANGE);
        if (errorMsg != null) {
            log.warning("Validation failed - " + errorMsg);
            log.saveError("Error", errorMsg);
            if (localTrx != null) {
                localTrx.rollback();
                m_trxName = null;
            } else {
                trx.rollback(savepoint);
            }
            return false;
        }
        //	Save
        if (newRecord) {
            boolean b = saveNew();
            if (b) {
                if (localTrx != null)
                    return localTrx.commit();
                else
                    return b;
            } else {
                if (localTrx != null)
                    localTrx.rollback();
                else
                    trx.rollback(savepoint);
                return b;
            }
        } else {
            boolean b = saveUpdate();
            if (b) {
                if (localTrx != null)
                    return localTrx.commit();
                else
                    return b;
            } else {
                if (localTrx != null)
                    localTrx.rollback();
                else
                    trx.rollback(savepoint);
                return b;
            }
        }
    } catch (SQLException e) {
        log.log(Level.WARNING, "afterSave - " + toString(), e);
        if (localTrx != null) {
            localTrx.rollback();
        } else if (savepoint != null) {
            try {
                trx.rollback(savepoint);
            } catch (SQLException e1) {
            }
            savepoint = null;
        }
        return false;
    } finally {
        if (localTrx != null) {
            localTrx.close();
            m_trxName = null;
        } else {
            if (savepoint != null) {
                try {
                    trx.releaseSavepoint(savepoint);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            savepoint = null;
            trx = null;
        }
    }
}
Also used : SQLException(java.sql.SQLException) Savepoint(java.sql.Savepoint) Trx(org.compiere.util.Trx) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException) AdempiereException(org.adempiere.exceptions.AdempiereException)

Example 85 with Savepoint

use of java.sql.Savepoint in project adempiere by adempiere.

the class MWFActivity method run.

//	getApproval
/**************************************************************************
	 * 	Execute Work.
	 * 	Called from MWFProcess.startNext
	 * 	Feedback to Process via setWFState -> checkActivities
	 */
public void run() {
    log.info("Node=" + getNode());
    m_newValue = null;
    //m_trx = Trx.get(, true);
    Trx trx = null;
    boolean localTrx = false;
    if (get_TrxName() == null) {
        this.set_TrxName(Trx.createTrxName("WFA"));
        localTrx = true;
    }
    trx = Trx.get(get_TrxName(), true);
    Savepoint savepoint = null;
    //
    try {
        if (!localTrx)
            savepoint = trx.setSavepoint(null);
        if (!m_state.isValidAction(StateEngine.ACTION_Start)) {
            setTextMsg("State=" + getWFState() + " - cannot start");
            addTextMsg(new Exception(""));
            setWFState(StateEngine.STATE_Terminated);
            return;
        }
        //
        setWFState(StateEngine.STATE_Running);
        if (getNode().get_ID() == 0) {
            setTextMsg("Node not found - AD_WF_Node_ID=" + getAD_WF_Node_ID());
            setWFState(StateEngine.STATE_Aborted);
            return;
        }
        //	Do Work
        /****	Trx Start	****/
        boolean done = performWork(Trx.get(get_TrxName(), false));
        // Reason: if the commit fails the document should be put in Invalid state
        if (localTrx) {
            try {
                trx.commit(true);
            } catch (Exception e) {
                // If we have a DocStatus, change it to Invalid, and throw the exception to the next level
                if (m_docStatus != null)
                    m_docStatus = DocAction.STATUS_Invalid;
                throw e;
            }
        }
        setWFState(done ? StateEngine.STATE_Completed : StateEngine.STATE_Suspended);
    } catch (Exception e) {
        log.log(Level.WARNING, "" + getNode(), e);
        /****	Trx Rollback	****/
        if (localTrx) {
            trx.rollback();
        } else if (savepoint != null) {
            try {
                trx.rollback(savepoint);
            } catch (SQLException e1) {
            }
        }
        //
        if (e.getCause() != null)
            log.log(Level.WARNING, "Cause", e.getCause());
        String processMsg = e.getLocalizedMessage();
        if (processMsg == null || processMsg.length() == 0)
            processMsg = e.getMessage();
        setTextMsg(processMsg);
        addTextMsg(e);
        //	unlocks
        setWFState(StateEngine.STATE_Terminated);
        //	Set Document Status 
        if (m_po != null && m_po instanceof DocAction && m_docStatus != null) {
            m_po.load(get_TrxName());
            DocAction doc = (DocAction) m_po;
            doc.setDocStatus(m_docStatus);
            m_po.saveEx();
        }
    } finally {
        if (localTrx && trx != null) {
            trx.close();
        }
    }
}
Also used : DocAction(org.compiere.process.DocAction) SQLException(java.sql.SQLException) Savepoint(java.sql.Savepoint) Trx(org.compiere.util.Trx) SQLException(java.sql.SQLException) AdempiereException(org.adempiere.exceptions.AdempiereException)

Aggregations

Savepoint (java.sql.Savepoint)167 Statement (java.sql.Statement)61 Connection (java.sql.Connection)56 SQLException (java.sql.SQLException)55 PreparedStatement (java.sql.PreparedStatement)32 Test (org.junit.Test)31 ResultSet (java.sql.ResultSet)26 DatabaseMetaData (java.sql.DatabaseMetaData)13 UnitTest (nl.topicus.jdbc.test.category.UnitTest)13 TransactionStatus (org.springframework.transaction.TransactionStatus)12 TransactionCallbackWithoutResult (org.springframework.transaction.support.TransactionCallbackWithoutResult)12 TransactionTemplate (org.springframework.transaction.support.TransactionTemplate)12 ArrayList (java.util.ArrayList)11 Vector (java.util.Vector)11 Test (org.junit.jupiter.api.Test)10 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)10 SQLClientInfoException (java.sql.SQLClientInfoException)7 HashMap (java.util.HashMap)5 ConcurrencyFailureException (org.springframework.dao.ConcurrencyFailureException)5 SQLFeatureNotSupportedException (java.sql.SQLFeatureNotSupportedException)4