Executes the modifying action in new transaction

@param txManager
transaction manager interface
@param transactionName
the name of the new transaction
@param action
the callback to execute in new tranaction

@return the result of the action
490835
public static <T> T runInNewTransaction(@NotNull final PlatformTransactionManager txManager,
            final String transactionName, @NotNull final TransactionCallback<T> action) {
        return runInNewTransaction(txManager, transactionName, Isolation.DEFAULT.value(), action);
    }
1089084
public void generateMethodExecuteTransaction(String daoFactory) {
		// create interface
		String transationExecutorName = "Transaction";
		// @formatter:off
		ParameterizedTypeName parameterizedTypeName = ParameterizedTypeName.get(className(AbstractExecutable.class),
				className(daoFactory));
		classBuilder.addType(TypeSpec.interfaceBuilder(transationExecutorName).addModifiers(Modifier.PUBLIC)
				.addSuperinterface(parameterizedTypeName).addJavadoc("Rapresents transational operation.\n")
				.addMethod(MethodSpec.methodBuilder("onExecute").addParameter(className(daoFactory), "daoFactory")
						.addJavadoc(
								"Execute transation. Method need to return {@link TransactionResult#COMMIT} to commit results\nor {@link TransactionResult#ROLLBACK} to rollback.")
						.addJavadoc("\nIf exception is thrown, a rollback will be done.")
						.addJavadoc("\n\n@param daoFactory\n@return\n@throws Throwable\n")
						.addModifiers(Modifier.PUBLIC, Modifier.ABSTRACT).returns(TransactionResult.class).build())
				.build());
		// @formatter:on

		{
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC)
					.returns(Boolean.TYPE).addParameter(className(transationExecutorName), "transaction");
			// generate javadoc
			executeMethod.addJavadoc(
					"<p>Executes a transaction. This method <strong>is thread safe</strong> to avoid concurrent problems. The "
							+ "drawback is only one transaction at time can be executed. The database will be open in write mode. This method uses default error listener to intercept errors.</p>\n");
			executeMethod.addJavadoc("\n");
			executeMethod.addJavadoc("@param transaction\n\ttransaction to execute\n");
			executeMethod.addJavadoc("@return <code>true</code> if transaction successful finished\n");

			executeMethod.addStatement("return execute(transaction, onErrorListener)");

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

		{
			MethodSpec.Builder executeMethod = MethodSpec.methodBuilder("execute").addModifiers(Modifier.PUBLIC)
					.addParameter(className(transationExecutorName), "transaction").returns(Boolean.TYPE)
					.addParameter(className(OnErrorListener.class), "onErrorListener");

			executeMethod.addStatement("boolean needToOpened=!this.isOpenInWriteMode()");
			executeMethod.addStatement("boolean success=false");
			executeMethod.addCode("@SuppressWarnings(\"resource\")\n");
			executeMethod.addStatement("$T connection=needToOpened ? openWritableDatabase() : database()",
					SQLiteDatabase.class);

			// support for live data
			executeMethod.addStatement("$L currentDaoFactory=_daoFactorySingleThread.bindToThread()",
					DATA_SOURCE_SINGLE_THREAD_NAME);
			executeMethod.addStatement("currentDaoFactory.onSessionOpened()");

			executeMethod.beginControlFlow("try");
			executeMethod.addCode("connection.beginTransaction();\n");

			executeMethod.beginControlFlow(
					"if (transaction!=null && $T.$L == transaction.onExecute(currentDaoFactory))",
					TransactionResult.class, TransactionResult.COMMIT);
			executeMethod.addStatement("connection.setTransactionSuccessful()");

			// support for live data
			executeMethod.addStatement("success=true");

			executeMethod.endControlFlow();
			executeMethod.nextControlFlow("catch($T e)", Throwable.class);

			executeMethod.addStatement("$T.error(e.getMessage())", Logger.class);
			executeMethod.addStatement("e.printStackTrace()");
			executeMethod.addStatement("if (onErrorListener!=null) onErrorListener.onError(e)");

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

			// generate javadoc
			executeMethod.addJavadoc(
					"<p>Executes a transaction. This method <strong>is thread safe</strong> to avoid concurrent problems. The "
							+ "drawback is only one transaction at time can be executed. The database will be open in write mode.</p>\n");
			executeMethod.addJavadoc("\n");
			executeMethod.addJavadoc("@param transaction\n\ttransaction to execute\n");
			executeMethod.addJavadoc("@param onErrorListener\n\terror listener\n");
			executeMethod.addJavadoc("@return <code>true</code> if transaction successful finished\n");

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

	}
1113363
@Override
    public TransactionManagerAdapter getTransactionManager(StepContext stepContext) throws TransactionManagementException {
        logger.entering(CLASSNAME, "getTransactionManager", stepContext);

        TransactionManagerAdapter transactionManager = null;

        // get the JTA tran manager if we are in Java EE
        if (! this.batchConfig.isJ2seMode()) {
            // use the container JNDI java:comp/UserTransaction
            logger.fine("getting transaction object from JNDI java:comp/UserTransaction");
            transactionManager = new JTAUserTransactionAdapter("java:comp/UserTransaction");
        } 
        else if (this.batchConfig.isJ2seMode()) { 
        // If we are in J2SE mode use the non-transactional manager
        
            // java environment is Java SE
            // NoOp transaction manager
            logger.fine("J2SE mode non-transactional manager");
            transactionManager = new DefaultNonTransactionalManager();
        }

        logger.exiting(CLASSNAME, "getTransactionManager", transactionManager);
        return transactionManager;
    }
77416
private StatementResult addCompany( final Transaction tx, final String name )
    {
        return tx.run( "CREATE (:Company {name: $name})", parameters( "name", name ) );
    }
681579
function ManagePendingTransactionStatus($txnID, $action) {
    if (!in_array($action, array('Accept', 'Deny'))) return FALSE;
    $values['TRANSACTIONID'] = $txnID;
    $values['ACTION'] = $action;
    return $this->_request($values, 'ManagePendingTransactionStatus');
  }
820907
private static IAction createAction(String action) {
        IAction actn = null;
        
        if (!StringUtils.isEmpty(action)) {
            if ((actn = ActionRegistry.getRegisteredAction(action)) == null) {
                actn = ActionUtil.createAction(null, action);
            }
        }
        
        return actn;
    }
824282
public Transaction findByTransactionId(String transactionId) {
        EntityManager entityManager = getEntityManager();
        try {
            return entityManager.createQuery("SELECT t FROM io.motown.operatorapi.viewmodel.persistence.entities.Transaction AS t WHERE t.transactionId = :transactionId", Transaction.class)
                    .setParameter("transactionId", transactionId)
                    .getSingleResult();
        } finally {
            entityManager.close();
        }
    }
373967
private StatementResult addPerson( final Transaction tx, final String name )
    {
        return tx.run( "CREATE (:Person {name: $name})", parameters( "name", name ) );
    }
94109
public function execute(TransactionData $transactionData, $argument = null)
    {
        $this->logger->debug('Searching matching expectation for request');
        $request = $transactionData->getRequest();
        $this->logger->info('Request received: ' . $this->getLoggableRequest($request));
        $foundExpectation = $this->searchForMatchingExpectation($request);
        if (null === $foundExpectation) {
            $transactionData->set('foundExpectation', false);

            return;
        }
        $transactionData->set('foundExpectation', $foundExpectation);
    }
1294441
public CreateTransactionResult createTransaction(
            final long connectionId,
            final long txnId,
            final long uniqueId,
            final StoredProcedureInvocation invocation,
            final boolean isReadOnly,
            final boolean isSinglePartition,
            final boolean isEveryPartition,
            final int partition,
            final int messageSize,
            long nowNanos,
            final boolean isForReplay)
    {
        return m_dispatcher.createTransaction(
                connectionId,
                txnId,
                uniqueId,
                invocation,
                isReadOnly,
                isSinglePartition,
                isEveryPartition,
                new int [] { partition },
                messageSize,
                nowNanos,
                isForReplay);
    }
1289412
@Override
    public TransactionManager newTransactionManager(Environment env) {
        return new JtaTransactionManager(
            env.get(EnvironmentName.TRANSACTION),
            env.get(EnvironmentName.TRANSACTION_SYNCHRONIZATION_REGISTRY),
            env.get(EnvironmentName.TRANSACTION_MANAGER ));
    }
220242
private int runTransactionalAssignment(final TargetFilterQuery targetFilterQuery, final Long dsId) {
        final String actionMessage = String.format(ACTION_MESSAGE, targetFilterQuery.getName());

        return DeploymentHelper.runInNewTransaction(transactionManager, "autoAssignDSToTargets",
                Isolation.READ_COMMITTED.value(), status -> {
                    final List<TargetWithActionType> targets = getTargetsWithActionType(targetFilterQuery.getQuery(),
                            dsId, targetFilterQuery.getAutoAssignActionType(), PAGE_SIZE);
                    final int count = targets.size();
                    if (count > 0) {
                        deploymentManagement.assignDistributionSet(dsId, targets, actionMessage);
                    }
                    return count;
                });
    }
399341
public MultiTransactionStatus getTransaction(TransactionDefinition definition) throws TransactionException {

		MultiTransactionStatus mts = new MultiTransactionStatus(transactionManagers.get(0));

		if (!synchronizationManager.isSynchronizationActive() && canCreateTransaction(definition)) {
			synchronizationManager.initSynchronization();
			mts.setNewSynchronization();
		}

		try {

			for (PlatformTransactionManager transactionManager : transactionManagers) {
				mts.registerTransactionManager(definition, transactionManager);
			}

		} catch (Exception ex) {

			Map<PlatformTransactionManager, TransactionStatus> transactionStatuses = mts.getTransactionStatuses();

			for (PlatformTransactionManager transactionManager : transactionManagers) {
				try {
					if (transactionStatuses.get(transactionManager) != null) {
						transactionManager.rollback(transactionStatuses.get(transactionManager));
					}
				} catch (Exception ex2) {
					LOGGER.warn("Rollback exception (" + transactionManager + ") " + ex2.getMessage(), ex2);
				}
			}

			if (mts.isNewSynchronization()) {
				synchronizationManager.clearSynchronization();
			}

			throw new CannotCreateTransactionException(ex.getMessage(), ex);
		}

		return mts;
	}
88084
public <T> T doInTransaction(final SpecificTxAction<T, C> action) {
        return doInTransaction(null, action);
    }
677274
private void completeCommittingTransaction(TransactionId transactionId) {
    // Change ownership of the transaction to the local node and then commit it.
    completeTransaction(
        transactionId,
        TransactionState.COMMITTING,
        info -> new TransactionInfo(localMemberId, TransactionState.COMMITTING, info.participants),
        info -> info.state == TransactionState.COMMITTING && info.coordinator.equals(localMemberId),
        (id, transactional) -> transactional.commit(id))
        .whenComplete((result, error) -> {
          if (error != null) {
            error = Throwables.getRootCause(error);
            if (error instanceof TransactionException) {
              LOGGER.warn("Failed to complete transaction", error);
            } else {
              LOGGER.warn("Failed to commit transaction " + transactionId);
            }
          }
        });
  }
193991
private void completeTransaction(final String txId, String wsName) {
        getWorkspace().clear();
        // reset the ws cache to the shared (global one)
        setWorkspaceCache(sharedWorkspaceCache());
        // and clear some tx specific data
        COMPLETE_FUNCTION_BY_TX_AND_WS.compute(txId, (transactionId, funcsByWsName) -> {
            funcsByWsName.remove(wsName);
            if (funcsByWsName.isEmpty()) {
                // this is the last ws cache we are clearing for this tx so mark all the keys as unlocked
                LOCKED_KEYS_BY_TX_ID.remove(txId);
                // and remove the map 
                return null;                
            }
            // there are other ws caches which need clearing for this tx, so just return the updated map
            return funcsByWsName;
        });  
    }
616809
public Response sendTransaction(Transaction tx) {
        if (this.peers.isEmpty()) {
            throw new NoValidPeerException(String.format("chain %s has no peers", getName()));
        }

        for(Peer peer : peers) {
            try {
                return peer.sendTransaction(tx);
            } catch (PeerException exp) {
                logger.info(String.format("Failed sending transaction to peer:%s", exp.getMessage()));
            }
        }

        throw new RuntimeException("No peer available to respond");
    }