Search in sources :

Example 1 with MColumn

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

the class CreateAdempiere method createTable.

//	createTables
/**
	 * 	Create Table
	 *	@param mTable table model
	 *	@param md meta data
	 *	@return true if created
	 */
private boolean createTable(MTable mTable, DatabaseMetaData md) {
    String tableName = mTable.getTableName();
    log.info(tableName);
    String catalog = m_dbSource.getCatalog();
    String schema = m_dbSource.getSchema();
    String table = tableName.toUpperCase();
    //	
    MColumn[] columns = mTable.getColumns(false);
    StringBuffer sb = new StringBuffer("CREATE TABLE ");
    sb.append(tableName).append(" (");
    try {
        //	Columns
        boolean first = true;
        ResultSet sourceColumns = md.getColumns(catalog, schema, table, null);
        while (sourceColumns.next()) {
            sb.append(first ? "" : ", ");
            first = false;
            //	Case sensitive Column Name
            MColumn column = null;
            String columnName = sourceColumns.getString("COLUMN_NAME");
            for (int i = 0; i < columns.length; i++) {
                String cn = columns[i].getColumnName();
                if (cn.equalsIgnoreCase(columnName)) {
                    columnName = cn;
                    column = columns[i];
                    break;
                }
            }
            sb.append(columnName).append(" ");
            //	Data Type & Precision
            //	sql.Types
            int sqlType = sourceColumns.getInt("DATA_TYPE");
            //	DB Dependent
            String typeName = sourceColumns.getString("TYPE_NAME");
            int size = sourceColumns.getInt("COLUMN_SIZE");
            int decDigits = sourceColumns.getInt("DECIMAL_DIGITS");
            if (sourceColumns.wasNull())
                decDigits = -1;
            if (typeName.equals("NUMBER")) {
                /** Oracle Style	*
					if (decDigits == -1)
						sb.append(typeName);
					else
						sb.append(typeName).append("(")
							.append(size).append(",").append(decDigits).append(")");
					/** Other DBs		*/
                int dt = column.getAD_Reference_ID();
                if (DisplayType.isID(dt))
                    sb.append("INTEGER");
                else {
                    int scale = DisplayType.getDefaultPrecision(dt);
                    sb.append("DECIMAL(").append(18 + scale).append(",").append(scale).append(")");
                }
            } else if (typeName.equals("DATE") || typeName.equals("BLOB") || typeName.equals("CLOB"))
                sb.append(typeName);
            else if (typeName.equals("CHAR") || typeName.startsWith("VARCHAR"))
                sb.append(typeName).append("(").append(size).append(")");
            else if (typeName.startsWith("NCHAR") || typeName.startsWith("NVAR"))
                sb.append(typeName).append("(").append(size / 2).append(")");
            else if (typeName.startsWith("TIMESTAMP"))
                sb.append("DATE");
            else
                log.severe("Do not support data type " + typeName);
            //	Default
            String def = sourceColumns.getString("COLUMN_DEF");
            if (def != null) {
                //jz: replace '' to \', otherwise exception
                def.replaceAll("''", "\\'");
                sb.append(" DEFAULT ").append(def);
            }
            //	Null
            if (sourceColumns.getInt("NULLABLE") == DatabaseMetaData.columnNoNulls)
                sb.append(" NOT NULL");
            else
                sb.append(" NULL");
        //	Check Contraints
        }
        //	for all columns
        sourceColumns.close();
        //	Primary Key
        ResultSet sourcePK = md.getPrimaryKeys(catalog, schema, table);
        //	TABLE_CAT=null, TABLE_SCHEM=REFERENCE, TABLE_NAME=A_ASSET, COLUMN_NAME=A_ASSET_ID, KEY_SEQ=1, PK_NAME=A_ASSET_KEY
        first = true;
        boolean hasPK = false;
        while (sourcePK.next()) {
            hasPK = true;
            if (first)
                sb.append(", CONSTRAINT ").append(sourcePK.getString("PK_NAME")).append(" PRIMARY KEY (");
            else
                sb.append(",");
            first = false;
            String columnName = sourcePK.getString("COLUMN_NAME");
            sb.append(checkColumnName(columnName));
        }
        if (//	close constraint
        hasPK)
            // USING INDEX TABLESPACE INDX
            sb.append(")");
        sourcePK.close();
        //
        //	close create table
        sb.append(")");
    } catch (Exception ex) {
        log.log(Level.SEVERE, "createTable", ex);
        return false;
    }
    //	Execute Create Table
    if (!executeCommands(new String[] { sb.toString() }, m_conn, false, true))
        // continue
        return true;
    //	Create Inexes
    createTableIndexes(mTable, md);
    return createTableData(mTable);
}
Also used : MColumn(org.compiere.model.MColumn) ResultSet(java.sql.ResultSet) DBException(org.adempiere.exceptions.DBException) SQLException(java.sql.SQLException)

Example 2 with MColumn

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

the class ImportHelper method setReplicaValues.

/**
	 * 
	 * @param value
	 * @param line
	 * @param po
	 * @param result
	 * @throws Exception
	 */
private void setReplicaValues(Object value, MEXPFormatLine line, PO po, StringBuffer result) throws Exception {
    MColumn column = MColumn.get(ctx, line.getAD_Column_ID());
    log.info("column=[" + column + "]");
    if (value != null) {
        if (!MEXPFormatLine.TYPE_EmbeddedEXPFormat.equals(line.getType())) {
            // Clazz
            Class<?> clazz = DisplayType.getClass(column.getAD_Reference_ID(), true);
            //	Handle Posted
            if (column.getColumnName().equalsIgnoreCase("Posted") || column.getColumnName().equalsIgnoreCase("Processed") || column.getColumnName().equalsIgnoreCase("Processing")) {
                clazz = Boolean.class;
            } else if (column.getColumnName().equalsIgnoreCase("Record_ID")) {
                clazz = Integer.class;
            } else if (column.getColumnName().equalsIgnoreCase("AD_Language") || column.getColumnName().equalsIgnoreCase("EntityType")) {
                clazz = String.class;
            }
            log.info("clazz = " + clazz.getName());
            // Handle Date and Time
            value = handleDateTime(value, column, line);
            log.info("formatLinesType = " + line.getType());
            if (MEXPFormatLine.TYPE_EmbeddedEXPFormat.equals(line.getType())) {
                // DO NOTHING
                throw new Exception("We can't be here!!!");
            } else {
                if (DisplayType.DateTime == column.getAD_Reference_ID() || DisplayType.Date == column.getAD_Reference_ID()) {
                    // 
                    po.set_ValueOfColumn(line.getAD_Column_ID(), value);
                    log.info("Set value of column [" + column.getColumnName() + "]=[" + value + "]");
                } else if (DisplayType.isID(column.getAD_Reference_ID()) || DisplayType.Integer == column.getAD_Reference_ID()) {
                    //
                    if (!Util.isEmpty(value.toString())) {
                        int intValue = Integer.parseInt(value.toString());
                        value = new Integer(intValue);
                    } else {
                        value = null;
                    }
                    log.info("About to set int value of column [" + column.getColumnName() + "]=[" + value + "]");
                    po.set_ValueOfColumn(line.getAD_Column_ID(), value);
                    log.info("Set int value of column [" + column.getColumnName() + "]=[" + value + "]");
                } else if (DisplayType.isNumeric(column.getAD_Reference_ID()) && column.getAD_Reference_ID() != DisplayType.Integer) {
                    //
                    if (!Util.isEmpty(value.toString())) {
                        value = new BigDecimal(value.toString());
                    //value = new Double( doubleValue );
                    } else {
                        value = null;
                    }
                    log.info("About to set BigDecimal value of column [" + column.getColumnName() + "]=[" + value + "]");
                    po.set_ValueOfColumn(line.getAD_Column_ID(), value);
                    log.info("Set BigDecimal value of column [" + column.getColumnName() + "]=[" + value + "]");
                } else if (DisplayType.YesNo == column.getAD_Reference_ID()) {
                    if (clazz == Boolean.class) {
                        String v = value.toString().equals("true") ? "Y" : "N";
                        po.set_ValueOfColumn(line.getAD_Column_ID(), v);
                    }
                } else {
                    //
                    try {
                        log.info("About to set value of column [" + column.getColumnName() + "]=[" + value + "]");
                        if (clazz == Boolean.class) {
                            String v = value.toString().equals("true") ? "Y" : "N";
                            po.set_ValueOfColumn(line.getAD_Column_ID(), v);
                        } else {
                            po.set_ValueOfColumn(line.getAD_Column_ID(), clazz.cast(value));
                        }
                        log.info("Set value of column [" + column.getColumnName() + "]=[" + value + "]");
                    } catch (ClassCastException ex) {
                        ex.printStackTrace();
                        throw new Exception(ex);
                    }
                }
                result.append(column.getColumnName()).append("=").append(value).append("; ");
            }
        //end else			
        }
    //end if TYPE_EmbeddedEXPFormat			
    }
//end if value !=null
}
Also used : MColumn(org.compiere.model.MColumn) XPathExpressionException(javax.xml.xpath.XPathExpressionException) SQLException(java.sql.SQLException) ParseException(java.text.ParseException) AdempiereException(org.adempiere.exceptions.AdempiereException) BigDecimal(java.math.BigDecimal)

Example 3 with MColumn

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

the class ExportHelper method generateExportFormat.

/**
	 * Trifon Generate Export Format process; result =
	 * <C_Invoice>
	 *   <DocumentNo>101</DocumentNo>
	 * </C_Invoice>
	 * @param rootElement
	 * @param exportFormat
	 * @param masterPO
	 * @param masterID
	 * @param variableMap
	 * @throws SQLException
     * @throws Exception
     */
private void generateExportFormat(Element rootElement, MEXPFormat exportFormat, PO masterPO, int masterID, HashMap<String, Integer> variableMap) throws SQLException, Exception {
    Collection<MEXPFormatLine> formatLines = exportFormat.getFormatLines();
    @SuppressWarnings("unused") boolean elementHasValue = false;
    //for (int i = 0; i < formatLines.length; i++) {
    for (MEXPFormatLine formatLine : formatLines) {
        if (formatLine.getType().equals(X_EXP_FormatLine.TYPE_XMLElement)) {
            // process single XML Attribute
            // Create new element
            Element newElement = outDocument.createElement(formatLine.getValue());
            log.info("Format Line Seach key: " + formatLine.getValue());
            if (formatLine.getAD_Column_ID() == 0) {
                throw new Exception(Msg.getMsg(masterPO.getCtx(), "EXPColumnMandatory"));
            }
            MColumn column = MColumn.get(masterPO.getCtx(), formatLine.getAD_Column_ID());
            if (column == null) {
                throw new Exception(Msg.getMsg(masterPO.getCtx(), "EXPColumnMandatory"));
            }
            if (column.isVirtualColumn()) {
                log.info("This is Virtual Column!");
            } else {
            }
            //log.info("["+column.getColumnName()+"]");
            Object value = masterPO.get_Value(column.getColumnName());
            String valueString = null;
            if (value != null) {
                valueString = value.toString();
            } else {
                //  Could remove this exception and create empty XML Element when column do not have value. 
                if (formatLine.isMandatory()) {
                //throw new Exception(Msg.getMsg (masterPO.getCtx(), "EXPFieldMandatory"));
                }
            }
            if (column.getAD_Reference_ID() == DisplayType.Date) {
                if (valueString != null) {
                    if (formatLine.getDateFormat() != null && !"".equals(formatLine.getDateFormat())) {
                        // "MM/dd/yyyy"
                        customDateFormat = new SimpleDateFormat(formatLine.getDateFormat());
                        valueString = customDateFormat.format(Timestamp.valueOf(valueString));
                        // Add "DateForamt attribute"
                        newElement.setAttribute("DateFormat", customDateFormat.toPattern());
                    } else {
                        newElement.setAttribute("DateFormat", valueString);
                    }
                }
            } else if (column.getAD_Reference_ID() == DisplayType.DateTime) {
                if (valueString != null) {
                    if (formatLine.getDateFormat() != null && !"".equals(formatLine.getDateFormat())) {
                        // "MM/dd/yyyy"
                        customDateFormat = new SimpleDateFormat(formatLine.getDateFormat());
                        valueString = customDateFormat.format(Timestamp.valueOf(valueString));
                        // Add "DateForamt attribute"
                        newElement.setAttribute("DateFormat", customDateFormat.toPattern());
                    } else {
                        newElement.setAttribute("DateFormat", valueString);
                    }
                }
            }
            log.info("EXP Field - column=[" + column.getColumnName() + "]; value=" + value);
            if (valueString != null && !"".equals(valueString) && !"null".equals(valueString)) {
                Text newText = outDocument.createTextNode(valueString);
                newElement.appendChild(newText);
                rootElement.appendChild(newElement);
                elementHasValue = true;
            } else {
                // Empty field.
                if (formatLine.isMandatory()) {
                    Text newText = outDocument.createTextNode("");
                    newElement.appendChild(newText);
                    rootElement.appendChild(newElement);
                    elementHasValue = true;
                }
            }
        } else if (formatLine.getType().equals(X_EXP_FormatLine.TYPE_XMLAttribute)) {
            // process single XML Attribute
            if (formatLine.getAD_Column_ID() == 0) {
                throw new Exception(Msg.getMsg(masterPO.getCtx(), "EXPColumnMandatory"));
            }
            MColumn column = MColumn.get(masterPO.getCtx(), formatLine.getAD_Column_ID());
            if (column == null) {
                throw new Exception(Msg.getMsg(masterPO.getCtx(), "EXPColumnMandatory"));
            }
            if (column.isVirtualColumn()) {
                log.info("This is Virtual Column!");
            } else {
            }
            //log.info("["+column.getColumnName()+"]");
            Object value = masterPO.get_Value(column.getColumnName());
            String valueString = null;
            if (value != null) {
                valueString = value.toString();
            } else {
                if (formatLine.isMandatory()) {
                    throw new Exception(Msg.getMsg(masterPO.getCtx(), "EXPFieldMandatory"));
                }
            }
            /*				if (column.getAD_Reference_ID() == DisplayType.Date) {
					if (valueString != null) {
						if (formatLines[i].getDateFormat() != null && !"".equals(formatLines[i].getDateFormat())) {
							m_customDateFormat = new SimpleDateFormat( formatLines[i].getDateFormat() ); // "MM/dd/yyyy"
							//Date date = m_customDateFormat.parse ( valueString );
							valueString = m_customDateFormat.format(Timestamp.valueOf (valueString));
						} else {
							valueString = m_dateFormat.format (Timestamp.valueOf (valueString));
						}
								
					}
				} else if (column.getAD_Reference_ID() == DisplayType.DateTime) {
					if (valueString != null) {
						if (formatLines[i].getDateFormat() != null && !"".equals(formatLines[i].getDateFormat())) {
							m_customDateFormat = new SimpleDateFormat( formatLines[i].getDateFormat() ); // "MM/dd/yyyy"
							//Date date = m_customDateFormat.parse ( valueString );
							valueString = m_customDateFormat.format(Timestamp.valueOf (valueString));
						} else {
							valueString = m_dateTimeFormat.format (Timestamp.valueOf (valueString));
						}
					}
				}*/
            log.info("EXP Field - column=[" + column.getColumnName() + "]; value=" + value);
            if (valueString != null && !"".equals(valueString) && !"null".equals(valueString)) {
                rootElement.setAttribute(formatLine.getValue(), valueString);
                elementHasValue = true;
            } else {
            // Empty field.
            }
        } else if (formatLine.getType().equals(X_EXP_FormatLine.TYPE_EmbeddedEXPFormat)) {
            // process Embedded Export Format
            int embeddedFormat_ID = formatLine.getEXP_EmbeddedFormat_ID();
            //get from cache
            MEXPFormat embeddedFormat = MEXPFormat.get(masterPO.getCtx(), embeddedFormat_ID, masterPO.get_TrxName());
            MTable tableEmbedded = MTable.get(masterPO.getCtx(), embeddedFormat.getAD_Table_ID());
            log.info("Table Embedded = " + tableEmbedded);
            final StringBuffer whereClause = new StringBuffer(masterPO.get_KeyColumns()[0] + "=?");
            if (embeddedFormat.getWhereClause() != null & !"".equals(embeddedFormat.getWhereClause())) {
                whereClause.append(" AND ").append(embeddedFormat.getWhereClause());
            }
            Collection<PO> instances = new Query(masterPO.getCtx(), tableEmbedded.getTableName(), whereClause.toString(), masterPO.get_TrxName()).setClient_ID().setParameters(new Object[] { masterID }).list();
            for (PO instance : instances) {
                Element embeddedElement = outDocument.createElement(formatLine.getValue());
                if (formatLine.getDescription() != null && !"".equals(formatLine.getDescription())) {
                    embeddedElement.appendChild(outDocument.createComment(formatLine.getDescription()));
                }
                generateExportFormat(embeddedElement, embeddedFormat, instance, instance.get_ID(), variableMap);
                rootElement.appendChild(embeddedElement);
            }
        } else if (formatLine.getType().equals(X_EXP_FormatLine.TYPE_ReferencedEXPFormat)) {
            // process Referenced Export Format
            int embeddedFormat_ID = formatLine.getEXP_EmbeddedFormat_ID();
            //get from cache
            MEXPFormat embeddedFormat = MEXPFormat.get(masterPO.getCtx(), embeddedFormat_ID, masterPO.get_TrxName());
            MTable tableEmbedded = MTable.get(masterPO.getCtx(), embeddedFormat.getAD_Table_ID());
            log.info("Table Embedded = " + tableEmbedded);
            final StringBuffer whereClause = new StringBuffer(tableEmbedded.getTableName() + "_ID =?");
            if (embeddedFormat.getWhereClause() != null & !"".equals(embeddedFormat.getWhereClause())) {
                whereClause.append(" AND ").append(embeddedFormat.getWhereClause());
            }
            String columnName = "";
            if (formatLine.getAD_Reference_ID() == DisplayType.Table | formatLine.getAD_Reference_ID() == DisplayType.Search) {
                MColumn column = MColumn.get(masterPO.getCtx(), formatLine.getAD_Column_ID());
                columnName = column.getColumnName();
            } else {
                columnName = tableEmbedded.getTableName() + "_ID";
            }
            Object value = masterPO.get_Value(columnName);
            if (value == null) {
                continue;
            }
            Collection<PO> instances = new Query(masterPO.getCtx(), tableEmbedded.getTableName(), whereClause.toString(), masterPO.get_TrxName()).setClient_ID().setParameters(value).list();
            for (PO instance : instances) {
                Element embeddedElement = outDocument.createElement(formatLine.getValue());
                if (formatLine.getDescription() != null && !"".equals(formatLine.getDescription())) {
                    embeddedElement.appendChild(outDocument.createComment(formatLine.getDescription()));
                }
                generateExportFormat(embeddedElement, embeddedFormat, instance, instance.get_ID(), variableMap);
                rootElement.appendChild(embeddedElement);
            }
        } else {
            throw new Exception(Msg.getMsg(masterPO.getCtx(), "EXPUnknownLineType"));
        }
    }
}
Also used : MColumn(org.compiere.model.MColumn) MEXPFormat(org.compiere.model.MEXPFormat) Query(org.compiere.model.Query) Element(org.w3c.dom.Element) Text(org.w3c.dom.Text) SQLException(java.sql.SQLException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) MEXPFormatLine(org.compiere.model.MEXPFormatLine) MTable(org.compiere.model.MTable) Collection(java.util.Collection) SimpleDateFormat(java.text.SimpleDateFormat) PO(org.compiere.model.PO)

Example 4 with MColumn

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

the class AbstractDocumentSearch method getID.

/**
	 * search for id's that fit the searchString
	 *
	 * @param transactionCode
	 * @param searchString
	 */
private void getID(String transactionCode, String searchString) {
    ResultSet rsSO = null;
    ResultSet rsPO = null;
    PreparedStatement pstmtSO = null;
    PreparedStatement pstmtPO = null;
    String sqlSO = null;
    String sqlPO = null;
    final Properties ctx = Env.getCtx();
    final MRole role = MRole.get(ctx, Env.getAD_Role_ID(ctx), Env.getAD_User_ID(ctx), true);
    try {
        for (MSearchDefinition msd : MSearchDefinition.getForCode(transactionCode)) {
            MTable table = new MTable(Env.getCtx(), msd.getAD_Table_ID(), null);
            // SearchDefinition with a given table and column
            if (msd.getSearchType().equals(MSearchDefinition.SEARCHTYPE_TABLE)) {
                MColumn column = new MColumn(Env.getCtx(), msd.getAD_Column_ID(), null);
                sqlSO = "SELECT " + table.getTableName() + "_ID FROM " + table.getTableName() + " ";
                // search for an Integer
                if (msd.getDataType().equals(MSearchDefinition.DATATYPE_INTEGER)) {
                    sqlSO += "WHERE " + column.getColumnName() + "=?";
                // search for a String
                } else {
                    sqlSO += "WHERE UPPER(" + column.getColumnName() + ") LIKE UPPER(?)";
                }
                if (msd.getPO_Window_ID() != 0) {
                    sqlPO = sqlSO + " AND IsSOTrx='N'";
                    sqlSO += " AND IsSOTrx='Y'";
                }
                pstmtSO = DB.prepareStatement(sqlSO, null);
                pstmtPO = DB.prepareStatement(sqlPO, null);
                // search for a Integer
                if (msd.getDataType().equals(MSearchDefinition.DATATYPE_INTEGER)) {
                    pstmtSO.setInt(1, Integer.valueOf(searchString.replaceAll("\\D", "")));
                    if (msd.getPO_Window_ID() != 0) {
                        pstmtPO.setInt(1, Integer.valueOf(searchString.replaceAll("\\D", "")));
                    }
                // search for a String
                } else if (msd.getDataType().equals(MSearchDefinition.DATATYPE_STRING)) {
                    pstmtSO.setString(1, searchString);
                    if (msd.getPO_Window_ID() != 0) {
                        pstmtPO.setString(1, searchString);
                    }
                }
            // SearchDefinition with a special query
            } else if (msd.getSearchType().equals(MSearchDefinition.SEARCHTYPE_QUERY)) {
                sqlSO = msd.getQuery();
                pstmtSO = DB.prepareStatement(sqlSO, null);
                // count '?' in statement
                int count = 1;
                for (char c : sqlSO.toCharArray()) {
                    if (c == '?') {
                        count++;
                    }
                }
                for (int i = 1; i < count; i++) {
                    if (msd.getDataType().equals(MSearchDefinition.DATATYPE_INTEGER)) {
                        pstmtSO.setInt(i, Integer.valueOf(searchString.replaceAll("\\D", "")));
                    } else if (msd.getDataType().equals(MSearchDefinition.DATATYPE_STRING)) {
                        pstmtSO.setString(i, searchString);
                    }
                }
            }
            if (pstmtSO != null) {
                log.fine("SQL Sales: " + sqlSO);
                rsSO = pstmtSO.executeQuery();
                Vector<Integer> idSO = new Vector<Integer>();
                while (rsSO.next()) {
                    idSO.add(new Integer(rsSO.getInt(1)));
                }
                if (role.getWindowAccess(msd.getAD_Window_ID()) != null) {
                    log.fine("Open Window: " + msd.getAD_Window_ID() + " / Table: " + table.getTableName() + " / Number of Results: " + idSO.size());
                    if (idSO.size() == 0 && (searchString == null || searchString.trim().length() == 0)) {
                        // No search string - open the window with new record
                        idSO.add(new Integer(0));
                    }
                    openWindow(idSO, table.getTableName(), msd.getAD_Window_ID());
                } else {
                    log.warning("Role is not allowed to view this window");
                }
            }
            if (pstmtPO != null) {
                log.fine("SQL Purchase: " + sqlPO);
                rsPO = pstmtPO.executeQuery();
                Vector<Integer> idPO = new Vector<Integer>();
                while (rsPO.next()) {
                    idPO.add(new Integer(rsPO.getInt(1)));
                }
                if (role.getWindowAccess(msd.getPO_Window_ID()) != null) {
                    log.fine("Open Window: " + msd.getPO_Window_ID() + " / Table: " + table.getTableName() + " / Number of Results: " + idPO.size());
                    openWindow(idPO, table.getTableName(), msd.getPO_Window_ID());
                } else {
                    log.warning("Role is not allowed to view this window");
                }
            }
            DB.close(rsSO, pstmtSO);
            DB.close(rsPO, pstmtPO);
            pstmtSO = null;
            pstmtPO = null;
            rsSO = null;
            rsPO = null;
        }
    } catch (Exception e) {
        log.severe(e.toString());
        e.printStackTrace();
    } finally {
        DB.close(rsSO, pstmtSO);
        DB.close(rsPO, pstmtPO);
        rsSO = null;
        rsPO = null;
        pstmtSO = null;
        pstmtPO = null;
    }
}
Also used : MColumn(org.compiere.model.MColumn) MTable(org.compiere.model.MTable) MSearchDefinition(org.compiere.model.MSearchDefinition) MRole(org.compiere.model.MRole) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) Properties(java.util.Properties) Vector(java.util.Vector) SQLException(java.sql.SQLException)

Example 5 with MColumn

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

the class ImportBudget method fillIdValues.

/**
     * Fill Id Values
     * @param importBudget
     * @param acctSchemaElements
     * @param trxName
     */
private void fillIdValues(X_I_Budget importBudget, MAcctSchemaElement[] acctSchemaElements, String trxName) {
    StringBuffer stringError = new StringBuffer("");
    // Set Organization
    Integer orgId = 0;
    if (importBudget.getAD_Org_ID() > 0)
        orgId = importBudget.getAD_Org_ID();
    if (orgId <= 0 && importBudget.getOrgValue() != null)
        orgId = getId(MOrg.Table_Name, MOrg.COLUMNNAME_Value + "=?", trxName, importBudget.getOrgValue());
    if (orgId > 0 && importBudget.getAD_Org_ID() <= 0)
        importBudget.setAD_Org_ID(orgId);
    if (importBudget.getAD_Org_ID() <= 0 && importBudget.getOrgValue() != null)
        stringError.append("@AD_Org_ID@ @NotFound@ ");
    // Set Organization Trx
    Integer orgTrxId = 0;
    if (importBudget.getAD_OrgTrx_ID() > 0)
        orgTrxId = importBudget.getAD_OrgTrx_ID();
    if (orgTrxId <= 0 && importBudget.getOrgTrxValue() != null)
        orgTrxId = getId(MOrg.Table_Name, MOrg.COLUMNNAME_Value + "=?", trxName, importBudget.getOrgTrxValue());
    if (orgTrxId > 0 && importBudget.getAD_OrgTrx_ID() <= 0)
        importBudget.setAD_OrgTrx_ID(orgTrxId);
    if (importBudget.getAD_Org_ID() <= 0 && importBudget.getOrgTrxValue() != null)
        stringError.append("@AD_OrgTrx_ID@ @NotFound@ ");
    // Set Account Schema
    Integer accountSchemaId = 0;
    if (importBudget.getC_AcctSchema_ID() > 0)
        accountSchemaId = importBudget.getC_AcctSchema_ID();
    if (accountSchemaId <= 0 && importBudget.getAcctSchemaName() != null)
        accountSchemaId = getId(MAcctSchema.Table_Name, MAcctSchema.COLUMNNAME_Name + "=?", trxName, importBudget.getAcctSchemaName());
    if (accountSchemaId > 0 && importBudget.getC_AcctSchema_ID() <= 0)
        importBudget.setC_AcctSchema_ID(accountSchemaId);
    else {
        accountSchemaId = getAccountingSchemaId();
        importBudget.setC_AcctSchema_ID(accountSchemaId);
    }
    // Set Budget
    Integer budgetId = 0;
    if (importBudget.getGL_Budget_ID() > 0)
        budgetId = importBudget.getGL_Budget_ID();
    if (budgetId <= 0 && importBudget.getBudgetCode() != null)
        budgetId = getId(X_GL_Budget.Table_Name, X_GL_Budget.COLUMNNAME_Name + "=?", trxName, importBudget.getBudgetCode());
    if (budgetId > 0 && importBudget.getGL_Budget_ID() <= 0)
        importBudget.setGL_Budget_ID(budgetId);
    if (importBudget.getGL_Budget_ID() <= 0 && importBudget.getBudgetCode() != null)
        stringError.append("@GL_Budget_ID@ @NotFound@ ");
    // Set Asset
    Integer assetId = 0;
    if (importBudget.getA_Asset_ID() > 0)
        assetId = importBudget.getA_Asset_ID();
    if (assetId <= 0 && importBudget.getAssetValue() != null)
        assetId = getId(X_A_Asset.Table_Name, X_A_Asset.COLUMNNAME_Value + "=?", trxName, importBudget.getAssetValue());
    if (assetId > 0 && importBudget.getA_Asset_ID() <= 0)
        importBudget.setA_Asset_ID(assetId);
    if (importBudget.getA_Asset_ID() <= 0 && importBudget.getAssetValue() != null)
        stringError.append("@A_Asset_ID@ @NotFound@ ");
    // Set Account
    int accountId = 0;
    if (importBudget.getAccount_ID() > 0)
        accountId = importBudget.getAccount_ID();
    if (accountId <= 0 && importBudget.getAccountValue() != null)
        accountId = getId(MElementValue.Table_Name, MElementValue.COLUMNNAME_Value + "=?", trxName, importBudget.getAccountValue());
    if (accountId > 0 && importBudget.getAccount_ID() <= 0)
        importBudget.setAccount_ID(accountId);
    if (importBudget.getAccount_ID() <= 0 && importBudget.getAccountValue() != null)
        stringError.append("@Account_ID@ @NotFound@ ");
    int partnerId = 0;
    if (importBudget.getC_BPartner_ID() > 0)
        partnerId = importBudget.getC_BPartner_ID();
    if (partnerId <= 0 && importBudget.getBPartnerValue() != null) {
        MBPartner partner = MBPartner.get(getCtx(), importBudget.getBPartnerValue());
        if (partner != null)
            partnerId = partner.getC_BPartner_ID();
    }
    if (partnerId > 0 && importBudget.getC_BPartner_ID() <= 0)
        importBudget.setC_BPartner_ID(partnerId);
    if (importBudget.getC_BPartner_ID() <= 0 && importBudget.getBPartnerValue() != null)
        stringError.append("@C_BPartner_ID@ @NotFound@ ");
    // Set Product
    Integer productId = 0;
    if (importBudget.getM_Product_ID() > 0)
        productId = importBudget.getM_Product_ID();
    if (productId <= 0 && importBudget.getProductValue() != null)
        productId = getId(MProduct.Table_Name, MProduct.COLUMNNAME_Value + "=?", trxName, importBudget.getProductValue());
    if (productId > 0 && importBudget.getM_Product_ID() <= 0)
        importBudget.setM_Product_ID(productId);
    if (importBudget.getM_Product_ID() <= 0 && importBudget.getProductValue() != null)
        stringError.append("@M_Product_ID@ @NotFound@ ");
    // Set Project
    Integer projectId = 0;
    if (importBudget.getC_Project_ID() > 0)
        projectId = importBudget.getC_Project_ID();
    if (projectId <= 0 && importBudget.getProjectValue() != null)
        projectId = getId(MProject.Table_Name, MProject.COLUMNNAME_Value + "=?", trxName, importBudget.getProjectValue());
    if (projectId > 0 && importBudget.getC_Project_ID() <= 0)
        importBudget.setC_Project_ID(projectId);
    if (importBudget.getC_Project_ID() <= 0 && importBudget.getProjectValue() != null)
        stringError.append("@C_Project_ID@ @NotFound@ ");
    // Set Campaign
    Integer campaignId = 0;
    if (importBudget.getC_Campaign_ID() > 0)
        campaignId = importBudget.getC_Campaign_ID();
    if (campaignId <= 0 && importBudget.getCampaignValue() != null)
        campaignId = getId(MCampaign.Table_Name, MCampaign.COLUMNNAME_Value + "=?", trxName, importBudget.getCampaignValue());
    if (campaignId > 0 && importBudget.getC_Campaign_ID() <= 0)
        importBudget.setC_Campaign_ID(campaignId);
    if (importBudget.getC_Campaign_ID() <= 0 && importBudget.getCampaignValue() != null)
        stringError.append("@C_Campaign_ID@ @NotFound@ ");
    // Set Sales Region
    Integer salesRegionId = 0;
    if (importBudget.getC_SalesRegion_ID() > 0)
        salesRegionId = importBudget.getC_SalesRegion_ID();
    if (salesRegionId <= 0 && importBudget.getSalesRegionValue() != null)
        salesRegionId = getId(MSalesRegion.Table_Name, MSalesRegion.COLUMNNAME_Value + "=?", trxName, importBudget.getSalesRegionValue());
    if (salesRegionId > 0 && importBudget.getC_SalesRegion_ID() <= 0)
        importBudget.setC_SalesRegion_ID(salesRegionId);
    if (importBudget.getC_SalesRegion_ID() <= 0 && importBudget.getSalesRegionValue() != null)
        stringError.append("@C_SalesRegion_ID@ @NotFound@");
    // Set Activity Id
    Integer activityId = 0;
    if (importBudget.getC_Activity_ID() > 0)
        activityId = importBudget.getC_Activity_ID();
    if (activityId <= 0 && importBudget.getActivityValue() != null)
        activityId = getId(MActivity.Table_Name, MActivity.COLUMNNAME_Value + "=?", trxName, importBudget.getActivityValue());
    if (accountId > 0 && importBudget.getC_Activity_ID() <= 0)
        importBudget.setC_Activity_ID(activityId);
    if (importBudget.getC_Activity_ID() <= 0 && importBudget.getActivityValue() != null)
        stringError.append("@C_SalesRegion_ID@ @NotFound@ ");
    // Set Sub Acct Id
    Integer subAcctountId = 0;
    if (importBudget.getC_SubAcct_ID() > 0)
        subAcctountId = importBudget.getC_SubAcct_ID();
    if (subAcctountId <= 0 && importBudget.getSubAcctValue() != null)
        subAcctountId = getId(X_C_SubAcct.Table_Name, X_C_SubAcct.COLUMNNAME_Value + "=?", trxName, importBudget.getSubAcctValue());
    if (subAcctountId > 0 && importBudget.getC_SubAcct_ID() <= 0)
        importBudget.setC_SubAcct_ID(subAcctountId);
    if (importBudget.getC_SubAcct_ID() <= 0 && importBudget.getSubAcctValue() != null)
        stringError.append("@C_SubAcct_ID@ @NotFound@ ");
    // Set User 1
    Integer user1Id = 0;
    if (importBudget.getUser1_ID() > 0)
        user1Id = importBudget.getUser1_ID();
    if (user1Id <= 0 && importBudget.getUser1_ID() <= 0 && importBudget.getUserValue1() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList1.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser1_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue1()));
        });
    }
    if (importBudget.getUser1_ID() <= 0 && importBudget.getUserValue1() != null)
        stringError.append("@User1_ID@ @NotFound@ ");
    // User 2
    Integer user2Id = 0;
    if (importBudget.getUser2_ID() > 0)
        user2Id = importBudget.getUser2_ID();
    if (user2Id <= 0 && importBudget.getUser2_ID() <= 0 && importBudget.getUserValue2() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList2.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser2_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue2()));
        });
    }
    if (importBudget.getUser2_ID() <= 0 && importBudget.getUserValue2() != null)
        stringError.append("@User2_ID@ @NotFound@ ");
    Integer user3Id = 0;
    if (importBudget.getUser3_ID() > 0)
        user3Id = importBudget.getUser3_ID();
    if (user3Id <= 0 && importBudget.getUser3_ID() <= 0 && importBudget.getUserValue3() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList3.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser3_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue3()));
        });
    }
    if (importBudget.getUser3_ID() <= 0 && importBudget.getUserValue3() != null)
        stringError.append("@User3_ID@ @NotFound@ ");
    Integer user4Id = 0;
    if (importBudget.getUser4_ID() > 0)
        user4Id = importBudget.getUser4_ID();
    if (user4Id <= 0 && importBudget.getUser4_ID() <= 0 && importBudget.getUserValue4() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserList4.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            String where = MElementValue.COLUMNNAME_C_Element_ID + "=? AND " + MElementValue.COLUMNNAME_Value + "=?";
            importBudget.setUser4_ID(getId(MElementValue.Table_Name, where, trxName, acctSchemaElement.getC_Element_ID(), importBudget.getUserValue4()));
        });
    }
    if (importBudget.getUser4_ID() <= 0 && importBudget.getUserValue4() != null)
        stringError.append("@User4_ID@ @NotFound@ ");
    Integer userElement1Id = 0;
    if (importBudget.getUserElement1_ID() > 0)
        userElement1Id = importBudget.getUserElement1_ID();
    if (userElement1Id <= 0 && importBudget.getUserElement1_ID() <= 0 && importBudget.getUserElementValue1() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserElement1.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            I_AD_Column column = acctSchemaElement.getAD_Column();
            MTable table = (MTable) column.getAD_Table();
            MColumn columnName = table.getColumn("Value");
            if (columnName == null)
                columnName = table.getColumn("Name");
            if (columnName != null)
                importBudget.setUserElement1_ID(getId(table.getTableName(), columnName.getColumnName() + "=?", trxName, importBudget.getUserElementValue1()));
        });
    }
    if (importBudget.getUserElement1_ID() <= 0 && importBudget.getUserElementValue1() != null)
        stringError.append("@UserElement1_ID@ @NotFound@ ");
    Integer userElement2Id = 0;
    if (importBudget.getUserElement2_ID() > 0)
        userElement2Id = importBudget.getUserElement2_ID();
    if (userElement2Id <= 0 && importBudget.getUserElement2_ID() <= 0 && importBudget.getUserElementValue2() != null) {
        Arrays.stream(acctSchemaElements).filter(acctSchemaElement -> MAcctSchemaElement.ELEMENTTYPE_UserElement2.equals(acctSchemaElement.getElementType())).forEach(acctSchemaElement -> {
            I_AD_Column column = acctSchemaElement.getAD_Column();
            MTable table = (MTable) column.getAD_Table();
            MColumn columnName = table.getColumn("Value");
            if (columnName == null)
                columnName = table.getColumn("Name");
            if (columnName != null)
                importBudget.setUserElement2_ID(getId(table.getTableName(), columnName.getColumnName() + "=?", trxName, importBudget.getUserElementValue2()));
        });
    }
    if (importBudget.getUserElement2_ID() <= 0 && importBudget.getUserElementValue2() != null)
        stringError.append("@UserElement2_ID@ @NotFound@ ");
    if (accountSchemaId <= 0)
        stringError.append("@C_AcctSchema_ID@ @NotFound@ ");
    if (budgetId <= 0)
        stringError.append("@GL_Budget_ID@ @NotFound@ ");
    if (accountId <= 0)
        stringError.append("@Account_ID@ @NotFound@ ");
    if (!stringError.toString().isEmpty() && stringError.toString().length() > 0) {
        importBudget.setI_ErrorMsg(Msg.parseTranslation(getCtx(), stringError.toString()));
        importBudget.saveEx();
    }
    importBudget.saveEx();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MAcctSchemaElement(org.compiere.model.MAcctSchemaElement) Arrays(java.util.Arrays) MProject(org.compiere.model.MProject) X_I_Budget(org.compiere.model.X_I_Budget) CLogger(org.compiere.util.CLogger) MJournalLine(org.compiere.model.MJournalLine) MJournalBatch(org.compiere.model.MJournalBatch) Env(org.compiere.util.Env) SimpleDateFormat(java.text.SimpleDateFormat) X_GL_Budget(org.compiere.model.X_GL_Budget) MCampaign(org.compiere.model.MCampaign) AtomicReference(java.util.concurrent.atomic.AtomicReference) MAcctSchema(org.compiere.model.MAcctSchema) ArrayList(java.util.ArrayList) MActivity(org.compiere.model.MActivity) MSalesRegion(org.compiere.model.MSalesRegion) BigDecimal(java.math.BigDecimal) Query(org.compiere.model.Query) DB(org.compiere.util.DB) Calendar(java.util.Calendar) MBPartner(org.compiere.model.MBPartner) Msg(org.compiere.util.Msg) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MElementValue(org.compiere.model.MElementValue) MPeriod(org.compiere.model.MPeriod) Trx(org.compiere.util.Trx) MJournal(org.compiere.model.MJournal) DateFormat(java.text.DateFormat) Timestamp(java.sql.Timestamp) X_C_SubAcct(org.compiere.model.X_C_SubAcct) Logger(java.util.logging.Logger) MColumn(org.compiere.model.MColumn) Date(java.sql.Date) I_AD_Column(org.compiere.model.I_AD_Column) List(java.util.List) MOrg(org.compiere.model.MOrg) AdempiereException(org.adempiere.exceptions.AdempiereException) X_A_Asset(org.compiere.model.X_A_Asset) MTable(org.compiere.model.MTable) MAccount(org.compiere.model.MAccount) MProduct(org.compiere.model.MProduct) I_I_Budget(org.compiere.model.I_I_Budget) MColumn(org.compiere.model.MColumn) MTable(org.compiere.model.MTable) I_AD_Column(org.compiere.model.I_AD_Column) MBPartner(org.compiere.model.MBPartner)

Aggregations

MColumn (org.compiere.model.MColumn)40 MTable (org.compiere.model.MTable)15 SQLException (java.sql.SQLException)11 BigDecimal (java.math.BigDecimal)9 AdempiereException (org.adempiere.exceptions.AdempiereException)7 PreparedStatement (java.sql.PreparedStatement)6 ResultSet (java.sql.ResultSet)6 Query (org.compiere.model.Query)6 MEXPFormat (org.compiere.model.MEXPFormat)5 Timestamp (java.sql.Timestamp)4 ArrayList (java.util.ArrayList)4 Vector (java.util.Vector)4 MEXPFormatLine (org.compiere.model.MEXPFormatLine)4 MLookup (org.compiere.model.MLookup)4 MUser (org.compiere.model.MUser)4 DBException (org.adempiere.exceptions.DBException)3 MField (org.compiere.model.MField)3 ParseException (java.text.ParseException)2 SimpleDateFormat (java.text.SimpleDateFormat)2 Calendar (java.util.Calendar)2