Search in sources :

Example 16 with Trx

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

the class ModelADServiceImpl method deleteData.

// getList
public StandardResponseDocument deleteData(ModelCRUDRequestDocument req) throws XFireFault {
    StandardResponseDocument ret = StandardResponseDocument.Factory.newInstance();
    StandardResponse resp = ret.addNewStandardResponse();
    ModelCRUD modelCRUD = req.getModelCRUDRequest().getModelCRUD();
    String serviceType = modelCRUD.getServiceType();
    ADLoginRequest reqlogin = req.getModelCRUDRequest().getADLoginRequest();
    String err = modelLogin(reqlogin, webServiceName, "deleteData", serviceType);
    if (err != null && err.length() > 0) {
        resp.setError(err);
        resp.setIsError(true);
        return ret;
    }
    // Validate parameters vs service type
    validateCRUD(modelCRUD);
    String tableName = modelCRUD.getTableName();
    int recordID = modelCRUD.getRecordID();
    resp.setRecordID(recordID);
    Properties ctx = m_cs.getM_ctx();
    // start a trx
    String trxName = Trx.createTrxName("ws_modelDeleteData");
    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);
    if (!po.delete(false))
        return rollbackAndSetError(trx, resp, ret, true, "Cannot delete record " + recordID + " in " + tableName + ": " + CLogger.retrieveErrorString("no log message"));
    // close the trx
    if (!trx.commit())
        return rollbackAndSetError(trx, resp, ret, true, "Cannot commit transaction after delete record " + recordID + " in " + tableName);
    trx.close();
    return ret;
}
Also used : ADLoginRequest(pl.x3E.adInterface.ADLoginRequest) MTable(org.compiere.model.MTable) StandardResponse(pl.x3E.adInterface.StandardResponse) ModelCRUD(pl.x3E.adInterface.ModelCRUD) Trx(org.compiere.util.Trx) Properties(java.util.Properties) StandardResponseDocument(pl.x3E.adInterface.StandardResponseDocument) PO(org.compiere.model.PO)

Example 17 with Trx

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

the class ModelADServiceImpl method createData.

public StandardResponseDocument createData(ModelCRUDRequestDocument req) throws XFireFault {
    StandardResponseDocument ret = StandardResponseDocument.Factory.newInstance();
    StandardResponse resp = ret.addNewStandardResponse();
    ModelCRUD modelCRUD = req.getModelCRUDRequest().getModelCRUD();
    String serviceType = modelCRUD.getServiceType();
    ADLoginRequest reqlogin = req.getModelCRUDRequest().getADLoginRequest();
    String err = modelLogin(reqlogin, webServiceName, "createData", serviceType);
    if (err != null && err.length() > 0) {
        resp.setError(err);
        resp.setIsError(true);
        return ret;
    }
    // Validate parameters vs service type
    validateCRUD(modelCRUD);
    String tableName = modelCRUD.getTableName();
    Properties ctx = m_cs.getM_ctx();
    // start a trx
    String trxName = Trx.createTrxName("ws_modelCreateData");
    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(0, trxName);
    if (po == null)
        return rollbackAndSetError(trx, resp, ret, true, "Cannot create PO for " + tableName);
    POInfo poinfo = POInfo.getPOInfo(ctx, table.getAD_Table_ID());
    DataRow dr = modelCRUD.getDataRow();
    for (DataField field : dr.getFieldList()) {
        // TODO: Implement lookup
        if (m_webservicetype.isInputColumnNameAllowed(field.getColumn())) {
            int idxcol = po.get_ColumnIndex(field.getColumn());
            if (idxcol < 0) {
                // The column doesn't exist - it must exist as it's defined in security
                return rollbackAndSetError(trx, resp, ret, true, "Web service type " + m_webservicetype.getValue() + ": input column " + field.getColumn() + " does not exist");
            } else {
                try {
                    setValueAccordingToClass(po, poinfo, field, idxcol);
                } catch (XFireFault e) {
                    log.log(Level.WARNING, "Error setting value", e);
                    return rollbackAndSetError(trx, resp, ret, true, "Web service type " + m_webservicetype.getValue() + ": input column " + field.getColumn() + " value could not be set: " + e.getLocalizedMessage());
                }
            }
        } else {
            return rollbackAndSetError(trx, resp, ret, true, "Web service type " + m_webservicetype.getValue() + ": input column " + field.getColumn() + " not allowed");
        }
    }
    if (!po.save())
        return rollbackAndSetError(trx, resp, ret, true, "Cannot save record in " + tableName + ": " + CLogger.retrieveErrorString("no log message"));
    int recordID = po.get_ID();
    resp.setRecordID(recordID);
    // close the trx
    if (!trx.commit())
        return rollbackAndSetError(trx, resp, ret, true, "Cannot commit transaction after create record " + recordID + " in " + tableName);
    trx.close();
    return ret;
}
Also used : ADLoginRequest(pl.x3E.adInterface.ADLoginRequest) StandardResponse(pl.x3E.adInterface.StandardResponse) Properties(java.util.Properties) XFireFault(org.codehaus.xfire.fault.XFireFault) DataRow(pl.x3E.adInterface.DataRow) StandardResponseDocument(pl.x3E.adInterface.StandardResponseDocument) POInfo(org.compiere.model.POInfo) MTable(org.compiere.model.MTable) DataField(pl.x3E.adInterface.DataField) ModelCRUD(pl.x3E.adInterface.ModelCRUD) Trx(org.compiere.util.Trx) PO(org.compiere.model.PO)

Example 18 with Trx

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

the class GridTabDataBinder method valueChange.

/**
	 * @param e
	 */
public void valueChange(ValueChangeEvent e) {
    if (//  only active records
    gridTab.isProcessed()) {
        Object source = e.getSource();
        if (source instanceof WEditor) {
            // Elaine 2009/05/06
            WEditor editor = (WEditor) source;
            GridField gridField = editor.getGridField();
            if (gridField != null) {
                if (!gridField.isEditable(true)) {
                    logger.config("(" + gridTab.toString() + ") " + e.getPropertyName());
                    return;
                }
            } else if (!editor.isReadWrite()) {
                logger.config("(" + gridTab.toString() + ") " + e.getPropertyName());
                return;
            }
        } else {
            logger.config("(" + gridTab.toString() + ") " + e.getPropertyName());
            return;
        }
    }
    //  processed
    logger.config("(" + gridTab.toString() + ") " + e.getPropertyName() + "=" + e.getNewValue() + " (" + e.getOldValue() + ") " + (e.getOldValue() == null ? "" : e.getOldValue().getClass().getName()));
    //  Get Row/Col Info
    GridTable mTable = gridTab.getTableModel();
    int row = gridTab.getCurrentRow();
    int col = mTable.findColumn(e.getPropertyName());
    //
    if (e.getNewValue() == null && e.getOldValue() != null && //  some editors return "" instead of null
    e.getOldValue().toString().length() > 0)
        //        	  this is the original code from GridController, don't know what it does there but it breaks ignore button for web ui        
        //            mTable.setChanged (true);  
        mTable.setValueAt(e.getNewValue(), row, col);
    else {
        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[]) {
            logger.severe("Multiple values can only be processed for IDs (Integer)");
            throw new IllegalArgumentException("Multiple Selection values not available for this field. " + e.getPropertyName());
        }
        mTable.setValueAt(newValue, row, col);
        //  Force Callout
        if (e.getPropertyName().equals("S_ResourceAssignment_ID")) {
            GridField mField = gridTab.getField(col);
            if (mField != null && mField.getCallout().length() > 0) {
                //  Dependencies & Callout
                gridTab.processFieldChange(mField);
            }
        }
        if (newValues != null && newValues.length > 0) {
            // Save data, since record need to be used for generating clones.
            if (!gridTab.dataSave(false)) {
                throw new AdempiereException("SaveError");
            }
            // Retrieve the current record ID
            int recordId = gridTab.getKeyID(gridTab.getCurrentRow());
            Trx trx = Trx.get(Trx.createTrxName(), true);
            trx.start();
            try {
                saveMultipleRecords(Env.getCtx(), gridTab.getTableName(), e.getPropertyName(), recordId, newValues, trx.getTrxName());
                trx.commit();
                gridTab.dataRefreshAll();
            } catch (Exception ex) {
                trx.rollback();
                logger.severe(ex.getMessage());
                throw new AdempiereException("SaveError");
            } finally {
                trx.close();
            }
        }
    }
}
Also used : AdempiereException(org.adempiere.exceptions.AdempiereException) GridTable(org.compiere.model.GridTable) WEditor(org.adempiere.webui.editor.WEditor) GridField(org.compiere.model.GridField) Trx(org.compiere.util.Trx) AdempiereException(org.adempiere.exceptions.AdempiereException)

Example 19 with Trx

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

the class MSequence method getDocumentNo.

/**
	 * 	Get Document No based on Document Type
	 *	@param C_DocType_ID document type
	 * 	@param trxName optional Transaction Name
	 *  @param definite asking for a definitive or temporary sequence
	 *  @param po
	 *	@return document no or null
	 */
public static String getDocumentNo(int C_DocType_ID, String trxName, boolean definite, PO po) {
    if (C_DocType_ID == 0) {
        s_log.severe("C_DocType_ID=0");
        return null;
    }
    //	wrong for SERVER, but r/o
    MDocType dt = MDocType.get(Env.getCtx(), C_DocType_ID);
    if (dt != null && !dt.isDocNoControlled()) {
        s_log.finer("DocType_ID=" + C_DocType_ID + " Not DocNo controlled");
        return null;
    }
    if (definite && !dt.isOverwriteSeqOnComplete()) {
        s_log.finer("DocType_ID=" + C_DocType_ID + " Not Sequence Overwrite on Complete");
        return null;
    }
    if (dt == null || dt.getDocNoSequence_ID() == 0) {
        s_log.warning("No Sequence for DocType - " + dt);
        return null;
    }
    if (definite && dt.getDefiniteSequence_ID() == 0) {
        s_log.warning("No Definite Sequence for DocType - " + dt);
        return null;
    }
    //	Check AdempiereSys
    boolean adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS);
    if (CLogMgt.isLevel(LOGLEVEL))
        s_log.log(LOGLEVEL, "DocType_ID=" + C_DocType_ID + " [" + trxName + "]");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    boolean isStartNewYear = false;
    String dateColumn = null;
    if (!adempiereSys) {
        // Get the Start New Year & Sequence Type
        String startNewYearSQL = "SELECT StartNewYear, DateColumn FROM AD_Sequence " + "WHERE AD_Sequence_ID = ? AND IsActive = 'Y' AND IsTableID = 'N' AND IsAutoSequence='Y'";
        try {
            pstmt = DB.prepareStatement(startNewYearSQL, trxName);
            pstmt.setInt(1, definite ? dt.getDefiniteSequence_ID() : dt.getDocNoSequence_ID());
            rs = pstmt.executeQuery();
            if (rs.next()) {
                isStartNewYear = "Y".equals(rs.getString(1));
                dateColumn = rs.getString(2);
            }
        } catch (Exception e) {
            s_log.log(Level.SEVERE, "(Table) [" + trxName + "]", e);
        } finally {
            DB.close(rs, pstmt);
        }
    }
    String selectSQL = null;
    if (DB.isOracle() == false) {
        if (isStartNewYear) {
            selectSQL = "SELECT y.CurrentNext, s.CurrentNextSys, s.IncrementNo, s.Prefix, s.Suffix, s.DecimalPattern, s.AD_Client_ID, s.AD_Sequence_ID " + "FROM AD_Sequence_No y, AD_Sequence s " + "WHERE y.AD_Sequence_ID = s.AD_Sequence_ID " + "AND s.AD_Sequence_ID = ? " + "AND y.CalendarYear = ? " + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " + //OF y"; //dete: MySql
            "FOR UPDATE ";
        } else {
            selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, Prefix, Suffix, DecimalPattern, AD_Client_ID, AD_Sequence_ID " + "FROM AD_Sequence " + "WHERE AD_Sequence_ID = ? " + "AND IsActive='Y' AND IsTableID='N' AND IsAutoSequence='Y' " + //OF AD_Sequence"; //dete: MySql
            "FOR UPDATE ";
        }
        USE_PROCEDURE = false;
    } else {
        if (isStartNewYear) {
            selectSQL = "SELECT y.CurrentNext, s.CurrentNextSys, s.IncrementNo, s.Prefix, s.Suffix, s.DecimalPattern, s.AD_Client_ID, s.AD_Sequence_ID " + "FROM AD_Sequence_No y, AD_Sequence s " + "WHERE y.AD_Sequence_ID = s.AD_Sequence_ID " + "AND s.AD_Sequence_ID = ? " + "AND y.CalendarYear = ? " + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' ";
        } else {
            selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, Prefix, Suffix, DecimalPattern, AD_Client_ID, AD_Sequence_ID " + "FROM AD_Sequence " + "WHERE AD_Sequence_ID = ? " + "AND IsActive='Y' AND IsTableID='N' AND IsAutoSequence='Y' ";
        }
        USE_PROCEDURE = true;
    }
    Connection conn = null;
    Trx trx = trxName == null ? null : Trx.get(trxName, true);
    //
    int AD_Sequence_ID = 0;
    int incrementNo = 0;
    int next = -1;
    String prefix = "";
    String suffix = "";
    String decimalPattern = "";
    String calendarYear = "";
    try {
        if (trx != null)
            conn = trx.getConnection();
        else
            conn = DB.getConnectionID();
        //	Error
        if (conn == null)
            return null;
        if (isStartNewYear) {
            if (po != null && dateColumn != null && dateColumn.length() > 0) {
                Date docDate = (Date) po.get_Value(dateColumn);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                calendarYear = sdf.format(docDate);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                calendarYear = sdf.format(new Date());
            }
        }
        pstmt = conn.prepareStatement(selectSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
        if (definite)
            pstmt.setInt(1, dt.getDefiniteSequence_ID());
        else
            pstmt.setInt(1, dt.getDocNoSequence_ID());
        if (isStartNewYear)
            pstmt.setString(2, calendarYear);
        //
        if (!USE_PROCEDURE && DB.getDatabase().isQueryTimeoutSupported())
            pstmt.setQueryTimeout(QUERY_TIME_OUT);
        rs = pstmt.executeQuery();
        //		+ " - Type=" + pstmt.getResultSetType() + " - Concur=" + pstmt.getResultSetConcurrency());
        if (rs.next()) {
            incrementNo = rs.getInt(3);
            prefix = rs.getString(4);
            suffix = rs.getString(5);
            decimalPattern = rs.getString(6);
            int AD_Client_ID = rs.getInt(7);
            if (adempiereSys && AD_Client_ID > 11)
                adempiereSys = false;
            AD_Sequence_ID = rs.getInt(8);
            if (USE_PROCEDURE) {
                next = isStartNewYear ? nextIDByYear(conn, AD_Sequence_ID, incrementNo, calendarYear) : nextID(conn, AD_Sequence_ID, adempiereSys);
            } else {
                PreparedStatement updateSQL = null;
                try {
                    if (adempiereSys) {
                        updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNextSys = CurrentNextSys + ? WHERE AD_Sequence_ID = ?");
                        next = rs.getInt(2);
                    } else {
                        String sql = isStartNewYear ? "UPDATE AD_Sequence_No SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID = ? AND CalendarYear = ?" : "UPDATE AD_Sequence SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID = ?";
                        updateSQL = conn.prepareStatement(sql);
                        next = rs.getInt(1);
                    }
                    updateSQL.setInt(1, incrementNo);
                    updateSQL.setInt(2, AD_Sequence_ID);
                    if (isStartNewYear)
                        updateSQL.setString(3, calendarYear);
                    updateSQL.executeUpdate();
                } finally {
                    DB.close(updateSQL);
                }
            }
        } else {
            s_log.warning("(DocType)- no record found - " + dt);
            next = -2;
        }
        //	Commit
        if (trx == null) {
            conn.commit();
        }
    } catch (Exception e) {
        s_log.log(Level.SEVERE, "(DocType) [" + trxName + "]", e);
        if (DBException.isTimeout(e))
            throw new AdempiereException("GenerateDocumentNoTimeOut", e);
        else
            throw new AdempiereException("GenerateDocumentNoError", e);
    } finally {
        //	Finish
        try {
            DB.close(rs, pstmt);
            if (trx == null && conn != null) {
                conn.close();
                conn = null;
            }
        } catch (Exception e) {
            s_log.log(Level.SEVERE, "(DocType) - finish", e);
        }
    }
    //	Error
    if (next < 0)
        return null;
    //	create DocumentNo
    StringBuffer doc = new StringBuffer();
    if (prefix != null && prefix.length() > 0)
        doc.append(Env.parseVariable(prefix, po, trxName, false));
    if (decimalPattern != null && decimalPattern.length() > 0)
        doc.append(new DecimalFormat(decimalPattern).format(next));
    else
        doc.append(next);
    if (suffix != null && suffix.length() > 0)
        doc.append(Env.parseVariable(suffix, po, trxName, false));
    String documentNo = doc.toString();
    s_log.finer(documentNo + " (" + incrementNo + ")" + " - C_DocType_ID=" + C_DocType_ID + " [" + trx + "]");
    return documentNo;
}
Also used : DecimalFormat(java.text.DecimalFormat) HttpURLConnection(java.net.HttpURLConnection) Connection(java.sql.Connection) CConnection(org.compiere.db.CConnection) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException) AdempiereException(org.adempiere.exceptions.AdempiereException) Date(java.util.Date) AdempiereException(org.adempiere.exceptions.AdempiereException) ResultSet(java.sql.ResultSet) Trx(org.compiere.util.Trx) SimpleDateFormat(java.text.SimpleDateFormat)

Example 20 with Trx

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

the class MSequence method getDocumentNo.

/**************************************************************************
	 * 	Get Document No from table
	 *	@param AD_Client_ID client
	 *	@param TableName table name
	 * 	@param trxName optional Transaction Name
	 *  @param PO
	 *	@return document no or null
	 */
public static String getDocumentNo(int AD_Client_ID, String TableName, String trxName, PO po) {
    if (TableName == null || TableName.length() == 0)
        throw new IllegalArgumentException("TableName missing");
    //	Check AdempiereSys
    boolean adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS);
    if (adempiereSys && AD_Client_ID > 11)
        adempiereSys = false;
    //
    if (CLogMgt.isLevel(LOGLEVEL))
        s_log.log(LOGLEVEL, TableName + " - AdempiereSys=" + adempiereSys + " [" + trxName + "]");
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    boolean isStartNewYear = false;
    String dateColumn = null;
    if (!adempiereSys) {
        // Get the Start New Year flag
        String startNewYearSQL = "SELECT StartNewYear, DateColumn FROM AD_Sequence " + "WHERE Name = ? AND IsActive = 'Y' AND IsTableID = 'N' AND IsAutoSequence='Y' AND AD_Client_ID = ?";
        try {
            pstmt = DB.prepareStatement(startNewYearSQL, trxName);
            pstmt.setString(1, PREFIX_DOCSEQ + TableName);
            pstmt.setInt(2, AD_Client_ID);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                isStartNewYear = "Y".equals(rs.getString(1));
                dateColumn = rs.getString(2);
            }
        } catch (Exception e) {
            s_log.log(Level.SEVERE, "(Table) [" + trxName + "]", e);
        } finally {
            DB.close(rs, pstmt);
        }
    }
    String selectSQL = null;
    if (DB.isOracle() == false) {
        if (isStartNewYear) {
            selectSQL = "SELECT y.CurrentNext, s.CurrentNextSys, s.IncrementNo, s.Prefix, s.Suffix, s.DecimalPattern, s.AD_Sequence_ID " + "FROM AD_Sequence_No y, AD_Sequence s " + "WHERE y.AD_Sequence_ID = s.AD_Sequence_ID " + "AND s.Name = ? " + "AND s.AD_Client_ID = ? " + "AND y.CalendarYear = ? " + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " + "ORDER BY s.AD_Client_ID DESC " + //OF y"; // dete: MySql
            "FOR UPDATE ";
        } else {
            selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, Prefix, Suffix, DecimalPattern, AD_Sequence_ID " + "FROM AD_Sequence " + "WHERE Name = ? " + "AND AD_Client_ID = ? " + "AND IsActive='Y' AND IsTableID='N' AND IsAutoSequence='Y' " + "ORDER BY AD_Client_ID DESC " + //OF AD_Sequence"; //dete: MySql
            "FOR UPDATE ";
        }
        USE_PROCEDURE = false;
    } else {
        if (isStartNewYear) {
            selectSQL = "SELECT y.CurrentNext, s.CurrentNextSys, s.IncrementNo, Prefix, Suffix, DecimalPattern, s.AD_Sequence_ID " + "FROM AD_Sequence_No y, AD_Sequence s " + "WHERE y.AD_Sequence_ID = s.AD_Sequence_ID " + "AND s.Name = ? " + "AND s.AD_Client_ID = ? " + "AND y.CalendarYear = ? " + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " + "ORDER BY s.AD_Client_ID DESC";
        } else {
            selectSQL = "SELECT CurrentNext, CurrentNextSys, IncrementNo, Prefix, Suffix, DecimalPattern, AD_Sequence_ID " + "FROM AD_Sequence " + "WHERE Name = ? " + "AND AD_Client_ID = ? " + "AND IsActive='Y' AND IsTableID='N' AND IsAutoSequence='Y' " + "ORDER BY AD_Client_ID DESC";
        }
        USE_PROCEDURE = true;
    }
    Connection conn = null;
    Trx trx = trxName == null ? null : Trx.get(trxName, true);
    //
    int AD_Sequence_ID = 0;
    int incrementNo = 0;
    int next = -1;
    String prefix = "";
    String suffix = "";
    String decimalPattern = "";
    String calendarYear = "";
    try {
        if (trx != null)
            conn = trx.getConnection();
        else
            conn = DB.getConnectionID();
        //	Error
        if (conn == null)
            return null;
        if (isStartNewYear) {
            if (po != null && dateColumn != null && dateColumn.length() > 0) {
                Date docDate = (Date) po.get_Value(dateColumn);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                calendarYear = sdf.format(docDate);
            } else {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                calendarYear = sdf.format(new Date());
            }
        }
        //
        pstmt = conn.prepareStatement(selectSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
        pstmt.setString(1, PREFIX_DOCSEQ + TableName);
        pstmt.setInt(2, AD_Client_ID);
        if (isStartNewYear)
            pstmt.setString(3, calendarYear);
        //
        if (!USE_PROCEDURE && DB.getDatabase().isQueryTimeoutSupported())
            pstmt.setQueryTimeout(QUERY_TIME_OUT);
        rs = pstmt.executeQuery();
        //		+ " - Type=" + pstmt.getResultSetType() + " - Concur=" + pstmt.getResultSetConcurrency());
        if (rs.next()) {
            AD_Sequence_ID = rs.getInt(7);
            prefix = rs.getString(4);
            suffix = rs.getString(5);
            decimalPattern = rs.getString(6);
            incrementNo = rs.getInt(3);
            if (USE_PROCEDURE) {
                next = isStartNewYear ? nextIDByYear(conn, AD_Sequence_ID, incrementNo, calendarYear) : nextID(conn, AD_Sequence_ID, adempiereSys);
            } else {
                PreparedStatement updateSQL = null;
                try {
                    if (adempiereSys) {
                        updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNextSys = CurrentNextSys + ? WHERE AD_Sequence_ID = ?");
                        next = rs.getInt(2);
                    } else {
                        String sql = isStartNewYear ? "UPDATE AD_Sequence_No SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID = ? AND CalendarYear = ?" : "UPDATE AD_Sequence SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID = ?";
                        updateSQL = conn.prepareStatement(sql);
                        next = rs.getInt(1);
                    }
                    updateSQL.setInt(1, incrementNo);
                    updateSQL.setInt(2, AD_Sequence_ID);
                    if (isStartNewYear)
                        updateSQL.setString(3, calendarYear);
                    updateSQL.executeUpdate();
                } finally {
                    DB.close(updateSQL);
                }
            }
        } else {
            s_log.warning("(Table) - no record found - " + TableName);
            MSequence seq = new MSequence(Env.getCtx(), AD_Client_ID, TableName, null);
            next = seq.getNextID();
            seq.saveEx();
        }
        //	Commit
        if (trx == null) {
            conn.commit();
        }
    } catch (Exception e) {
        s_log.log(Level.SEVERE, "(Table) [" + trxName + "]", e);
        if (DBException.isTimeout(e))
            throw new AdempiereException("GenerateDocumentNoTimeOut", e);
        else
            throw new AdempiereException("GenerateDocumentNoError", e);
    } finally {
        //Finish
        DB.close(rs, pstmt);
        try {
            if (trx == null && conn != null) {
                conn.close();
                conn = null;
            }
        } catch (Exception e) {
            s_log.log(Level.SEVERE, "(Table) - finish", e);
        }
    }
    //	Error
    if (next < 0)
        return null;
    //	create DocumentNo
    StringBuffer doc = new StringBuffer();
    if (prefix != null && prefix.length() > 0)
        doc.append(Env.parseVariable(prefix, po, trxName, false));
    if (decimalPattern != null && decimalPattern.length() > 0)
        doc.append(new DecimalFormat(decimalPattern).format(next));
    else
        doc.append(next);
    if (suffix != null && suffix.length() > 0)
        doc.append(Env.parseVariable(suffix, po, trxName, false));
    String documentNo = doc.toString();
    s_log.finer(documentNo + " (" + incrementNo + ")" + " - Table=" + TableName + " [" + trx + "]");
    return documentNo;
}
Also used : DecimalFormat(java.text.DecimalFormat) HttpURLConnection(java.net.HttpURLConnection) Connection(java.sql.Connection) CConnection(org.compiere.db.CConnection) PreparedStatement(java.sql.PreparedStatement) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException) AdempiereException(org.adempiere.exceptions.AdempiereException) Date(java.util.Date) AdempiereException(org.adempiere.exceptions.AdempiereException) ResultSet(java.sql.ResultSet) Trx(org.compiere.util.Trx) SimpleDateFormat(java.text.SimpleDateFormat)

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