/*
TODO: add in alpha06
@Context
ProcedureTransaction procedureTransaction;
171885
@Procedure
    @Description("apoc.cypher.run(fragment, params) yield value - executes reading fragment with the given parameters")
    public Stream<MapResult> run(@Name("cypher") String statement, @Name("params") Map<String, Object> params) {
        if (params == null) params = Collections.emptyMap();
        return db.execute(withParamMapping(statement, params.keySet()), params).stream().map(MapResult::new);
    }
1117754
private TransactionalType getTransactionalType(FQMethod method) {
        TransactionalType type = transactionalMethods.get(method);
        if (type == null) {
            return TransactionalType.NONE;
        }

        return type;
    }
1327279
public void withVoidTransaction(@NotNull TransactionSettings settings,
                                    @NotNull VoidTransactionCallback callback) {
        withTransaction(settings, fromVoidCallback(callback));
    }
1348188
protected <T> T processCheckRowCountError(Transaction t, Exception root, Throwable e, TxCallable<T> process) throws Exception {
        if (e == null) {
            throw root;
        }
        if (e instanceof OptimisticLockException) {
            if ("checkRowCount".equals(e.getStackTrace()[0].getMethodName())) {
                if (process != null)
                    return process.call(t);
            }
        }
        return processCheckRowCountError(t, root, e.getCause(), process);
    }
873390
@Override
	public boolean doProcedure(final SqlContext sqlContext, final CallableStatement callableStatement,
			final boolean result) throws SQLException {
		if (getFilters().isEmpty()) {
			return result;
		}
		boolean rs = result;
		for (final SqlFilter filter : getFilters()) {
			rs = filter.doProcedure(sqlContext, callableStatement, rs);
		}
		return rs;
	}
817244
StatementDMQL compileCallStatement(RangeVariable[] outerRanges,
                                       boolean isStrictlyProcedure) {

        read();

        if (isIdentifier()) {
            checkValidCatalogName(token.namePrePrefix);

            RoutineSchema routineSchema =
                (RoutineSchema) database.schemaManager.findSchemaObject(
                    token.tokenString,
                    session.getSchemaName(token.namePrefix),
                    SchemaObject.PROCEDURE);

            if (routineSchema != null) {
                read();

                HsqlArrayList list = new HsqlArrayList();

                readThis(Tokens.OPENBRACKET);

                if (token.tokenType == Tokens.CLOSEBRACKET) {
                    read();
                } else {
                    while (true) {
                        Expression e = XreadValueExpression();

                        list.add(e);

                        if (token.tokenType == Tokens.COMMA) {
                            read();
                        } else {
                            readThis(Tokens.CLOSEBRACKET);

                            break;
                        }
                    }
                }

                Expression[] arguments = new Expression[list.size()];

                list.toArray(arguments);

                Routine routine =
                    routineSchema.getSpecificRoutine(arguments.length);
                HsqlList unresolved = null;

                for (int i = 0; i < arguments.length; i++) {
                    Expression e = arguments[i];

                    if (e.isParam()) {
                        e.setAttributesAsColumn(
                            routine.getParameter(i),
                            routine.getParameter(i).isWriteable());
                    } else {
                        int paramMode =
                            routine.getParameter(i).getParameterMode();

                        unresolved =
                            arguments[i].resolveColumnReferences(outerRanges,
                                unresolved);

                        if (paramMode
                                != SchemaObject.ParameterModes.PARAM_IN) {
                            if (e.getType() != OpTypes.VARIABLE) {
                                throw Error.error(ErrorCode.X_42603);
                            }
                        }
                    }
                }

                ExpressionColumn.checkColumnsResolved(unresolved);

                for (int i = 0; i < arguments.length; i++) {
                    arguments[i].resolveTypes(session, null);
                }

                StatementDMQL cs = new StatementProcedure(session, routine,
                    arguments, compileContext);

                return cs;
            }
        }

        if (isStrictlyProcedure) {
            throw Error.error(ErrorCode.X_42501, token.tokenString);
        }

        Expression expression = this.XreadValueExpression();
        HsqlList unresolved = expression.resolveColumnReferences(outerRanges,
            null);

        ExpressionColumn.checkColumnsResolved(unresolved);
        expression.resolveTypes(session, null);

//        expression.paramMode = PARAM_OUT;
        StatementDMQL cs = new StatementProcedure(session, expression,
            compileContext);

        return cs;
    }
11980
public void processTransactionTerminated(
            TransactionTerminatedEvent transactionTerminatedEvent) {
        Transaction transaction = null;
        if(transactionTerminatedEvent.isServerTransaction()) {
            transaction = transactionTerminatedEvent.getServerTransaction();
            if(logger.isDebugEnabled()) {
                logger.debug("timeout => " + transaction.getRequest().toString());
            }
        } else {
            transaction = transactionTerminatedEvent.getClientTransaction();
            if(logger.isDebugEnabled()) {
                logger.debug("timeout => " + transaction.getRequest().toString());
            }
        }
        if(Request.BYE.equals(transaction.getRequest().getMethod())) {
            String callId = ((CallIdHeader)transaction.getRequest().getHeader(CallIdHeader.NAME)).getCallId();
            register.unStickSessionFromNode(callId);
        }
    }
1272786
@Override
    public int doStartTag() throws JspException {

        if ((rawDataSource == null) && dataSourceSpecified) {
            throw new JspException(
                    Resources.getMessage("SQL_DATASOURCE_NULL"));
        }

        DataSource dataSource = DataSourceUtil.getDataSource(rawDataSource,
                pageContext);

        try {
            conn = dataSource.getConnection();
            origIsolation = conn.getTransactionIsolation();
            if (origIsolation == Connection.TRANSACTION_NONE) {
                throw new JspTagException(
                        Resources.getMessage("TRANSACTION_NO_SUPPORT"));
            }
            if ((isolation != Connection.TRANSACTION_NONE)
                    && (isolation != origIsolation)) {
                conn.setTransactionIsolation(isolation);
            }
            conn.setAutoCommit(false);
        } catch (SQLException e) {
            throw new JspTagException(
                    Resources.getMessage("ERROR_GET_CONNECTION",
                            e.toString()), e);
        }

        return EVAL_BODY_INCLUDE;
    }
1105678
public void doCBAComplexityFromTransaction(final UUID invoiceId,
                                               final List<Tag> invoicesTags,
                                               final EntitySqlDaoWrapperFactory entitySqlDaoWrapperFactory,
                                               final InternalCallContext context) throws EntityPersistenceException, InvoiceApiException {
        final InvoiceSqlDao transInvoiceDao = entitySqlDaoWrapperFactory.become(InvoiceSqlDao.class);
        final InvoiceModelDao invoice = transInvoiceDao.getById(invoiceId.toString(), context);
        invoiceDaoHelper.populateChildren(invoice, invoicesTags, entitySqlDaoWrapperFactory, context);

        doCBAComplexityFromTransaction(invoice, invoicesTags, entitySqlDaoWrapperFactory, context);
    }
1242733
@Override
    public String buildStoredProcedureQuery(String name, int paramsCount) {
        StringBuilder sb = new StringBuilder("SELECT * FROM ");
        sb.append(name);
        sb.append("(");
        for (int i = 0; i < paramsCount; i++) {
            sb.append("?,");
        }
        if (paramsCount > 0) {
            sb.setLength(sb.length() - 1);
        }
        sb.append(")");

        return sb.toString();
    }
1219201
@Override
    public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException
    {
        assert(procedureNamePattern != null && !procedureNamePattern.isEmpty());
        checkClosed();
        this.sysCatalog.setString(1, "PROCEDURECOLUMNS");
        JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery();
        VoltTable vtable = res.getVoltTable().clone(0);

        // Filter the results based on procedure name and column name
        while (res.next()) {
            if (res.getString("PROCEDURE_NAME").equals(procedureNamePattern)) {
                if (columnNamePattern == null || columnNamePattern.equals("%") ||
                    res.getString("COLUMN_NAME").equals(columnNamePattern)) {
                    vtable.addRow(res.getRowData());
                }
            }
        }

        return new JDBC4ResultSet(sysCatalog, vtable);
    }
857534
@FFDCIgnore(NoSuchMethodException.class)
    private void setRRSTransactional() {
        try {
            ivRRSTransactional = (Boolean) activationSpec.getClass().getMethod("getRRSTransactional").invoke(activationSpec);
        } catch (NoSuchMethodException x) {
            ivRRSTransactional = false;
        } catch (Exception x) {
            ivRRSTransactional = x == null; // always false - avoid a FindBugs warning by using the value of x in some trivial way
        }
    }
151656
function _logTransaction($operation, $elapsed, $response, $errors) {
    $values = $this->_parseNameValueList($response);
    $token = isset($values['TOKEN']) ? $values['TOKEN'] : '';
    $token = preg_replace('/[^0-9.A-Z\-]/', '', urldecode($token));
    $success = false;
    if ($response) {
      if ((isset($values['RESULT']) && $values['RESULT'] == 0) || (isset($values['ACK']) && (strstr($values['ACK'],'Success') || strstr($values['ACK'],'SuccessWithWarning')) && !strstr($values['ACK'],'Failure'))) {
        $success = true;
      }
    }
    $message =   date('Y-m-d h:i:s') . "\n-------------------\n";
    $message .=  '(' . $this->_server . ' transaction) --> ' . $this->_endpoints[$this->_server] . "\n";
    $message .= 'Request Headers: ' . "\n" . $this->_sanitizeLog($this->lastHeaders) . "\n\n";
    $message .= 'Request Parameters: {' . $operation . '} ' . "\n" . urldecode($this->_sanitizeLog($this->_parseNameValueList($this->lastParamList))) . "\n\n";
    $message .= 'Response: ' . "\n" . urldecode($this->_sanitizeLog($values)) . $errors;

    if ($this->_logLevel > 0 || $success == FALSE) {
      $this->log($message, $token);
      // extra debug email: //
      if (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log and Email') {
        zen_mail(STORE_NAME, STORE_OWNER_EMAIL_ADDRESS, 'PayPal Debug log - ' . $operation, $message, STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, array('EMAIL_MESSAGE_HTML'=>nl2br($message)), 'debug');
      }
      $this->log($operation . ', Elapsed: ' . $elapsed . 'ms -- ' . (isset($values['ACK']) ? $values['ACK'] : ($success ? 'Succeeded' : 'Failed')) . $errors, $token);

      if (!$response) {
        $this->log('No response from server' . $errors, $token);
      } else {
        if ((isset($values['RESULT']) && $values['RESULT'] != 0) || strstr($values['ACK'],'Failure')) {
          $this->log($response . $errors, $token);
        }
      }
    }
  }
51053
StatementSchema compileCreateProcedureOrFunction() {

        int routineType = token.tokenType == Tokens.PROCEDURE
                          ? SchemaObject.PROCEDURE
                          : SchemaObject.FUNCTION;
        HsqlName name;

        read();

        name = readNewSchemaObjectNameNoCheck(routineType);

        Routine routine = new Routine(routineType);

        routine.setName(name);
        readThis(Tokens.OPENBRACKET);

        if (token.tokenType == Tokens.CLOSEBRACKET) {
            read();
        } else {
            while (true) {
                ColumnSchema newcolumn = readRoutineParameter(routine);

                routine.addParameter(newcolumn);

                if (token.tokenType == Tokens.COMMA) {
                    read();
                } else {
                    readThis(Tokens.CLOSEBRACKET);

                    break;
                }
            }
        }

        if (routineType != SchemaObject.PROCEDURE) {
            readThis(Tokens.RETURNS);

            if (token.tokenType == Tokens.TABLE) {
                read();

                TableDerived table =
                    new TableDerived(database, name, TableBase.FUNCTION_TABLE);

                readThis(Tokens.OPENBRACKET);

                if (token.tokenType == Tokens.CLOSEBRACKET) {
                    read();
                } else {
                    while (true) {
                        ColumnSchema newcolumn = readRoutineParameter(routine);

                        table.addColumn(newcolumn);

                        if (token.tokenType == Tokens.COMMA) {
                            read();
                        } else {
                            readThis(Tokens.CLOSEBRACKET);

                            break;
                        }
                    }
                }

                routine.setReturnTable(table);
            } else {
                Type type = readTypeDefinition(true);

                routine.setReturnType(type);
            }
        }

        readRoutineCharacteristics(routine);

        if (token.tokenType == Tokens.EXTERNAL) {
            if (routine.getLanguage() != Routine.LANGUAGE_JAVA) {
                throw unexpectedToken();
            }

            read();
            readThis(Tokens.NAME);
            checkIsValue(Types.SQL_CHAR);
            routine.setMethodURL((String) token.tokenValue);
            read();

            if (token.tokenType == Tokens.PARAMETER) {
                read();
                readThis(Tokens.STYLE);
                readThis(Tokens.JAVA);
            }
        } else {
            startRecording();

            Statement statement = readSQLProcedureStatementOrNull(routine,
                null);
            Token[] tokenList = getRecordedStatement();
            String  sql       = Token.getSQL(tokenList);

            statement.setSQL(sql);
            routine.setProcedure(statement);
        }

        Object[] args = new Object[]{ routine };
        String   sql  = getLastPart();
        StatementSchema cs = new StatementSchema(sql,
            StatementTypes.CREATE_ROUTINE, args, null, null);

        return cs;
    }
651859
@Pure
	public static <P1> Procedure0 curry(final Procedure1<? super P1> procedure, final P1 argument) {
		if (procedure == null)
			throw new NullPointerException("procedure");
		return new Procedure0() {
			@Override
			public void apply() {
				procedure.apply(argument);
			}
		};
	}
1347356
final void localTransactionStarted() {

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

        final ConnectionEvent event = new ConnectionEvent(this,
                        ConnectionEvent.LOCAL_TRANSACTION_STARTED);

        // Copy list to protect against concurrent modification by listener

        final List<ConnectionEventListener> copy;
        synchronized (_connectionListeners) {
            copy = new ArrayList<ConnectionEventListener>(_connectionListeners);
        }

        for (final Iterator iterator = copy.iterator(); iterator.hasNext();) {
            final Object object = iterator.next();
            if (object instanceof ConnectionEventListener) {
                ((ConnectionEventListener) object)
                                .localTransactionStarted(event);
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && TRACE.isEntryEnabled()) {
            SibTr.exit(this, TRACE, "localTransactionStarted");
        }

    }
162973
private function _buildTransaction($action, HpsCheck $check, $amount, $clientTransactionId = null)
    {
        $amount = HpsInputValidation::checkAmount($amount);

        if ($check->secCode == HpsSECCode::CCD &&
            ($check->checkHolder == null || $check->checkHolder->checkName == null)) {
            throw new HpsInvalidRequestException(
                HpsExceptionCodes::MISSING_CHECK_NAME,
                'For SEC code CCD, the check name is required',
                'check_name'
            );
        }

        $xml = new DOMDocument();
        $hpsTransaction = $xml->createElement('hps:Transaction');
        $hpsCheckSale = $xml->createElement('hps:CheckSale');
        $hpsBlock1 = $xml->createElement('hps:Block1');

        $hpsBlock1->appendChild($xml->createElement('hps:Amt', sprintf("%0.2f", round($amount, 3))));
        $hpsBlock1->appendChild($this->_hydrateCheckData($check, $xml));
        $hpsBlock1->appendChild($xml->createElement('hps:CheckAction', $action));
        $hpsBlock1->appendChild($xml->createElement('hps:SECCode', $check->secCode));
        if ($check->checkType != null) {
            $hpsBlock1->appendChild($xml->createElement('hps:CheckType', $check->checkType));
        }
        $hpsBlock1->appendChild($xml->createElement('hps:DataEntryMode', $check->dataEntryMode));
        if ($check->checkHolder != null) {
            $hpsBlock1->appendChild($this->_hydrateConsumerInfo($check, $xml));
        }

        $hpsCheckSale->appendChild($hpsBlock1);
        $hpsTransaction->appendChild($hpsCheckSale);

        return $this->_submitTransaction($hpsTransaction, 'CheckSale', $clientTransactionId);
    }