Search in sources :

Example 31 with Trx

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

the class WReport method launchReport.

//	launchReport
/**
	 * 	Launch Report
	 * 	@param pf print format
	 */
private File launchReport(MPrintFormat pf, HttpServletRequest request, GridTab m_curTab, MQuery m_query) {
    int Record_ID = 0;
    WebSessionCtx wsc = WebSessionCtx.get(request);
    WWindowStatus ws = WWindowStatus.get(request);
    //Instance pInstance = new MPInstance (wsc.ctx, 0, 0);
    File fileName = null;
    if (m_query.getRestrictionCount() == 1 && m_query.getCode(0) instanceof Integer) {
        Record_ID = ((Integer) m_query.getCode(0)).intValue();
    }
    PrintInfo info = new PrintInfo(pf.getName(), pf.getAD_Table_ID(), Record_ID);
    info.setDescription(m_query.getInfo());
    if (pf != null && pf.getJasperProcess_ID() > 0) {
        // It's a report using the JasperReports engine
        ProcessInfo pi = new ProcessInfo("", pf.getJasperProcess_ID());
        Trx trx = Trx.get(Trx.createTrxName("WebPrc"), true);
        //	Execute Process
        WProcessCtl.process(this, m_curTab.getAD_Window_ID(), pi, trx, request);
    } else {
        // It's a default report using the standard printing engine
        ReportEngine re = new ReportEngine(wsc.ctx, pf, m_query, info);
        if (re == null) {
            log.info("Could not start ReportEngine");
        } else {
            try {
                File file = File.createTempFile("WProcess", ".pdf");
                boolean ok = re.createPDF(file);
                if (ok) {
                    fileName = file;
                } else {
                    log.info("Could not create Report");
                }
            } catch (Exception e) {
                log.info(e.toString());
            }
        }
    }
    return fileName;
}
Also used : ReportEngine(org.compiere.print.ReportEngine) PrintInfo(org.compiere.model.PrintInfo) ProcessInfo(org.compiere.process.ProcessInfo) Trx(org.compiere.util.Trx) WebSessionCtx(org.compiere.util.WebSessionCtx) File(java.io.File) ServletException(javax.servlet.ServletException) SQLException(java.sql.SQLException) IOException(java.io.IOException)

Example 32 with Trx

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

the class AdempiereTreeModel method saveChangedNodes.

public void saveChangedNodes(MTreeNode from, MTreeNode to) {
    int AD_Tree_ID = m_MTree.getAD_Tree_ID();
    Trx trx = Trx.get(Trx.createTrxName("AdempiereTreeModel"), true);
    try {
        for (int i = 0; i < from.getChildCount(); i++) {
            MTreeNode nd = (MTreeNode) from.getChildAt(i);
            String whereClause = "AD_Tree_ID=" + AD_Tree_ID + " AND Node_ID=" + nd.getNode_ID();
            PO tree = MTable.get(Env.getCtx(), m_MTree.getNodeTableName()).getPO(whereClause, trx.getTrxName());
            if (tree.get_ValueAsInt("Parent_ID") != from.getNode_ID() || tree.get_ValueAsInt("SeqNo") != i) {
                tree.set_CustomColumn("Parent_ID", from.getNode_ID());
                tree.set_CustomColumn("SeqNo", i);
                tree.saveEx();
            }
        }
        if (from != to) {
            // Renumber and set parent ID for the children of the 'to' node.
            int nextSeqNo = 0;
            for (int i = 0; i < to.getChildCount(); i++) {
                // Skip the entry of the 'from' node to avoid duplication
                if (i == Integer.parseInt(from.getSeqNo()))
                    continue;
                MTreeNode nd = (MTreeNode) to.getChildAt(i);
                String whereClause = "AD_Tree_ID=" + AD_Tree_ID + " AND Node_ID=" + nd.getNode_ID();
                PO tree = MTable.get(Env.getCtx(), m_MTree.getNodeTableName()).getPO(whereClause, trx.getTrxName());
                if (tree.get_ValueAsInt("Parent_ID") != to.getNode_ID() || tree.get_ValueAsInt("SeqNo") < nextSeqNo) {
                    tree.set_CustomColumn("Parent_ID", to.getNode_ID());
                    tree.set_CustomColumn("SeqNo", nextSeqNo++);
                    tree.saveEx();
                } else {
                    nextSeqNo = tree.get_ValueAsInt("SeqNo") + 1;
                }
            }
        }
        trx.commit(true);
    } catch (Exception e) {
        trx.rollback();
        log.log(Level.SEVERE, "move", e);
    }
    trx.close();
    trx = null;
    log.config("complete");
}
Also used : MTreeNode(org.compiere.model.MTreeNode) Trx(org.compiere.util.Trx) PO(org.compiere.model.PO)

Example 33 with Trx

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

the class WWFActivity method onOK.

//	cmd_button
/**
	 * 	Save
	 */
public void onOK() {
    log.config("Activity=" + m_activity);
    if (m_activity == null) {
        Clients.clearBusy();
        return;
    }
    int AD_User_ID = Env.getAD_User_ID(Env.getCtx());
    String textMsg = fTextMsg.getValue();
    //
    MWFNode node = m_activity.getNode();
    //fForward.getValue();
    Object forward = null;
    // ensure activity is ran within a transaction - [ 1953628 ]
    Trx trx = null;
    try {
        trx = Trx.get(Trx.createTrxName("FWFA"), true);
        m_activity.set_TrxName(trx.getTrxName());
        if (forward != null) {
            log.config("Forward to " + forward);
            int fw = ((Integer) forward).intValue();
            if (fw == AD_User_ID || fw == 0) {
                log.log(Level.SEVERE, "Forward User=" + fw);
                trx.rollback();
                trx.close();
                return;
            }
            if (!m_activity.forwardTo(fw, textMsg)) {
                FDialog.error(m_WindowNo, this, "CannotForward");
                trx.rollback();
                trx.close();
                return;
            }
        } else //	User Choice - Answer
        if (MWFNode.ACTION_UserChoice.equals(node.getAction())) {
            if (m_column == null)
                m_column = node.getColumn();
            //	Do we have an answer?
            int dt = m_column.getAD_Reference_ID();
            String value = fAnswerText.getText();
            if (dt == DisplayType.YesNo || dt == DisplayType.List) {
                ListItem li = fAnswerList.getSelectedItem();
                if (li != null)
                    value = li.getValue().toString();
            }
            if (value == null || value.length() == 0) {
                FDialog.error(m_WindowNo, this, "FillMandatory", Msg.getMsg(Env.getCtx(), "Answer"));
                trx.rollback();
                trx.close();
                return;
            }
            //
            log.config("Answer=" + value + " - " + textMsg);
            try {
                m_activity.setUserChoice(AD_User_ID, value, dt, textMsg);
            } catch (Exception e) {
                log.log(Level.SEVERE, node.getName(), e);
                FDialog.error(m_WindowNo, this, "Error", e.toString());
                trx.rollback();
                trx.close();
                return;
            }
        } else //	User Action
        {
            log.config("Action=" + node.getAction() + " - " + textMsg);
            try {
                // ensure activity is ran within a transaction
                m_activity.setUserConfirmation(AD_User_ID, textMsg);
            } catch (Exception e) {
                log.log(Level.SEVERE, node.getName(), e);
                FDialog.error(m_WindowNo, this, "Error", e.toString());
                trx.rollback();
                trx.close();
                return;
            }
        }
        trx.commit();
    } finally {
        Clients.clearBusy();
        if (trx != null)
            trx.close();
        FDialog.info(m_WindowNo, this, "WorkflowResult", Msg.parseTranslation(Env.getCtx(), "@AD_WF_Node_ID@") + " : " + m_activity.getNodeName() + " -> " + m_activity.getTextMsg());
    }
    //	Next
    loadActivities();
    display(-1);
}
Also used : MWFNode(org.compiere.wf.MWFNode) Trx(org.compiere.util.Trx) ListItem(org.adempiere.webui.component.ListItem)

Example 34 with Trx

use of org.compiere.util.Trx in project lar_361 by comitsrl.

the class MSequence method getDocumentNoFromSeq.

// getDocumentNo
private static String getDocumentNoFromSeq(MSequence seq, String trxName, PO po) {
    // Check AdempiereSys
    boolean adempiereSys = Ini.isPropertyBool(Ini.P_ADEMPIERESYS);
    if (adempiereSys && Env.getAD_Client_ID(Env.getCtx()) > 11)
        adempiereSys = false;
    // 
    int AD_Sequence_ID = seq.getAD_Sequence_ID();
    boolean isStartNewYear = seq.isStartNewYear();
    boolean isStartNewMonth = seq.isStartNewMonth();
    String dateColumn = seq.getDateColumn();
    boolean isUseOrgLevel = seq.isOrgLevelSequence();
    String orgColumn = seq.getOrgColumn();
    int startNo = seq.getStartNo();
    int incrementNo = seq.getIncrementNo();
    String prefix = seq.getPrefix();
    String suffix = seq.getSuffix();
    String decimalPattern = seq.getDecimalPattern();
    String selectSQL = null;
    if (isStartNewYear || isUseOrgLevel) {
        selectSQL = "SELECT y.CurrentNext, s.CurrentNextSys " + "FROM AD_Sequence_No y, AD_Sequence s " + "WHERE y.AD_Sequence_ID = s.AD_Sequence_ID " + "AND s.AD_Sequence_ID = ? " + "AND y.CalendarYearMonth = ? " + "AND y.AD_Org_ID = ? " + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " + "ORDER BY s.AD_Client_ID DESC";
    } else {
        selectSQL = "SELECT s.CurrentNext, s.CurrentNextSys " + "FROM AD_Sequence s " + "WHERE s.AD_Sequence_ID = ? " + "AND s.IsActive='Y' AND s.IsTableID='N' AND s.IsAutoSequence='Y' " + "ORDER BY s.AD_Client_ID DESC";
    }
    if (DB.isPostgreSQL()) {
        if ((isStartNewYear || isUseOrgLevel) && !adempiereSys) {
            selectSQL = selectSQL + " FOR UPDATE OF y";
        } else {
            selectSQL = selectSQL + " FOR UPDATE OF s";
        }
    }
    Connection conn = null;
    Trx trx = trxName == null ? null : Trx.get(trxName, true);
    // 
    String calendarYearMonth = NoYearNorMonth;
    int docOrg_ID = 0;
    int next = -1;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        if (trx != null)
            conn = trx.getConnection();
        else
            conn = DB.getConnectionID();
        // Error
        if (conn == null)
            return null;
        if (isStartNewYear) {
            SimpleDateFormat sdf = null;
            if (isStartNewMonth)
                sdf = new SimpleDateFormat("yyyyMM");
            else
                sdf = new SimpleDateFormat("yyyy");
            if (po != null && dateColumn != null && dateColumn.length() > 0) {
                Date docDate = (Date) po.get_Value(dateColumn);
                calendarYearMonth = sdf.format(docDate);
            } else {
                calendarYearMonth = sdf.format(new Date());
            }
        }
        if (isUseOrgLevel) {
            if (po != null && orgColumn != null && orgColumn.length() > 0) {
                docOrg_ID = po.get_ValueAsInt(orgColumn);
            }
        }
        pstmt = conn.prepareStatement(selectSQL, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_UPDATABLE);
        int index = 1;
        pstmt.setInt(index++, AD_Sequence_ID);
        if (isUseOrgLevel || isStartNewYear) {
            pstmt.setString(index++, calendarYearMonth);
            pstmt.setInt(index++, docOrg_ID);
        }
        // 
        if (DB.getDatabase().isQueryTimeoutSupported())
            pstmt.setQueryTimeout(QUERY_TIME_OUT);
        rs = pstmt.executeQuery();
        // + " - Type=" + pstmt.getResultSetType() + " - Concur=" + pstmt.getResultSetConcurrency());
        if (rs.next()) {
            s_log.fine("AD_Sequence_ID=" + AD_Sequence_ID);
            PreparedStatement updateSQL = null;
            try {
                if (adempiereSys) {
                    updateSQL = conn.prepareStatement("UPDATE AD_Sequence SET CurrentNextSys = CurrentNextSys + ? WHERE AD_Sequence_ID = ?");
                    next = rs.getInt(2);
                } else {
                    String sql;
                    if (isStartNewYear || isUseOrgLevel)
                        sql = "UPDATE AD_Sequence_No SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID=? AND CalendarYearMonth=? AND AD_Org_ID=?";
                    else
                        sql = "UPDATE AD_Sequence SET CurrentNext = CurrentNext + ? WHERE AD_Sequence_ID=?";
                    updateSQL = conn.prepareStatement(sql);
                    next = rs.getInt(1);
                }
                updateSQL.setInt(1, incrementNo);
                updateSQL.setInt(2, AD_Sequence_ID);
                if (isStartNewYear || isUseOrgLevel) {
                    updateSQL.setString(3, calendarYearMonth);
                    updateSQL.setInt(4, docOrg_ID);
                }
                updateSQL.executeUpdate();
            } finally {
                DB.close(updateSQL);
            }
        } else {
            // did not find sequence no
            if (isUseOrgLevel || isStartNewYear) {
                // create sequence (CurrentNo = StartNo + IncrementNo) for this year/month/org and return first number (=StartNo)
                next = startNo;
                X_AD_Sequence_No seqno = new X_AD_Sequence_No(Env.getCtx(), 0, trxName);
                seqno.setAD_Sequence_ID(AD_Sequence_ID);
                seqno.setAD_Org_ID(docOrg_ID);
                seqno.setCalendarYearMonth(calendarYearMonth);
                seqno.setCurrentNext(startNo + incrementNo);
                seqno.saveEx();
            } else // standard
            {
                s_log.warning("(Sequence)- no record found - " + seq);
                next = -2;
            }
        }
        // Commit
        if (trx == null) {
            conn.commit();
        }
    } catch (Exception e) {
        s_log.log(Level.SEVERE, "(DocType) [" + trxName + "]", e);
        if (DBException.isTimeout(e))
            throw new AdempiereException("GenerateDocumentNoTimeOut", e);
        else
            throw new AdempiereException("GenerateDocumentNoError", e);
    } finally {
        DB.close(rs, pstmt);
        // Finish
        try {
            if (trx == null && conn != null) {
                conn.close();
                conn = null;
            }
        } catch (Exception e) {
            s_log.log(Level.SEVERE, "(DocType) - finish", e);
        }
    }
    // Error
    if (next < 0)
        return null;
    // create DocumentNo
    StringBuffer doc = new StringBuffer();
    if (prefix != null && prefix.length() > 0)
        doc.append(Env.parseVariable(prefix, po, trxName, false));
    if (decimalPattern != null && decimalPattern.length() > 0)
        doc.append(new DecimalFormat(decimalPattern).format(next));
    else
        doc.append(next);
    if (suffix != null && suffix.length() > 0)
        doc.append(Env.parseVariable(suffix, po, trxName, false));
    String documentNo = doc.toString();
    s_log.finer(documentNo + " (" + incrementNo + ")" + " - Sequence=" + AD_Sequence_ID + " [" + trx + "]");
    return documentNo;
}
Also used : DecimalFormat(java.text.DecimalFormat) HttpURLConnection(java.net.HttpURLConnection) Connection(java.sql.Connection) CConnection(org.compiere.db.CConnection) PreparedStatement(java.sql.PreparedStatement) Date(java.util.Date) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException) AdempiereException(org.adempiere.exceptions.AdempiereException) AdempiereException(org.adempiere.exceptions.AdempiereException) ResultSet(java.sql.ResultSet) Trx(org.compiere.util.Trx) SimpleDateFormat(java.text.SimpleDateFormat)

Example 35 with Trx

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

the class ColumnElementHandler method createColumn.

/**
	 * Check if column exists in database and modify. If not create column.
	 * 
	 * @param tablename
	 * @param columnname
	 * @param v_AD_Reference_ID
	 * @param v_FieldLength
	 * @param v_DefaultValue
	 * @param v_IsMandatory
	 * 
	 */
private int createColumn(Properties ctx, MTable table, MColumn column, boolean doAlter) {
    int no = 0;
    String sql = null;
    ResultSet rst = null;
    ResultSet rsc = null;
    Connection conn = null;
    Trx trx = Trx.get(getTrxName(ctx), true);
    if (!trx.commit())
        return 0;
    try {
        // Find Column in Database
        conn = trx.getConnection();
        DatabaseMetaData md = conn.getMetaData();
        String catalog = DB.getDatabase().getCatalog();
        String schema = DB.getDatabase().getSchema();
        String tableName = table.getTableName();
        String columnName = column.getColumnName();
        if (DB.isOracle()) {
            tableName = tableName.toUpperCase();
            columnName = columnName.toUpperCase();
        } else if (DB.isPostgreSQL()) {
            tableName = tableName.toLowerCase();
            columnName = columnName.toLowerCase();
        }
        rst = md.getTables(catalog, schema, tableName, new String[] { "TABLE" });
        if (!rst.next()) {
            // table doesn't exist
            sql = table.getSQLCreate();
        } else {
            //
            rsc = md.getColumns(catalog, schema, tableName, columnName);
            if (rsc.next()) {
                if (doAlter) {
                    // update existing column
                    boolean notNull = DatabaseMetaData.columnNoNulls == rsc.getInt("NULLABLE");
                    sql = column.getSQLModify(table, column.isMandatory() != notNull);
                }
            } else {
                // No existing column
                sql = column.getSQLAdd(table);
            }
            rsc.close();
            rsc = null;
        }
        rst.close();
        rst = null;
        //execute modify or add if needed
        if (sql != null && sql.trim().length() > 0) {
            log.info(sql);
            if (sql.indexOf(DB.SQLSTATEMENT_SEPARATOR) == -1) {
                no = DB.executeUpdate(sql, false, trx.getTrxName());
                if (no == -1)
                    return 0;
            } else {
                String[] statements = sql.split(DB.SQLSTATEMENT_SEPARATOR);
                for (int i = 0; i < statements.length; i++) {
                    int count = DB.executeUpdate(statements[i], false, trx.getTrxName());
                    if (count == -1) {
                        return 0;
                    }
                    no += count;
                }
            }
        }
        trx.commit(true);
    } catch (SQLException e) {
        log.log(Level.SEVERE, e.getLocalizedMessage(), e);
        if (rsc != null) {
            try {
                rsc.close();
            } catch (SQLException e1) {
            }
            rsc = null;
        }
        if (rst != null) {
            try {
                rst.close();
            } catch (SQLException e1) {
            }
            rst = null;
        }
        trx.rollback();
        return 0;
    }
    return 1;
}
Also used : SQLException(java.sql.SQLException) ResultSet(java.sql.ResultSet) Connection(java.sql.Connection) Trx(org.compiere.util.Trx) DatabaseMetaData(java.sql.DatabaseMetaData)

Aggregations

Trx (org.compiere.util.Trx)62 SQLException (java.sql.SQLException)21 ProcessInfo (org.compiere.process.ProcessInfo)17 AdempiereException (org.adempiere.exceptions.AdempiereException)13 MPInstance (org.compiere.model.MPInstance)12 DBException (org.adempiere.exceptions.DBException)11 Timestamp (java.sql.Timestamp)9 File (java.io.File)8 Connection (java.sql.Connection)8 Properties (java.util.Properties)8 MPInstancePara (org.compiere.model.MPInstancePara)8 PreparedStatement (java.sql.PreparedStatement)7 ResultSet (java.sql.ResultSet)7 BigDecimal (java.math.BigDecimal)6 IOException (java.io.IOException)5 CConnection (org.compiere.db.CConnection)5 MTable (org.compiere.model.MTable)5 PO (org.compiere.model.PO)5 SimpleDateFormat (java.text.SimpleDateFormat)4 ServletException (javax.servlet.ServletException)4