Search in sources :

Example 41 with Trx

use of org.compiere.util.Trx 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 42 with Trx

use of org.compiere.util.Trx in project adempiere by adempiere.

the class MWorkflow method start.

/**************************************************************************
	 * 	Start Workflow.
	 * 	@param pi Process Info (Record_ID)
	 *	@return process
	 */
public MWFProcess start(ProcessInfo pi, String trxName) {
    MWFProcess workflowProcess = null;
    Trx localTrx = null;
    if (trxName == null)
        localTrx = Trx.get(Trx.createTrxName("WFP"), true);
    try {
        if (MWorkflow.WORKFLOWTYPE_DocumentProcess.equals(getWorkflowType()) && isLock(getAD_Table_ID(), pi.getRecord_ID()))
            throw new IllegalStateException(Msg.getMsg(getCtx(), "OtherProcessActive"));
        else if (MWorkflow.WORKFLOWTYPE_DocumentProcess.equals(getWorkflowType()))
            lock(getAD_Table_ID(), pi.getRecord_ID());
        workflowProcess = new MWFProcess(this, pi, trxName != null ? trxName : localTrx.getTrxName());
        workflowProcess.saveEx();
        pi.setSummary(Msg.getMsg(getCtx(), "Processing"));
        workflowProcess.startWork();
        if (localTrx != null)
            localTrx.commit(true);
        if (MWorkflow.WORKFLOWTYPE_DocumentProcess.equals(getWorkflowType()))
            unlock(getAD_Table_ID(), pi.getRecord_ID());
    } catch (Exception e) {
        if (localTrx != null)
            localTrx.rollback();
        log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        pi.setSummary(e.getMessage(), true);
        workflowProcess = null;
    } finally {
        if (localTrx != null)
            localTrx.close();
    }
    return workflowProcess;
}
Also used : Trx(org.compiere.util.Trx) DBException(org.adempiere.exceptions.DBException) SQLException(java.sql.SQLException)

Example 43 with Trx

use of org.compiere.util.Trx in project adempiere by adempiere.

the class AdempiereTestCase method rollback.

/**
	 * Rollback active transaction
	 */
protected void rollback() {
    Trx trx = null;
    if (trxName != null)
        trx = Trx.get(trxName, false);
    if (trx != null && trx.isActive()) {
        try {
            trx.rollback();
        } finally {
            trx.close();
        }
    }
    trx = null;
}
Also used : Trx(org.compiere.util.Trx)

Example 44 with Trx

use of org.compiere.util.Trx in project adempiere by adempiere.

the class ModelADServiceImpl method setDocAction.

/*
	 * Model oriented web service to change DocAction for documents, i.e. Complete a Material Receipt
	 * WARNING!!! This web service complete documents not via workflow, so it jump over any approval step considered in document workflow
	 *   To complete documents using workflow it's better to use the runProcess web service
	 */
public StandardResponseDocument setDocAction(ModelSetDocActionRequestDocument req) throws XFireFault {
    StandardResponseDocument ret = StandardResponseDocument.Factory.newInstance();
    StandardResponse resp = ret.addNewStandardResponse();
    ModelSetDocAction modelSetDocAction = req.getModelSetDocActionRequest().getModelSetDocAction();
    String serviceType = modelSetDocAction.getServiceType();
    ADLoginRequest reqlogin = req.getModelSetDocActionRequest().getADLoginRequest();
    String err = modelLogin(reqlogin, webServiceName, "setDocAction", serviceType);
    if (err != null && err.length() > 0) {
        resp.setError(err);
        resp.setIsError(true);
        return ret;
    }
    Properties ctx = m_cs.getM_ctx();
    // Validate parameters
    modelSetDocAction.setTableName(validateParameter("tableName", modelSetDocAction.getTableName()));
    modelSetDocAction.setRecordID(validateParameter("recordID", modelSetDocAction.getRecordID()));
    modelSetDocAction.setDocAction(validateParameter("docAction", modelSetDocAction.getDocAction()));
    String tableName = modelSetDocAction.getTableName();
    int recordID = modelSetDocAction.getRecordID();
    String docAction = modelSetDocAction.getDocAction();
    resp.setRecordID(recordID);
    // start a trx
    String trxName = Trx.createTrxName("ws_modelSetDocAction");
    Trx trx = Trx.get(trxName, false);
    // get the PO for the tablename and record ID
    MTable table = MTable.get(ctx, tableName);
    if (table == null)
        return rollbackAndSetError(trx, resp, ret, true, "No table " + tableName);
    PO po = table.getPO(recordID, trxName);
    if (po == null)
        return rollbackAndSetError(trx, resp, ret, true, "No Record " + recordID + " in " + tableName);
    // set explicitly the column DocAction to avoid automatic process of default option
    po.set_ValueOfColumn("DocAction", docAction);
    if (!po.save())
        return rollbackAndSetError(trx, resp, ret, true, "Cannot save before set docAction: " + CLogger.retrieveErrorString("no log message"));
    // call process it
    try {
        if (!((org.compiere.process.DocAction) po).processIt(docAction))
            return rollbackAndSetError(trx, resp, ret, true, "Couldn't set docAction: " + ((org.compiere.process.DocAction) po).getProcessMsg());
    } catch (Exception e) {
        return rollbackAndSetError(trx, resp, ret, true, e.toString());
    }
    // close the trx
    if (!po.save())
        return rollbackAndSetError(trx, resp, ret, true, "Cannot save after set docAction: " + CLogger.retrieveErrorString("no log message"));
    if (!trx.commit())
        return rollbackAndSetError(trx, resp, ret, true, "Cannot commit after docAction");
    trx.close();
    // resp.setError("");
    resp.setIsError(false);
    return ret;
}
Also used : ADLoginRequest(pl.x3E.adInterface.ADLoginRequest) StandardResponse(pl.x3E.adInterface.StandardResponse) Properties(java.util.Properties) ModelSetDocAction(pl.x3E.adInterface.ModelSetDocAction) SQLException(java.sql.SQLException) StandardResponseDocument(pl.x3E.adInterface.StandardResponseDocument) MTable(org.compiere.model.MTable) Trx(org.compiere.util.Trx) PO(org.compiere.model.PO)

Example 45 with Trx

use of org.compiere.util.Trx in project adempiere by adempiere.

the class OrderDistributionReceipt method generate.

//	saveSelection
/**************************************************************************
	 *	Generate Movements
	 */
public String generate(MiniTable miniTable, IStatusBar statusBar, String docActionSelected) {
    String info = "";
    log.info("DD_Order_ID=" + m_DD_Order_ID);
    log.info("MovementDate" + m_MovementDate);
    String trxName = Trx.createTrxName("MVG");
    Trx trx = Trx.get(trxName, true);
    //  prevents from being called twice
    setSelectionActive(false);
    statusBar.setStatusLine(Msg.translate(Env.getCtx(), "M_Movement_ID"));
    statusBar.setStatusDB(String.valueOf(getSelection().size()));
    Properties m_ctx = Env.getCtx();
    Timestamp movementDate = (Timestamp) m_MovementDate;
    MDDOrder order = new MDDOrder(m_ctx, Integer.parseInt(m_DD_Order_ID.toString()), trxName);
    MMovement movement = new MMovement(order, movementDate);
    movement.saveEx();
    ArrayList<Integer> ids = getSelection();
    int i = 0;
    for (int DD_OrderLine_ID : ids) {
        MDDOrderLine oline = new MDDOrderLine(m_ctx, DD_OrderLine_ID, trxName);
        MMovementLine line = new MMovementLine(movement);
        line.setM_Product_ID(oline.getM_Product_ID());
        BigDecimal QtyDeliver = (BigDecimal) miniTable.getValueAt(i, 1);
        if (QtyDeliver == null | QtyDeliver.compareTo(oline.getQtyInTransit()) > 0)
            throw new AdempiereException("Error in Qty");
        line.setOrderLine(oline, QtyDeliver, true);
        line.saveEx();
        i++;
    }
    //	Fails if there is a confirmation
    if (!movement.processIt(MMovement.ACTION_Complete))
        log.warning("Failed: " + movement);
    movement.setDocStatus(MMovement.DOCACTION_Complete);
    movement.setDocAction(MMovement.ACTION_Close);
    movement.saveEx();
    return info;
}
Also used : Properties(java.util.Properties) Timestamp(java.sql.Timestamp) BigDecimal(java.math.BigDecimal) MDDOrderLine(org.eevolution.model.MDDOrderLine) AdempiereException(org.adempiere.exceptions.AdempiereException) Trx(org.compiere.util.Trx) MDDOrder(org.eevolution.model.MDDOrder) MMovementLine(org.compiere.model.MMovementLine) MMovement(org.compiere.model.MMovement)

Aggregations

Trx (org.compiere.util.Trx)62 SQLException (java.sql.SQLException)21 ProcessInfo (org.compiere.process.ProcessInfo)17 AdempiereException (org.adempiere.exceptions.AdempiereException)13 MPInstance (org.compiere.model.MPInstance)12 DBException (org.adempiere.exceptions.DBException)11 Timestamp (java.sql.Timestamp)9 File (java.io.File)8 Connection (java.sql.Connection)8 Properties (java.util.Properties)8 MPInstancePara (org.compiere.model.MPInstancePara)8 PreparedStatement (java.sql.PreparedStatement)7 ResultSet (java.sql.ResultSet)7 BigDecimal (java.math.BigDecimal)6 IOException (java.io.IOException)5 CConnection (org.compiere.db.CConnection)5 MTable (org.compiere.model.MTable)5 PO (org.compiere.model.PO)5 SimpleDateFormat (java.text.SimpleDateFormat)4 ServletException (javax.servlet.ServletException)4