Exception in rollback

Hi,
I get the following exception while trying to rollback a unit-of-work in a client session. Since my application is multithreaded I guess that while the first thread was rollbacking the first unit of work, another client session was trying to write something using another unit-of-work.
This exception usually occurs when one thread is trying to read a list while it is being modified by another thread. The list in this case is a TopLink internal so I have no way to synchronize it, any idea?
SEVERE: java.util.ConcurrentModificationException
     at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:448)
     at java.util.AbstractList$Itr.next(AbstractList.java:419)
     at oracle.toplink.internal.queryframework.InterfaceContainerPolicy.next(Unknown Source)
     at oracle.toplink.internal.queryframework.ContainerPolicy.next(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.CollectionMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.mappings.ObjectReferenceMapping.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.descriptors.ObjectBuilder.mergeIntoObject(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChangesOfOriginalIntoWorkingCopy(Unknown Source)
     at oracle.toplink.internal.sessions.MergeManager.mergeChanges(Unknown Source)
     at oracle.toplink.publicinterface.UnitOfWork.revertAndResume(Unknown Source)
     at cellglide.infrastructure.toplink.TopLink.rollback(TopLink.java:273)
     at cellglide.infrastructure.cim.CimView.rollback(CimView.java:748)
     at cellglide.infrastructure.adapters.CimEventHandlerManager.runEventHandlerNoThread(CimEventHandlerManager.java:99)
     at cellglide.infrastructure.adapters.EventHandlerManager$EventHandlerDequeuer.run(EventHandlerManager.java:94)
     at cellglide.infrastructure.util.ThreadPool$WorkerThread.run(ThreadPool.java:282)

I'm a little surprised this happens when you roll back a unit of work, really rolling back a unit of work is more of an abandonment situation where nothing really happens to the cache.
This kind of situation can occur, however, when you commit a unit of work. What happens is that when a unit of work commits, the database is updated and then the cache is updated. Unfortunately if a collection has a new target being added at the same time some other thread is beginning a UOW and registering the same relationship, you can hit this concurrent modification exception.
The million $ questions is, what should happen if you're making a working copy of an object and somewhere during that work another thread has just successfully changed that object... Should you just have got the stale version of the collection? Yuck. Should you restart the copying to get the updated data? But what if that collection is being hammered to the point that every time you almost get a working copy, someone had changed it. Virtual deadlock. And what is the likelyhood that just the collection changed, what about related data. I.e., this is kind of a pre-emptive optimistic lock situation.
It is very much a transaction isolation issue. This whole situation can be prevented by changing TopLink's own transaction isolation level (aka "Cache locking and Isolation"). But, there is a cost, and it's performance. I generally strongly discourage people from changing TopLink uow txn isolation levels as the benefits don't seem to outweigh the costs. I'd rather somehow manage this proactively in the application...
Check out this link for more info. Experiment with the options and see what works for you.
http://download-west.oracle.com/docs/cd/B10464_01/web.904/b10313/cache.htm#1128354
- Don

Similar Messages

  • [EMF Transaction] Exception during rollback

    On a number of occasions we have faced some exception during rollback, if our code encounters an exception while processing the transaction.
    Here is a very typical example:
    org.eclipse.emf.common.util.BasicEList$BasicIndexOutOfBoundsException: index=1, size=1
    at org.eclipse.emf.common.util.BasicEList.remove(BasicEList.java:602)
    at org.eclipse.emf.common.notify.impl.NotifyingListImpl.doRemove(NotifyingListImpl.java:756)
    at org.eclipse.emf.common.notify.impl.NotifyingListImpl.remove(NotifyingListImpl.java:707)
    at org.eclipse.emf.ecore.change.impl.ListChangeImpl.process(ListChangeImpl.java:546)
    at org.eclipse.emf.ecore.change.impl.ListChangeImpl.apply(ListChangeImpl.java:476)
    at org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.apply(FeatureChangeImpl.java:701)
    at org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.process(FeatureChangeImpl.java:611)
    at org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.apply(FeatureChangeImpl.java:518)
    at org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.apply(FeatureChangeImpl.java:493)
    at org.eclipse.emf.ecore.change.impl.ChangeDescriptionImpl.apply(ChangeDescriptionImpl.java:300)
    at org.eclipse.emf.transaction.util.CompositeChangeDescription.apply(CompositeChangeDescription.java:104)
    at org.eclipse.emf.transaction.impl.TransactionImpl.doRollback(TransactionImpl.java:570)
    at org.eclipse.emf.transaction.impl.TransactionImpl.commit(TransactionImpl.java:417)
    at org.eclipse.emf.transaction.impl.TransactionalCommandStackImpl.doExecute(TransactionalCommandStackImpl.java:70)
    at org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:165)
    at org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:219)
    at org.eclipse.emf.emfstore.internal.client.transaction.EMFStoreTransactionalCommandStack.execute(EMFStoreTransactionalCommandStack.java:52)
    This seems to be caused by an attempt to remove an element from a list. Debugging here is showing that the rollback is trying to apply the undo changes produced by the transaction recorder. But the element that it is attempting to remove doesn't exist in the list, and thus the error. I suspect that this is because when the initial exception occurred that this command had not been executed yet. If that is the case, I would expect the rollback to have a way to check for the commands that have completed and to reverse them, but to ignore any commands that have never completed yet. Is it what I might be saying and what is the solution?
    I'm adding below portion of the stacktrace that represents the original exception that triggered the rollback. This might help a bit in understanding the situation.
    Caused by: java.lang.ClassCastException: ....
    at com.castortech.util.emf.VersioningUtils.runInCompositeOperation(VersioningUtils.java:83)
    at org.eclipse.sirius.table.business.internal.dialect.TableDialectServices.refresh(TableDialectServices.java:272)
    at org.eclipse.sirius.business.internal.dialect.DialectManagerImpl.refresh(DialectManagerImpl.java:106)
    at org.eclipse.sirius.business.api.dialect.command.RefreshRepresentationsCommand.doExecute(RefreshRepresentationsCommand.java:85)
    at org.eclipse.emf.transaction.RecordingCommand.execute(RecordingCommand.java:135)
    at org.eclipse.emf.common.command.CompoundCommand.execute(CompoundCommand.java:261)
    at org.eclipse.sirius.business.internal.session.SessionEventBrokerImpl$PreCommitPriorityNotifyListenersCommand.launchCommands(SessionEventBrokerImpl.java:251)
    at org.eclipse.sirius.business.internal.session.SessionEventBrokerImpl$PreCommitPriorityNotifyListenersCommand.doExecute(SessionEventBrokerImpl.java:242)
    at org.eclipse.emf.transaction.RecordingCommand.execute(RecordingCommand.java:135)
    at org.eclipse.emf.transaction.util.TriggerCommand.execute(TriggerCommand.java:113)
    at org.eclipse.emf.transaction.impl.TransactionalCommandStackImpl.executeTriggers(TransactionalCommandStackImpl.java:218)
    at org.eclipse.emf.transaction.impl.TransactionalEditingDomainImpl.precommit(TransactionalEditingDomainImpl.java:712)
    at org.eclipse.emf.transaction.impl.TransactionImpl.commit(TransactionImpl.java:414)
    at org.eclipse.emf.transaction.impl.TransactionalCommandStackImpl.doExecute(TransactionalCommandStackImpl.java:70)
    at org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:165)
    at org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:219)
    at org.eclipse.emf.emfstore.internal.client.transaction.EMFStoreTransactionalCommandStack.execute(EMFStoreTransactionalCommandStack.java:52)
    Thanks
    Alain

    Hi, Alain,
    Indeed, the transaction will have difficulty rolling back if the
    ChangeDescription cannot successfully be applied. However, a
    ChangeDescription records only changes that actually are effected in
    the model. I don't know how it could record changes that haven't yet
    occurred.
    Does your model have custom implementations of some of these list
    features, as UML2 does, that perhaps coordinate changes with other
    features? Could it be that undoing some changes causes side-effects in
    others that then invalidate changes recorded in those?
    Or are there non-ChangeDescription-based commands being undone by the
    transaction that could interfere with ChangeDescriptions?
    There's not really much that a transaction can do to validate the
    applicability of a ChangeDescription ... it seems to me that it's up to
    the model and the commands captured by a transaction to ensure that
    undo will happen correctly. Although, perhaps failed rollback could
    somehow be handled more gracefully? I'm not sure.
    Cheers,
    Christian
    On 2015-08-08 18:12:21 +0000, Alain Picard said:
    > On a number of occasions we have faced some exception during rollback,
    > if our code encounters an exception while processing the transaction.
    > Here is a very typical example:
    >
    >
    > org.eclipse.emf.common.util.BasicEList$BasicIndexOutOfBoundsException:
    > index=1, size=1
    > at org.eclipse.emf.common.util.BasicEList.remove(BasicEList.java:602)
    > at
    > org.eclipse.emf.common.notify.impl.NotifyingListImpl.doRemove(NotifyingListImpl.java:756)
    >
    > at
    > org.eclipse.emf.common.notify.impl.NotifyingListImpl.remove(NotifyingListImpl.java:707)
    >
    > at
    > org.eclipse.emf.ecore.change.impl.ListChangeImpl.process(ListChangeImpl.java:546)
    >
    > at
    > org.eclipse.emf.ecore.change.impl.ListChangeImpl.apply(ListChangeImpl.java:476)
    >
    > at
    > org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.apply(FeatureChangeImpl.java:701)
    >
    > at
    > org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.process(FeatureChangeImpl.java:611)
    >
    > at
    > org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.apply(FeatureChangeImpl.java:518)
    >
    > at
    > org.eclipse.emf.ecore.change.impl.FeatureChangeImpl.apply(FeatureChangeImpl.java:493)
    >
    > at
    > org.eclipse.emf.ecore.change.impl.ChangeDescriptionImpl.apply(ChangeDescriptionImpl.java:300)
    >
    > at
    > org.eclipse.emf.transaction.util.CompositeChangeDescription.apply(CompositeChangeDescription.java:104)
    >
    > at
    > org.eclipse.emf.transaction.impl.TransactionImpl.doRollback(TransactionImpl.java:570)
    >
    > at
    > org.eclipse.emf.transaction.impl.TransactionImpl.commit(TransactionImpl.java:417)
    >
    > at
    > org.eclipse.emf.transaction.impl.TransactionalCommandStackImpl.doExecute(TransactionalCommandStackImpl.java:70)
    >
    > at
    > org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:165)
    >
    > at
    > org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:219)
    >
    > at
    > org.eclipse.emf.emfstore.internal.client.transaction.EMFStoreTransactionalCommandStack.execute(EMFStoreTransactionalCommandStack.java:52)
    >
    >
    >
    > This seems to be caused by an attempt to remove an element from a list.
    > Debugging here is showing that the rollback is trying to apply the undo
    > changes produced by the transaction recorder. But the element that it
    > is attempting to remove doesn't exist in the list, and thus the error.
    > I suspect that this is because when the initial exception occurred that
    > this command had not been executed yet. If that is the case, I would
    > expect the rollback to have a way to check for the commands that have
    > completed and to reverse them, but to ignore any commands that have
    > never completed yet. Is it what I might be saying and what is the
    > solution?
    >
    > I'm adding below portion of the stacktrace that represents the original
    > exception that triggered the rollback. This might help a bit in
    > understanding the situation.
    >
    > Caused by: java.lang.ClassCastException: ....
    > ...
    > at
    > com.castortech.util.emf.VersioningUtils.runInCompositeOperation(VersioningUtils.java:83)
    >
    > at
    > org.eclipse.sirius.table.business.internal.dialect.TableDialectServices.refresh(TableDialectServices.java:272)
    >
    > at
    > org.eclipse.sirius.business.internal.dialect.DialectManagerImpl.refresh(DialectManagerImpl.java:106)
    >
    > at
    > org.eclipse.sirius.business.api.dialect.command.RefreshRepresentationsCommand.doExecute(RefreshRepresentationsCommand.java:85)
    >
    > at
    > org.eclipse.emf.transaction.RecordingCommand.execute(RecordingCommand.java:135)
    >
    > at
    > org.eclipse.emf.common.command.CompoundCommand.execute(CompoundCommand.java:261)
    >
    > at
    > org.eclipse.sirius.business.internal.session.SessionEventBrokerImpl$PreCommitPriorityNotifyListenersCommand.launchCommands(SessionEventBrokerImpl.java:251)
    >
    > at
    > org.eclipse.sirius.business.internal.session.SessionEventBrokerImpl$PreCommitPriorityNotifyListenersCommand.doExecute(SessionEventBrokerImpl.java:242)
    >
    > at
    > org.eclipse.emf.transaction.RecordingCommand.execute(RecordingCommand.java:135)
    >
    > at
    > org.eclipse.emf.transaction.util.TriggerCommand.execute(TriggerCommand.java:113)
    >
    > at
    > org.eclipse.emf.transaction.impl.TransactionalCommandStackImpl.executeTriggers(TransactionalCommandStackImpl.java:218)
    >
    > at
    > org.eclipse.emf.transaction.impl.TransactionalEditingDomainImpl.precommit(TransactionalEditingDomainImpl.java:712)
    >
    > at
    > org.eclipse.emf.transaction.impl.TransactionImpl.commit(TransactionImpl.java:414)
    >
    > at
    > org.eclipse.emf.transaction.impl.TransactionalCommandStackImpl.doExecute(TransactionalCommandStackImpl.java:70)
    >
    > at
    > org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:165)
    >
    > at
    > org.eclipse.emf.transaction.impl.AbstractTransactionalCommandStack.execute(AbstractTransactionalCommandStack.java:219)
    >
    > at
    > org.eclipse.emf.emfstore.internal.client.transaction.EMFStoreTransactionalCommandStack.execute(EMFStoreTransactionalCommandStack.java:52)
    >
    >
    >
    > Thanks
    > Alain

  • GetWarnings on Connection throws exception if rollback = true

    I am trying to use hibernate within WLS 7SP4 and I get an exception everytime it
    tries to close an exception.
    inside
    weblogic.jdbc.jts.Connection.getWarnings()
    the first thing it does is call the method
    checkIfRoleBack(). This essentially throws an exception if the Transaction is
    currently in a roleback state
    If you look at the java API for get warnings it says it should only throw an exception
    if a database access error occurs. However a transaction being in a roleback state
    is not exactly a database error it is a perfectly valid state.
    THe problem I have is that when Hibernate tries to close a connection it also
    tries to log all the warnings on the connection. This means that closing a rolledback
    connection always throws an exception.
    Is this a bug in the weblogic implementation of Connection or is this expected
    beahviour.

    In that case we will be fine and the change is not that important
    Thanks
    Carl
    Joe Weinstein <[email protected]> wrote:
    >
    >
    Carl wrote:
    If the tx times out will I still be able to use sessionContext.getRollBackOnly()
    or will this only work if manually set.That should certainly still work. It is only JDBC that is prevented after
    the
    tx is done.
    Joe
    Thanks
    Carl
    Joe Weinstein <[email protected]> wrote:
    Carl Marais wrote:
    Thanks Joe for the response.
    My current solution is just to log and consume the exceptions if doinga close
    when the SessionContext of the EJB is set to Rollback. Judging fromwhat you are
    saying this should not have any impact on overall processing and theoriginal
    business exception can still flow through to the clientCorrect. The exception from getWarnings() has no effect on any processing
    and
    can be ignored if it's meaning is understood. We will currently allow
    no jdbc
    to be done, as soon as the tx is done for any reason. This could occur
    at any
    time, if for instance the tx reached it's timeout limit in-flight.
    Let me know how important the change I suggested is, or whether
    you're
    OK
    as-is for now with the above explained.
    thanks,
    Joe
    Joe Weinstein <[email protected]> wrote:
    Carl Marais wrote:
    I am trying to use hibernate within WLS 7SP4 and I get an exceptioneverytime it
    tries to close an exception.
    inside
    weblogic.jdbc.jts.Connection.getWarnings()
    the first thing it does is call the method
    checkIfRoleBack(). This essentially throws an exception if the Transactionis
    currently in a roleback state
    If you look at the java API for get warnings it says it should onlythrow an exception
    if a database access error occurs. However a transaction being in
    a
    roleback state
    is not exactly a database error it is a perfectly valid state.
    THe problem I have is that when Hibernate tries to close a connectionit also
    tries to log all the warnings on the connection. This means that
    closing
    a rolledback
    connection always throws an exception.
    Is this a bug in the weblogic implementation of Connection or is
    this
    expected
    beahviour.Hi. I can see it's being unexpected, but we must do all we can toensure
    that
    application code does no JDBC (which for the most part is intendedto
    contribute
    to the transaction) when the transaction is not in an accepting state.
    For maximum
    concurrency we actually reclaim the underlying pooled connection
    as
    soon
    as the
    fate of the transaction is sealed. This means that the warnings itmay
    have accrued
    are no longer accessible to the client. This is because we turn offthe
    wrapper
    object that the client has (generating that exception), and for pool
    cleanliness
    we always clear any warnings the connection may have collected during

  • Forall exception rollback

    Hi Guys,
    I have a forall statement that I want to continue processing if it hits an exception, and rollback anything it fails on. I have limits set so I am only lifting 300 records at a time, but if only one record fails in the forall, then i want the other 299 to process and commit, and only rollback that one failure..is it possible? This is using oracle 10g.
    Example snippet below, the "dots" are just were I have removed unneeded code for this example. I want to know if I can add a rollback in the EXCEPTION that will rollback the forall failure for the one saved exception, and the "commit" will commit the remaining 299 that were success?
    BEGIN
    LOOP
    FETCH cursor1
    BULK COLLECT INTO table1 LIMIT 300;
    IF table1.COUNT > 0
    THEN
    BEGIN
    FORALL i IN 1 .. table1.COUNT SAVE EXCEPTIONS
    END IF;
    EXIT WHENtable1.COUNT = 0;
    table1.DELETE;
    END LOOP;
    CLOSE cursor1;
    COMMIT;
    EXCEPTION
    WHEN OTHERS
    THEN
    ROLLBACK;
    END;
    Edited by: fixxxer on 13-Oct-2011 01:36

    You can not do INSERT and DELETE using same FORALL statelemt. For that you have to create seperate copy of Collection.
    If you want to ROLLBACK everything thnen omit the SAVE EXCEPTION statement in FORALL.
    You can gothrough below FORALL restriction...
    Restrictions
    The following restrictions apply to the FORALL statement:
    •You cannot loop through the elements of an associative array that has a string type for the key.
    •Within a FORALL loop, you cannot refer to the same collection in both the SET clause and the WHERE clause of an UPDATE statement. You might need to make a second copy of the collection and refer to the new name in the WHERE clause.
    •You can use the FORALL statement only in server-side programs, not in client-side programs.
    •The INSERT, UPDATE, or DELETE statement must reference at least one collection. For example, a FORALL statement that inserts a set of constant values in a loop raises an exception.
    •When you specify an explicit range, all collection elements in that range must exist. If an element is missing or was deleted, you get an error.
    •When you use the INDICES OF or VALUES OF clauses, all the collections referenced in the DML statement must have subscripts matching the values of the index variable. Make sure that any DELETE, EXTEND, and so on operations are applied to all the collections so that they have the same set of subscripts. If any of the collections is missing a referenced element, you get an error. If you use the SAVE EXCEPTIONS clause, this error is treated like any other error and does not stop the FORALL statement.
    •You cannot refer to individual record fields within DML statements called by a FORALL statement. Instead, you can specify the entire record with the SET ROW clause in an UPDATE statement, or the VALUES clause in an INSERT statement.
    •Collection subscripts must be just the index variable rather than an expression, such as i rather than i+1.
    •The cursor attribute %BULK_ROWCOUNT cannot be assigned to other collections, or be passed as a parameter to subprograms.

  • Transaction rollback in stateless session EJB 3.0

    Hello everyone !
    I have a stateless session EJB as per 3.0 spec.
    /*Remote Interface*/
    package com.nseit.ncfm2.data.ejb;
    import java.sql.SQLException;
    import java.util.Collection;
    import javax.ejb.Remote;
    import javax.ejb.TransactionAttribute;
    import javax.ejb.TransactionAttributeType;
    import javax.naming.NamingException;
    import com.nseit.ncfm2.security.Audit;
    @Remote
    public interface ProductionDataChangesRequestsRemote {
         @TransactionAttribute(TransactionAttributeType.REQUIRED)
         public boolean shiftCandidateDetails(String sourceNcfmId,
                   String destinationNcfmId, Collection<String> specialCasesList, String shiftingRemarks, String user, Audit updtAudit) throws NamingException, SQLException;
    /*Bean Class*/
    package com.nseit.ncfm2.data.ejb;
    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.ejb.TransactionAttribute;
    import javax.ejb.TransactionAttributeType;
    import javax.ejb.TransactionManagement;
    import javax.ejb.TransactionManagementType;
    import javax.naming.NamingException;
    import com.nseit.ncfm2.security.Audit;
    import com.nseit.ncfm2.util.server.lookup.LookUpServerResources;
    import java.sql.*;
    import java.util.*;
    * Session Bean implementation class ProductionDataChangesRequestsBean
    @Stateless(name = "ProductionDataChangesRequestsBean", mappedName = "ProductionDataChangesRequestsEJB")
    @Remote(ProductionDataChangesRequestsRemote.class)
    @TransactionManagement(TransactionManagementType.CONTAINER)
    public class ProductionDataChangesRequestsBean implements
              ProductionDataChangesRequestsRemote {
         * Default constructor.
         public ProductionDataChangesRequestsBean() {
              // TODO Auto-generated constructor stub
         @Override
         @TransactionAttribute(TransactionAttributeType.REQUIRED)
         public boolean shiftCandidateDetails(String sourceNcfmId,
                   String destinationNcfmId, Collection<String> specialCasesList,
                   String shiftingRemarks, String user, Audit updtAudit)
                   throws NamingException, SQLException {
              // TODO Auto-generated method stub
              Connection conn = null;
              PreparedStatement pstmt = null;
              int updtCnt = 0;
              boolean areDetailsShifted = false;
              try {
                   /* Start: update table-1 */
                   updtCnt = pstmt.executeUpdate();
                   /* End: update table-1 */
                   /* Start: update table-2 */
                   updtCnt = pstmt.executeUpdate();
                   /* End: update table-2 */
                   areDetailsShifted = true;
              } /*catch (SQLException e) {
                   // TODO Auto-generated catch block
                   System.out
                             .println("SQLException in ProductionDataChangesRequestsBean.shiftCandidateDetails(...) "
                                       + e.getMessage());
                   // e.printStackTrace();
                   context.setRollbackOnly();
              } */finally {
                   LookUpServerResources.closeStatement(pstmt);
                   LookUpServerResources.closeConnection(conn);
              return areDetailsShifted;
    Currently,if the 1st table update succeeds and the 2nd table update gives an exception,a rollback is not taking place i.e records in 1st table are updated.
    I want the transaction to be rolled back in case an SQLException occurs(or for that matter,any runtime exception occurs).
    I tried two approaches :
    i: Use of context.setRollbackOnly() in catch block for SQLException
    ii:Throwing the SQLException
    In both the cases, the transaction didn't roll back.
    How can I achieve this :
    i: Without the usage of @ApplicationException annotation(as I do not have any application exceptions)
    ii: Without catching the SQLException and then calling context.setRollbackOnly()
    Or what is the standard way?
    Thanks !

    Where is your connection object coming from?

  • How to handle multiple save exceptions (Bulk Collect)

    Hi
    How to handle Multiple Save exceptions? Is it possible to rollback to first deletion(of child table) took place in the procedure.
    There are 3 tables
    txn_header_interface(Grand Parent)
    orders(parent)
    order_items (Child)
    One transaction can have one or multiple orders in it.
    and one orders can have one or multiple order_items in it.
    We need to delete the data from child table first then its parent and then from the grand parent table.if some error occurs anywhere I need to rollback to child record deletion. Since there is flag in child table which tells us when to delete data from database.
    Is it possible to give name to Save exceptions?
    e.g.
    FORALL i IN ABC.FIRST..ABC.LAST SAVE EXCEPTIONS A
    FORALL i IN abc.FIRST..ABC.LAST SAVE EXCEPTIONS B
    if some error occurs then
    ROLLBACK A; OR ROLLBACK B;
    Please find the procedure attached
    How to handle the errors with Save exception and rollback upto child table deletion.
    CREATE OR REPLACE
    PROCEDURE DELETE_CONFIRMED_DATA IS
    TYPE TXN_HDR_INFC_ID IS TABLE OF TXN_HEADER_INTERFACE.ID%TYPE;
    TXN_HDR_INFC_ID_ARRAY TXN_HDR_INFC_ID;
    ERROR_COUNT NUMBER;
    BULK_ERRORS EXCEPTION;
    PRAGMA exception_init(bulk_errors, -24381);
    BEGIN
    SELECT THI.ID BULK COLLECT
    INTO TXN_HDR_INFC_ID_ARRAY
    FROM TXN_HEADER_INTERFACE THI,ORDERS OS,ORDER_ITEMS OI
    WHERE THI.ID = OS.TXN_HDR_INFC_ID
    AND OS.ID = OI.ORDERS_ID
    AND OI.POSTING_ITEM_ID = VPI.ID
    OI.DW_STATUS_FLAG =4 --data is moved to Datawarehouse
    MINUS
    (SELECT THI.ID FROM TXN_HEADER_INTERFACE THI,ORDERS OS,ORDER_ITEMS OI
    WHERE THI.ID = OS.TXN_HDR_INFC_ID
    AND OS.ID = OI.ORDERS_ID
    OI.DW_STATUS_FLAG !=4);
    IF SQL%NOTFOUND
    THEN
    EXIT;
    END IF;
    FORALL i IN TXN_HDR_INFC_ID_ARRAY.FIRST..TXN_HDR_INFC_ID_ARRAY.LAST SAVE
    EXCEPTIONS
    DELETE FROM ORDER_ITEMS OI
    WHERE OI.ID IN (SELECT OI.ID FROM ORDER_ITEMS OI,ORDERS
    OS,TXN_HEADER_INTERFACE THI
    WHERE OS.ID = OI.ORDERS_ID
    AND OS.TXN_HDR_INFC_ID = THI.ID
    AND THI.ID = TXN_HDR_INFC_ID_ARRAY(i));
    FORALL i IN TXN_HDR_INFC_ID_ARRAY.FIRST..TXN_HDR_INFC_ID_ARRAY.LAST SAVE
    EXCEPTIONS
    DELETE FROM ORDERS OS
    WHERE OS.ID IN (SELECT OS.ID FROM ORDERS OS,TXN_HEADER_INTERFACE THI
    WHERE OS.TXN_HDR_INFC_ID = THI.ID
    AND THI.ID = TXN_HDR_INFC_ID_ARRAY(i));
    FORALL i IN TXN_HDR_INFC_ID_ARRAY.FIRST..TXN_HDR_INFC_ID_ARRAY.LAST SAVE
    EXCEPTIONS
    DELETE FROM TXN_HEADER_INTERFACE THI
    WHERE THI.ID = TXN_HDR_INFC_ID_ARRAY(i);
    COMMIT;
    DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE, 'DD-MON-YY HH:MIPM')||':
    DELETE_CONFIRMED_DATA: INFO:DELETION SUCCESSFUL');
    EXCEPTION
    WHEN OTHERS THEN
    ERROR_COUNT := SQL%BULK_EXCEPTIONS.COUNT;
    DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE, 'DD-MON-YY HH:MIPM')||':
    DELETE_CONFIRMED_DATA: ERROR:Number of errors is ' ||ERROR_COUNT);
    FOR indx IN 1..ERROR_COUNT LOOP
    DBMS_OUTPUT.PUT_LINE('Error ' || indx || 'occurred during
    '||'iteration'||SQL%BULK_EXCEPTIONS(indx).ERROR_INDEX);
    DBMS_OUTPUT.PUT_LINE('Error is '
    ||SQLERRM(-SQL%BULK_EXCEPTIONS(indx).ERROR_CODE));
    END LOOP;
    END DELETE_CONFIRMED_DATA;
    Any suggestion would be of great help.
    Thanks in advance
    Anu

    If you have one or two places in your code that need multiple exceptions, just do it with multiple catch statements. Unless you are trying to write the most compact Programming 101 homework program, inventing tricks to remove two lines of code is not good use of your time.
    If you have multiple catches all over your code it could be a code smell. You may have too much stuff happening inside one try statement. It becomes hard to know what method call throws one of those exceptions, and you end up handling an exception from some else piece of code than what you intended. E.g. you mention NumberFormatException -- only process one user input inside that try/catch so it is easy to see what error message is given if that particular input is gunk. The next step of processing goes inside its own try/catch.
    In my case, the ArrayIndexOutOfBoundsException and
    NumberFormatException should be handled by the same way.Why?
    I don't think I have ever seen an ArrayIndexOutOfBoundsException that didn't indicate a bug in the code. Instead of an AIOOBE perhaps there should be an if statement somewhere that prevents it, or the algorithm logic should prevent it automatically.

  • Weblogic 7 SP5 SQL Exceptions follow a JTA transaction timeout

    I have a problem in Weblogic 7 SP5 that was not happening in SP2. I'm using the
    Weblogic jDriver (weblogic.jdbc.mssqlserver4.Driver)
    I have a transaction that times out due to JTA transaction timeout, and then gets
    marked for rollback. For several minutes after the timeout, I get many SQL Exceptions
    with bogus messages like "invalid column name" when the column name is, in fact,
    correct.
    Then the weblogic log file shows "Exception during rollback of transaction" (javax.transaction.SystemException:
    Heuristic hazard). Next, the connection is tested on reserve, this test fails,
    and the connection is refreshed. As soon as the connection is refreshed, I stop
    getting SQL exceptions and everything starts working correctly again.
    It seems like the transaction timeout is making the connection go bad, and somehow
    other requests are using this bad connection before the transaction finishes rolling
    back. What could the problem be? Some excerpts from my app log and weblogic log
    are below.
    com.workpoint.server.ejb.WorkPointEJBException: The transaction is no longer active
    - status: 'Marked rollback. [Reason=weblogic.transaction.internal.TimedOutException:
    Transaction timed out after 901 seconds
    Name=[EJB com.storeperform.taskmgr.ejb.procrelease.ProcReleaseBean.distributeToOrgUnit(com.storeperform.taskmgr.values.DistributionUnit)],Xid=17109:68c10765ba68aaaa(12114044),Status=Active,numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds
    since begin=901,seconds left=60,activeThread=Thread[WorkQueueThread[q=1, qName=ProcReleaseTaskWorkers,
    id=6],5,WorkQueueGroup[id=1, name=ProcReleaseTaskWorkers]],ServerResourceInfo[weblogic.jdbc.jts.Connection]=(state=ended,assigned=none,xar=weblogic.jdbc.jts.Connection@18cd616,re-Registered
    = false),SCInfo[DomainManager+edwards-s1]=(state=active),properties=({weblogic.transaction.name=[EJB
    com.storeperform.taskmgr.ejb.procrelease.ProcReleaseBean.distributeToOrgUnit(com.storeperform.taskmgr.values.DistributionUnit)],
    weblogic.jdbc=t3://10.10.3.17:7001}),OwnerTransactionManager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=edwards-s1+10.10.3.17:7001+DomainManager+t3+,
    Resources={})],CoordinatorURL=edwards-s1+10.10.3.17:7001+DomainManager+t3+)]'.
    No further JDBC access is allowed within this transaction.SQL Command = INSERT
    INTO WP_PROCI_NODE_HIST (NODE_HIST_ID, NODE_HIST_DB, PROCI_ID, PROCI_DB, PROCI_NODE_ID,
    PROCI_NODE_DB, NODE_ITERATION, NODE_STATE_ID, ROW_VERSION, LU_ID, LU_DATE) VALUES
    weblogic.jdbc.mssqlserver4.TdsException: Invalid column name 'user_fname'.
    [from weblogic log]
    ####<Jun 17, 2004 8:14:16 AM MDT> <Error> <EJB> <EDWARDS> <edwards-s1> <WorkQueueThread[q=1,
    qName=ProcReleaseTaskWorkers, id=7]> <kernel identity> <> <010025> <Exception
    during rollback of transaction Name=[EJB com.storeperform.taskmgr.ejb.procrelease.ProcReleaseBean.distributeToOrgUnit(com.storeperform.taskmgr.values.DistributionUnit)],Xid=17439:68c10765ba68aaaa(31878774),Status=Rolled
    back. [Reason=weblogic.transaction.internal.AppSetRollbackOnlyException],HeuristicErrorCode=XA_HEURHAZ,numRepliesOwedMe=0,numRepliesOwedOthers=0,seconds
    since begin=3,seconds left=57,ServerResourceInfo[weblogic.jdbc.jts.Connection]=(state=rolledback,assigned=edwards-s1,xar=weblogic.jdbc.jts.Connection@15e1b7e,re-Registered
    = false),SCInfo[DomainManager+edwards-s1]=(state=rolledback),properties=({weblogic.transaction.name=[EJB
    com.storeperform.taskmgr.ejb.procrelease.ProcReleaseBean.distributeToOrgUnit(com.storeperform.taskmgr.values.DistributionUnit)],
    weblogic.jdbc=t3://10.10.3.17:7001}),OwnerTransactionManager=ServerTM[ServerCoordinatorDescriptor=(CoordinatorURL=edwards-s1+10.10.3.17:7001+DomainManager+t3+,
    Resources={})],CoordinatorURL=edwards-s1+10.10.3.17:7001+DomainManager+t3+): javax.transaction.SystemException:
    Heuristic hazard: (weblogic.jdbc.jts.Connection, HeuristicHazard, (javax.transaction.xa.XAException:
    I/O exception while talking to the server, java.io.EOFException))
    ####<Jun 17, 2004 8:14:17 AM MDT> <Warning> <JDBC> <EDWARDS> <edwards-s1> <ExecuteThread:
    '8' for queue: 'default'> <kernel identity> <> <001094> <A connection from pool
    "sp_connection_pool" was tested during reserve with the SQL "select 1" and failed:
    weblogic.jdbc.mssqlserver4.TdsException: I/O exception while talking to the server,
    java.io.EOFException
    ...[stack trace omitted]...
    This connection will now be refreshed.>

    Brad Swanson wrote:
    According to BEA's documentation, the jDriver is deprecated (no longer supported)
    in WLS 7 SP5. Not sure when they stopped supporting it, but sometime after SP2,
    apparently. Our solution, unfortunately, was to stay with SP2. Using the newer,
    supported JDBC driver would presumably fix the problem, but we didn't have time
    to do a full regression test with a different driver.Hi, no. The jDriver is deprecated, not unsupported. For WLS releases that contain
    the jDriver it will be supported for as long as we support the WLS release!
    Deprecation just means that we may choose to not supply that driver in any future
    release, and will not support it in that or any subsequent release.
    Practically, much depends on which jDriver you're using. In decreasing order
    of practical support we have: The weblogic.jdbc.oci.Driver to Oracle: We do actively
    continue to fix bugs in it. The weblogic.jdbc.mssqlserver4.Driver: Very unlikely that
    we will fix any new problem with it. The weblogic.jdbc.ifmx.Driver: Even less
    likely that we will do anything with it...
    I hope that makes it better for you.
    Joe

  • Cmp 2.0 how to rollback all related transactions

    Hi,
    As to rollback in cmp 2.0, I'm wondering:
    1. how to make a rollback (is call rollbackOnly the only way)?
    2. how to define within same transactions when an exception caught, rollback all other trans?
    3. modify in descriptor or in code, how? what's diff
    Thanks
    John

    Hi,
    As to rollback in cmp 2.0, I'm wondering:
    1. how to make a rollback (is call rollbackOnly the
    only way)?Yes. Entity beans can only have Container-managed transactions,
    so the only way to tell the container to mark the tx as rollback only
    is to call EntityContext.setRollbackOnly().
    >
    2. how to define within same transactions when an
    exception caught, rollback all other trans?There is no such behavior in EJB or J2EE. There is
    no special relationship/association like this
    between J2EE transactions. E.g., there are no
    nested transactions in J2EE. All transactions are
    independent and peers of one another.
    >
    3. modify in descriptor or in code, how? what's diff
    Thanks
    John

  • Commit/Rollback in EclipseLink

    Hi,
    Most of my changes are wrapped in a pair of
    EntityManagerHelper.beginTransaction();
    save(entity);//or delete(), update(), ...
    EntityManagerHelper.commit();
    How do I handle exceptions and rollbacks?
    In the above example, do I catch all exceptions (ie, Throwable) and do a rollback (EntityManagerHelper.rollback())?
    Without any rollbacks, EclipseLink complains about inconsistant transactions (already in a transaction), when failures occur.
    Regards,
    Ramin

    Hello,
    EclipseLink unit tests generally wrap test code within a try/catch block an call:
    if (getEntityManager().getTransaction().isActive()){
    getEntityManager().getTransaction().rollback();
    at the end to rollback the transaction if it hasn't already. The if statement will prevent rolling back the transaction if it is not active.
    Most JPA exceptions should mark the transaction for rollback already though, as per the spec:
    "All instances of PersistenceException except for instances of NoResultException, NonUniqueResultException, LockTimeoutException, and
    QueryTimeoutException will cause the current transaction, if one is active, to be marked for rollback."
    Best Regards,
    Chris

  • Rollbacks and Commits

    I have a question. I'm writing a group of inserts for a database. In the event that one of those inserts fail due to a constraint issue, I want the whole group of inserts to roll back. How would I do that?
    Example:
    Begin
    Insert into table1
    values ('1', 'M', '12321');
    Insert into table2
    values ('2','12345','lmnop','data','data1','data3')
    End;
    commit;
    Well table 2 requires a constraint on the 6th column to be either data1 or data2, but I've got data3.
    How can I write this so that it will rollback on both inserts, because at least one of them failed?
    Thank you,
    MG

    If you are running your code in a PL/SQL block you can include an exception handler to catch the error and then rollback.
    Sample:
    BEGIN
    --insert statement
    --insert statement 2
    EXCEPTION
        WHEN &lt;EXCEPTION HERE&gt; THEN
            ROLLBACK;
            RAISE;
    END;
    /The &lt;EXCEPTION HERE&gt; can be a named exception (like shown here: [http://www.techonthenet.com/oracle/exceptions/named_system.php]), or a custom defined exception.
    However, if this code is part of a larger structure than you can let the constraint error propogate out of this block to the calling program and handle the exception and rollback there.
    Hope this helps!

  • JMS - rollback but no redelivery

    All,
              I have a simple pub/sub on weblogic 8.1 that has a independent thread doing sychronous consumption. The session is transacted. Everything is smooth except when I attempt to rollback a transaction. In such a case, the message is not redelivered when I re-invoke the receive method 1 minute later. It is discarded.
              Looking at the pending messages on the queue, the message is always discarded 40 seconds after transaction is rolled back. If I shorten my wait and call the receive method 20 seconds after the rollback, the message is discarded after 20 seconds on the receive call. I was expecting to pull the message I had previously pulled.
              Message has infinite lifespan, redelivery limit is infinite. I also created a template and hardcoded the redelivery limit for the jms server and topic with no success.
              Any pointers or leads would be appreciated.
              thanks - Dan

    Tom,
              I pasted relevant pieces of config.xml and the listener code below, I hope it's intelligible. We're using the default ConnectionFactory.
              We're using topics and TopicSubscriber for consumption. The flow here is consume a message through receive(), attempt to deliver this message to our client, rollback in case of failure, sleep 60 seconds, then attempt redelivery. When receive is invoked the second time, the message is gone. TopicSession code and the line that does invokes the rollback are surrounded by -------------.
              - Dan
              ------------portions of config.xml---------------
              (the first JmsServer entry was not created by me, second was)
              <JMSServer Name="WSStoreForwardInternalJMSServerwlsD01S001"
              Store="FileStore" Targets="wlsD01S001">
              <JMSQueue CreationTime="1085198870801"
              JNDIName="jms.internal.queue.WSStoreForwardQueue"
              JNDINameReplicated="false" Name="WSInternaljms.internal.queue.WSStoreForwardQueuewlsD01S001"/>
              <JMSQueue CreationTime="1085198871294"
              JNDIName="jms.internal.queue.WSDupsEliminationHistoryQueue"
              JNDINameReplicated="false" Name="WSInternaljms.internal.queue.WSDupsEliminationHistoryQueuewlsD01S001"/>
              </JMSServer>
              <JMSServer Name="Gov JMS Server WLSD04S001"
              Store="Gov JMS File Store" Targets="wlsD01S001" TemporaryTemplate="MyJMS Template">
              <JMSTopic CreationTime="1135118604257" JNDIName="GovJMSTopic"
              Name="Gov JMS Topic" Template="MyJMS Template"/>
              </JMSServer>
              <JMSFileStore Directory="govJmsFileStore" Name="Gov JMS File Store"/>
              <JMSTemplate ExpirationPolicy="Discard" Name="MyJMS Template" RedeliveryDelayOverride="0" RedeliveryLimit="250"/>
              -----------------portions of listener code---------------
              public class RubyMessageListener extends Thread
                   private TopicConnection topicConnection = null;
                   private TopicSession topicSession = null;
                   private TopicSubscriber topicSubscriber = null;
                   Context jndiContext = null;
                   private RubyMessageListener() {;}
                   public RubyMessageListener(String url, AgmemsFilter aFilter, ClientManager cmParam)
                             throws NamingException, JMSException, ConfigurationException
                             Create a JNDI API InitialContext object if none exists
                             yet.
                             jndiContext = new InitialContext();
                                  We're taking care of the connection establishment at object
                                  startup time so that if we throw exception, we can throw
                                  exception back up to subscribe caller who can report NG to
                                  client
                                  Look up connection factory and queue. If either does
                                  not exist, exit.
                             TopicConnectionFactory topicConnectionFactory = null;
                             Topic topic = null;
                             TextMessage message = null;     
                             topicConnectionFactory = (TopicConnectionFactory) PortableRemoteObject.narrow(jndiContext.lookup("weblogic.jms.ConnectionFactory"), TopicConnectionFactory.class);
                             topic = (Topic) PortableRemoteObject.narrow(jndiContext.lookup("GovJMSTopic"), Topic.class);
                             Create connection.
                             Create session from connection; true means session is
                             transacted.
                             Create receiver, then start message delivery.
                             Close connection.
                        topicConnection = topicConnectionFactory.createTopicConnection();
                        topicSession = topicConnection.createTopicSession(true, Session.AUTO_ACKNOWLEDGE);
                        topicSubscriber = topicSession.createSubscriber(topic);
                        topicConnection.start();
                        myLogger.info("RubyMessageListener(): queue connection has been started, now listening on events");
                   public void confirmAndFallout(TopicSession ts, String sleepTime, boolean commitFlag)
                        try
                             if (commitFlag)
                                  ts.commit();
                                  myLogger.info("confirmAndFallout(): transaction is committed.");
                             else
                                  ts.rollback();
                                  myLogger.info("confirmAndFallout(): transaction successfully rolled back, must wait the sleepTime, " + sleepTime + " ms, before pulling message off of queue.");
                                  try
                                       Thread.sleep(Integer.parseInt(sleepTime));
                                  catch (Exception e)
                                       myLogger.error("confirmAndFallout(): After rollback, thread sleep failed, moving on without sleep.");
                             myLogger.info("confirmAndFallout(): sleep has been completed, return to event listening.");
                             return;
                        catch (JMSException je)
                             try
                                  myLogger.error("confirmAndFallout(): Unable to confirm delivery transaction, sleep, then try once more before bailing.");
                                  Thread.sleep(Integer.parseInt(sleepTime));
                                  if (commitFlag)
                                       ts.commit();
                                       myLogger.info("confirmAndFallout(): transaction is committed.");
                                  else
                                       ts.rollback();
                                       myLogger.info("confirmAndFallout(): transaction successfully rolled back.");
                             catch (Exception e)
                                  myLogger.error("confirmAndFallout(): The second attempt at jms confirmation has failed, return.");
                                  return;
                   public void run()
                        try
                             myLogger.info("run(): Client has asked us to begin pulling events for url: " + listenerUrl);
                             while (!haltFlag)
                                  myLogger.info("run(): BACK up at top of receive loop");
                                  StringBuffer errstr = new StringBuffer();
                                  //receive will initiate our jms transaction,
                                  //commit or rollback will end the transaction
                                  //receive is blocking, wait 55 minutes before committing
                                  //transaction and looping again. We do this to avoid
                                  //default 60 minute transaction timeout
                                  Message m = topicSubscriber.receive(3300000);
                                  if (m != null)
                                       if (m instanceof TextMessage)
                                            TextMessage message = (TextMessage) m;
                                            String messageText = "";     
                                            String eventType = "";
                                            Document doc;
                                            Node rootNode=null;
                                            try
                                                 messageText = message.getText();
                                                 myLogger.info("run(): the following message has been pulled from the queue: " + messageText);
                                                 eventType = "";
                                                 doc = rubyxml.stringToXML(messageText);
                                                 rootNode = doc.getFirstChild();
                                            catch (Exception e)
                                                 myLogger.error("run(): unable to understand the message we've pulled off the queue, commit transaction and continue. " + listenerUrl + " will not be receiving this message.");
                                                 confirmAndFallout(topicSession, listenerSleep, true);
                                                 continue;
                                            String operationNodeName = "";
                                            if (rootNode!=null)
                                                 operationNodeName = rootNode.getNodeName();
                                            myLogger.info("run(): operationNodeName: " + operationNodeName);
                                            if (operationNodeName.equals("tktInfoEvt"))
                                                 eventType = "tktInfoEvt";
                                            else if (operationNodeName.equals("prmInfoEvt"))
                                                 eventType = "prmInfoEvt";
                                            else if (operationNodeName.equals("rubyFacilityStatusEvt"))
                                                 eventType = "rubyFacilityStatusEvt";
                                            else if (operationNodeName.equals("killEvt"))
                                                 eventType = "killEvt";
                                            else
                                                 eventType = "heartbeatEvt";
                                            /** If the message is a rubyFacilityStatusEvt,
                                                 tktInfoEvt, or prmInfoEvt
                                                 - perform filter(listenerUrl, mcn) to determine
                                                 whether our client cares about this message
                                                 - if client cares, stamp(url) to refresh clock,
                                                 convert the xml string to java class, and send
                                                 message
                                                 - if client does not care, invoke discardedMsg(mcn)
                                                 and commit the transaction
                                                 - if ws request succeeds, commit
                                                 - if ws request fails, rollback and sit tight      
                                                 for one minute
                                            else if (eventType.equals("rubyFacilityStatusEvt") ||
                                                      eventType.equals("tktInfoEvt") ||
                                                      eventType.equals("prmInfoEvt"))
                                                 String mcn = rubyxml.getValueByTag((Element)rootNode, "mcn", errstr);
                                                 if (gs.filter(listenerUrl, mcn)
                                                      == AgmemsFilter.FILTER_PASSED)
                                                      myLogger.info("run(): we've pulled a " + eventType + " message off of the queue and it's time to send it out to client: " + listenerUrl);
                                                      messageCount += 1;
                                                      Socket agmemsSocket = null;
                                                      try
                                                      if (eventType.equals("rubyFacilityStatusEvt"))
                                                                agmemsSocket = HttpUtilities.sendCommand(cu.populateFacilityEvt(facStatusServiceUrl, messageText, messageCount, facStatusAction, rdate, agmemsUsername, agmemsPassword, "", false), agmemsHost, Integer.parseInt(agmemsPort), Integer.parseInt(agmemsTimeout), facStatusServiceUrl);
                                                      else if (eventType.equals("tktInfoEvt"))
                                                                agmemsSocket = HttpUtilities.sendCommand(cu.populateTicketEvt(tktInfoServiceUrl, messageText, messageCount, tktInfoAction, rdate, agmemsUsername, agmemsPassword), agmemsHost, Integer.parseInt(agmemsPort), Integer.parseInt(agmemsTimeout), tktInfoServiceUrl);
                                                      else
                                                                agmemsSocket = HttpUtilities.sendCommand(cu.populatePrmEvt(prmInfoServiceUrl, messageText, messageCount, prmInfoAction, rdate, agmemsUsername, agmemsPassword), agmemsHost, Integer.parseInt(agmemsPort), Integer.parseInt(agmemsTimeout), prmInfoServiceUrl);
                                                      catch (Exception e)
                                                           //these are the kind of failures,
                                                           //timeout, socketException, etc. that we
                                                           //would like to retry
                                                           myLogger.error("run(): ERROR, " + eventType + " push was unable to be sent to " + listenerUrl + " because of following exception, rolling back transaction." + e);
              ------------------------                         confirmAndFallout(topicSession, listenerSleep, false);
                   continue;
                                       myLogger.info("run(): Continued to readReplyFromSocket");
                                                      StringBuffer respStr = new StringBuffer();
                                                      try
                                                           HttpUtilities.readReplyFromSocket
                                                                (agmemsSocket, respStr);
                                                           myLogger.info("run(): response returned was " + respStr);
                                                      catch (Exception ie)     
                                                           //rollback, something wrong on client side
                                                           myLogger.error("run(): ERROR, " + eventType + " NOT delivered to " + listenerUrl + " rolling back transaction. " + ie.toString());
                                                           confirmAndFallout(topicSession, listenerSleep, false);
                                                           continue;
                                                      int agmemsMessageNumber=0;
                                                      agmemsMessageNumber =
                                                           cu.parseAgmemsResponse(respStr.toString());
                                                      if ((agmemsMessageNumber==-1) ||
                                                           (agmemsMessageNumber!=messageCount))
                                                           confirmAndFallout(topicSession, listenerSleep, true);
                                                           myLogger.error("run(): ERROR, " + eventType + " push response came back with NOT delivered to " + listenerUrl + " confirming transaction.");
                                                      else
                                                           confirmAndFallout(topicSession, listenerSleep, true);
                                                           myLogger.info("run(): " + eventType + " delivered to " + listenerUrl + " and transaction is committed.");
                                                 //Assumes CLIENT_INACTIVE return
                                                 else
                                                      //commit for cleanup only
                                                      confirmAndFallout(topicSession, listenerSleep, true);
                                                      setHaltFlag(true);
                                                      myLogger.error("run(): " + eventType + " NOT delivered to " + listenerUrl + ", CLIENT_INACTIVE, halting message receive on this listener.");
                                            else
                                                 myLogger.error("run(): we've pulled a text message from the queue that is UNKNOWN, commit and continue.");
                                                 confirmAndFallout(topicSession, listenerSleep, true);
                                       else
                                            myLogger.error("run(): we've pulled a message from the queue that is UNKNOWN and not text, commit and continue.");
                                            confirmAndFallout(topicSession, listenerSleep, true);
                                  else
                                       myLogger.error("run(): something strange happened, receive() returned with NO MESSAGE, commit and continue.");
                                       confirmAndFallout(topicSession, listenerSleep, true);
                        catch (JMSException je)
                             myLogger.error("run(): ERROR, exception, cleanup connections: " + je.toString());
                        catch (Exception e)
                             myLogger.error("run(): ERROR, exception, cleanup connections: " + e.toString());
                        finally
                             myLogger.error("run(): broken out of message receive loop, closing session, subscription, and topicConnection and KILLING this thread.");
                             if (topicConnection != null)
                                  try
                                       cm.listenerTable.remove(listenerUrl);
                                       topicSession.close();
                                       topicSubscriber.close();
                                       topicConnection.close();
                                  catch (JMSException e)
                                       myLogger.error("run(): As part of cleanup process, there was an exception attempting to close our topicConnection.");
              Message was edited by:
              whoopsy

  • Transient persestant memory-begin abort transaction-arraycopynonatomic

    If array defined as transient, then abort doesnt make any sense, chages are not rolled back.(Both for arrayCopy and arraycopyNonAtomic functions)
         public void AtomicNonatomic()
    byte hello[] = {'H','E','L','L','O'};
              byte[] key_buffer = JCSystem.makeTransientByteArray((byte)16, JCSystem.CLEAR_ON_RESET);
              //byte[] key_buffer = new byte[16];
              JCSystem.beginTransaction();
              //Util.arrayCopy(hello, (short)0, key_buffer, (short)0, (short)5);
              Util.arrayCopyNonAtomic(hello,(short)0, key_buffer, (short)0, (short)5);
              for(byte i =0; i<2; i++)
              key_buffer=0; //This types of assigning values are atomic operations, so can be thougth as arrayCopy
              JCSystem.abortTransaction();          
    If array not defined as transient and if arrayCopy is used then abort works
    If array not defined as transient and if arrayCopyNonatomic is used then abort not works
         public void AtomicNonatomic()
              //byte[] key_buffer = JCSystem.makeTransientByteArray((byte)16, JCSystem.CLEAR_ON_RESET);
              byte[] key_buffer = new byte[16];
              JCSystem.beginTransaction();
              //Util.arrayCopy(hello, (short)0, key_buffer, (short)0, (short)5);
              Util.arrayCopyNonAtomic(hello,(short)0, key_buffer, (short)0, (short)5);
              for(byte i =0; i<2; i++)
              key_buffer[i]=0;
              JCSystem.abortTransaction();          
    As a result begin-abort-commit should be used with non-transient arrays and without arrayCopyNonatomic function.
    Edited by: simeranya_00 on Aug 7, 2010 6:51 AM
    Edited by: simeranya_00 on Aug 7, 2010 6:56 AM

    Check out JCRE specification. Therein you will find what is (not) part of a transaction.
    1. All global arrays are not part of a transaction
    2. All transient fields/arrays/keys are not part of a transaction
    3. OwnerPIN object is not part of a transaction
    4. All Java Card API methods are transactional, except arrayCopyNonAtomic and arrayFillNonAtomic
    Lifetime of a transaction
    begin <--> commit
    begin <--> abort < -- rollback
    begin <--> JCRE context (process method exit) < -- abort transaction (done by JCRE) < -- rollback
    begin <--> uncaught exception < -- abort < -- rollback
    begin <--> tear/reset < -- rollback

  • TOO many OPEN CURSORS during loop of INSERT's

    Running ODP.NET beta2 (can't move up yet but will do that soon)
    I don't think it is related with ODP itself but probably on how .Net works with cursors. We have a for/next loop that executes INSERT INTO xxx VALUES (:a,:b,:c)
    statements. Apparently, when monitoring v$sysstat (current open cursors) we see these raising with 1 INSERT = 1 cursor. If subsequently we try to perform another action, we get max cursors exceeded. We allready set open_cursor = 1000, but the number of inserts can be very high. Is there a way to release these cursors (already wrote oDataAdaptor.dispose, oCmd.dispose but this does not help.
    Is it normal that each INSERT has it's own cursor ? they all have the same hashvalue in v$open_cursor. They seem to be released after a while, especially when moving to another asp.net page, but it's not clear when that happens and if it is possible to force the release of the (implicit?) cursors faster.
    Below is a snippet of the code, I unrolled a couple of function-calls into the code so this is just an example, not sure it will run without errors like this, but the idea should be clear (the code looks rather complex for what it does but the unrolled functions make the code more generic and we have a database-independend datalayer):
    Try
    ' Set the Base Delete statement
    lBaseSql = _
    "INSERT INTO atable(col1,col2,col3) " & _
    "VALUES(:col1,:col2,:col3)"
    ' Initialize a transaction
    lTransaction = oConnection.BeginTransaction()
    ' Create the parameter collection, containing for each
    ' row in the list the arguments
    For Each lDataRow In aList.Rows
    lOracleParamters = New OracleParameterCollection()
    lOracleParameter = New OracleParameter("luserid", OracleDbType.Varchar2,
    _ CType(aCol1, Object))
    lOracleParamters.Add(lOracleParameter)
    lOracleParameter = New OracleParameter("part_no", OracleDbType.Varchar2, _
    CType(lDataRow.Item("col2"), Object))
    lOracleParamters.Add(lOracleParameter)
    lOracleParameter = New OracleParameter("revision", OracleDbType.Int32, _
    CType(lDataRow.Item("col3"), Object))
    lOracleParamters.Add(lOracleParameter)
    ' Execute the Statement;
    ' If the execution fails because the row already exists,
    ' then the insert should be considered as succesfull.
    Try
    Dim aCommand As New OracleCommand()
    Dim retval As Integer
    'associate the aConnection with the aCommand
    aCommand.Connection = oConnection
    'set the aCommand text (stored procedure name or SQL statement)
    aCommand.CommandText = lBaseSQL
    'set the aCommand type
    aCommand.CommandType = CommandType.Text
    'attach the aCommand parameters if they are provided
    If Not (lOracleParameters Is Nothing) Then
    Dim lParameter As OracleParameter
    For Each lParameter In lOracleParameters
    'check for derived output value with no value assigned
    If lParameter.Direction = ParameterDirection.InputOutput _
    And lParameter.Value Is Nothing Then
    lParameter.Value = Nothing
    End If
    aCommand.Parameters.Add(lParameter)
    Next lParameter
    End If
    Return
    ' finally, execute the aCommand.
    retval = cmd.ExecuteNonQuery()
    ' detach the OracleParameters from the aCommand object,
    ' so they can be used again
    cmd.Parameters.Clear()
    Catch ex As Exception
    Dim lErrorMsg As String
    lErrorMsg = ex.ToString
    If Not lTransaction Is Nothing Then
    lTransaction.Rollback()
    End If
    End Try
    Next
    lTransaction.Commit()
    Catch ex As Exception
    lTransaction.Rollback()
    Throw New DLDataException(aConnection, ex)
    End Try

    I have run into this problem as well. To my mind
    Phillip's solution will work but seems completey unnecessary. This is work the provider itself should be managing.
    I've done extensive testing with both ODP and OracleClient. Here is one of the scenarios: In a tight loop of 10,000 records, each of which is either going to be inserted or updated via a stored procedure call, the ODP provider throws the "too many cursor errors at around the 800th iteration. With over 300 cursors being open. The exact same code with OracleClient as the provider never throws an error and opens up 40+ cursors during execution.
    The applicaation I have updates a Oracle8i database from a DB2 database. There are over 30 tables being updated in near real time. Reusing the command object is not an option and adding all the code Phillip did for each call seems highly unnecessary. I say Oracle needs to fix this problem. As much as I hate to say it the microsoft provider seems superior at this point.

  • Java.util.MissingResourceException: Can't find bundl :ERROR plz Help

    hey guys am trying to connect to my data base and view data toa jsp page but i got this error :
    Exception report
    message
    descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: java.util.MissingResourceException: Can't find bundle for base name DataBase, locale en_US
    root cause
    java.util.MissingResourceException: Can't find bundle for base name DataBase, locale en_US
    note The full stack traces of the exception and its root causes are available in the Sun Java System Application Server 9.1 logs.
    here is the code database _proper
    drivername=oracle.jdbc.driver.OracleDriver
    dataSourceName=jdbc/orcl/WOH
    dsLookupPrefix=WOH.getstring("dslookupprefix");
    user=SYSTEM
    password=SYSTEM
    location=192.168.1.3
    port=1521
    sid=ORCL
    and here is the Dao connection class
    package version.dao;
    import java.util.*;
    //to provide JDBC classes
    import java.sql.*;
    * @author freddy
    public class DAODirect {
    * Insert the type's description here.
    * Creation date: (12/25/2006 12:13:56 PM)
    * @author: Administrator
         private Connection connection = null;
         private Statement statement = null;
         private String driverName =null;// "oracle.jdbc.driver.OracleDriver";//null;
         private String url =null;//"jdbc:oracle:thin:scott/tiger@localhost:1521:ORCL";//null;
         private ResultSet rs = null;
         private String columnNames[];
         private int columnCount;
         private Object[] record;
         * PFSDataBase constructor comment.
         public DAODirect() {
              super();
              ResourceBundle database = ResourceBundle.getBundle("DataBase");
    //1 get the driver name
              driverName = database.getString("drivername");
              String user = database.getString("user");
              String password = database.getString("password");
              String location = database.getString("location");
              String port = database.getString("port");
              String sid = database.getString("sid");
    //String dataSourceName=database.getString("dataSourceName");
    //2- get the Connection url
              url =
                   "jdbc:oracle:thin:"
                        + user
                        + "/"
                        + password
                        + "@"
                        + location
                        + ":"
                        + port
                        + ":"
                        + sid;
              System.out.println("++++++++"+url);
    System.out.println("++++++++"+url);
         public void closeStatement() {
              try {
                   if (statement != null) {
                        statement.close();
                        statement = null;
              } catch (Exception e) {
         public void commitDB() throws Exception{
              connection.commit();     
         public boolean connect() throws Exception {
              try {
                   if (connection == null) {
    //1- loading of JDBC Drivers
                        Class.forName(driverName);
                        System.out.println(url);
    //this line =conn = DriverManager.getConnection(
    // "jdbc:oracle:thin:@noizmaker:1521:osiris",
    // "scott", "tiger");
    //2- Establish Connection
                        connection = DriverManager.getConnection(url);
                        return true;
                   } else {
                        throw (
                             new Exception("connection is not disconnected, you have to disconnect this connection before reconnecting it again"));
              } catch (SQLException e) {
                   e.printStackTrace();
                   throw (new Exception("Unable to connect to database,Error Loading Driver"));
         public void createStatement() throws Exception {
              if (statement != null) {
                   closeStatement();
              if (connection == null) {
                   throw (new Exception("database is not connected"));
              statement = connection.createStatement();//3-bulit_in funnction that create and send sql statment
         public void disconnect() throws Exception {
              if (connection != null) {
                   try {
                        connection.close();
                        connection = null;
                   } catch (Exception e) {
                   //isConnected = false;
              } else {
                   throw (new Exception("can not disconnect database"));
    // ResultSet is: A table of data representing a database result set, which is usually generated by executing a statement that queries the database
         public ResultSet execute(String query) throws Exception {
              if (connection == null) {
                   throw (new Exception("database is not connected"));
              if (statement == null) {
                   throw (new Exception("statement is not created"));
              return statement.executeQuery(query);//bulit_in funnction that 4-execute given sql statment
         public void getColumnNames(ResultSet result) throws Exception {
              try {
    //An object that can be used to get information about the types and properties of the columns in a ResultSet object.
                   ResultSetMetaData resultsMetaData = result.getMetaData();
                   columnCount = resultsMetaData.getColumnCount();
                   columnNames = new String[columnCount];
                   for (int i = 1; i < columnCount + 1; i++) {
                        columnNames[i - 1] = resultsMetaData.getColumnName(i).trim();//trim to remove whaite space
              } catch (Exception e) {
                   throw (new Exception("Result Set Columns " + e.getMessage()));
         public Connection getConnection(){
              return connection;     
         public void rollBack() throws Exception{
              connection.rollback();     
         public Vector rsToVector(ResultSet rs) throws Exception {
              getColumnNames(rs);
              Vector resultSetData = new Vector();
              resultSetData.addElement(columnNames);
              try {
                   this.record = new Object[columnCount];
                   while (rs.next()) {
    //ave each raw
                        Object[] record = new Object[columnCount];
                        for (int i = 1; i < columnCount + 1; i++) {
                             Object entry = rs.getObject(i);
                             record[i - 1] = entry;
    // here we print the whole tabel after we save each record in record[]
                        resultSetData.addElement(record);
                   return resultSetData;
              } catch (Exception e) {
                   resultSetData.clear();
                   throw (new Exception("Result Set : " + e.getMessage()));
         public void setAutoCommit(boolean commitType) throws Exception{
              connection.setAutoCommit(commitType);     
         public boolean update(String query) throws Exception {
              if (connection == null) {
                   throw (new Exception("database is not connected"));
              try {
    //create query and execute it
                   createStatement();
                   statement.execute(query);
                   return true;
              } catch (Exception e) {
                   throw (
                        new Exception(
                             "Error in manipulating query :" + e.getMessage()));
              } finally {
                   closeStatement();
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package version.dao;
    import java.sql.ResultSet;
    import java.sql.Connection;
    import java.sql.Statement;
    import java.sql.SQLException;
    import javax.sql.DataSource;
    import javax.naming.InitialContext;//unknown
    import java.util.ResourceBundle;//unknown
    * @author freddy
    * This is the Data Access Object (DAO), which deals with all Database transactions,
    * connections,and pooling (through Data Source implementation).
    * This class configured through the database.properties file
    * which contains all the database parameters
    * @author: Tariq Qasem
    public class DAO {
         private Connection connection = null;
         private Statement statement = null;
         private String dataSourceName =null; //MyDataSource; //null;
         private String dsLookupPrefix = null;//java:comp/env/;
    //null;
         private ResultSet rs = null;
         * DAO constructor comment.
         public DAO() {
              super();
              ResourceBundle database = ResourceBundle.getBundle("DataBase");
              dataSourceName = database.getString("dataSourceName");
              dsLookupPrefix = database.getString("dsLookupPrefix");
         * @param request PortletRequest
         * @return void
         * this method close pooled statement
         public void closeStatement() {
              try {
                   if (statement != null) {
                        statement.close();
                        statement = null;
              } catch (Exception e) {
         * @param request PortletRequest
         * @return boolean
         * this method connects to the database
         public boolean connect() throws Exception {
              try {
                   if (connection == null) {
                        InitialContext ctx = new InitialContext();
                   DataSource ds = (DataSource) ctx.lookup(dsLookupPrefix+dataSourceName);
                        connection = ds.getConnection();
                        return true;
                   } else {
                        throw (
                             new Exception("connection is not disconnected, you have to disconnect this connection before reconnecting it again"));
              } catch (SQLException e) {
                   e.printStackTrace();
                   throw (new Exception("Unable to connect to database"));
         public void createStatement() throws Exception {
              if (statement != null) {
                   closeStatement();
              if (connection == null) {
                   throw (new Exception("database is not connected"));
              statement = connection.createStatement();
         * @param request PortletRequest
         * @return void
         * this method disconnect the database connection
         public void disconnect() throws Exception {
              if (connection != null) {
                   try {
                        connection.close();
                        connection = null;
                   } catch (Exception e) {
              } else {
                   throw (new Exception("can not disconnect database"));
         * @param request PortletRequest
         * @return boolean
         * this method updates (executes) Insert and Updates queries on the database
    /*     public boolean update(String query) throws Exception {
              if (connection == null) {
                   throw (new Exception("database is not connected"));
              try {
                   createStatement();
                   statement.execute(query);
                   return true;
              } catch (Exception e) {
                   throw (
                        new Exception(
                             "Error in manipulating query :" + e.getMessage()));
              } finally {
                   closeStatement();
         public int update(String query) throws Exception {
              int records = 0;
              if (connection == null) {
                   throw (new Exception("database is not connected"));
              try {
                   createStatement();
                   records = statement.executeUpdate(query);
                   return records;
              } catch (Exception e) {
                   throw (
                        new Exception(
                             "Error in manipulating query :" + e.getMessage()));
              } finally {
                   closeStatement();
         * @param request PortletRequest
         * @return ResultSet
         * this method executes select queries on the database
         public ResultSet execute(String query) throws Exception {
              if (connection == null) {
                   throw (new Exception("database is not connected"));
              if (statement == null) {
                   throw (new Exception("statement is not created"));
              return statement.executeQuery(query);
         * @param request PortletRequest
         * @return void
         * this method to set the commit transaction on the database to be auto
         public void setAutoCommit(boolean commitType) throws Exception{
              connection.setAutoCommit(commitType);     
         * @param request PortletRequest
         * @return void
         * this method commit database transaction
         public void commitDB() throws Exception{
              connection.commit();     
         * @param request PortletRequest
         * @return void
         * this method rollback database transaction
         public void rollBack() throws Exception{
              connection.rollback();     
         * @param request PortletRequest
         * @return Connection
         * this method return the database connection as java object
         public Connection getConnection(){
              return connection;     
    and this is my jsp page:
    <%--
    Document : index
    Created on : Mar 16, 2008, 10:14:55 AM
    Author : freddy
    --%>
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
    </head>
    <body>
    <h2>Hello World!</h2>
    <%
    version.dao.DAODirect dao=new version.dao.DAODirect();
    try
    boolean connected = dao.connect();
    dao.createStatement();
    String query = " SELECT ID,NAME FROM version";
    java.sql.ResultSet rs = dao.execute(query);
    while(rs.next()){
    out.println(rs.getInt("P_ID")+" ");
    out.println(rs.getString("P_FN")+"<BR>");
    dao.closeStatement();
    dao.disconnect();
    catch(Exception e)
    out.print(e.getMessage());
    %>
    </body>
    </html>
    plz guys help me i need this for my graduation project also if anyone know kind of tutorialsfor building J2me/J2EE application using wifi plzzzsend me links or anything ,thx in advance

    This can happen after modifying the calendar properties and not reloading the application. Try reloading or restarting the application. This could also mean the Calendar.properties file has been moved, deleted, or become corrupted. A default properties file can be found at:
    "Tomcat-install-dir"\webapps\"your-web-application"\WEB-INF\classes\defaultPropFile\. Copy this file to: "Tomcat-install-dir"\webapps\"your-web-application"\WEB-INF\classes\. Stop and restart the web server. From a browser, run "hostname"/"your-web-application"/src/setupCalendar.jsp.

  • EJB 3.0 Stateful - Limiting number of bean instances

    Hello EJB Experts,
    I have just started to learn EJB 3.0 and have some basic queries. The application server that I am using is Glassfish. Please find my queries below:
    1. To remove an bean instance from the container, we can use the annotation '@Remove'. I basically had 2 methods and annotated the 2nd method with '@Remove'. Whenever the 2nd method is called, the container is removing this instance also in my program. My problem is that, i might get some invalid parameter values in the 2nd method, so in that case I have to just log the error message and whenever the input parameters are correct, then only the instance should be removed. But lets say, if someone calls my 2nd method with invalid parameters, I log the message and the container removes it, but after some time if the 2nd method is called with correct parameters, then the instance will not be available. Can we programatically tell the container when to remove a bean instance?
    2. From the docs, I am clear that pooling works only for 'Stateless' beans. I however (I am using 'Statuful' bean), wanted to limit the max number of instance to 2. I did below mentioned configuration in the 'sun-ejb-jar.xml' file:
    <bean-cache>
                        <is-cache-overflow-allowed>false</is-cache-overflow-allowed>
                        <cache-idle-timeout-in-seconds>1</cache-idle-timeout-in-seconds>
                        <max-cache-size>2</max-cache-size>
                        <resize-quantity>0</resize-quantity>
                        <removal-timeout-in-seconds>2</removal-timeout-in-seconds>
                        <victim-selection-policy>LRU</victim-selection-policy>
              </bean-cache>
    But i think, it is still creating more that 2 instances of this bean.
    Please help me in getting answers to these questions. I will be very thankful for your replies.
    Regards,
    San
    Edited by: SolarisUser1 on Jun 27, 2010 11:00 PM

    @Remove is used for stateful EJBs and you call it when your client has finished using that instance of the stateful EJB.
    If you are passing in parameters to the method and letting it do some work with your parameters then perhaps it should not be a remove method at all. Make it a normal method and only put cleanup related logic in the remove method. You can also throw some application exception and rollback if the parameters are not correct.

Maybe you are looking for

  • Oracle 8i Installation on Redhat Linux AS 3.0

    Hi guys, I am just doing some home work before installation of Oracle 8i Enterprise server on Redhat Linux AS 3.0. Before I started my work on this, I planned to install 8i on AIX 5L, which was a bad idea. Because 8i being a 32bit db and 5L being 64b

  • How do I get line-in to a new iMac?

    Hi all So I am new to this forum and have a somewhat convulted and probaly unusual problem. Thanks in advance to anyone who might be able to help. I have a new iMac and although I quite like it there are a couple of aspects that annoy me: 1. The soun

  • How to use task flow's transaction options with session's user data

    Hi. I have custom extension of ApplicationModuleImpl class: package test.model imports... public class CustomAppModuleImpl extends ApplicationModuleImpl {     public static final String SESSION_VAR = "MySessionVar";     public CustomAppModuleImpl() {

  • Purchase Order Request: (Third party -- XI-- SRM)

    Hi, We have the following scenario: Purchase order is send from our application to XI and then from XI to SRM. This purchase order will have a unique ID (our application assigns the ID). We would like SRM to send back Purchase Order Confirmation, and

  • Authorizations at Object level

    Hi Guru's, I have a query regarding Authorizations i.e i have a Cost center hierarchy and have more than 40 users with different costcenter eligibility. Now i need to restrict particular user id with selected costcenters....please give me suggestion