Package org.apache.ojb.broker.accesslayer

Examples of org.apache.ojb.broker.accesslayer.ConnectionManagerIF


     * DB set <em>true</em>, else set <em>false</em> to improve performance.
     */
    public void writeObjects(boolean needsReusePrepare) throws TransactionAbortedException, LockNotGrantedException
    {
        PersistenceBroker broker = transaction.getBroker();
        ConnectionManagerIF connMan = broker.serviceConnectionManager();
        boolean saveBatchMode = connMan.isBatchMode();

        try
        {
            if (log.isDebugEnabled())
            {
                log.debug(
                    "PB is in internal tx: "
                        + broker.isInTransaction()
                        + "  broker was: "
                        + broker);
            }
            // all neccessary db operations are executed within a PersistenceBroker transaction:
            if (!broker.isInTransaction())
            {
                log.error("PB associated with current odmg-tx is not in tx");
                throw new TransactionAbortedException("Underlying PB is not in tx, was begin call done before commit?");
            }

            // Committing has to be done in two phases. First implicitly upgrade to lock on all related
            // objects of objects in this transaction. Then the list of locked objects has to be
            // reordered to solve referential integrity dependencies, then the objects are
            // written into the database.

            // 0. turn on the batch mode
            connMan.setBatchMode(true);

            // 1. mark objects no longer available in collection
            // for delete and add new found objects
            checkAllEnvelopes(broker);

            // 2. mark all dependend objects for cascading insert/delete
            cascadingDependents();

            // 3. upgrade implicit locks.
            //upgradeImplicitLocksAndCheckIfCommitIsNeeded();
            upgradeLockIfNeeded();

            // 4. Reorder objects
            reorder();

            // 5. write objects.
            writeAllEnvelopes(broker, needsReusePrepare);

            // 6. execute batch
            connMan.executeBatch();

            // 7. Update all Envelopes to new CleanState
            cleanupEnvelopes(needsReusePrepare);

            // 6. commit cleanup
            afterWriteCleanup();

        }
        catch (Exception e)
        {
            connMan.clearBatch();
            if(e instanceof OptimisticLockException)
            {
                log.warn("Optimistic lock exception while write objects", e);
                // PB OptimisticLockException should be clearly signalled to the user
                Object sourceObject = ((OptimisticLockException) e).getSourceObject();
                throw new LockNotGrantedException("Optimistic lock exception occur, source object was (" + sourceObject + ")," +
                        " message was (" + e.getMessage() + ")");
            }
            else if(!(e instanceof RuntimeException))
            {
                log.warn("Error while write objects for tx " + transaction, e);
                throw new ODMGRuntimeException("Unexpected error while write objects: " + e.getMessage());
            }
            else
            {
                log.warn("Error while write objects for tx " + transaction, e);
                throw (RuntimeException) e;
            }
        }
        finally
        {
            needsCommit = false;
            connMan.setBatchMode(saveBatchMode);
        }
    }
View Full Code Here


    public void testBatchStatementsOrder()
    {
        if(batchModeDisabled()) return;

        String name = "testBatchStatementsOrder_" + System.currentTimeMillis();
        ConnectionManagerIF conMan = broker.serviceConnectionManager();
        // try to enable batch mode
        conMan.setBatchMode(true);
        broker.beginTransaction();

        ProductGroup pg1 = new ProductGroup();
        pg1.setName("ProductGroup#1_" + name);
        broker.store(pg1);

        conMan.executeBatch();

        Article a1 = new Article();
        a1.setArticleName(name);
        a1.setProductGroup(pg1);
        pg1.add(a1);
        broker.store(pg1);
        broker.store(a1);

        ProductGroup pg2 = new ProductGroup();
        pg2.setName("ProductGroup #2_" + name);
        broker.store(pg2);

        Article a2 = new Article();
        a2.setArticleName(name);
        a2.setProductGroup(pg2);
        pg2.add(a2);
        broker.store(a2);

        ProductGroup pg3 = new ProductGroup();
        pg3.setName("ProductGroup #3_" + name);
        broker.store(pg3);

        Article a3 = new Article();
        a3.setArticleName(name);
        a3.setProductGroup(pg3);
        pg3.add(a3);
        broker.store(a3);

        conMan.executeBatch();

        broker.delete(a1);

        conMan.executeBatch();

        broker.delete(pg1);
        broker.delete(a2);
        broker.delete(pg2);
        broker.delete(a3);
        broker.delete(pg3);
        broker.commitTransaction();


        broker.beginTransaction();
        pg3.getAllArticles().clear();
        broker.store(pg3);
        broker.delete(pg3);
        broker.store(pg3);
        broker.delete(pg3);
        conMan.executeBatch();
        broker.commitTransaction();
    }
View Full Code Here

     */
    public void testBatchStatementsOrder2()
    {
        if(batchModeDisabled()) return;

        ConnectionManagerIF conMan = broker.serviceConnectionManager();
        broker.beginTransaction();

        Zoo zoo1 = new Zoo();
        zoo1.setName("BatchModeTest Zoo #1");
        broker.store(zoo1);

        conMan.executeBatch();

        Mammal m1 = new Mammal();
        m1.setName("BatchModeTest Mammal #1");
        m1.setAge(5);
        m1.setNumLegs(4);
        m1.setZooId(zoo1.getZooId());
        zoo1.getAnimals().add(m1);
        broker.store(m1);

        Zoo zoo2 = new Zoo();
        zoo2.setName("BatchModeTest Zoo #2");
        broker.store(zoo2);

        Mammal m2 = new Mammal();
        m2.setName("BatchModeTest Mammal #2");
        m2.setAge(5);
        m2.setNumLegs(4);
        m2.setZooId(zoo2.getZooId());
        zoo2.getAnimals().add(m2);
        broker.store(m2);

        Zoo zoo3 = new Zoo();
        zoo3.setName("BatchModeTest Zoo #3");
        broker.store(zoo3);

        Mammal m3 = new Mammal();
        m3.setName("BatchModeTest Mammal #3");
        m3.setAge(5);
        m3.setNumLegs(4);
        m3.setZooId(zoo3.getZooId());
        zoo3.getAnimals().add(m3);
        broker.store(m3);

        conMan.executeBatch();

        broker.delete(m1);

        conMan.executeBatch();

        broker.delete(zoo1);
        broker.delete(m2);
        broker.delete(zoo2);
        broker.delete(m3);
        broker.delete(zoo3);

        conMan.executeBatch();
        broker.commitTransaction();
    }
View Full Code Here

     * perform commit on all tx-states
     */
    public void commit() throws TransactionAbortedException, LockNotGrantedException
    {
        PersistenceBroker broker = transaction.getBroker();
        ConnectionManagerIF connMan = broker.serviceConnectionManager();
        boolean saveBatchMode = connMan.isBatchMode();

        try
        {
            if (log.isDebugEnabled())
            {
                log.debug(
                    "PB is in internal tx: "
                        + broker.isInTransaction()
                        + "  broker was: "
                        + broker);
            }
            // all neccessary db operations are executed within a PersistenceBroker transaction:
            if (!broker.isInTransaction())
            {
//                if (log.isDebugEnabled())
//                    log.debug("call beginTransaction() on PB instance");
//                broker.beginTransaction();
                log.error("PB associated with current odmg-tx is not in tx");
                throw new TransactionAbortedException("Underlying PB is not in tx");
            }

            // Committing has to be done in two phases. First implicitly upgrade to lock on all related
            // objects of objects in this transaction. Then the list of locked objects has to be
            // reordered to solve referential integrity dependencies, then the objects are
            // written into the database.

            // 0. turn on the batch mode
            connMan.setBatchMode(true);

            // 1. upgrade implicit locks.
            upgradeImplicitLocksAndCheckIfCommitIsNeeded();

            // 2. Reorder objects
            reorder();

            // 3. commit objects.
            commitAllEnvelopes(broker);

            // 4. execute batch
            connMan.executeBatch();

            // 5.Update all Envelopes to new CleanState
            setCleanState();

        }
        catch (Throwable t)
        {
            // we do that in TransactionImpl#abort()
            //            broker.abortTransaction();
            connMan.clearBatch();
            log.error("Commit on object level failed for tx " + transaction, t);
            if (t instanceof OptimisticLockException)
            {
                // PB OptimisticLockException should be clearly signalled to the user
                Object sourceObject = ((OptimisticLockException) t).getSourceObject();
                throw new LockNotGrantedException("(" + sourceObject + ")" + t.getMessage());
            }
            else
            {
                throw new TransactionAbortedExceptionOJB(t);
            }
        }
        finally
        {
            needsCommit = false;
            connMan.setBatchMode(saveBatchMode);
        }
    }
View Full Code Here

        }

        public void beforeCompletion()
        {
            if (log.isDebugEnabled()) log.debug("beforeCompletion was called, nothing to do");
            ConnectionManagerIF cm = serviceConnectionManager();
            if(cm.isBatchMode()) cm.executeBatch();
            // close connection immediately when in JTA-tx to avoid bad reports from server con-pool
            if(cm.isInLocalTransaction())
            {
                // we should not be in a local tx when performing tx completion
                log.warn("Seems the used PersistenceBroker handle wasn't closed, close the used" +
                        " handle before the transaction completes.");
                // in managed environments this call will be ignored by
                // the wrapped connection
                cm.localCommit();
            }
            cm.releaseConnection();
        }
View Full Code Here

                But to free used resources as soon as possible, we release the used connection
                immediately. The JTA-tx will handle the connection status in a proper way.
                */
                if (log.isDebugEnabled())
                    log.debug("PB close was called, only close the PB handle when in JTA-tx");
                ConnectionManagerIF cm = serviceConnectionManager();
                if(cm.isInLocalTransaction())
                {
                    /*
                    arminw:
                    in managed environment this call will be ignored because, the JTA transaction
                    manager control the connection status. But to make connectionManager happy we
                    have to complete the "local tx" of the connectionManager before release the
                    connection
                    */
                    cm.localCommit();
                }
                cm.releaseConnection();
            }
            return true;
        }
View Full Code Here

            return;
        }

        removeCollectionProxyListeners();

        ConnectionManagerIF connMan = _pb.serviceConnectionManager();
        boolean saveBatchMode = connMan.isBatchMode();
        Swizzling swizzlingStrategy = _tx.getKit().getSwizzlingStrategy();
        LockManager lockManager = LockManager.getInstance();
        Identity[] lockOrder = (Identity[]) _order.toArray(new Identity[_order.size()]);
        ObjectCache cache = _pb.serviceObjectCache();
        boolean isInsertVerified = _tx.getKit().isInsertVerified();
        ArrayList changedCollections = new ArrayList();

        // sort objects in the order of oid.hashCode to avoid deadlocks
        Arrays.sort(lockOrder, new Comparator()
        {
            public int compare(Object o1, Object o2)
            {
                return o1.hashCode() - o2.hashCode();
            }

            public boolean equals(Object obj)
            {
                return false;
            }
        });

        try {
            // mark dirty objects and lock them for write
            // also handle dependent objects and if there were inserted once,
            // repeat this process for their dependants ("cascade create")
            ArrayList newObjects = new ArrayList();
            int countNewObjects;
            do
            {
                newObjects.clear();
                countNewObjects = 0;
                for (int i = 0; i < lockOrder.length; i++)
                {
                    Identity oid = lockOrder[i];
                    ContextEntry entry = (ContextEntry) _objects.get(oid);
                    State state = entry.state;

                    if (entry.userObject == null) // invalidated
                    {
                        continue;
                    }

                    if (entry.handler == null) // materialized
                    {
                        if (!state.isDeleted())
                        {
                            Object[][] origFields = (Object[][]) _checkpointed.get(oid);
                            Object[][] newFields = getFields(entry.userObject, true, !isCommit);

                            if (origFields == null)
                            {
                                entry.needsCacheSwizzle = true;
                                newObjects.addAll(
                                        handleDependentReferences(oid, entry.userObject,
                                        null, newFields[0], newFields[2]));
                                newObjects.addAll(
                                        handleDependentCollections(oid, entry.userObject,
                                        null, newFields[1], newFields[3]));
                            }
                            else
                            {
                                if (isModified(origFields[0], newFields[0]))
                                {
                                    entry.state = state.markDirty();
                                    entry.needsCacheSwizzle = true;
                                    lockManager.ensureLock(oid, _tx, LockType.WRITE_LOCK, _pb);
                                    newObjects.addAll(
                                            handleDependentReferences(oid, entry.userObject,
                                            origFields[0], newFields[0], newFields[2]));
                                }

                                if (isModified(origFields[1], newFields[1]))
                                {
                                    // there are modified collections,
                                    // so we need to lock the object and to swizzle it to cache
                                    entry.needsCacheSwizzle = true;
                                    lockManager.ensureLock(oid, _tx, LockType.WRITE_LOCK, _pb);
                                    newObjects.addAll(
                                            handleDependentCollections(oid, entry.userObject,
                                            origFields[1], newFields[1], newFields[3]));
                                    changedCollections.add(oid);
                                }
                            }
                        }
                    }
                }
                countNewObjects = newObjects.size();
                if (countNewObjects > 0)
                {
                    // new objects are not locked, so we don't need to ensure the order
                    lockOrder = (Identity[]) newObjects.toArray(
                            new Identity[countNewObjects]);
                }
            }
            while (countNewObjects > 0);

            // Swizzle the context objects and the cache objects
            for (Iterator it = _order.iterator(); it.hasNext(); )
            {
                Identity oid = (Identity) it.next();
                ContextEntry entry = (ContextEntry) _objects.get(oid);

                if (entry.needsCacheSwizzle)
                {
                    entry.userObject = swizzlingStrategy.getRealTarget(entry.userObject);
                    entry.cacheObject = swizzlingStrategy.swizzle(
                    // we create the special ObjectCache implememntation
                            // that returns cacheObject, not userObject
                            entry.userObject, entry.cacheObject, _pb, new ObjectCache()
                            {
                                public Object lookup(Identity anOid)
                                {
                                    ContextEntry ent = (ContextEntry) _objects.get(anOid);
                                    return (ent == null ? null : ent.cacheObject);
                                }

                                public void cache(Identity anOid, Object obj)
                                {
                                    // do nothing
                                }

                                public void clear()
                                {
                                    // do nothing
                                }

                                public void remove(Identity anOid)
                                {
                                    // do nothing
                                }
                            });
                }
            }

            // Cascade delete for dependent objects
            int countCascadeDeleted;
            do
            {
                countCascadeDeleted = 0;
                // Use intermediate new ArrayList(_order) because _order
                // may be changed during cascade delete
                for (Iterator it = (new ArrayList(_order)).iterator(); it.hasNext(); )
                {
                    Identity oid = (Identity) it.next();
                    ContextEntry entry = (ContextEntry) _objects.get(oid);

                    if (entry.state.isDeleted())
                    {
                        countCascadeDeleted += doCascadeDelete(oid, entry.userObject);
                    }
                }
            }
            while (countCascadeDeleted > 0);

            // perform database operations
            connMan.setBatchMode(true);
            try
            {
                for (Iterator it = _order.iterator(); it.hasNext(); )
                {
                    Identity oid = (Identity) it.next();
                    ContextEntry entry = (ContextEntry) _objects.get(oid);
                    State state = entry.state;

                    if (!state.needsInsert() && !state.needsUpdate()
                            && !state.needsDelete())
                    {
                        if (changedCollections.contains(oid)) {
                            _pb.store(entry.cacheObject, state);
                        }
                        continue;
                    }

                    if (state.needsInsert())
                    {
                        if (isInsertVerified)
                        {
                            // PB verifies object existence by default
                            _pb.store(entry.cacheObject);
                        }
                        else
                        {
                            // PB migth already created the object by auto-update
                            if (cache.lookup(oid) == null) {
                                _pb.store(entry.cacheObject, state);
                            }
                        }

                    }
                    else if (state.needsUpdate())
                    {
                        _pb.store(entry.cacheObject, state);
                    }
                    else if (state.needsDelete())
                    {
                        _pb.delete(entry.cacheObject);
                    }
                    entry.state = state.commit();
                }
                connMan.executeBatch();
            }
            finally
            {
                connMan.setBatchMode(saveBatchMode);
            }
        } catch (Throwable ex) {
            ex.printStackTrace();
            throw new TransactionAbortedException(ex);
        }
View Full Code Here

                    PersistenceBrokerHandle pbh = (PersistenceBrokerHandle) handleList.get(i);
                    pbh.close();
                }
                handleList.clear();
            }
            ConnectionManagerIF cm = serviceConnectionManager();
            if(cm.isBatchMode()) cm.executeBatch();
            // close connection immediately when in JTA-tx to avoid bad reports from server con-pool
            if(cm.isInLocalTransaction())
            {
                // we should not be in a local tx when performing tx completion
                log.warn("Seems the used PersistenceBroker handle wasn't closed, close the used" +
                        " handle before the transaction completes.");
                // in managed environments this call will be ignored by
                // the wrapped connection
                cm.localCommit();
            }
            cm.releaseConnection();
        }
View Full Code Here

                    a PBStateListener and below we close the connection.
                    */
                    PersistenceBrokerImpl pb = ((PersistenceBrokerImpl) getInnermostDelegate());
                    pb.fireBrokerEvent(pb.BEFORE_CLOSE_EVENT);

                    ConnectionManagerIF cm = serviceConnectionManager();
                    if(cm.isInLocalTransaction())
                    {
                        /*
                        arminw:
                        in managed environment con.commit calls will be ignored because, the JTA
                        transaction manager control the connection status. But to make
                        connectionManager happy we have to complete the "local tx" of the
                        connectionManager before release the connection
                        */
                        cm.localCommit();
                    }
                    cm.releaseConnection();
                }
            }
            return true;
        }
View Full Code Here

            if(log.isDebugEnabled())
            {
                log.debug("Do internal cleanup and close the internal used connection without" +
                        " closing the used broker");
            }
            ConnectionManagerIF cm = broker.serviceConnectionManager();
            if(cm.isInLocalTransaction())
            {
                /*
                arminw:
                in managed environment this call will be ignored because, the JTA transaction
                manager control the connection status. But to make connectionManager happy we
                have to complete the "local tx" of the connectionManager before release the
                connection
                */
                cm.localCommit();
            }
            cm.releaseConnection();
        }
    }
View Full Code Here

TOP

Related Classes of org.apache.ojb.broker.accesslayer.ConnectionManagerIF

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.