Search in sources :

Example 26 with Trx

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

the class AdempiereMonitor method createLogMgtPage.

//	createSummaryPage
/**
	 * 	Add Log Management to page
	 *	@param bb body
	 */
private void createLogMgtPage(body bb) {
    bb.addElement(new hr());
    //	Ini Parameters
    table table = new table();
    table.setBorder(1);
    table.setCellSpacing(2);
    table.setCellPadding(2);
    //
    Properties ctx = new Properties();
    MSystem system = MSystem.get(ctx);
    tr line = new tr();
    line.addElement(new th().addElement(system.getDBAddress()));
    line.addElement(new td().addElement(Ini.getAdempiereHome()));
    table.addElement(line);
    //	OS + Name
    line = new tr();
    String info = System.getProperty("os.name") + " " + System.getProperty("os.version");
    String s = System.getProperty("sun.os.patch.level");
    if (s != null && s.length() > 0)
        info += " (" + s + ")";
    line.addElement(new th().addElement(info));
    info = system.getName();
    if (system.getCustomPrefix() != null)
        info += " (" + system.getCustomPrefix() + ")";
    line.addElement(new td().addElement(info));
    table.addElement(line);
    //	Java + email
    line = new tr();
    info = System.getProperty("java.vm.name") + " " + System.getProperty("java.vm.version");
    line.addElement(new th().addElement(info));
    line.addElement(new td().addElement(system.getUserName()));
    table.addElement(line);
    //	DB + Instance
    line = new tr();
    CConnection cc = CConnection.get();
    AdempiereDatabase db = cc.getDatabase();
    info = db.getDescription();
    line.addElement(new th().addElement(info));
    line.addElement(new td().addElement(cc.getConnectionURL()));
    //		line.addElement(new td().addElement(system.getDBInstance()));
    table.addElement(line);
    //	Processors/Support
    line = new tr();
    line.addElement(new th().addElement("Processor/Support"));
    line.addElement(new td().addElement(system.getNoProcessors() + "/" + system.getSupportUnits()));
    table.addElement(line);
    //	Memory
    line = new tr();
    MemoryMXBean memory = ManagementFactory.getMemoryMXBean();
    line.addElement(new th().addElement("VM Memory"));
    line.addElement(new td().addElement(new CMemoryUsage(memory.getNonHeapMemoryUsage()).toString()));
    table.addElement(line);
    line = new tr();
    line.addElement(new th().addElement("Heap Memory"));
    line.addElement(new td().addElement(new CMemoryUsage(memory.getHeapMemoryUsage()).toString()));
    table.addElement(line);
    //	Runtime
    line = new tr();
    RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
    line.addElement(new th().addElement("Runtime " + rt.getName()));
    line.addElement(new td().addElement(TimeUtil.formatElapsed(rt.getUptime())));
    table.addElement(line);
    //	Threads
    line = new tr();
    ThreadMXBean th = ManagementFactory.getThreadMXBean();
    line.addElement(new th().addElement("Threads " + th.getThreadCount()));
    line.addElement(new td().addElement("Peak=" + th.getPeakThreadCount() + ", Demons=" + th.getDaemonThreadCount() + ", Total=" + th.getTotalStartedThreadCount()));
    table.addElement(line);
    //Transactions
    Trx[] trxs = Trx.getActiveTransactions();
    for (Trx trx : trxs) {
        if (trx != null && trx.isActive()) {
            line = new tr();
            line.addElement(new th().addElement("Active Transaction "));
            line.addElement(new td().addElement("Name=" + trx.getTrxName() + ", StartTime=" + trx.getStartTime()));
            table.addElement(line);
        }
    }
    //	Cache Reset
    line = new tr();
    line.addElement(new th().addElement(CacheMgt.get().toStringX()));
    line.addElement(new td().addElement(new a("adempiereMonitor?CacheReset=Yes", "Reset Cache")));
    table.addElement(line);
    //	Trace Level
    line = new tr();
    line.addElement(new th().addElement(new label("TraceLevel").addElement("Trace Log Level")));
    form myForm = new form("adempiereMonitor", form.METHOD_POST, form.ENC_DEFAULT);
    //	LogLevel Selection
    option[] options = new option[CLogMgt.LEVELS.length];
    for (int i = 0; i < options.length; i++) {
        options[i] = new option(CLogMgt.LEVELS[i].getName());
        options[i].addElement(CLogMgt.LEVELS[i].getName());
        if (CLogMgt.LEVELS[i] == CLogMgt.getLevel())
            options[i].setSelected(true);
    }
    select sel = new select("TraceLevel", options);
    myForm.addElement(sel);
    myForm.addElement(new input(input.TYPE_SUBMIT, "Set", "Set"));
    line.addElement(new td().addElement(myForm));
    table.addElement(line);
    //
    line = new tr();
    CLogFile fileHandler = CLogFile.get(true, null, false);
    line.addElement(new th().addElement("Trace File"));
    line.addElement(new td().addElement(new a("adempiereMonitor?Trace=" + fileHandler.getFileName(), "Current")));
    table.addElement(line);
    //
    line = new tr();
    line.addElement(new td().addElement(new a("adempiereMonitor?Trace=ROTATE", "Rotate Trace Log")));
    line.addElement(new td().addElement(new a("adempiereMonitor?Trace=DELETE", "Delete all Trace Logs")));
    table.addElement(line);
    //
    bb.addElement(table);
    //	List Log Files
    p p = new p();
    p.addElement(new b("All Log Files: "));
    //	All in dir
    File logDir = fileHandler.getLogDirectory();
    if (logDir != null && logDir.isDirectory()) {
        File[] logs = logDir.listFiles();
        for (int i = 0; i < logs.length; i++) {
            // Skip if is not a file - teo_sarca [ 1726066 ]
            if (!logs[i].isFile())
                continue;
            if (i != 0)
                p.addElement(" - ");
            String fileName = logs[i].getAbsolutePath();
            a link = new a("adempiereMonitor?Trace=" + fileName, fileName);
            p.addElement(link);
            int size = (int) (logs[i].length() / 1024);
            if (size < 1024)
                p.addElement(" (" + size + "k)");
            else
                p.addElement(" (" + size / 1024 + "M)");
        }
    }
    bb.addElement(p);
    //	Clients and Web Stores
    table = new table();
    table.setBorder(1);
    table.setCellSpacing(2);
    table.setCellPadding(2);
    //	
    line = new tr();
    MClient[] clients = MClient.getAll(ctx);
    line.addElement(new th().addElement("Client #" + clients.length + " - EMail Test:"));
    p = new p();
    for (int i = 0; i < clients.length; i++) {
        MClient client = clients[i];
        if (i > 0)
            p.addElement(" - ");
        p.addElement(new a("adempiereMonitor?EMail=" + client.getAD_Client_ID(), client.getName()));
    }
    if (clients.length == 0)
        p.addElement("&nbsp;");
    line.addElement(new td().addElement(p));
    table.addElement(line);
    //	
    line = new tr();
    MStore[] wstores = MStore.getActive();
    line.addElement(new th().addElement("Active Web Stores #" + wstores.length));
    p = new p();
    for (int i = 0; i < wstores.length; i++) {
        MStore store = wstores[i];
        if (i > 0)
            p.addElement(" - ");
        a a = new a(store.getWebContext(), store.getName());
        a.setTarget("t" + i);
        p.addElement(a);
    }
    if (wstores.length == 0)
        p.addElement("&nbsp;");
    line.addElement(new td().addElement(p));
    table.addElement(line);
    //
    bb.addElement(table);
}
Also used : org.apache.ecs.xhtml.select(org.apache.ecs.xhtml.select) org.apache.ecs.xhtml.hr(org.apache.ecs.xhtml.hr) Properties(java.util.Properties) MClient(org.compiere.model.MClient) MemoryMXBean(java.lang.management.MemoryMXBean) Trx(org.compiere.util.Trx) MSystem(org.compiere.model.MSystem) org.apache.ecs.xhtml.table(org.apache.ecs.xhtml.table) ThreadMXBean(java.lang.management.ThreadMXBean) org.apache.ecs.xhtml.a(org.apache.ecs.xhtml.a) CLogFile(org.compiere.util.CLogFile) org.apache.ecs.xhtml.b(org.apache.ecs.xhtml.b) RuntimeMXBean(java.lang.management.RuntimeMXBean) org.apache.ecs.xhtml.label(org.apache.ecs.xhtml.label) org.apache.ecs.xhtml.td(org.apache.ecs.xhtml.td) CConnection(org.compiere.db.CConnection) org.apache.ecs.xhtml.p(org.apache.ecs.xhtml.p) Timestamp(java.sql.Timestamp) org.apache.ecs.xhtml.input(org.apache.ecs.xhtml.input) AdempiereDatabase(org.compiere.db.AdempiereDatabase) org.apache.ecs.xhtml.th(org.apache.ecs.xhtml.th) org.apache.ecs.xhtml.form(org.apache.ecs.xhtml.form) CMemoryUsage(org.compiere.util.CMemoryUsage) MStore(org.compiere.model.MStore) CLogFile(org.compiere.util.CLogFile) File(java.io.File) org.apache.ecs.xhtml.tr(org.apache.ecs.xhtml.tr) org.apache.ecs.xhtml.option(org.apache.ecs.xhtml.option)

Example 27 with Trx

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

the class Doc method post.

//	getPO
/**
	 *  Post Document.
	 *  <pre>
	 *  - try to lock document (Processed='Y' (AND Processing='N' AND Posted='N'))
	 * 		- if not ok - return false
	 *          - postlogic (for all Accounting Schema)
	 *              - create Fact lines
	 *          - postCommit
	 *              - commits Fact lines and Document & sets Processing = 'N'
	 *              - if error - create Note
	 *  </pre>
	 *  @param force if true ignore that locked
	 *  @param repost if true ignore that already posted
	 *  @return null if posted error otherwise
	 */
public final String post(boolean force, boolean repost) {
    if (m_DocStatus == null)
        //	return "No DocStatus for DocumentNo=" + getDocumentNo();
        ;
    else if (m_DocStatus.equals(DocumentEngine.STATUS_Completed) || m_DocStatus.equals(DocumentEngine.STATUS_Closed) || m_DocStatus.equals(DocumentEngine.STATUS_Voided) || m_DocStatus.equals(DocumentEngine.STATUS_Reversed))
        ;
    else
        return "Invalid DocStatus='" + m_DocStatus + "' for DocumentNo=" + getDocumentNo();
    //
    if (p_po.getAD_Client_ID() != m_ass[0].getAD_Client_ID()) {
        String error = "AD_Client_ID Conflict - Document=" + p_po.getAD_Client_ID() + ", AcctSchema=" + m_ass[0].getAD_Client_ID();
        log.severe(error);
        return error;
    }
    //  Lock Record ----
    //	outside trx if on server
    String trxName = null;
    if (!m_manageLocalTrx)
        // on trx if it's in client
        trxName = getTrxName();
    StringBuffer sql = new StringBuffer("UPDATE ");
    sql.append(get_TableName()).append(" SET Processing='Y' WHERE ").append(get_TableName()).append("_ID=").append(get_ID()).append(" AND Processed='Y' AND IsActive='Y'");
    if (!force)
        sql.append(" AND (Processing='N' OR Processing IS NULL)");
    if (!repost)
        sql.append(" AND Posted='N'");
    if (DB.executeUpdate(sql.toString(), trxName) == 1)
        log.info("Locked: " + get_TableName() + "_ID=" + get_ID());
    else {
        log.log(Level.SEVERE, "Resubmit - Cannot lock " + get_TableName() + "_ID=" + get_ID() + ", Force=" + force + ",RePost=" + repost);
        if (force)
            return "Cannot Lock - ReSubmit";
        return "Cannot Lock - ReSubmit or RePost with Force";
    }
    p_Error = loadDocumentDetails();
    if (p_Error != null)
        return p_Error;
    Trx trx = Trx.get(getTrxName(), true);
    //  Delete existing Accounting
    if (repost) {
        if (//	already posted - don't delete if period closed
        isPosted() && !isPeriodOpen()) {
            log.log(Level.SEVERE, toString() + " - Period Closed for already posed document");
            unlock();
            trx.commit();
            trx.close();
            return "PeriodClosed";
        }
        //	delete it
        deleteAcct();
    } else if (isPosted()) {
        log.log(Level.SEVERE, toString() + " - Document already posted");
        unlock();
        trx.commit();
        trx.close();
        return "AlreadyPosted";
    }
    p_Status = STATUS_NotPosted;
    //  Create Fact per AcctSchema
    m_fact = new ArrayList<Fact>();
    //  for all Accounting Schema
    boolean OK = true;
    getPO().setDoc(this);
    try {
        for (int i = 0; OK && i < m_ass.length; i++) {
            //	if acct schema has "only" org, skip
            boolean skip = false;
            if (m_ass[i].getAD_OrgOnly_ID() != 0) {
                //	Header Level Org
                skip = m_ass[i].isSkipOrg(getAD_Org_ID());
                //	Line Level Org
                if (p_lines != null) {
                    for (int line = 0; skip && line < p_lines.length; line++) {
                        skip = m_ass[i].isSkipOrg(p_lines[line].getAD_Org_ID());
                        if (!skip)
                            break;
                    }
                }
            }
            if (skip)
                continue;
            //	post
            log.info("(" + i + ") " + p_po);
            p_Status = postLogic(i);
            if (!p_Status.equals(STATUS_Posted))
                OK = false;
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        p_Status = STATUS_Error;
        p_Error = e.toString();
        OK = false;
    }
    String validatorMsg = null;
    // Call validator on before post
    if (p_Status.equals(STATUS_Posted)) {
        validatorMsg = ModelValidationEngine.get().fireDocValidate(getPO(), ModelValidator.TIMING_BEFORE_POST);
        if (validatorMsg != null) {
            p_Status = STATUS_Error;
            p_Error = validatorMsg;
            OK = false;
        }
    }
    //  commitFact
    p_Status = postCommit(p_Status);
    if (p_Status.equals(STATUS_Posted)) {
        validatorMsg = ModelValidationEngine.get().fireDocValidate(getPO(), ModelValidator.TIMING_AFTER_POST);
        if (validatorMsg != null) {
            p_Status = STATUS_Error;
            p_Error = validatorMsg;
            OK = false;
        }
    }
    //  Create Note
    if (!p_Status.equals(STATUS_Posted)) {
        //  Insert Note
        String AD_MessageValue = "PostingError-" + p_Status;
        int AD_User_ID = p_po.getUpdatedBy();
        MNote note = new MNote(getCtx(), AD_MessageValue, AD_User_ID, getAD_Client_ID(), getAD_Org_ID(), null);
        note.setRecord(p_po.get_Table_ID(), p_po.get_ID());
        //  Reference
        //	Document
        note.setReference(toString());
        //	Text
        StringBuffer Text = new StringBuffer(Msg.getMsg(Env.getCtx(), AD_MessageValue));
        if (p_Error != null)
            Text.append(" (").append(p_Error).append(")");
        String cn = getClass().getName();
        Text.append(" - ").append(cn.substring(cn.lastIndexOf('.'))).append(" (").append(getDocumentType()).append(" - DocumentNo=").append(getDocumentNo()).append(", DateAcct=").append(getDateAcct().toString().substring(0, 10)).append(", Amount=").append(getAmount()).append(", Sta=").append(p_Status).append(" - PeriodOpen=").append(isPeriodOpen()).append(", Balanced=").append(isBalanced());
        note.setTextMsg(Text.toString());
        note.saveEx();
        p_Error = Text.toString();
    }
    //  dispose facts
    for (int i = 0; i < m_fact.size(); i++) {
        Fact fact = m_fact.get(i);
        if (fact != null)
            fact.dispose();
    }
    p_lines = null;
    if (p_Status.equals(STATUS_Posted))
        return null;
    return p_Error;
}
Also used : Trx(org.compiere.util.Trx) MNote(org.compiere.model.MNote) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException)

Example 28 with Trx

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

the class Doc method postCommit.

//  postLogic
/**
	 *  Post Commit.
	 *  Save Facts & Document
	 *  @param status status
	 *  @return Posting Status
	 */
private final String postCommit(String status) {
    log.info("Sta=" + status + " DT=" + getDocumentType() + " ID=" + p_po.get_ID());
    p_Status = status;
    Trx trx = Trx.get(getTrxName(), true);
    try {
        //  Commit Facts
        if (status.equals(STATUS_Posted)) {
            for (int i = 0; i < m_fact.size(); i++) {
                Fact fact = m_fact.get(i);
                if (fact == null)
                    ;
                else if (fact.save(getTrxName()))
                    ;
                else {
                    log.log(Level.SEVERE, "(fact not saved) ... rolling back");
                    if (m_manageLocalTrx) {
                        trx.rollback();
                        trx.close();
                    }
                    unlock();
                    return STATUS_Error;
                }
            }
        }
        //  Commit Doc
        if (//  contains unlock & document status update
        !save(getTrxName())) {
            log.log(Level.SEVERE, "(doc not saved) ... rolling back");
            if (m_manageLocalTrx) {
                trx.rollback();
                trx.close();
            }
            unlock();
            return STATUS_Error;
        }
        //	Success
        if (m_manageLocalTrx) {
            trx.commit(true);
            trx.close();
            trx = null;
        }
    //  *** Transaction End         ***
    } catch (Exception e) {
        log.log(Level.SEVERE, "... rolling back", e);
        status = STATUS_Error;
        if (m_manageLocalTrx) {
            try {
                if (trx != null)
                    trx.rollback();
            } catch (Exception e2) {
            }
            try {
                if (trx != null)
                    trx.close();
                trx = null;
            } catch (Exception e3) {
            }
        }
        unlock();
    }
    p_Status = status;
    return status;
}
Also used : Trx(org.compiere.util.Trx) SQLException(java.sql.SQLException) DBException(org.adempiere.exceptions.DBException)

Example 29 with Trx

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

the class SequenceCheck method checkClientSequences.

//	checkTableID
/**
	 *	Check/Initialize DocumentNo/Value Sequences for all Clients 	
	 *	@param ctx context
	 *	@param sp server process or null
	 */
private static void checkClientSequences(Properties ctx, SvrProcess sp) {
    String trxName = null;
    if (sp != null)
        trxName = sp.get_TrxName();
    // CarlosRuiz - globalqss - [ 1887608 ] SequenceCheck deadlock 
    // Commit previous work on AD_Sequence
    // previously could update a sequence record needed now that is going to create new ones
    Trx trx = Trx.get(trxName, false);
    trx.commit();
    //	Sequence for DocumentNo/Value
    MClient[] clients = MClient.getAll(ctx);
    for (int i = 0; i < clients.length; i++) {
        MClient client = clients[i];
        if (!client.isActive())
            continue;
        MSequence.checkClientSequences(ctx, client.getAD_Client_ID(), trxName);
    }
//	for all clients
}
Also used : Trx(org.compiere.util.Trx) MClient(org.compiere.model.MClient)

Example 30 with Trx

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

the class GenerateCostDetail method generateCostDetail.

public void generateCostDetail() {
    //Generate Costdetail
    KeyNamePair[] transactions = getTransactionIdsByDateAcct();
    // System.out.println("Transaction to process : " + transactions.length);
    Integer process = 0;
    Integer productId = 0;
    boolean processNewProduct = true;
    Trx dbTransaction = null;
    try {
        //Process transaction
        for (KeyNamePair keyNamePair : transactions) {
            int transactionId = keyNamePair.getKey();
            int transactionProductId = new Integer(keyNamePair.getName());
            //Detected a new product
            if (productId != transactionProductId) {
                //commit last transaction by product
                if (dbTransaction != null) {
                    dbTransaction.commit(true);
                    dbTransaction.close();
                }
                productId = transactionProductId;
                processNewProduct = true;
                //Create new transaction for this product
                dbTransaction = Trx.get(productId.toString(), true);
            }
            MTransaction transaction = new MTransaction(getCtx(), transactionId, dbTransaction.getTrxName());
            // for each Account Schema
            for (MAcctSchema accountSchema : acctSchemas) {
                // for each Cost Type
                for (MCostType costType : costTypes) {
                    // for each Cost Element
                    for (MCostElement costElement : costElements) {
                        if (processNewProduct) {
                            applyCriteria(accountSchema.getC_AcctSchema_ID(), costType.getM_CostType_ID(), costElement.getM_CostElement_ID(), productId, getAccountDate(), getAccountDateTo());
                            deleteCostDetail(dbTransaction.getTrxName());
                            resetCostDimension(costType.getCostingMethod(), dbTransaction.getTrxName());
                            generateCostCollectorNotTransaction(accountSchema, costType, productId, dbTransaction.getTrxName());
                            processNewProduct = false;
                        }
                        generateCostDetail(accountSchema, costType, costElement, transaction);
                    }
                }
            }
            process++;
        //System.out.println("Transaction : " + transactionId + " Transaction Type :"+ transaction.getMovementType() + " record ..." + process);
        }
        if (dbTransaction != null) {
            dbTransaction.commit(true);
            dbTransaction.close();
            dbTransaction = null;
        }
    } catch (Exception e) {
        if (dbTransaction != null) {
            dbTransaction.rollback();
            dbTransaction.close();
            dbTransaction = null;
            e.printStackTrace();
            addLog(e.getMessage());
        }
    } finally {
        if (dbTransaction != null) {
            dbTransaction.commit();
            dbTransaction.close();
            dbTransaction = null;
        }
    }
}
Also used : MCostElement(org.compiere.model.MCostElement) MAcctSchema(org.compiere.model.MAcctSchema) MTransaction(org.compiere.model.MTransaction) KeyNamePair(org.compiere.util.KeyNamePair) Trx(org.compiere.util.Trx) MCostType(org.compiere.model.MCostType) SQLException(java.sql.SQLException)

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