Search in sources :

Example 46 with MTable

use of org.compiere.model.MTable in project adempiere by adempiere.

the class HouseKeeping method doIt.

//prepare
protected String doIt() throws Exception {
    X_AD_HouseKeeping houseKeeping = new X_AD_HouseKeeping(getCtx(), p_AD_HouseKeeping_ID, get_TrxName());
    int tableID = houseKeeping.getAD_Table_ID();
    MTable table = new MTable(getCtx(), tableID, get_TrxName());
    String tableName = table.getTableName();
    String whereClause = houseKeeping.getWhereClause();
    int noins = 0;
    int noexp = 0;
    int nodel = 0;
    if (houseKeeping.isSaveInHistoric()) {
        String sql = "INSERT INTO hst_" + tableName + " SELECT * FROM " + tableName;
        if (whereClause != null && whereClause.length() > 0)
            sql = sql + " WHERE " + whereClause;
        noins = DB.executeUpdate(sql, get_TrxName());
        if (noins == -1)
            throw new AdempiereSystemError("Cannot insert into hst_" + tableName);
        addLog("@Inserted@ " + noins);
    }
    //saveInHistoric
    Date date = new Date();
    if (houseKeeping.isExportXMLBackup()) {
        String pathFile = houseKeeping.getBackupFolder();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateString = dateFormat.format(date);
        FileWriter file = new FileWriter(pathFile + File.separator + tableName + dateString + ".xml");
        String sql = "SELECT * FROM " + tableName;
        if (whereClause != null && whereClause.length() > 0)
            sql = sql + " WHERE " + whereClause;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        StringBuffer linexml = null;
        try {
            pstmt = DB.prepareStatement(sql, get_TrxName());
            rs = pstmt.executeQuery();
            while (rs.next()) {
                GenericPO po = new GenericPO(tableName, getCtx(), rs, get_TrxName());
                linexml = po.get_xmlString(linexml);
                noexp++;
            }
            if (linexml != null)
                file.write(linexml.toString());
            file.close();
        } catch (Exception e) {
            throw e;
        } finally {
            DB.close(rs, pstmt);
            pstmt = null;
            rs = null;
        }
        addLog("@Exported@ " + noexp);
    }
    //XmlExport
    String sql = "DELETE FROM " + tableName;
    if (whereClause != null && whereClause.length() > 0)
        sql = sql + " WHERE " + whereClause;
    nodel = DB.executeUpdate(sql, get_TrxName());
    if (nodel == -1)
        throw new AdempiereSystemError("Cannot delete from " + tableName);
    Timestamp time = new Timestamp(date.getTime());
    houseKeeping.setLastRun(time);
    houseKeeping.setLastDeleted(nodel);
    houseKeeping.saveEx();
    addLog("@Deleted@ " + nodel);
    String msg = Msg.translate(getCtx(), tableName + "_ID") + " #" + nodel;
    return msg;
}
Also used : AdempiereSystemError(org.compiere.util.AdempiereSystemError) GenericPO(org.adempiere.model.GenericPO) FileWriter(java.io.FileWriter) X_AD_HouseKeeping(org.compiere.model.X_AD_HouseKeeping) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) Date(java.util.Date) MTable(org.compiere.model.MTable) ResultSet(java.sql.ResultSet) SimpleDateFormat(java.text.SimpleDateFormat)

Example 47 with MTable

use of org.compiere.model.MTable in project adempiere by adempiere.

the class ColumnEncryption method doIt.

// prepare
/**
	 * Process
	 * 
	 * @return info
	 * @throws Exception
	 */
protected String doIt() throws Exception {
    log.info("AD_Column_ID=" + p_AD_Column_ID + ", IsEncrypted=" + p_IsEncrypted + ", ChangeSetting=" + p_ChangeSetting + ", MaxLength=" + p_MaxLength);
    MColumn column = new MColumn(getCtx(), p_AD_Column_ID, get_TrxName());
    if (column.get_ID() == 0 || column.get_ID() != p_AD_Column_ID)
        throw new AdempiereUserError("@NotFound@ @AD_Column_ID@ - " + p_AD_Column_ID);
    //
    String columnName = column.getColumnName();
    int dt = column.getAD_Reference_ID();
    // Can it be enabled?
    if (column.isKey() || column.isParent() || column.isStandardColumn() || column.isVirtualColumn() || column.isIdentifier() || column.isTranslated() || DisplayType.isLookup(dt) || DisplayType.isLOB(dt) || "DocumentNo".equalsIgnoreCase(column.getColumnName()) || "Value".equalsIgnoreCase(column.getColumnName()) || "Name".equalsIgnoreCase(column.getColumnName())) {
        if (column.isEncrypted()) {
            column.setIsEncrypted(false);
            column.saveEx();
        }
        return columnName + ": cannot be encrypted";
    }
    // Start
    addLog(0, null, null, "Encryption Class = " + SecureEngine.getClassName());
    boolean error = false;
    // Test Value
    if (p_TestValue != null && p_TestValue.length() > 0) {
        String encString = SecureEngine.encrypt(p_TestValue);
        addLog(0, null, null, "Encrypted Test Value=" + encString);
        String clearString = SecureEngine.decrypt(encString);
        if (p_TestValue.equals(clearString))
            addLog(0, null, null, "Decrypted=" + clearString + " (same as test value)");
        else {
            addLog(0, null, null, "Decrypted=" + clearString + " (NOT the same as test value - check algorithm)");
            error = true;
        }
        int encLength = encString.length();
        addLog(0, null, null, "Test Length=" + p_TestValue.length() + " -> " + encLength);
        if (encLength <= column.getFieldLength())
            addLog(0, null, null, "Encrypted Length (" + encLength + ") fits into field (" + column.getFieldLength() + ")");
        else {
            addLog(0, null, null, "Encrypted Length (" + encLength + ") does NOT fit into field (" + column.getFieldLength() + ") - resize field");
            error = true;
        }
    }
    // Length Test
    if (p_MaxLength != 0) {
        String testClear = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
        while (testClear.length() < p_MaxLength) testClear += testClear;
        testClear = testClear.substring(0, p_MaxLength);
        log.config("Test=" + testClear + " (" + p_MaxLength + ")");
        //
        String encString = SecureEngine.encrypt(testClear);
        int encLength = encString.length();
        addLog(0, null, null, "Test Max Length=" + testClear.length() + " -> " + encLength);
        if (encLength <= column.getFieldLength())
            addLog(0, null, null, "Encrypted Max Length (" + encLength + ") fits into field (" + column.getFieldLength() + ")");
        else {
            addLog(0, null, null, "Encrypted Max Length (" + encLength + ") does NOT fit into field (" + column.getFieldLength() + ") - resize field");
            error = true;
        }
    }
    // settings resize the physical column and encrypt all its contents.
    if (p_IsEncrypted && p_ChangeSetting) {
        // and exit.
        if (column.isEncrypted()) {
            log.severe("EncryptError: Column already encrypted.");
            throw new Exception();
        }
        // Init the transaction and setup the connection.
        m_trx = Trx.get(get_TrxName(), true);
        if ((m_conn = m_trx.getConnection()) == null) {
            log.warning("EncryptError: No connections available");
            throw new Exception();
        }
        m_conn.setAutoCommit(false);
        int columnID = column.get_ID();
        MTable table = MTable.get(getCtx(), column.getAD_Table_ID());
        String tableName = table.getTableName();
        // Check if the encryption exceeds the current length.
        int oldLength = column.getFieldLength();
        int newLength = encryptedColumnLength(oldLength);
        if (newLength > oldLength)
            if (changeFieldLength(columnID, columnName, newLength, tableName) == -1) {
                log.warning("EncryptError [ChangeFieldLength]: " + "ColumnID=" + columnID + ", NewLength=" + newLength);
                throw new Exception();
            }
        // Encrypt column contents.
        if (encryptColumnContents(columnName, column.getAD_Table_ID()) == -1) {
            log.warning("EncryptError: No records encrypted.");
            throw new Exception();
        }
        if (p_IsEncrypted != column.isEncrypted()) {
            if (error || !p_ChangeSetting)
                addLog(0, null, null, "Encryption NOT changed - Encryption=" + column.isEncrypted());
            else {
                column.setIsEncrypted(p_IsEncrypted);
                if (column.save())
                    addLog(0, null, null, "Encryption CHANGED - Encryption=" + column.isEncrypted());
                else
                    addLog(0, null, null, "Save Error");
            }
        }
    }
    return "Encryption=" + column.isEncrypted();
}
Also used : MColumn(org.compiere.model.MColumn) AdempiereUserError(org.compiere.util.AdempiereUserError) MTable(org.compiere.model.MTable)

Example 48 with MTable

use of org.compiere.model.MTable in project adempiere by adempiere.

the class MWFProcess method getPO.

//	performStart
/**************************************************************************
	 * 	Get Persistent Object
	 *	@return po
	 */
public PO getPO() {
    if (m_po != null)
        return m_po;
    if (getRecord_ID() == 0)
        return null;
    MTable table = MTable.get(getCtx(), getAD_Table_ID());
    m_po = table.getPO(getRecord_ID(), get_TrxName());
    return m_po;
}
Also used : MTable(org.compiere.model.MTable)

Example 49 with MTable

use of org.compiere.model.MTable in project adempiere by adempiere.

the class ModelADServiceImpl method setDocAction.

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

Example 50 with MTable

use of org.compiere.model.MTable in project adempiere by adempiere.

the class ModelADServiceImpl method getList.

public WindowTabDataDocument getList(ModelGetListRequestDocument req) throws XFireFault {
    WindowTabDataDocument resdoc = WindowTabDataDocument.Factory.newInstance();
    WindowTabData res = resdoc.addNewWindowTabData();
    DataSet ds = res.addNewDataSet();
    ModelGetList modelGetList = req.getModelGetListRequest().getModelGetList();
    String serviceType = modelGetList.getServiceType();
    int cnt = 0;
    ADLoginRequest reqlogin = req.getModelGetListRequest().getADLoginRequest();
    String err = modelLogin(reqlogin, webServiceName, "getList", serviceType);
    if (err != null && err.length() > 0) {
        res.setError(err);
        res.setErrorInfo(err);
        res.setSuccess(false);
        return resdoc;
    }
    int roleid = reqlogin.getRoleID();
    // Validate parameters
    modelGetList.setADReferenceID(validateParameter("AD_Reference_ID", modelGetList.getADReferenceID()));
    modelGetList.setFilter(validateParameter("Filter", modelGetList.getFilter()));
    int ref_id = modelGetList.getADReferenceID();
    String filter = modelGetList.getFilter();
    if (filter == null || filter.length() == 0)
        filter = "";
    else
        filter = " AND " + filter;
    Properties ctx = m_cs.getM_ctx();
    X_AD_Reference ref = new X_AD_Reference(ctx, ref_id, null);
    String sql = null;
    ArrayList<String> listColumnNames = new ArrayList<String>();
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    if (X_AD_Reference.VALIDATIONTYPE_ListValidation.equals(ref.getValidationType())) {
        // Fill List Reference
        String ad_language = Env.getAD_Language(ctx);
        boolean isBaseLanguage = Env.isBaseLanguage(ad_language, "AD_Ref_List");
        sql = isBaseLanguage ? "SELECT AD_Ref_List.AD_Ref_List_ID, AD_Ref_List.Value, AD_Ref_List.Name, AD_Ref_List.Description " + "FROM AD_Ref_List " + "WHERE AD_Ref_List.AD_Reference_ID=? AND AD_Ref_List.IsActive='Y' " + filter + " ORDER BY AD_Ref_List.Name" : "SELECT AD_Ref_List.AD_Ref_List_ID, AD_Ref_List.Value, AD_Ref_List_Trl.Name, AD_Ref_List_Trl.Description " + "FROM AD_Ref_List, AD_Ref_List_Trl " + "WHERE AD_Ref_List.AD_Reference_ID=? AND AD_Ref_List.IsActive='Y' AND AD_Ref_List_Trl.AD_Language=? AND AD_Ref_List.AD_Ref_List_ID=AD_Ref_List_Trl.AD_Ref_List_ID " + filter + " ORDER BY AD_Ref_List_Trl.Name";
        listColumnNames.add("AD_Ref_List_ID");
        listColumnNames.add("Value");
        listColumnNames.add("Name");
        listColumnNames.add("Description");
        try {
            pstmt = DB.prepareStatement(sql, null);
            pstmt.setInt(1, ref_id);
            if (!isBaseLanguage)
                pstmt.setString(2, ad_language);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            res.setError(e.getMessage());
            res.setErrorInfo(sql);
            res.setSuccess(false);
            DB.close(rs, pstmt);
            rs = null;
            pstmt = null;
            throw new XFireFault(e.getClass().toString() + " " + e.getMessage() + " sql=" + sql, e.getCause(), new QName("getList"));
        }
    } else if (X_AD_Reference.VALIDATIONTYPE_TableValidation.equals(ref.getValidationType())) {
        // Fill values from a reference table
        MRole role = new MRole(ctx, roleid, null);
        String sqlrt = "SELECT * FROM AD_Ref_Table WHERE AD_Reference_ID=?";
        MRefTable rt = null;
        PreparedStatement pstmtrt = null;
        ResultSet rsrt = null;
        try {
            pstmtrt = DB.prepareStatement(sqlrt, null);
            pstmtrt.setInt(1, ref_id);
            rsrt = pstmtrt.executeQuery();
            if (rsrt.next())
                rt = new MRefTable(ctx, rsrt, null);
        } catch (Exception e) {
        // ignore this exception
        } finally {
            DB.close(rsrt, pstmtrt);
            rsrt = null;
            pstmtrt = null;
        }
        if (rt == null)
            throw new XFireFault("Web service type " + m_webservicetype.getValue() + ": reference table " + ref_id + " not found", new QName("getList"));
        MTable table = new MTable(ctx, rt.getAD_Table_ID(), null);
        MColumn column = new MColumn(ctx, rt.getAD_Key(), null);
        // TODO: if any value or identifier column is translated, then get them from trl table (and client has multilanguage documents enabled)
        sql = "SELECT " + column.getColumnName();
        listColumnNames.add(column.getColumnName());
        if (rt.isValueDisplayed()) {
            sql += ",Value";
            listColumnNames.add("Value");
        }
        String sqlident = "SELECT ColumnName FROM AD_Column WHERE AD_Table_ID=? AND IsActive='Y' AND IsIdentifier='Y' ORDER BY SeqNo";
        PreparedStatement pstmtident = null;
        ResultSet rsident = null;
        try {
            pstmtident = DB.prepareStatement(sqlident, null);
            pstmtident.setInt(1, rt.getAD_Table_ID());
            rsident = pstmtident.executeQuery();
            while (rsident.next()) {
                String colnameident = rsident.getString("ColumnName");
                if (rt.isValueDisplayed() && colnameident.equalsIgnoreCase("Value")) {
                // Value already added
                } else {
                    sql += "," + colnameident;
                    listColumnNames.add(colnameident);
                }
            }
        } catch (Exception e) {
        // ignore this exception
        } finally {
            DB.close(rsident, pstmtident);
            rsident = null;
            pstmtident = null;
        }
        sql += " FROM " + table.getTableName() + " WHERE IsActive='Y'";
        /** 2014-11-05 Carlos Parada Change for ReadOnly SQL Access */
        //sql = role.addAccessSQL(sql, table.getTableName(), true, true);
        sql = role.addAccessSQL(sql, table.getTableName(), true, false);
        /** End Carlos Parada */
        sql += filter;
        if (rt.getWhereClause() != null && rt.getWhereClause().length() > 0)
            sql += " AND " + rt.getWhereClause();
        if (rt.getOrderByClause() != null && rt.getOrderByClause().length() > 0)
            sql += " ORDER BY " + rt.getOrderByClause();
        try {
            pstmt = DB.prepareStatement(sql, null);
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            res.setError(e.getMessage());
            res.setErrorInfo(sql);
            res.setSuccess(false);
            DB.close(rs, pstmt);
            rs = null;
            pstmt = null;
            throw new XFireFault(e.getClass().toString() + " " + e.getMessage() + " sql=" + sql, e.getCause(), new QName("getList"));
        }
    } else {
    // Don't fill - wrong type
    }
    if (rs != null) {
        try {
            while (rs.next()) {
                cnt++;
                // Add values to the dataset
                DataRow dr = ds.addNewDataRow();
                for (String listColumnName : listColumnNames) {
                    if (m_webservicetype.isOutputColumnNameAllowed(listColumnName)) {
                        DataField dfid = dr.addNewField();
                        dfid.setColumn(listColumnName);
                        dfid.setVal(rs.getString(listColumnName));
                    }
                }
            }
            res.setSuccess(true);
        } catch (SQLException e) {
            res.setError(e.getMessage());
            res.setErrorInfo(sql);
            res.setSuccess(false);
            throw new XFireFault(e.getClass().toString() + " " + e.getMessage() + " sql=" + sql, e.getCause(), new QName("getList"));
        } finally {
            DB.close(rs, pstmt);
            rs = null;
            pstmt = null;
        }
    }
    res.setRowCount(cnt);
    res.setNumRows(cnt);
    res.setTotalRows(cnt);
    res.setStartRow(1);
    return resdoc;
}
Also used : MColumn(org.compiere.model.MColumn) ADLoginRequest(pl.x3E.adInterface.ADLoginRequest) DataSet(pl.x3E.adInterface.DataSet) SQLException(java.sql.SQLException) QName(javax.xml.namespace.QName) MRole(org.compiere.model.MRole) WindowTabData(pl.x3E.adInterface.WindowTabData) ArrayList(java.util.ArrayList) ModelGetList(pl.x3E.adInterface.ModelGetList) PreparedStatement(java.sql.PreparedStatement) Properties(java.util.Properties) XFireFault(org.codehaus.xfire.fault.XFireFault) DataRow(pl.x3E.adInterface.DataRow) MRefTable(org.compiere.model.MRefTable) SQLException(java.sql.SQLException) WindowTabDataDocument(pl.x3E.adInterface.WindowTabDataDocument) X_AD_Reference(org.compiere.model.X_AD_Reference) MTable(org.compiere.model.MTable) DataField(pl.x3E.adInterface.DataField) ResultSet(java.sql.ResultSet)

Aggregations

MTable (org.compiere.model.MTable)67 PO (org.compiere.model.PO)18 ResultSet (java.sql.ResultSet)16 SQLException (java.sql.SQLException)16 PreparedStatement (java.sql.PreparedStatement)15 MColumn (org.compiere.model.MColumn)15 Query (org.compiere.model.Query)13 ArrayList (java.util.ArrayList)10 Properties (java.util.Properties)9 AdempiereException (org.adempiere.exceptions.AdempiereException)7 ADLoginRequest (pl.x3E.adInterface.ADLoginRequest)7 XFireFault (org.codehaus.xfire.fault.XFireFault)5 POInfo (org.compiere.model.POInfo)5 Trx (org.compiere.util.Trx)5 DataField (pl.x3E.adInterface.DataField)5 DataRow (pl.x3E.adInterface.DataRow)5 ModelCRUD (pl.x3E.adInterface.ModelCRUD)5 List (java.util.List)4 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)4 POSaveFailedException (org.adempiere.pipo.exception.POSaveFailedException)4