Search in sources :

Example 21 with Trx

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

the class InvoiceGenFromShipment method generate.

/**************************************************************************
	 *	Generate Invoices
	 */
public String generate(IStatusBar statusBar, KeyNamePair docTypeKNPair, String docActionSelected) {
    String info = "";
    String trxName = Trx.createTrxName("IVG");
    //trx needs to be committed too
    Trx trx = Trx.get(trxName, true);
    //  prevents from being called twice
    setSelectionActive(false);
    statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InvGenerateGen"));
    statusBar.setStatusDB(String.valueOf(getSelection().size()));
    //	Prepare Process
    int AD_Process_ID = 0;
    if (docTypeKNPair.getKey() == MInOut.Table_ID) {
        // HARDCODED- AD_Process.Value=C_Invoice_Generate_from_Shipment; class=org.adempiere.process.InvoiceGenerateFromShipment
        AD_Process_ID = 53345;
    } else {
    //        	AD_Process_ID = 52002; // AD_Process.Value=C_Invoice_GenerateRMA (Manual); class=org.adempiere.process.InvoiceGenerateRMA
    }
    MPInstance instance = new MPInstance(Env.getCtx(), AD_Process_ID, 0);
    if (!instance.save()) {
        info = Msg.getMsg(Env.getCtx(), "ProcessNoInstance");
        return info;
    }
    //insert selection
    StringBuffer insert = new StringBuffer();
    insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
    int counter = 0;
    for (Integer selectedId : getSelection()) {
        counter++;
        if (counter > 1)
            insert.append(" UNION ");
        insert.append("SELECT ");
        insert.append(instance.getAD_PInstance_ID());
        insert.append(", ");
        insert.append(selectedId);
        insert.append(" FROM DUAL ");
        if (counter == 1000) {
            if (DB.executeUpdate(insert.toString(), trxName) < 0) {
                //  not translated!
                String msg = "No Invoices";
                info = msg;
                log.config(msg);
                trx.rollback();
                return info;
            }
            insert = new StringBuffer();
            insert.append("INSERT INTO T_SELECTION(AD_PINSTANCE_ID, T_SELECTION_ID) ");
            counter = 0;
        }
    }
    if (counter > 0) {
        if (DB.executeUpdate(insert.toString(), trxName) < 0) {
            //  not translated!
            String msg = "No Invoices";
            info = msg;
            log.config(msg);
            trx.rollback();
            return info;
        }
    }
    ProcessInfo pi = new ProcessInfo("", AD_Process_ID);
    pi.setAD_PInstance_ID(instance.getAD_PInstance_ID());
    //	Add Parameters
    MPInstancePara para = new MPInstancePara(instance, 10);
    para.setParameter("Selection", "Y");
    if (!para.save()) {
        //  not translated
        String msg = "No Selection Parameter added";
        info = msg;
        log.log(Level.SEVERE, msg);
        return info;
    }
    para = new MPInstancePara(instance, 20);
    para.setParameter("DocAction", docActionSelected);
    if (!para.save()) {
        //  not translated
        String msg = "No DocAction Parameter added";
        info = msg;
        log.log(Level.SEVERE, msg);
        return info;
    }
    setTrx(trx);
    setProcessInfo(pi);
    return info;
}
Also used : MPInstancePara(org.compiere.model.MPInstancePara) MPInstance(org.compiere.model.MPInstance) Trx(org.compiere.util.Trx) ProcessInfo(org.compiere.process.ProcessInfo)

Example 22 with Trx

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

the class GridController method vetoableChange.

/**************************************************************************
	 *  Vetoable Change Listener.
	 * 	Called from VEditor
	 *  <pre>
	 *  - for Save Confirmation dialog
	 *  - for Single Row from VEditor: Update MTable
	 *  </pre>
	 *  @param e event
	 *  @throws PropertyVetoException
	 */
public void vetoableChange(PropertyChangeEvent e) throws PropertyVetoException {
    if (//	only active records
    m_mTab.isProcessed() || !m_mTab.isActive()) {
        Object source = e.getSource();
        if (source instanceof VEditor) {
            if (!((VEditor) source).isReadWrite()) {
                log.config("(" + m_mTab.toString() + ") " + e.getPropertyName());
                return;
            }
        } else {
            log.config("(" + m_mTab.toString() + ") " + e.getPropertyName());
            return;
        }
    }
    //	processed
    log.config("(" + m_mTab.toString() + ") " + e.getPropertyName() + "=" + e.getNewValue() + " (" + e.getOldValue() + ") " + (e.getOldValue() == null ? "" : e.getOldValue().getClass().getName()));
    //  Save Confirmation dialog    MTable-RowSave
    if (e.getPropertyName().equals(GridTable.PROPERTY)) {
        //  throw new PropertyVetoException will call this listener again to revert to old value
        if (m_vetoActive) {
            //ignore
            m_vetoActive = false;
            return;
        }
        if (!Env.isAutoCommit(Env.getCtx(), m_WindowNo) || m_mTab.getCommitWarning().length() > 0) {
            if (!ADialog.ask(m_WindowNo, this, "SaveChanges?", m_mTab.getCommitWarning())) {
                m_vetoActive = true;
                throw new PropertyVetoException("UserDeniedSave", e);
            }
        }
        return;
    }
    //  saveConfirmation
    //  Get Row/Col Info
    GridTable mTable = m_mTab.getTableModel();
    int row = m_mTab.getCurrentRow();
    int col = mTable.findColumn(e.getPropertyName());
    //
    if ((e.getNewValue() == null || e.getNewValue().toString().isEmpty()) && e.getOldValue() != null && //	some editors return "" instead of null
    e.getOldValue().toString().length() > 0) {
        //  #283 Set value to null
        GridField gridField = m_mTab.getField(col);
        if (!gridField.getVO().IsMandatory)
            //	-> dataStatusChanged -> dynamicDisplay
            mTable.setValueAt(null, row, col);
        mTable.setChanged(true);
    } else {
        //	mTable.setValueAt (e.getNewValue(), row, col, true);
        /*
         	 * Changes: Added the logic below to handle multiple values for a single field
         	 *          due to multiple selection in Lookup (Info).
         	 * @author ashley
         	 */
        Object newValue = e.getNewValue();
        Integer[] newValues = null;
        if (newValue instanceof Integer[]) {
            newValues = ((Integer[]) newValue);
            newValue = newValues[0];
            if (newValues.length > 1) {
                Integer[] valuesCopy = new Integer[newValues.length - 1];
                System.arraycopy(newValues, 1, valuesCopy, 0, valuesCopy.length);
                newValues = valuesCopy;
            } else {
                newValues = null;
            }
        } else if (newValue instanceof Object[]) {
            log.severe("Multiple values can only be processed for IDs (Integer)");
            throw new PropertyVetoException("Multiple Selection values not available for this field", e);
        }
        //	-> dataStatusChanged -> dynamicDisplay
        mTable.setValueAt(newValue, row, col);
        //	Force Callout
        if (e.getPropertyName().equals("S_ResourceAssignment_ID")) {
            GridField mField = m_mTab.getField(col);
            if (mField != null && mField.getCallout().length() > 0)
                //  Dependencies & Callout
                m_mTab.processFieldChange(mField);
        }
        if (newValues != null && newValues.length > 0) {
            // Save data, since record need to be used for generating clones.
            if (!m_mTab.dataSave(false)) {
                throw new PropertyVetoException("SaveError", e);
            }
            // Retrieve the current record ID
            int recordId = m_mTab.getKeyID(m_mTab.getCurrentRow());
            Trx trx = Trx.get(Trx.createTrxName(), true);
            trx.start();
            try {
                saveMultipleRecords(Env.getCtx(), mTable.getTableName(), e.getPropertyName(), recordId, newValues, trx.getTrxName());
                trx.commit();
                m_mTab.dataRefreshAll();
            } catch (Exception ex) {
                trx.rollback();
                log.severe(ex.getMessage());
                throw new PropertyVetoException("SaveError", e);
            } finally {
                trx.close();
            }
        }
    }
//	log.config( "GridController.vetoableChange (" + m_mTab.toString() + ") - fini", e.getPropertyName() + "=" + e.getNewValue());
}
Also used : PropertyVetoException(java.beans.PropertyVetoException) GridTable(org.compiere.model.GridTable) VEditor(org.compiere.grid.ed.VEditor) GridField(org.compiere.model.GridField) Trx(org.compiere.util.Trx) PropertyVetoException(java.beans.PropertyVetoException)

Example 23 with Trx

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

the class CPOS method setPOReference.

/**
	 * Set Purchase Order Reference 
	 * @param documentNo
	 * @return void
	 */
public void setPOReference(String documentNo) {
    String trxName = currentOrder.get_TrxName();
    Trx trx = Trx.get(trxName, true);
    currentOrder.setPOReference(documentNo);
    currentOrder.saveEx(trx.getTrxName());
    trx.close();
}
Also used : Trx(org.compiere.util.Trx)

Example 24 with Trx

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

the class PO_LOB method save.

//	save
/**
	 * 	Save LOB.
	 * 	see also org.compiere.session.ServerBean#updateLOB
	 * 	@param trxName trx name
	 *	@return true if saved
	 */
public boolean save(String trxName) {
    if (m_value == null || (!(m_value instanceof String || m_value instanceof byte[])) || (m_value instanceof String && m_value.toString().length() == 0) || (m_value instanceof byte[] && ((byte[]) m_value).length == 0)) {
        StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=null WHERE ").append(m_whereClause);
        int no = DB.executeUpdate(sql.toString(), trxName);
        log.fine("save [" + trxName + "] #" + no + " - no data - set to null - " + m_value);
        if (no == 0)
            log.warning("[" + trxName + "] - not updated - " + sql);
        return true;
    }
    StringBuffer sql = new StringBuffer("UPDATE ").append(m_tableName).append(" SET ").append(m_columnName).append("=? WHERE ").append(m_whereClause);
    //
    log.fine("[" + trxName + "] - Local - " + m_value);
    //	Connection
    Trx trx = null;
    if (trxName != null)
        trx = Trx.get(trxName, false);
    Connection con = null;
    //	Create Connection
    if (trx != null)
        con = trx.getConnection();
    if (con == null)
        con = DB.createConnection(false, Connection.TRANSACTION_READ_COMMITTED);
    if (con == null) {
        log.log(Level.SEVERE, "Could not get Connection");
        return false;
    }
    PreparedStatement pstmt = null;
    boolean success = true;
    try {
        pstmt = con.prepareStatement(sql.toString());
        if (DisplayType.isText(m_displayType))
            pstmt.setString(1, (String) m_value);
        else
            pstmt.setBytes(1, (byte[]) m_value);
        int no = pstmt.executeUpdate();
        if (no != 1) {
            log.warning("[" + trxName + "] - Not updated #" + no + " - " + sql);
            success = false;
        }
    } catch (Throwable e) {
        log.log(Level.SEVERE, "[" + trxName + "] - " + sql, e);
        success = false;
    } finally {
        DB.close(pstmt);
        pstmt = null;
    }
    //	Success - commit local trx
    if (success) {
        if (trx != null) {
            trx = null;
            con = null;
        } else {
            try {
                con.commit();
            } catch (Exception e) {
                log.log(Level.SEVERE, "[" + trxName + "] - commit ", e);
                success = false;
            } finally {
                try {
                    con.close();
                } catch (SQLException e) {
                }
                con = null;
            }
        }
    }
    //	Error - roll back
    if (!success) {
        log.severe("[" + trxName + "] - rollback");
        if (trx != null) {
            trx.rollback();
            trx = null;
            con = null;
        } else {
            try {
                con.rollback();
            } catch (Exception ee) {
                log.log(Level.SEVERE, "[" + trxName + "] - rollback", ee);
            } finally {
                try {
                    con.close();
                } catch (SQLException e) {
                }
                con = null;
            }
        }
    }
    return success;
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) Trx(org.compiere.util.Trx) SQLException(java.sql.SQLException)

Example 25 with Trx

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

the class WFActivity method cmd_OK.

//	cmd_button
/**
	 * 	Save
	 */
private void cmd_OK() {
    log.config("Activity=" + m_activity);
    if (m_activity == null)
        return;
    int AD_User_ID = Env.getAD_User_ID(Env.getCtx());
    String textMsg = fTextMsg.getText();
    //
    MWFNode node = m_activity.getNode();
    Object forward = fForward.getValue();
    // ensure activity is ran within a transaction - [ 1953628 ]
    Trx trx = Trx.get(Trx.createTrxName("FWFA"), true);
    m_activity.set_TrxName(trx.getTrxName());
    if (forward != null) {
        log.config("Forward to " + forward);
        int fw = ((Integer) forward).intValue();
        if (fw == AD_User_ID || fw == 0) {
            log.log(Level.SEVERE, "Forward User=" + fw);
            trx.rollback();
            trx.close();
            return;
        }
        if (!m_activity.forwardTo(fw, textMsg)) {
            ADialog.error(m_WindowNo, this, "CannotForward");
            trx.rollback();
            trx.close();
            return;
        }
    } else //	User Choice - Answer
    if (MWFNode.ACTION_UserChoice.equals(node.getAction())) {
        if (m_column == null)
            m_column = node.getColumn();
        //	Do we have an answer?
        int dt = m_column.getAD_Reference_ID();
        String value = fAnswerText.getText();
        if (dt == DisplayType.YesNo || dt == DisplayType.List) {
            ValueNamePair pp = (ValueNamePair) fAnswerList.getSelectedItem();
            value = pp.getValue();
        }
        if (value == null || value.length() == 0) {
            ADialog.error(m_WindowNo, this, "FillMandatory", Msg.getMsg(Env.getCtx(), "Answer"));
            trx.rollback();
            trx.close();
            return;
        }
        //
        log.config("Answer=" + value + " - " + textMsg);
        try {
            m_activity.setUserChoice(AD_User_ID, value, dt, textMsg);
        } catch (Exception e) {
            log.log(Level.SEVERE, node.getName(), e);
            ADialog.error(m_WindowNo, this, "Error", e.toString());
            trx.rollback();
            trx.close();
            return;
        }
    } else //	User Action
    {
        log.config("Action=" + node.getAction() + " - " + textMsg);
        try {
            // ensure activity is ran within a transaction
            m_activity.setUserConfirmation(AD_User_ID, textMsg);
        } catch (Exception e) {
            log.log(Level.SEVERE, node.getName(), e);
            ADialog.error(m_WindowNo, this, "Error", e.toString());
            trx.rollback();
            trx.close();
            return;
        }
    }
    trx.commit();
    trx.close();
    this.setCursor(Cursor.getDefaultCursor());
    ADialog.info(m_WindowNo, this, "WorkflowResult", Msg.parseTranslation(Env.getCtx(), "@AD_WF_Node_ID@") + " : " + m_activity.getNodeName() + " -> " + m_activity.getTextMsg());
    //	Next
    loadActivities();
}
Also used : MWFNode(org.compiere.wf.MWFNode) Trx(org.compiere.util.Trx) ValueNamePair(org.compiere.util.ValueNamePair)

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