Search in sources :

Example 56 with DBException

use of org.adempiere.exceptions.DBException in project adempiere by adempiere.

the class GridTable method hasChanged.

//	setFieldVFormat	
// verify if the current record has changed
public boolean hasChanged(int row) {
    // compare Updated, IsProcessed
    if (getKeyID(row) > 0) {
        int colUpdated = findColumn("Updated");
        int colProcessed = findColumn("Processed");
        boolean hasUpdated = (colUpdated > 0);
        boolean hasProcessed = (colProcessed > 0);
        String columns = null;
        if (hasUpdated && hasProcessed) {
            columns = new String("Updated, Processed");
        } else if (hasUpdated) {
            columns = new String("Updated");
        } else if (hasProcessed) {
            columns = new String("Processed");
        } else {
            // no columns updated or processed to commpare
            return false;
        }
        // todo: temporary fix for carlos assumption that all windows have _id column
        if (findColumn(m_tableName + "_ID") == -1)
            return false;
        Timestamp dbUpdated = null;
        String dbProcessedS = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        String sql = "SELECT " + columns + " FROM " + m_tableName + " WHERE " + m_tableName + "_ID=?";
        try {
            pstmt = DB.prepareStatement(sql, null);
            pstmt.setInt(1, getKeyID(row));
            rs = pstmt.executeQuery();
            if (rs.next()) {
                int idx = 1;
                if (hasUpdated)
                    dbUpdated = rs.getTimestamp(idx++);
                if (hasProcessed)
                    dbProcessedS = rs.getString(idx++);
            } else
                log.info("No Value " + sql);
        } catch (SQLException e) {
            throw new DBException(e, sql);
        } finally {
            DB.close(rs, pstmt);
            rs = null;
            pstmt = null;
        }
        if (hasUpdated) {
            Timestamp memUpdated = null;
            memUpdated = (Timestamp) getOldValue(row, colUpdated);
            if (memUpdated == null)
                memUpdated = (Timestamp) getValueAt(row, colUpdated);
            if (memUpdated != null && !memUpdated.equals(dbUpdated))
                return true;
        }
        if (hasProcessed) {
            Boolean memProcessed = null;
            memProcessed = (Boolean) getOldValue(row, colProcessed);
            if (memProcessed == null)
                memProcessed = (Boolean) getValueAt(row, colProcessed);
            Boolean dbProcessed = Boolean.TRUE;
            if (dbProcessedS == null || dbProcessedS.isEmpty() || !dbProcessedS.equals("Y"))
                dbProcessed = Boolean.FALSE;
            if (memProcessed != null && !memProcessed.equals(dbProcessed))
                return true;
        }
    }
    // @TODO: configurable aggressive - compare each column with the DB
    return false;
}
Also used : DBException(org.adempiere.exceptions.DBException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp)

Example 57 with DBException

use of org.adempiere.exceptions.DBException in project adempiere by adempiere.

the class ModelClassGenerator method addListValidation.

/**
	 * 	Add List Validation
	 * 	@param sb buffer - example:
		if (NextAction.equals("N") || NextAction.equals("F"));
		else throw new IllegalArgumentException ("NextAction Invalid value - Reference_ID=219 - N - F");
	 * 	@param AD_Reference_ID reference
	 * 	@param columnName column
	 * 	@return static parameter - Example:
		public static final int NEXTACTION_AD_Reference_ID=219;
		public static final String NEXTACTION_None = "N";
		public static final String NEXTACTION_FollowUp = "F";
	 */
private String addListValidation(StringBuffer sb, int AD_Reference_ID, String columnName) {
    StringBuffer retValue = new StringBuffer();
    retValue.append("\n\t/** ").append(columnName).append(" AD_Reference_ID=").append(AD_Reference_ID).append(" */").append("\n\tpublic static final int ").append(columnName.toUpperCase()).append("_AD_Reference_ID=").append(AD_Reference_ID).append(";");
    //
    boolean found = false;
    StringBuffer values = new StringBuffer("Reference_ID=").append(AD_Reference_ID);
    StringBuffer statement = new StringBuffer();
    //
    String sql = "SELECT Value, Name FROM AD_Ref_List WHERE AD_Reference_ID=? ORDER BY AD_Ref_List_ID";
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(sql, null);
        pstmt.setInt(1, AD_Reference_ID);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            String value = rs.getString(1);
            values.append(" - ").append(value);
            if (statement.length() == 0)
                statement.append("\n\t\tif (").append(columnName).append(".equals(\"").append(value).append("\")");
            else
                statement.append(" || ").append(columnName).append(".equals(\"").append(value).append("\")");
            //
            if (!found) {
                found = true;
            }
            //	Name (SmallTalkNotation)
            String name = rs.getString(2);
            char[] nameArray = name.toCharArray();
            StringBuffer nameClean = new StringBuffer();
            boolean initCap = true;
            for (int i = 0; i < nameArray.length; i++) {
                char c = nameArray[i];
                if (Character.isJavaIdentifierPart(c)) {
                    if (initCap)
                        nameClean.append(Character.toUpperCase(c));
                    else
                        nameClean.append(c);
                    initCap = false;
                } else {
                    if (c == '+')
                        nameClean.append("Plus");
                    else if (c == '-')
                        nameClean.append("_");
                    else if (c == '>') {
                        if (//	ignore <xx>
                        name.indexOf('<') == -1)
                            nameClean.append("Gt");
                    } else if (c == '<') {
                        if (//	ignore <xx>
                        name.indexOf('>') == -1)
                            nameClean.append("Le");
                    } else if (c == '!')
                        nameClean.append("Not");
                    else if (c == '=')
                        nameClean.append("Eq");
                    else if (c == '~')
                        nameClean.append("Like");
                    initCap = true;
                }
            }
            retValue.append("\n\t/** ").append(name).append(" = ").append(value).append(" */");
            retValue.append("\n\tpublic static final String ").append(columnName.toUpperCase()).append("_").append(nameClean).append(" = \"").append(value).append("\";");
        }
    } catch (SQLException e) {
        throw new DBException(e, sql);
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    statement.append(")" + "; " + "else " + "throw new IllegalArgumentException (\"").append(columnName).append(" Invalid value - \" + ").append(columnName).append(" + \" - ").append(values).append("\");");
    // [1762461] - Remove hardcoded list items checking in generated models
    // if (found && !columnName.equals("EntityType"))
    //	sb.append (statement);
    sb.append("\n");
    return retValue.toString();
}
Also used : DBException(org.adempiere.exceptions.DBException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 58 with DBException

use of org.adempiere.exceptions.DBException in project adempiere by adempiere.

the class ModelClassGenerator method main.

/**************************************************************************
	 * 	Generate PO Model Class.
	 * 	<pre>
	 * 	Example: java GenerateModel.class mydirectory myPackage 'U','A'
	 * 	would generate entity type User and Application classes into mydirectory.
	 * 	Without parameters, the default is used:
	 * 	C:\Compiere\compiere-all\extend\src\compiere\model\ compiere.model 'U','A'
	 * 	</pre>
	 * 	@param args directory package entityType
	 * 	- directory where to save the generated file
	 * 	- package of the classes to be generated
	 * 	- entityType to be generated
	 */
public static void main(String[] args) {
    Adempiere.startupEnvironment(true);
    CLogMgt.setLevel(Level.FINE);
    log.info("Generate Model   $Revision: 1.42 $");
    log.info("----------------------------------");
    //	first parameter
    String directory = "C:\\Adempiere\\adempiere-all\\extend\\src\\compiere\\model\\";
    if (args.length > 0)
        directory = args[0];
    if (directory == null || directory.length() == 0) {
        System.err.println("No Directory");
        System.exit(1);
    }
    log.info("Directory: " + directory);
    //	second parameter
    String packageName = "compiere.model";
    if (args.length > 1)
        packageName = args[1];
    if (packageName == null || packageName.length() == 0) {
        System.err.println("No package");
        System.exit(1);
    }
    log.info("Package:   " + packageName);
    //	third parameter
    //	User, Application
    String entityType = "'U','A'";
    if (args.length > 2)
        entityType = args[2];
    if (entityType == null || entityType.length() == 0) {
        System.err.println("No EntityType");
        System.exit(1);
    }
    StringBuffer sql = new StringBuffer("EntityType IN (").append(entityType).append(")");
    log.info(sql.toString());
    log.info("----------------------------------");
    //	All tables
    String tableLike = "'%'";
    //tableLike = "'AD_OrgInfo', 'AD_Role', 'C_CashLine', 'C_Currency', 'C_Invoice', 'C_Order', 'C_Payment', 'M_InventoryLine', 'M_PriceList', 'M_Product', 'U_POSTerminal'";
    if (args.length > 3)
        tableLike = args[3];
    log.info("Table Like: " + tableLike);
    //	complete sql
    sql.insert(0, "SELECT AD_Table_ID " + "FROM AD_Table " + //	special views
    "WHERE (TableName IN ('RV_WarehousePrice','RV_BPartner')" + " OR IsView='N')" + " AND IsActive = 'Y' AND TableName NOT LIKE '%_Trl' AND ");
    sql.append(" AND TableName LIKE ").append(tableLike);
    sql.append(" ORDER BY TableName");
    //
    int count = 0;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = DB.prepareStatement(sql.toString(), null);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            new ModelClassGenerator(rs.getInt(1), directory, packageName);
            count++;
        }
    } catch (SQLException e) {
        throw new DBException(e, sql.toString());
    } finally {
        DB.close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    log.info("Generated = " + count);
}
Also used : DBException(org.adempiere.exceptions.DBException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement)

Example 59 with DBException

use of org.adempiere.exceptions.DBException in project adempiere by adempiere.

the class PO method delete.

//	decrypt
/**************************************************************************
	 * 	Delete Current Record
	 * 	@param force delete also processed records
	 * 	@return true if deleted
	 */
public boolean delete(boolean force) {
    CLogger.resetLast();
    if (is_new())
        return true;
    int AD_Table_ID = p_info.getAD_Table_ID();
    int Record_ID = get_ID();
    if (!force) {
        int iProcessed = get_ColumnIndex("Processed");
        if (iProcessed != -1) {
            Boolean processed = (Boolean) get_Value(iProcessed);
            if (processed != null && processed.booleanValue()) {
                //	CannotDeleteTrx
                log.warning("Record processed");
                log.saveError("Processed", "Processed", false);
                return false;
            }
        }
    //	processed
    }
    //	force
    Trx localTrx = null;
    boolean success = false;
    try {
        String localTrxName = m_trxName;
        if (localTrxName == null) {
            localTrxName = Trx.createTrxName("POdel");
            localTrx = Trx.get(localTrxName, true);
            m_trxName = localTrxName;
        }
        try {
            if (!beforeDelete()) {
                log.warning("beforeDelete failed");
                return false;
            }
        } catch (Exception e) {
            log.log(Level.WARNING, "beforeDelete", e);
            log.saveError("Error", e, false);
            //	throw new DBException(e);
            return false;
        }
        //	Delete Restrict AD_Table_ID/Record_ID (Requests, ..)
        String errorMsg = PO_Record.exists(AD_Table_ID, Record_ID, m_trxName);
        if (errorMsg != null) {
            log.saveError("CannotDelete", errorMsg);
            return false;
        }
        // Call ModelValidators TYPE_DELETE
        errorMsg = ModelValidationEngine.get().fireModelChange(this, isReplication() ? ModelValidator.TYPE_BEFORE_DELETE_REPLICATION : ModelValidator.TYPE_DELETE);
        // @Trifon
        setReplication(false);
        if (errorMsg != null) {
            log.saveError("Error", errorMsg);
            return false;
        }
        //
        deleteTranslations(localTrxName);
        //	Delete Cascade AD_Table_ID/Record_ID (Attachments, ..)
        PO_Record.deleteCascade(AD_Table_ID, Record_ID, localTrxName);
        //	The Delete Statement
        StringBuffer sql = //jz why no FROM??
        new StringBuffer("DELETE FROM ").append(p_info.getTableName()).append(" WHERE ").append(get_WhereClause(true));
        int no = 0;
        if (isUseTimeoutForUpdate())
            no = DB.executeUpdateEx(sql.toString(), localTrxName, QUERY_TIME_OUT);
        else
            no = DB.executeUpdate(sql.toString(), localTrxName);
        success = no == 1;
        //	Save ID
        m_idOld = get_ID();
        //
        if (!success) {
            log.warning("Not deleted");
            if (localTrx != null)
                localTrx.rollback();
        } else {
            if (success) {
                MSession session = MSession.get(p_ctx, false);
                if (session == null)
                    log.fine("No Session found");
                else if (Ini.isPropertyBool(Ini.P_LOGMIGRATIONSCRIPT))
                    session.logMigration(this, p_info, MMigrationStep.ACTION_Delete);
                if (p_info.isChangeLog()) {
                    //	Change Log
                    if (session != null && m_IDs.length == 1) {
                        int AD_ChangeLog_ID = 0;
                        int size = get_ColumnCount();
                        for (int i = 0; i < size; i++) {
                            Object value = m_oldValues[i];
                            if (value != null && //	logging allowed
                            p_info.isAllowLogging(i) && //	not encrypted
                            !p_info.isEncrypted(i) && //	no virtual column
                            !p_info.isVirtualColumn(i) && !"Password".equals(p_info.getColumnName(i))) {
                                // change log on delete
                                MChangeLog cLog = session.changeLog(m_trxName != null ? m_trxName : localTrxName, AD_ChangeLog_ID, AD_Table_ID, p_info.getColumn(i).AD_Column_ID, Record_ID, getAD_Client_ID(), getAD_Org_ID(), value, null, MChangeLog.EVENTCHANGELOG_Delete);
                                if (cLog != null)
                                    AD_ChangeLog_ID = cLog.getAD_ChangeLog_ID();
                            }
                        }
                    //   for all fields
                    }
                    //	Housekeeping
                    m_IDs[0] = I_ZERO;
                    if (m_trxName == null)
                        log.fine("complete");
                    else
                        log.fine("[" + m_trxName + "] - complete");
                    m_attachment = null;
                }
            } else {
                log.warning("Not deleted");
            }
        }
        try {
            success = afterDelete(success);
        } catch (Exception e) {
            log.log(Level.WARNING, "afterDelete", e);
            log.saveError("Error", e, false);
            success = false;
        //	throw new DBException(e);
        }
        // Call ModelValidators TYPE_AFTER_DELETE - teo_sarca [ 1675490 ]
        if (success) {
            errorMsg = ModelValidationEngine.get().fireModelChange(this, ModelValidator.TYPE_AFTER_DELETE);
            if (errorMsg != null) {
                log.saveError("Error", errorMsg);
                success = false;
            }
        }
        if (!success) {
            if (localTrx != null)
                localTrx.rollback();
        } else {
            if (localTrx != null) {
                try {
                    localTrx.commit(true);
                } catch (SQLException e) {
                    log.saveError("Error", e);
                    success = false;
                }
            }
        }
        //	Reset
        if (success) {
            m_idOld = 0;
            int size = p_info.getColumnCount();
            m_oldValues = new Object[size];
            m_newValues = new Object[size];
            CacheMgt.get().reset(p_info.getTableName());
        }
    } finally {
        if (localTrx != null) {
            localTrx.close();
            m_trxName = null;
        }
    }
    //	log.info("" + success);
    return success;
}
Also used : SQLException(java.sql.SQLException) Trx(org.compiere.util.Trx) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Savepoint(java.sql.Savepoint) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException) AdempiereException(org.adempiere.exceptions.AdempiereException)

Example 60 with DBException

use of org.adempiere.exceptions.DBException in project adempiere by adempiere.

the class DB method getSQLValueEx.

//	getRowSet
/**
     * Get int Value from sql
     * @param trxName trx
     * @param sql sql
     * @param params array of parameters
     * @return first value or -1 if not found
     * @throws DBException if there is any SQLException
     */
public static int getSQLValueEx(String trxName, String sql, Object... params) throws DBException {
    int retValue = -1;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        pstmt = prepareStatement(sql, trxName);
        setParameters(pstmt, params);
        rs = pstmt.executeQuery();
        if (rs.next())
            retValue = rs.getInt(1);
        else
            log.fine("No Value " + sql);
    } catch (SQLException e) {
        throw new DBException(e, sql);
    } finally {
        close(rs, pstmt);
        rs = null;
        pstmt = null;
    }
    return retValue;
}
Also used : DBException(org.adempiere.exceptions.DBException) SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) POResultSet(org.compiere.model.POResultSet) PreparedStatement(java.sql.PreparedStatement)

Aggregations

DBException (org.adempiere.exceptions.DBException)89 SQLException (java.sql.SQLException)82 PreparedStatement (java.sql.PreparedStatement)75 ResultSet (java.sql.ResultSet)75 BigDecimal (java.math.BigDecimal)27 ArrayList (java.util.ArrayList)23 Timestamp (java.sql.Timestamp)15 POResultSet (org.compiere.model.POResultSet)8 AdempiereException (org.adempiere.exceptions.AdempiereException)6 KeyNamePair (org.compiere.util.KeyNamePair)5 Connection (java.sql.Connection)4 Savepoint (java.sql.Savepoint)4 MProduct (org.compiere.model.MProduct)4 Trx (org.compiere.util.Trx)4 Date (java.util.Date)2 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)2 IDColumn (org.compiere.minigrid.IDColumn)2 MLocator (org.compiere.model.MLocator)2 MTable (org.compiere.model.MTable)2 MUOM (org.compiere.model.MUOM)2