Search in sources :

Example 1 with MSort

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

the class ResultTable method sort.

//	autoSize
/**
	 *  Sort Table
	 *  @param modelColumnIndex
	 */
private void sort(final int modelColumnIndex) {
    int rows = getRowCount();
    if (rows == 0)
        return;
    //  other column
    if (modelColumnIndex != m_lastSortIndex)
        m_asc = true;
    else
        m_asc = !m_asc;
    m_lastSortIndex = modelColumnIndex;
    //
    log.config("#" + modelColumnIndex + " - rows=" + rows + ", asc=" + m_asc);
    ResultTableModel model = (ResultTableModel) getModel();
    //  Prepare sorting
    final MSort sort = new MSort(0, null);
    sort.setSortAsc(m_asc);
    // Sort the data list - teo_sarca [ 1734327 ]
    Collections.sort(model.getDataList(), new Comparator<Object>() {

        public int compare(Object o1, Object o2) {
            Object item1 = ((ArrayList) o1).get(modelColumnIndex);
            Object item2 = ((ArrayList) o2).get(modelColumnIndex);
            return sort.compare(item1, item2);
        }
    });
}
Also used : MSort(org.compiere.util.MSort)

Example 2 with MSort

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

the class GridTable method dataRefresh.

/**
	 *	Refresh Row - ignore changes
	 *  @param row row
	 *  @param fireStatusEvent
	 */
public void dataRefresh(int row, boolean fireStatusEvent) {
    log.info("Row=" + row);
    if (row < 0 || m_sort.size() == 0 || m_inserting)
        return;
    MSort sort = (MSort) m_sort.get(row);
    Object[] rowData = getDataAtRow(row);
    //  ignore
    dataIgnore();
    //	Create SQL
    String where = getWhereClause(rowData);
    if (where == null || where.length() == 0)
        where = "1=2";
    String sql = m_SQL_Select + " WHERE " + where;
    sort = (MSort) m_sort.get(row);
    Object[] rowDataDB = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(sql, null);
        rs = pstmt.executeQuery();
        //	only one row
        if (rs.next())
            rowDataDB = readData(rs);
    } catch (SQLException e) {
        log.log(Level.SEVERE, sql, e);
        fireTableRowsUpdated(row, row);
        fireDataStatusEEvent("RefreshError", sql, true);
        return;
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    //	update buffer
    setDataAtRow(row, rowDataDB);
    //	info
    m_rowData = null;
    m_changed = false;
    m_rowChanged = -1;
    m_inserting = false;
    fireTableRowsUpdated(row, row);
    if (fireStatusEvent)
        fireDataStatusIEvent(DATA_REFRESH_MESSAGE, "");
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) MSort(org.compiere.util.MSort)

Example 3 with MSort

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

the class GridTable method dataSavePO.

//	dataSave
/**
	 * 	Save via PO
	 *	@param Record_ID
	 *	@return SAVE_ERROR or SAVE_OK
	 *	@throws Exception
	 */
private char dataSavePO(int Record_ID) throws Exception {
    log.fine("ID=" + Record_ID);
    //
    Object[] rowData = getDataAtRow(m_rowChanged);
    //
    MTable table = MTable.get(m_ctx, m_AD_Table_ID);
    PO po = null;
    if (Record_ID != -1)
        po = table.getPO(Record_ID, null);
    else
        //	Multi - Key
        po = table.getPO(getWhereClause(rowData), null);
    //	No Persistent Object
    if (po == null)
        throw new ClassNotFoundException("No Persistent Object");
    int size = m_fields.size();
    for (int col = 0; col < size; col++) {
        GridField field = (GridField) m_fields.get(col);
        if (field.isVirtualColumn())
            continue;
        String columnName = field.getColumnName();
        Object value = rowData[col];
        Object oldValue = m_rowData[col];
        //	RowID
        if (field.getDisplayType() == DisplayType.RowID)
            //	ignore
            ;
        else //	Nothing changed & null
        if (oldValue == null && value == null)
            //	ignore
            ;
        else //	***	Data changed ***
        if (m_inserting || isValueChanged(oldValue, value)) {
            //	Check existence
            int poIndex = po.get_ColumnIndex(columnName);
            if (poIndex < 0) {
                //	Custom Fields not in PO
                po.set_CustomColumn(columnName, value);
                //	log.log(Level.SEVERE, "Column not found: " + columnName);
                continue;
            }
            Object dbValue = po.get_Value(poIndex);
            if (m_inserting || !m_compareDB || //	Original == DB
            (oldValue == null && dbValue == null) || (oldValue != null && oldValue.equals(dbValue)) || //	Target == DB (changed by trigger to new value already)
            (value == null && dbValue == null) || (value != null && value.equals(dbValue)) || // - https://adempiere.atlassian.net/browse/ADEMPIERE-157
            ((oldValue != null && dbValue != null && oldValue.getClass().equals(byte[].class) && dbValue.getClass().equals(byte[].class)) && Arrays.equals((byte[]) oldValue, (byte[]) dbValue)) || ((value != null && dbValue != null && oldValue != null && value.getClass().equals(byte[].class) && dbValue.getClass().equals(byte[].class)) && Arrays.equals((byte[]) oldValue, (byte[]) dbValue))) {
                if (!po.set_ValueNoCheck(columnName, value)) {
                    ValueNamePair error = CLogger.retrieveError();
                    if (error != null)
                        fireDataStatusEEvent(error.getValue() != null ? error.getValue() : "", field.getHeader() + " - " + (error.getName() != null ? error.getName() : ""), true);
                    else
                        fireDataStatusEEvent(Msg.parseTranslation(po.getCtx(), "@Value@ @NotValid@ "), field.getHeader(), true);
                    return SAVE_ERROR;
                }
            } else //	Original != DB
            {
                String msg = columnName + "= " + oldValue + (oldValue == null ? "" : "(" + oldValue.getClass().getName() + ")") + " != DB: " + dbValue + (dbValue == null ? "" : "(" + dbValue.getClass().getName() + ")") + " -> New: " + value + (value == null ? "" : "(" + value.getClass().getName() + ")");
                //	CLogMgt.setLevel(Level.FINEST);
                //	po.dump();
                fireDataStatusEEvent("SaveErrorDataChanged", msg, true);
                dataRefresh(m_rowChanged);
                return SAVE_ERROR;
            }
        }
    //	Data changed
    }
    if (!po.save()) {
        String msg = "SaveError";
        String info = "";
        ValueNamePair ppE = CLogger.retrieveError();
        if (ppE != null) {
            msg = ppE.getValue();
            info = ppE.getName();
            //	Unique Constraint
            if (DBException.isUniqueContraintError(CLogger.retrieveException()))
                msg = "SaveErrorNotUnique";
        }
        fireDataStatusEEvent(msg, info, true);
        return SAVE_ERROR;
    } else if (m_virtual && po.get_ID() > 0) {
        //update ID
        MSort sort = m_sort.get(m_rowChanged);
        int oldid = sort.index;
        if (oldid != po.get_ID()) {
            sort.index = po.get_ID();
            Object[] data = m_virtualBuffer.remove(oldid);
            data[m_indexKeyColumn] = sort.index;
            m_virtualBuffer.put(sort.index, data);
        }
    }
    //	Refresh - update buffer
    String whereClause = po.get_WhereClause(true);
    log.fine("Reading ... " + whereClause);
    StringBuffer refreshSQL = new StringBuffer(m_SQL_Select).append(" WHERE ").append(whereClause);
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(refreshSQL.toString(), null);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            Object[] rowDataDB = readData(rs);
            //	update buffer
            setDataAtRow(m_rowChanged, rowDataDB);
            fireTableRowsUpdated(m_rowChanged, m_rowChanged);
        }
    } catch (SQLException e) {
        String msg = "SaveError";
        log.log(Level.SEVERE, refreshSQL.toString(), e);
        fireDataStatusEEvent(msg, e.getLocalizedMessage(), true);
        return SAVE_ERROR;
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    //	everything ok
    m_rowData = null;
    m_changed = false;
    m_compareDB = true;
    m_rowChanged = -1;
    m_newRow = -1;
    m_inserting = false;
    //
    ValueNamePair pp = CLogger.retrieveWarning();
    if (pp != null) {
        String msg = pp.getValue();
        String info = pp.getName();
        fireDataStatusEEvent(msg, info, false);
    } else {
        pp = CLogger.retrieveInfo();
        String msg = "Saved";
        String info = "";
        if (pp != null) {
            msg = pp.getValue();
            info = pp.getName();
        }
        fireDataStatusIEvent(msg, info);
    }
    //
    log.config("fini");
    return SAVE_OK;
}
Also used : SQLException(java.sql.SQLException) PreparedStatement(java.sql.PreparedStatement) MSort(org.compiere.util.MSort) ResultSet(java.sql.ResultSet) ValueNamePair(org.compiere.util.ValueNamePair)

Example 4 with MSort

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

the class GridTable method dataSave.

//  dataSave
/**
	 *	Save unconditional.
	 *  @param manualCmd if true, no vetoable PropertyChange will be fired for save confirmation
	 *	@return OK Or Error condition
	 *  Error info (Access*, FillMandatory, SaveErrorNotUnique,
	 *  SaveErrorRowNotFound, SaveErrorDataChanged) is saved in the log
	 */
public char dataSave(boolean manualCmd) {
    //	cannot save
    if (!m_open) {
        log.warning("Error - Open=" + m_open);
        return SAVE_ERROR;
    }
    //	no need - not changed - row not positioned - no Value changed
    if (m_rowChanged == -1) {
        log.config("NoNeed - Changed=" + m_changed + ", Row=" + m_rowChanged);
        //	return SAVE_ERROR;
        if (!manualCmd)
            return SAVE_OK;
    }
    //  Value not changed
    if (m_rowData == null) {
        //reset out of sync variable
        m_rowChanged = -1;
        log.fine("No Changes");
        return SAVE_ERROR;
    }
    if (m_readOnly) //	If Processed - not editable (Find always editable)  -> ok for changing payment terms, etc.
    {
        log.warning("IsReadOnly - ignored");
        dataIgnore();
        return SAVE_ACCESS;
    }
    //	row not positioned - no Value changed
    if (m_rowChanged == -1) {
        if (//  new row and nothing changed - might be OK
        m_newRow != -1)
            m_rowChanged = m_newRow;
        else {
            fireDataStatusEEvent("SaveErrorNoChange", "", true);
            return SAVE_ERROR;
        }
    }
    //	Can we change?
    int[] co = getClientOrg(m_rowChanged);
    int AD_Client_ID = co[0];
    int AD_Org_ID = co[1];
    if (!MRole.getDefault(m_ctx, false).canUpdate(AD_Client_ID, AD_Org_ID, m_AD_Table_ID, 0, true)) {
        fireDataStatusEEvent(CLogger.retrieveError());
        dataIgnore();
        return SAVE_ACCESS;
    }
    log.info("Row=" + m_rowChanged);
    //  inform about data save action, if not manually initiated
    try {
        if (!manualCmd)
            m_vetoableChangeSupport.fireVetoableChange(PROPERTY, -1, m_rowChanged);
    } catch (PropertyVetoException pve) {
        log.warning(pve.getMessage());
        //dataIgnore();
        return SAVE_ABORT;
    }
    //	get updated row data
    Object[] rowData = getDataAtRow(m_rowChanged);
    // CarlosRuiz - globalqss - fix [1722226] - Usability - Record_ID = 0 on 9 tables can't be modified
    boolean specialZeroUpdate = false;
    if (// not inserting, updating a record 
    !m_inserting && // in a manual way (pushing the save button)
    manualCmd && // user must know what is doing -> just allowed to System or SuperUser (Hardcoded)
    (Env.getAD_User_ID(m_ctx) == 0 || Env.getAD_User_ID(m_ctx) == 100) && getKeyID(m_rowChanged) == 0) {
        // the record being changed has ID = 0
        // just the allowed tables (HardCoded)
        String tablename = getTableName();
        if (tablename.equals("AD_Org") || tablename.equals("AD_ReportView") || tablename.equals("AD_Role") || tablename.equals("AD_System") || tablename.equals("AD_User") || tablename.equals("C_DocType") || tablename.equals("GL_Category") || tablename.equals("M_AttributeSet") || tablename.equals("M_AttributeSetInstance")) {
            specialZeroUpdate = true;
        }
    }
    //	Check Mandatory
    String missingColumns = getMandatory(rowData);
    if (missingColumns.length() != 0) {
        //	Trace.printStack(false, false);
        fireDataStatusEEvent("FillMandatory", missingColumns + "\n", true);
        return SAVE_MANDATORY;
    }
    /**
		 *	Update row *****
		 */
    int Record_ID = 0;
    if (!m_inserting)
        Record_ID = getKeyID(m_rowChanged);
    try {
        //	FR [ 392 ]
        if (//	translation tables have no model
        !specialZeroUpdate)
            return dataSavePO(Record_ID);
    } catch (Throwable e) {
        if (e instanceof ClassNotFoundException)
            log.warning(m_tableName + " - " + e.getLocalizedMessage());
        else {
            log.log(Level.SEVERE, "Persistency Issue - " + m_tableName + ": " + e.getLocalizedMessage(), e);
            return SAVE_ERROR;
        }
    }
    /**	Manual Update of Row (i.e. not via PO class)	**/
    log.info("NonPO");
    boolean error = false;
    lobReset();
    //
    String is = null;
    final String ERROR = "ERROR: ";
    final String INFO = "Info: ";
    //	Update SQL with specific where clause
    StringBuffer select = new StringBuffer("SELECT ");
    for (int i = 0, addedColumns = 0; i < m_fields.size(); i++) {
        GridField field = (GridField) m_fields.get(i);
        if (m_inserting && field.isVirtualColumn())
            continue;
        // Add "," if it is not the first added column - teo_sarca [ 1735618 ]
        if (addedColumns++ > 0)
            select.append(",");
        //	ColumnName or Virtual Column
        select.append(field.getColumnSQL(true));
    }
    //
    select.append(" FROM ").append(m_tableName);
    StringBuffer singleRowWHERE = new StringBuffer();
    StringBuffer multiRowWHERE = new StringBuffer();
    //	Create SQL	& RowID
    if (m_inserting)
        select.append(" WHERE 1=2");
    else
        //  FOR UPDATE causes  -  ORA-01002 fetch out of sequence
        select.append(" WHERE ").append(getWhereClause(rowData));
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(select.toString(), ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE, null);
        rs = pstmt.executeQuery();
        //	only one row
        if (!(m_inserting || rs.next())) {
            fireDataStatusEEvent("SaveErrorRowNotFound", "", true);
            dataRefresh(m_rowChanged);
            return SAVE_ERROR;
        }
        Object[] rowDataDB = null;
        //	Prepare
        boolean manualUpdate = ResultSet.CONCUR_READ_ONLY == rs.getConcurrency();
        // Manual update if log migration scripts is enabled - teo_sarca BF [ 1901192 ]
        if (!manualUpdate && Ini.isPropertyBool(Ini.P_LOGMIGRATIONSCRIPT))
            manualUpdate = true;
        if (manualUpdate)
            createUpdateSqlReset();
        if (m_inserting) {
            if (manualUpdate)
                log.fine("Prepare inserting ... manual");
            else {
                log.fine("Prepare inserting ... RowSet");
                rs.moveToInsertRow();
            }
        } else {
            log.fine("Prepare updating ... manual=" + manualUpdate);
            //	get current Data in DB
            rowDataDB = readData(rs);
        }
        /**	Data:
			 *		m_rowData	= original Data
			 *		rowData 	= updated Data
			 *		rowDataDB	= current Data in DB
			 *	1) Difference between original & updated Data?	N:next
			 *	2) Difference between original & current Data?	Y:don't update
			 *	3) Update current Data
			 *	4) Refresh to get last Data (changed by trigger, ...)
			 */
        //	Constants for Created/Updated(By)
        Timestamp now = new Timestamp(System.currentTimeMillis());
        int user = Env.getContextAsInt(m_ctx, "#AD_User_ID");
        /**
			 *	for every column
			 */
        int size = m_fields.size();
        int colRs = 1;
        for (int col = 0; col < size; col++) {
            GridField field = (GridField) m_fields.get(col);
            if (field.isVirtualColumn()) {
                if (!m_inserting)
                    colRs++;
                continue;
            }
            String columnName = field.getColumnName();
            //	RowID, Virtual Column
            if (field.getDisplayType() == DisplayType.RowID || field.isVirtualColumn())
                //	ignore
                ;
            else //	New Key
            if (field.isKey() && m_inserting) {
                if (columnName.endsWith("_ID") || columnName.toUpperCase().endsWith("_ID")) {
                    //	no trx
                    int insertID = DB.getNextID(m_ctx, m_tableName, null);
                    if (manualUpdate)
                        createUpdateSql(columnName, String.valueOf(insertID));
                    else
                        // ***
                        rs.updateInt(colRs, insertID);
                    singleRowWHERE.append(columnName).append("=").append(insertID);
                    //
                    is = INFO + columnName + " -> " + insertID + " (Key)";
                } else //	Key with String value
                {
                    String str = rowData[col].toString();
                    if (manualUpdate)
                        createUpdateSql(columnName, DB.TO_STRING(str));
                    else
                        // ***
                        rs.updateString(colRs, str);
                    //	overwrite
                    singleRowWHERE = new StringBuffer();
                    singleRowWHERE.append(columnName).append("=").append(DB.TO_STRING(str));
                    //
                    is = INFO + columnName + " -> " + str + " (StringKey)";
                }
                log.fine(is);
            } else //	New DocumentNo
            if (columnName.equals("DocumentNo")) {
                boolean newDocNo = false;
                String docNo = (String) rowData[col];
                //  we need to have a doc number
                if (docNo == null || docNo.length() == 0)
                    newDocNo = true;
                else //  Preliminary ID from CalloutSystem
                if (docNo.startsWith("<") && docNo.endsWith(">"))
                    newDocNo = true;
                if (newDocNo || m_inserting) {
                    String insertDoc = null;
                    //  always overwrite if insering with mandatory DocType DocNo
                    if (m_inserting)
                        insertDoc = DB.getDocumentNo(m_ctx, m_WindowNo, m_tableName, true, //	only doc type - no trx
                        null);
                    log.fine("DocumentNo entered=" + docNo + ", DocTypeInsert=" + insertDoc + ", newDocNo=" + newDocNo);
                    // can we use entered DocNo?
                    if (insertDoc == null || insertDoc.length() == 0) {
                        if (!newDocNo && docNo != null && docNo.length() > 0)
                            insertDoc = docNo;
                        else
                            //  get a number from DocType or Table
                            insertDoc = DB.getDocumentNo(m_ctx, m_WindowNo, m_tableName, false, //	no trx
                            null);
                    }
                    //	There might not be an automatic document no for this document
                    if (insertDoc == null || insertDoc.length() == 0) {
                        //  in case DB function did not return a value
                        if (docNo != null && docNo.length() != 0)
                            insertDoc = (String) rowData[col];
                        else {
                            error = true;
                            is = ERROR + field.getColumnName() + "= " + rowData[col] + " NO DocumentNo";
                            log.fine(is);
                            break;
                        }
                    }
                    //
                    if (manualUpdate)
                        createUpdateSql(columnName, DB.TO_STRING(insertDoc));
                    else
                        //	***
                        rs.updateString(colRs, insertDoc);
                    //
                    is = INFO + columnName + " -> " + insertDoc + " (DocNo)";
                    log.fine(is);
                }
            } else //  New Value(key)
            if (columnName.equals("Value") && m_inserting) {
                String value = (String) rowData[col];
                //  Get from Sequence, if not entered
                if (value == null || value.length() == 0) {
                    value = DB.getDocumentNo(m_ctx, m_WindowNo, m_tableName, false, null);
                    //  No Value
                    if (value == null || value.length() == 0) {
                        error = true;
                        is = ERROR + field.getColumnName() + "= " + rowData[col] + " No Value";
                        log.fine(is);
                        break;
                    }
                }
                if (manualUpdate)
                    createUpdateSql(columnName, DB.TO_STRING(value));
                else
                    //	***
                    rs.updateString(colRs, value);
                //
                is = INFO + columnName + " -> " + value + " (Value)";
                log.fine(is);
            } else //	Updated		- check database
            if (columnName.equals("Updated")) {
                if (//	changed
                m_compareDB && !m_inserting && !m_rowData[col].equals(rowDataDB[col])) {
                    error = true;
                    is = ERROR + field.getColumnName() + "= " + m_rowData[col] + " != DB: " + rowDataDB[col];
                    log.fine(is);
                    break;
                }
                if (manualUpdate)
                    createUpdateSql(columnName, DB.TO_DATE(now, false));
                else
                    //	***
                    rs.updateTimestamp(colRs, now);
                //
                is = INFO + "Updated/By -> " + now + " - " + user;
                log.fine(is);
            } else //	UpdatedBy	- update
            if (columnName.equals("UpdatedBy")) {
                if (manualUpdate)
                    createUpdateSql(columnName, String.valueOf(user));
                else
                    //	***
                    rs.updateInt(colRs, user);
            } else //	Created
            if (m_inserting && columnName.equals("Created")) {
                if (manualUpdate)
                    createUpdateSql(columnName, DB.TO_DATE(now, false));
                else
                    //	***
                    rs.updateTimestamp(colRs, now);
            } else //	CreatedBy
            if (m_inserting && columnName.equals("CreatedBy")) {
                if (manualUpdate)
                    createUpdateSql(columnName, String.valueOf(user));
                else
                    //	***
                    rs.updateInt(colRs, user);
            } else //	Nothing changed & null
            if (m_rowData[col] == null && rowData[col] == null) {
                if (m_inserting) {
                    if (manualUpdate)
                        createUpdateSql(columnName, "NULL");
                    else
                        //	***
                        rs.updateNull(colRs);
                    is = INFO + columnName + "= NULL";
                    log.fine(is);
                }
            } else //	***	Data changed ***
            if (m_inserting || (m_rowData[col] == null && rowData[col] != null) || (m_rowData[col] != null && rowData[col] == null) || //	changed
            !m_rowData[col].equals(rowData[col])) {
                //	Original == DB
                if (m_inserting || !m_compareDB || (m_rowData[col] == null && rowDataDB[col] == null) || (m_rowData[col] != null && m_rowData[col].equals(rowDataDB[col]))) {
                    if (CLogMgt.isLevelFinest())
                        log.fine(columnName + "=" + rowData[col] + " " + (rowData[col] == null ? "" : rowData[col].getClass().getName()));
                    //
                    boolean encrypted = field.isEncryptedColumn();
                    //
                    String type = "String";
                    if (rowData[col] == null) {
                        if (manualUpdate)
                            createUpdateSql(columnName, "NULL");
                        else
                            //	***
                            rs.updateNull(colRs);
                    } else //	ID - int
                    if (DisplayType.isID(field.getDisplayType()) || field.getDisplayType() == DisplayType.Integer) {
                        try {
                            Object dd = rowData[col];
                            Integer iii = null;
                            if (dd instanceof Integer)
                                iii = (Integer) dd;
                            else
                                iii = new Integer(dd.toString());
                            if (encrypted)
                                iii = (Integer) encrypt(iii);
                            if (manualUpdate)
                                createUpdateSql(columnName, String.valueOf(iii));
                            else
                                // 	***
                                rs.updateInt(colRs, iii.intValue());
                        } catch (//  could also be a String (AD_Language, AD_Message)
                        Exception e) {
                            if (manualUpdate)
                                createUpdateSql(columnName, DB.TO_STRING(rowData[col].toString()));
                            else
                                //	***
                                rs.updateString(colRs, rowData[col].toString());
                        }
                        type = "Int";
                    } else //	Numeric - BigDecimal
                    if (DisplayType.isNumeric(field.getDisplayType())) {
                        BigDecimal bd = (BigDecimal) rowData[col];
                        if (encrypted)
                            bd = (BigDecimal) encrypt(bd);
                        if (manualUpdate)
                            createUpdateSql(columnName, bd.toString());
                        else
                            //	***
                            rs.updateBigDecimal(colRs, bd);
                        type = "Number";
                    } else //	Date - Timestamp
                    if (DisplayType.isDate(field.getDisplayType())) {
                        Timestamp ts = (Timestamp) rowData[col];
                        if (encrypted)
                            ts = (Timestamp) encrypt(ts);
                        if (manualUpdate)
                            createUpdateSql(columnName, DB.TO_DATE(ts, false));
                        else
                            //	***
                            rs.updateTimestamp(colRs, ts);
                        type = "Date";
                    } else //	LOB
                    if (field.getDisplayType() == DisplayType.TextLong) {
                        PO_LOB lob = new PO_LOB(getTableName(), columnName, null, field.getDisplayType(), rowData[col]);
                        lobAdd(lob);
                        type = "CLOB";
                    } else //	Boolean
                    if (field.getDisplayType() == DisplayType.YesNo) {
                        String yn = null;
                        if (rowData[col] instanceof Boolean) {
                            Boolean bb = (Boolean) rowData[col];
                            yn = bb.booleanValue() ? "Y" : "N";
                        } else
                            yn = "Y".equals(rowData[col]) ? "Y" : "N";
                        if (encrypted)
                            yn = (String) yn;
                        if (manualUpdate)
                            createUpdateSql(columnName, DB.TO_STRING(yn));
                        else
                            //	***
                            rs.updateString(colRs, yn);
                    } else //	String and others
                    {
                        String str = rowData[col].toString();
                        if (encrypted)
                            str = (String) encrypt(str);
                        if (manualUpdate)
                            createUpdateSql(columnName, DB.TO_STRING(str));
                        else
                            //	***
                            rs.updateString(colRs, str);
                    }
                    //
                    is = INFO + columnName + "= " + m_rowData[col] + " -> " + rowData[col] + " (" + type + ")";
                    if (encrypted)
                        is += " encrypted";
                    log.fine(is);
                } else //	Original != DB
                {
                    error = true;
                    is = ERROR + field.getColumnName() + "= " + m_rowData[col] + " != DB: " + rowDataDB[col] + " -> " + rowData[col];
                    log.fine(is);
                }
            }
            //	Single Key - retrieval sql
            if (field.isKey() && !m_inserting) {
                if (rowData[col] == null)
                    throw new RuntimeException("Key is NULL - " + columnName);
                if (columnName.endsWith("_ID"))
                    singleRowWHERE.append(columnName).append("=").append(rowData[col]);
                else {
                    //	overwrite
                    singleRowWHERE = new StringBuffer();
                    singleRowWHERE.append(columnName).append("=").append(DB.TO_STRING(rowData[col].toString()));
                }
            }
            //	MultiKey Inserting - retrieval sql
            if (field.isParentColumn()) {
                if (rowData[col] == null)
                    throw new RuntimeException("MultiKey Parent is NULL - " + columnName);
                if (multiRowWHERE.length() != 0)
                    multiRowWHERE.append(" AND ");
                if (columnName.endsWith("_ID"))
                    multiRowWHERE.append(columnName).append("=").append(rowData[col]);
                else
                    multiRowWHERE.append(columnName).append("=").append(DB.TO_STRING(rowData[col].toString()));
            }
            //
            colRs++;
        }
        if (error) {
            if (manualUpdate)
                createUpdateSqlReset();
            else
                rs.cancelRowUpdates();
            fireDataStatusEEvent("SaveErrorDataChanged", "", true);
            dataRefresh(m_rowChanged);
            return SAVE_ERROR;
        }
        /**
			 *	Save to Database
			 */
        //
        String whereClause = singleRowWHERE.toString();
        if (whereClause.length() == 0)
            whereClause = multiRowWHERE.toString();
        if (m_inserting) {
            log.fine("Inserting ...");
            if (manualUpdate) {
                String sql = createUpdateSql(true, null);
                //	no Trx
                int no = DB.executeUpdateEx(sql, null);
                if (no != 1)
                    log.log(Level.SEVERE, "Insert #=" + no + " - " + sql);
            } else
                rs.insertRow();
        } else {
            log.fine("Updating ... " + whereClause);
            if (manualUpdate) {
                String sql = createUpdateSql(false, whereClause);
                //	no Trx
                int no = DB.executeUpdateEx(sql, null);
                if (no != 1)
                    log.log(Level.SEVERE, "Update #=" + no + " - " + sql);
            } else
                rs.updateRow();
        }
        log.fine("Committing ...");
        //	no Trx
        DB.commit(true, null);
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
        //
        lobSave(whereClause);
        //	Need to re-read row to get ROWID, Key, DocumentNo, Trigger, virtual columns
        log.fine("Reading ... " + whereClause);
        StringBuffer refreshSQL = new StringBuffer(m_SQL_Select).append(" WHERE ").append(whereClause);
        pstmt = DB.prepareStatement(refreshSQL.toString(), null);
        rs = pstmt.executeQuery();
        if (rs.next()) {
            rowDataDB = readData(rs);
            //	update buffer
            setDataAtRow(m_rowChanged, rowDataDB);
            if (m_virtual) {
                MSort sort = m_sort.get(m_rowChanged);
                int oldId = sort.index;
                int newId = getKeyID(m_rowChanged);
                if (newId != oldId) {
                    sort.index = newId;
                    Object[] data = m_virtualBuffer.remove(oldId);
                    m_virtualBuffer.put(newId, data);
                }
            }
            fireTableRowsUpdated(m_rowChanged, m_rowChanged);
        } else
            log.log(Level.SEVERE, "Inserted row not found");
    //
    } catch (Exception e) {
        String msg = "SaveError";
        if (//	Unique Constraint
        DBException.isUniqueContraintError(e)) {
            log.log(Level.SEVERE, "Key Not Unique", e);
            msg = "SaveErrorNotUnique";
        } else
            log.log(Level.SEVERE, select.toString(), e);
        fireDataStatusEEvent(msg, e.getLocalizedMessage(), true);
        return SAVE_ERROR;
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    //	everything ok
    m_rowData = null;
    m_changed = false;
    m_compareDB = true;
    m_rowChanged = -1;
    m_newRow = -1;
    m_inserting = false;
    fireDataStatusIEvent("Saved", "");
    //
    log.info("fini");
    return SAVE_OK;
}
Also used : PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) PropertyVetoException(java.beans.PropertyVetoException) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException) BigDecimal(java.math.BigDecimal) MSort(org.compiere.util.MSort) PropertyVetoException(java.beans.PropertyVetoException) ResultSet(java.sql.ResultSet)

Example 5 with MSort

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

the class GridTable method getDataAtRow.

private Object[] getDataAtRow(int row, boolean fetchIfNotFound) {
    MSort sort = (MSort) m_sort.get(row);
    Object[] rowData = null;
    if (m_virtual) {
        if (sort.index != NEW_ROW_ID && !(m_virtualBuffer.containsKey(sort.index)) && fetchIfNotFound) {
            fillBuffer(row, DEFAULT_FETCH_SIZE);
        }
        rowData = (Object[]) m_virtualBuffer.get(sort.index);
    } else {
        rowData = (Object[]) m_buffer.get(sort.index);
    }
    return rowData;
}
Also used : MSort(org.compiere.util.MSort)

Aggregations

MSort (org.compiere.util.MSort)10 PreparedStatement (java.sql.PreparedStatement)4 SQLException (java.sql.SQLException)4 ResultSet (java.sql.ResultSet)3 ValueNamePair (org.compiere.util.ValueNamePair)2 PropertyVetoException (java.beans.PropertyVetoException)1 BigDecimal (java.math.BigDecimal)1 Timestamp (java.sql.Timestamp)1 DefaultTableModel (javax.swing.table.DefaultTableModel)1 DBException (org.adempiere.exceptions.DBException)1