/*
If there is a transaction in progress, then create a new JMSContext add to Transaction registry and return the same
If there is no transaction, then create a new context and return the JMSContext
430604
private synchronized JMSContext getInternalJMSContext() {
        TransactionSynchronizationRegistry tranSyncRegistry = null;
        try {

            boolean tranIsActive = false;

            tranSyncRegistry = (TransactionSynchronizationRegistry) new InitialContext().lookup(TSR_LOOKUP_NAME);

            if (tranSyncRegistry != null)
            {
                tranIsActive = (tranSyncRegistry.getTransactionStatus() == Status.STATUS_ACTIVE);
            }

            if (tranIsActive)
            {

                Object resource = tranSyncRegistry.getResource(jmsContextInfo);

                if (resource != null) {

                    return (JMSContext) resource;

                } else {

                    final JMSContext transactedContext = createJMSContext(jmsContextInfo, tranIsActive);

                    //Once the new JMSContext is created,  add it to the transaction registry to 
                    //retrieve it later if the new JMSContext is requested for the same configuration
                    //but in same transactional context
                    tranSyncRegistry.putResource(jmsContextInfo, transactedContext);

                    //Register a Synchronization object in transaction registry for a call back
                    //when the transaction is complete,  we will close the JMSContext once the 
                    //Transaction is complete
                    tranSyncRegistry.registerInterposedSynchronization(new Synchronization() {
                        @Override
                        public void beforeCompletion() {}

                        @Override
                        public synchronized void afterCompletion(int status) {
                            transactedContext.close();
                            inTransaction = false;
                        }
                    });

                    return transactedContext;
                }
            } else {

                //Non transacted,  create a new JMSContext and return it
                if (internalJMSContext == null) {
                    internalJMSContext = createJMSContext(jmsContextInfo, tranIsActive);
                }
                return internalJMSContext;
            }
        } catch (Exception e)
        {
            throw new RuntimeException(e.getLocalizedMessage(), e);
        }
    }
815061
public final ControlNotFlushed createNewControlNotFlushed() throws MessageCreateFailedException {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "createNewControlNotFlushed");
    ControlNotFlushed msg = null;
    try {
      msg = new ControlNotFlushedImpl(MfpConstants.CONSTRUCTOR_NO_OP);
    }
    catch (MessageDecodeFailedException e) {
      /* No need to FFDC this as JsMsgObject will already have done so */
      // No FFDC code needed
      throw new MessageCreateFailedException(e);
    }
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "createNewControlNotFlushed");
    return msg;
  }
1323353
private SegmentMetadataUpdateTransaction getOrCreateSegmentUpdateTransaction(String segmentName, long segmentId) {
        SegmentMetadataUpdateTransaction sm = tryGetSegmentUpdateTransaction(segmentId);
        if (sm == null) {
            SegmentMetadata baseSegmentMetadata = createSegmentMetadata(segmentName, segmentId);
            sm = new SegmentMetadataUpdateTransaction(baseSegmentMetadata, this.recoveryMode);
            this.segmentUpdates.put(segmentId, sm);
        }

        return sm;
    }
1141449
public CreateTransactionResult createTransaction(
            final long connectionId,
            final StoredProcedureInvocation invocation,
            final boolean isReadOnly,
            final boolean isSinglePartition,
            final boolean isEveryPartition,
            final int partition,
            final int messageSize,
            final long nowNanos)
    {
        return m_dispatcher.createTransaction(
                connectionId,
                Iv2InitiateTaskMessage.UNUSED_MP_TXNID,
                0, //unused timestammp
                invocation,
                isReadOnly,
                isSinglePartition,
                isEveryPartition,
                new int [] { partition },
                messageSize,
                nowNanos,
                false);  // is for replay.
    }
1370264
@Override
    public JMSContext createContext(String userName, String password, int sessionMode) throws JMSRuntimeException, JMSSecurityRuntimeException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "createContext", new Object[] { userName, password, sessionMode });

        JmsConnectionImpl jmsConnection = null;
        JMSContext jmsContext = null;
        try {

            //CTS test failure was reported when the session mode was passed as -1,  so adding the validation
            switch (sessionMode)
            {
                case JMSContext.AUTO_ACKNOWLEDGE:
                case JMSContext.CLIENT_ACKNOWLEDGE:
                case JMSContext.DUPS_OK_ACKNOWLEDGE:
                case JMSContext.SESSION_TRANSACTED: {
                    break;
                }
                default:
                    throw (JMSRuntimeException) JmsErrorUtils.newThrowable(JMSRuntimeException.class,
                                                                           "INVALID_ACKNOWLEDGE_MODE_CWSIA0514",
                                                                           new Object[] { sessionMode },
                                                                           tc
                                    );
            }

            // Create JMSConnection to pass into JMSContext
            jmsConnection = (JmsConnectionImpl) createConnection(userName, password);
            jmsContext = new JmsJMSContextImpl(jmsConnection, sessionMode, true);
        } catch (JMSSecurityException jmsse) {
            throw (JMSSecurityRuntimeException) JmsErrorUtils.getJMS2Exception(jmsse, JMSSecurityRuntimeException.class);
        } catch (JMSException jmse) {
            throw (JMSRuntimeException) JmsErrorUtils.getJMS2Exception(jmse, JMSRuntimeException.class);
        } finally {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(this, tc, "createContext", jmsContext);
        }
        return jmsContext;

    }
523432
private static PersistenceContext newPersistenceContext(final String fJndiName, final String fUnitName, final int fCtxType,
                                                            final List<Property> fCtxProperties) {
        return new PersistenceContext() {

            @Override
            public Class<? extends Annotation> annotationType() {
                return PersistenceContext.class;
            }

            @Override
            public String name() {
                return fJndiName;
            }

            @Override
            public PersistenceProperty[] properties() {
                //TODO not ideal doing this conversion processing here
                PersistenceProperty[] props = new PersistenceProperty[fCtxProperties.size()];
                int i = 0;
                for (Property property : fCtxProperties) {
                    final String name = property.getName();
                    final String value = property.getValue();
                    PersistenceProperty prop = new PersistenceProperty() {

                        @Override
                        public Class<? extends Annotation> annotationType() {
                            return PersistenceProperty.class;
                        }

                        @Override
                        public String name() {
                            return name;
                        }

                        @Override
                        public String value() {
                            return value;
                        }

                    };
                    props[i++] = prop;
                }
                return props;
            }

            @Override
            public PersistenceContextType type() {
                if (fCtxType == PersistenceContextRef.TYPE_TRANSACTION) {
                    return PersistenceContextType.TRANSACTION;
                } else {
                    return PersistenceContextType.EXTENDED;
                }
            }

            @Override
            public String unitName() {
                return fUnitName;
            }

            @Override
            public String toString() {
                return "JPA.PersistenceContext(name=" + fJndiName +
                       ", unitName=" + fUnitName + ")";
            }
        };
    }
160008
private Transaction createTransaction(long writePointer, TransactionType type) {
    // For holding the first in progress short transaction Id (with timeout >= 0).
    long firstShortTx = Transaction.NO_TX_IN_PROGRESS;
    LongArrayList inProgressIds = new LongArrayList(inProgress.size());
    for (Map.Entry<Long, InProgressTx> entry : inProgress.entrySet()) {
      long txId = entry.getKey();
      inProgressIds.add(txId);
      // add any checkpointed write pointers to the in-progress list
      LongArrayList childIds = entry.getValue().getCheckpointWritePointers();
      if (childIds != null) {
        for (int i = 0; i < childIds.size(); i++) {
          inProgressIds.add(childIds.get(i));
        }
      }
      if (firstShortTx == Transaction.NO_TX_IN_PROGRESS && !entry.getValue().isLongRunning()) {
        firstShortTx = txId;
      }
    }

    return new Transaction(readPointer, writePointer, invalidArray, inProgressIds.toLongArray(), firstShortTx, type);
  }
785290
@Override
    public void commitChanges(SynchronizationBarrier barrier) throws JMSException
    {
    	checkNotClosed();
    	checkTransactionLock();
    	
    	if (!committables.isEmpty())
        {
    		long start = System.currentTimeMillis();
    		
    		Iterator<Committable> allCommitables = committables.iterator();
        	while (allCommitables.hasNext())
        	{
        		Committable committable = allCommitables.next();
        		committable.commitChanges(barrier);
        	}
        	
        	long end = System.currentTimeMillis();
        	notifyCommitTime(end-start);
        	
        	pendingChanges = false;
        }
    }
1368834
private ServiceRegistration<?> registerMBeanService(String jmsResourceName, BundleContext bundleContext) {
        Dictionary<String, String> props = new Hashtable<String, String>();
        props.put(KEY_SERVICE_VENDOR, "IBM");

        JmsServiceProviderMBeanImpl jmsProviderMBean = new JmsServiceProviderMBeanImpl(getServerName(), KEY_JMS2_PROVIDER);
        props.put(KEY_JMX_OBJECTNAME, jmsProviderMBean.getobjectName());

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "JmsQueueMBeanImpl=" + jmsProviderMBean.getobjectName() + " props=" + props);
        }
        return bundleContext.registerService(JmsServiceProviderMBeanImpl.class, jmsProviderMBean, props);
    }
107479
private void createManagedServiceFactory(BundleContext context) {
		// sanity check
		if (managedServiceFactoryReg != null) {
			managedServiceFactoryReg.unregister();
			managedServiceFactoryReg = null;
		}
		final Dictionary<String, String> props = new Hashtable<>();
		props.put(Constants.SERVICE_PID, HttpContextProcessing.PID);
		httpContextProcessing = new HttpContextProcessing(bundleContext, serverController);
		managedServiceFactoryReg = context.registerService(ManagedServiceFactory.class, httpContextProcessing, props);
	}
813613
@Override
    public void localTransactionStarted(ConnectionEvent event) {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "localTransactionStarted");
        }

        if (event.getId() == ConnectionEvent.LOCAL_TRANSACTION_STARTED) {

            //
            // The LocalTransactionStarted event for local transaction connections is analogous to the
            //  InteractionPending event for xa transaction connections.  JMS's usage of ManagedSessions
            //  is very dependent on the ability to use these two events for properly enlisting their
            //  unshared connections.  When a ManagedSession is first created, it is done under an LTC.
            //  When that LTC ends, some partial cleanup is done on the MCWrapper, but it is not put
            //  back into the pool because the unshared connection handle is still active.  One of the
            //  items that gets cleaned up is the coordinator within the MCWrapper.  This makes sense
            //  since the LTC has ended.  But, when it is determined by JMS that it's time to get
            //  enlisted in the current transaction, a null coordinator causes all kinds of problems
            //  (reference the string of defects that have attempted to correct this situation).  The
            //  solution determined seems to be the right one.  In both localTransactionStarted
            //  and interactionPending methods, we need to check if the MCWrapper coordinator is null and
            //  if it is null, then go out to the TM and get it updated.
            //
            // Note that this special null coordinator processing is due to the SmartHandle support
            //  utilized by JMS and RRA.  Without smart handles, the coordinator would have gotten
            //  re-initialized during the handle re-association logic.
            //
            // In addition, we have determined that the check for involvedInTransaction() is not necessary
            //  (and causes problems for the scenario described just previous).  Since the getCurrentTranWrapper()
            //  already checks for a valid state setting before returning, we can just rely on that method to
            //  do the proper checking instead of calling the involvedInTransaction() method.
            //
            UOWCoordinator uowCoordinator = mcWrapper.getUOWCoordinator();

            if (uowCoordinator == null) {
                uowCoordinator = mcWrapper.updateUOWCoordinator();
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "uowCoord was null, updating it to current coordinator");
                }
            }

            // if the coordinator is still null, then we are running with NO transaction
            //  context on the thread.  This case currently needs to be supported because
            //  servlets can spin their own threads which would not have context.
            // Note: it is very rare that users do this.  All other occurances are
            //  considered to be an error.
            if (uowCoordinator == null) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                    Tr.exit(this, tc, "localTransactionStarted", "no transaction context, return without enlisting");
                }
                return;
            }

            /*
             * We know we are in a transaction but we need to verify that it is not a global transaction
             * before continuing.
             */
            if (tc.isDebugEnabled() && uowCoordinator.isGlobal()) {
                IllegalStateException ise = new IllegalStateException("Illegal attempt to start a local transaction within a global (user) transaction");
                Tr.debug(this, tc, "ILLEGAL_USE_OF_LOCAL_TRANSACTION_J2CA0295", ise);
            }

            /*
             * The ManagedConnection should be associated with a transaction. And, if it's not,
             * the getCurrentTranWrapper() method will detect the situation and throw an
             * exception.
             *
             * enlist() the ManagedConnection from the transaction.
             */

            try {
                mcWrapper.getCurrentTranWrapper().enlist();
            } catch (ResourceException e) {
                /*
                 * // Can't enlist, something went wrong.
                 * // Destroy the connection(s) so it can't cause any future problems.
                 * try {
                 * mcWrapper.markStale();
                 * mcWrapper.releaseToPoolManager();
                 * }
                 * catch (Exception ex) {
                 * // Nothing to do here. PoolManager has already logged it.
                 * // Since we are in cleanup mode, we will not surface a Runtime exception to the ResourceAdapter
                 * FFDCFilter.processException(ex, "com.ibm.ejs.j2c.ConnectionEventListener.localTransactionStarted", "473", this);
                 * if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                 * Tr.debug(this, tc, "localTransactionStarted: Error when trying to enlist " + mcWrapper.getPoolManager().getPmiName() +
                 * " caught exception, but will continue processing: ", ex);
                 * }
                 * }
                 */

                FFDCFilter.processException(e, "com.ibm.ejs.j2c.ConnectionEventListener.localTransactionStarted", "481", this);
                // add datasource name to message
                Tr.error(tc, "ENLIST_FAILED_J2CA0074", "localTransactionStarted", e, mcWrapper.gConfigProps.cfName);
                // Moved event.getSource() inside of catch block for performance reasons
                ManagedConnection mc = null;
                try {
                    mc = (ManagedConnection) event.getSource();
                } catch (ClassCastException cce) {
                    Tr.error(tc, "GET_SOURCE_CLASS_CAST_EXCP_J2CA0098", cce);
                    throw new IllegalStateException("ClassCastException occurred attempting to cast event.getSource to ManagedConnection");
                }
                ConnectionEvent errorEvent = new ConnectionEvent(mc, ConnectionEvent.CONNECTION_ERROR_OCCURRED);
                this.connectionErrorOccurred(errorEvent);

                RuntimeException rte = new IllegalStateException(e.getMessage());
                throw rte;
            }
        } else {
            // Connection Event passed in doesn't match the method called.
            // This should never happen unless there is an error in the ResourceAdapter.
            processBadEvent("localTransactionStarted", ConnectionEvent.LOCAL_TRANSACTION_STARTED, event);
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "localTransactionStarted");
        }
        return;
    }
644113
public <T> T withTransaction(@NotNull TransactionSettings settings,
                                 @NotNull TransactionCallback<T> callback) {

        return transactionManager.withTransaction(settings, callback, dialect);
    }
911480
private J2EETransactionImpl newInternTransaction()
    {
        if (log.isDebugEnabled()) log.debug("obtain new intern odmg-transaction");
        J2EETransactionImpl tx = new J2EETransactionImpl(this);
        try
        {
            getConfigurator().configure(tx);
        }
        catch (ConfigurationException e)
        {
            throw new OJBRuntimeException("Cannot create new intern odmg transaction", e);
        }
        return tx;
    }
751046
void addTransaction(Transaction t, boolean runSanityChecks) {
        unCacheTransactions();
        if (transactions == null) {
            transactions = new ArrayList<>();
        }
        t.setParent(this);
        if (runSanityChecks && transactions.size() == 0 && !t.isCoinBase())
            throw new RuntimeException("Attempted to add a non-coinbase transaction as the first transaction: " + t);
        else if (runSanityChecks && transactions.size() > 0 && t.isCoinBase())
            throw new RuntimeException("Attempted to add a coinbase transaction when there already is one: " + t);
        transactions.add(t);
        adjustLength(transactions.size(), t.length);
        // Force a recalculation next time the values are needed.
        merkleRoot = null;
        hash = null;
    }
192019
private Transaction onBegin()
    {
        Transaction tx;
        if (((StatelessSessionImpl) s).getTransactionCoordinator().isTransactionActive())
        {
            tx = ((StatelessSessionImpl) s).getTransaction();
        }
        else
        {
            tx = s.beginTransaction();
        }
        return tx;
    }
12025
def begin_transaction
      if @transaction_stack.empty?
        # The new transaction is the top-level transaction. Flush the write
        # buffer to save the current state of all objects.
        flush
      else
        # Save a copy of all objects that were modified during the enclosing
        # transaction.
        @transaction_stack.last.each do |id|
          @transaction_objects[id]._stash(@transaction_stack.length - 1)
        end
      end
      # Push a transaction buffer onto the transaction stack. This buffer will
      # hold a reference to all objects modified during this transaction.
      @transaction_stack.push(::Array.new)
    end
291278
@Override
    public boolean getTransacted() throws JMSRuntimeException {

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "getTransacted");

        boolean transacted = false;
        try {
            transacted = jmsSession.getTransacted();
        } catch (JMSException jmse) {
            throw (JMSRuntimeException) JmsErrorUtils.getJMS2Exception(jmse, JMSRuntimeException.class);
        } finally {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                SibTr.exit(this, tc, "getTransacted", new Object[] { transacted });
        }

        return transacted;
    }