/*
(non-Javadoc)

@see com.ibm.wsspi.sib.core.SICoreConnection#createUncoordinatedTransaction()
545735
@Override
    public SIUncoordinatedTransaction createUncoordinatedTransaction()
                    throws SIConnectionUnavailableException, SIConnectionDroppedException,
                    SIErrorException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "createUncoordinatedTransaction");
        SIUncoordinatedTransaction tran = createUncoordinatedTransaction(true);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "createUncoordinatedTransaction", tran);
        return tran;
    }
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;
    }
431300
@Override
	@Transactional(enabled = false)
	public CommerceAccount createCommerceAccount(long commerceAccountId) {
		return commerceAccountPersistence.create(commerceAccountId);
	}
467533
@Override
	@Transactional(enabled = false)
	public CommerceOrderNote createCommerceOrderNote(long commerceOrderNoteId) {
		return commerceOrderNotePersistence.create(commerceOrderNoteId);
	}
1199998
@Override
    public synchronized UserTransaction getUserTransaction()
    {
        // d367572.1 start
        if (state == PRE_CREATE)
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Incorrect state: " + getStateName(state));
            throw new IllegalStateException(getStateName(state));
        }
        // d367572.1 end

        return UserTransactionWrapper.INSTANCE; // d631349

    }
663558
@Override
    public boolean importTransaction(String globalId, int expires) throws SystemException {

        //The first thing we need to do is distinguish between local and remote invocations. If the UOW currently associated
        //with the thread is a global txn then we know the invocation must be local. The other case is where the remote servers
        //web container has begun a local txn in the absence of the global context. We do know that there was a global txn on 
        //invocation else there wouldn't even be a cc available.
        final UOWCoordinator uowCoord = _uowc.getUOWCoord();
        _threadUOWCoord.set(uowCoord);

        if (uowCoord != null && uowCoord.isGlobal()) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "The Web Service request is a local invocation");

            ((DistributableTransaction) uowCoord).resumeAssociation();
            return false;
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "The Web Service request is a remote invocation");

        try {
            TMHelper.checkTMState();
        } catch (NotSupportedException e) {
            final SystemException se = new SystemException();
            se.initCause(e);
            throw se;
        }

        //The web container will start a local tran as there will not be a global context
        //on thread. We need to suspend this before attaching the global tran
        final LocalTransactionCoordinator ltc = LocalTranCurrentSet.instance().suspend();
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "Suspended LTC", ltc);

        boolean createdNewTransaction = false;

        DistributableTransaction tx = getTransactionForID(globalId);

        if (tx == null) {
            tx = new EmbeddableTransactionImpl(expires, globalId);
            createdNewTransaction = true;

            new TransactionWrapper((EmbeddableTransactionImpl) tx);
        }

        _threadImportedTran.set(tx);

        // Add association to police single thread per tran
        tx.addAssociation();

        // Resume transaction on this thread
        try {
            _tm.resume((Transaction) tx);
        } catch (Exception e) {
            SystemException se = new SystemException();
            se.initCause(e);
            throw se;
        }

        return createdNewTransaction;
    }
1019259
protected SITransaction getTransaction() {

        if (TRACE.isEntryEnabled()) {
            final String methodName = "getTransaction";
            SibTr.entry(this, TRACE, methodName);
            SibTr.exit(this, TRACE, methodName, null);
        }
        return null;

    }
125495
@VisibleForTesting
    void addCoinbaseTransaction(byte[] pubKeyTo, Coin value, final int height) {
        unCacheTransactions();
        transactions = new ArrayList<>();
        Transaction coinbase = new Transaction(params);
        final ScriptBuilder inputBuilder = new ScriptBuilder();

        if (height >= Block.BLOCK_HEIGHT_GENESIS) {
            inputBuilder.number(height);
        }
        inputBuilder.data(new byte[]{(byte) txCounter, (byte) (txCounter++ >> 8)});

        // A real coinbase transaction has some stuff in the scriptSig like the extraNonce and difficulty. The
        // transactions are distinguished by every TX output going to a different key.
        //
        // Here we will do things a bit differently so a new address isn't needed every time. We'll put a simple
        // counter in the scriptSig so every transaction has a different hash.
        coinbase.addInput(new TransactionInput(params, coinbase,
                inputBuilder.build().getProgram()));
        coinbase.addOutput(new TransactionOutput(params, coinbase, value,
                ScriptBuilder.createP2PKOutputScript(ECKey.fromPublicOnly(pubKeyTo)).getProgram()));
        transactions.add(coinbase);
        coinbase.setParent(this);
        coinbase.length = coinbase.unsafeBitcoinSerialize().length;
        adjustLength(transactions.size(), coinbase.length);
    }
1340408
public LocalTransaction getOrCreateLocalTransaction(Transaction transaction, boolean implicitTransaction, Supplier<GlobalTransaction> gtxFactory) {
      LocalTransaction current = localTransactions.get(transaction);
      if (current == null) {
         if (!running) {
            // Assume that we wouldn't get this far if the cache was already stopped
            throw log.cacheIsStopping(cacheName);
         }
         GlobalTransaction tx = gtxFactory.get();
         current = txFactory.newLocalTransaction(transaction, tx, implicitTransaction, currentTopologyId);
         if (trace) log.tracef("Created a new local transaction: %s", current);
         localTransactions.put(transaction, current);
         globalToLocalTransactions.put(current.getGlobalTransaction(), current);
         if (notifier.hasListener(TransactionRegistered.class)) {
            // TODO: this should be allowed to be async at some point
            CompletionStages.join(notifier.notifyTransactionRegistered(tx, true));
         }
      }
      return current;
   }
1301640
public BranchEvent setTransactionID(String transactionID) {
        return addStandardProperty(Defines.Jsonkey.TransactionID.getKey(), transactionID);
    }
450243
public void generatExecuteTransactionRx(ClassName dataSourceName, String daoFactory, RxType rxType) {
		String parameterName = "transaction";
		ParameterizedTypeName returnTypeName = ParameterizedTypeName.get(ClassName.get(rxType.clazz),
				TypeVariableName.get("T"));
		ParameterizedTypeName observableTypeName = ParameterizedTypeName.get(TypeUtility
				.className(rxType.clazz.getPackage().getName(), rxType.clazz.getSimpleName() + "OnSubscribe"),
				TypeVariableName.get("T"));
		ParameterizedTypeName emitterTypeName = ParameterizedTypeName.get(
				TypeUtility.className(rxType.clazz.getPackage().getName(), rxType.clazz.getSimpleName() + "Emitter"),
				TypeVariableName.get("T"));

		TypeSpec innerEmitter = TypeSpec.anonymousClassBuilder("").addSuperinterface(observableTypeName)
				.addMethod(MethodSpec.methodBuilder("subscribe").addAnnotation(Override.class)
						.addModifiers(Modifier.PUBLIC).addParameter(emitterTypeName, "emitter").returns(Void.TYPE)
						.addStatement("boolean needToOpened=!$L.this.isOpenInWriteMode()", dataSourceName.simpleName())
						.addStatement("boolean success=false").addCode("@SuppressWarnings(\"resource\")\n")
						.addStatement("$T connection=needToOpened ? openWritableDatabase() : database()",
								SQLiteDatabase.class)
						// support for live data
						.addStatement("$L currentDaoFactory=_daoFactorySingleThread.bindToThread()",
								DATA_SOURCE_SINGLE_THREAD_NAME)
						.addStatement("currentDaoFactory.onSessionOpened()")

						.beginControlFlow("try").addStatement("connection.beginTransaction()")
						.beginControlFlow(
								"if (transaction != null && $T.$L==transaction.onExecute(currentDaoFactory, emitter))",
								TransactionResult.class, TransactionResult.COMMIT)
						.addStatement("connection.setTransactionSuccessful()").addStatement("success=true")
						.endControlFlow().addStatement(rxType.onComplete ? "emitter.onComplete()" : "// no onComplete")

						.nextControlFlow("catch($T e)", Throwable.class)
						.addStatement("$T.error(e.getMessage())", Logger.class).addStatement("e.printStackTrace()")
						.addStatement("emitter.onError(e)")
						// support for live data
						.addStatement("currentDaoFactory.onSessionClear()").nextControlFlow("finally")
						.beginControlFlow("try").addStatement("connection.endTransaction()")
						.nextControlFlow("catch($T e)", Throwable.class).endControlFlow()
						.addCode("if (needToOpened) { close(); }\n")
						// support for live data
						.addCode(
								"if (success) { currentDaoFactory.onSessionClosed(); } else { currentDaoFactory.onSessionClear(); }\n")
						.endControlFlow().addStatement("return").build())
				.build();

		{
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC)
					.addTypeVariable(TypeVariableName.get("T"))
					.addParameter(
							ParameterizedTypeName.get(TypeUtility.className(dataSourceName.toString(),
									rxType.clazz.getSimpleName() + "Transaction"), TypeVariableName.get("T")),
							parameterName, Modifier.FINAL)
					.returns(returnTypeName);

			executeMethod.addStatement("$T emitter=$L", observableTypeName, innerEmitter);

			if (rxType == RxType.FLOWABLE) {
				executeMethod.addStatement("$T result=$T.create(emitter, $T.BUFFER)", returnTypeName, rxType.clazz,
						BackpressureStrategy.class);
			} else {
				executeMethod.addStatement("$T result=$T.create(emitter)", returnTypeName, rxType.clazz);
			}
			executeMethod.addStatement("if (globalSubscribeOn!=null) result.subscribeOn(globalSubscribeOn)");
			executeMethod.addStatement("if (globalObserveOn!=null) result.observeOn(globalObserveOn)");

			executeMethod.addStatement("return result");

			classBuilder.addMethod(executeMethod.build());
		}

	}
623796
@Override
	@Transactional(enabled = false)
	public CommerceAccountUserRel createCommerceAccountUserRel(
		CommerceAccountUserRelPK commerceAccountUserRelPK) {
		return commerceAccountUserRelPersistence.create(commerceAccountUserRelPK);
	}
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;
    }
893324
public void withVoidTransaction(@NotNull Isolation isolation, @NotNull VoidTransactionCallback callback) {
        withVoidTransaction(Propagation.REQUIRED, isolation, callback);
    }
659462
public TransactionContext createTransactionContext() {
    transactionContext = dataFabricFacade.createTransactionManager();
    for (TransactionAware transactionAware : transactionAwares) {
      this.transactionContext.addTransactionAware(transactionAware);
    }
    return transactionContext;
  }
435760
public void setOriginatingTransactionId(byte[] t) {
        if (t != null && t.length != 4)
            throw new IllegalArgumentException("TransactionId leng must be 4 bytes, found: " + t.length);
        this.originatingTransactionId = t;

    }
572107
public Transaction enterTop(IsolationLevel level) {
        mLock.lock();
        try {
            IsolationLevel actualLevel = mTxnMgr.selectIsolationLevel(null, level);
            if (actualLevel == null) {
                throw new UnsupportedOperationException
                    ("Desired isolation level not supported: " + level);
            }

            TransactionImpl<Txn> txn = new TransactionImpl<Txn>(this, mActive, true, actualLevel);
            mActive = txn;

            mTxnMgr.entered(txn, null);

            return txn;
        } finally {
            mLock.unlock();
        }
    }