Play back a transaction
@param oldReplayLog
@return map + result
@throws SQLException
545922
private TransactionRecoveryResult attemptRecovery(List<ReplayLog> oldReplayLog) throws SQLException{
		boolean tryAgain = false;
		Throwable failedThrowable = null;

		ConnectionHandle con = this.connectionHandle.get();
		if (con == null){ // safety! 
			throw PoolUtil.generateSQLException("ConnectionHandle is gone!", new IllegalStateException());
		}
		TransactionRecoveryResult recoveryResult = con.recoveryResult;
		ConnectionHook connectionHook = con.getPool().getConfig().getConnectionHook();

		int acquireRetryAttempts = con.getPool().getConfig().getAcquireRetryAttempts();
		long acquireRetryDelay = con.getPool().getConfig().getAcquireRetryDelayInMs();
		AcquireFailConfig acquireConfig = new AcquireFailConfig();
		acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts));
		acquireConfig.setAcquireRetryDelayInMs(acquireRetryDelay);
		acquireConfig.setLogMessage("Failed to replay transaction");

		Map<Object, Object> replaceTarget = new HashMap<Object, Object>();
		do{
			replaceTarget.clear(); 
			// make a copy
			for (Entry<Object, Object> entry: recoveryResult.getReplaceTarget().entrySet()){
				replaceTarget.put(entry.getKey(), entry.getValue());
			}

			List<PreparedStatement> prepStatementTarget = new ArrayList<PreparedStatement>();
			List<CallableStatement> callableStatementTarget = new ArrayList<CallableStatement>();
			List<Statement> statementTarget = new ArrayList<Statement>();
			Object result = null;
			tryAgain = false;
			// this connection is dead
			con.setInReplayMode(true); // don't go in a loop of saving our saved log!
			try{
				con.clearStatementCaches(true);
				con.getInternalConnection().close();
			} catch(Throwable t){
				// do nothing - also likely to fail here
			}
			try{
				con.setInternalConnection(memorize(con.getPool().obtainInternalConnection(con), con));
			} catch(SQLException e){
				throw con.markPossiblyBroken(e);
			}

			con.getOriginatingPartition().trackConnectionFinalizer(con); // track this too.

			for (ReplayLog replay: oldReplayLog){

				// we got new connections/statement handles so replace what we've got with the new ones
				if (replay.getTarget() instanceof Connection){
					replaceTarget.put(replay.getTarget(), con.getInternalConnection());
				}  else if (replay.getTarget() instanceof CallableStatement){
					if (replaceTarget.get(replay.getTarget()) == null){
						replaceTarget.put(replay.getTarget(), callableStatementTarget.remove(0));
					}
				} else if (replay.getTarget() instanceof PreparedStatement){
					if (replaceTarget.get(replay.getTarget()) == null){
						replaceTarget.put(replay.getTarget(), prepStatementTarget.remove(0));
					}
				}else if (replay.getTarget() instanceof Statement){
					if (replaceTarget.get(replay.getTarget()) == null){
						replaceTarget.put(replay.getTarget(), statementTarget.remove(0));
					}
				}


				try {
					// run again using the new connection/statement
					//					result = replay.getMethod().invoke(, replay.getArgs());
					result = runWithPossibleProxySwap(replay.getMethod(), replaceTarget.get(replay.getTarget()), replay.getArgs());

					// remember what we've got last 
					recoveryResult.setResult(result);

					// if we got a new statement (eg a prepareStatement call), save it, we'll use it for our search/replace
					if (result instanceof CallableStatement){
						callableStatementTarget.add((CallableStatement)result);
					} else if (result instanceof PreparedStatement){
						prepStatementTarget.add((PreparedStatement)result);
					} else if (result instanceof Statement){
						statementTarget.add((Statement)result);
					}  
				} catch (Throwable t) {
					// It blew up again, let's try a couple more times before giving up...
					// call the hook, if available.
					if (connectionHook != null){
						tryAgain = connectionHook.onAcquireFail(t, acquireConfig);
					} else {

						logger.error("Failed to replay transaction. Sleeping for "+acquireRetryDelay+"ms and trying again. Attempts left: "+acquireRetryAttempts+". Exception: "+t.getCause() + " Message:"+t.getMessage());

						try {
							Thread.sleep(acquireRetryDelay);
							if (acquireRetryAttempts > 0){
								tryAgain = (--acquireRetryAttempts) != 0;
							}
						} catch (InterruptedException e) {
							tryAgain=false;
						}
					}
					if (!tryAgain){
						failedThrowable = t;
					}
					break;
				}
			}
		} while (tryAgain);

		// fill last successful results
		for (Entry<Object, Object> entry: replaceTarget.entrySet()){
			recoveryResult.getReplaceTarget().put(entry.getKey(), entry.getValue());
		}

		for (ReplayLog replay: oldReplayLog){
			replay.setTarget(replaceTarget.get(replay.getTarget())); // fix our log
		}

		if (failedThrowable != null){
			throw PoolUtil.generateSQLException(failedThrowable.getMessage(), failedThrowable);
		}


		return recoveryResult;
	}
943999
@Override
    public void recover() {

        // not revoverable
        if (this.getCoreConnection() == null || !ImplementorUtils.isImplementationOf(getCoreConnection(), IXADataRecorderAware.class)) {
            return;
        }

        IXADataRecorderAware con = ImplementorUtils.cast(getCoreConnection(), IXADataRecorderAware.class);

        // the connection has to re establish the state of the message LOG
        IXADataRecorder msgLogger = this.getXADataRecorder();
        if (msgLogger.isEmpty()) {
            return;
        }
        this.fireConnectionRecovering();
        IDataRecordReplay dataRecordReplay = con.recoverReplayListener();

        if( dataRecordReplay==null) {
            throw new IllegalStateException("IPhynixxConnection.recoverReplayListener() has to provide a IDataRecordReplay to be recovered");
        }

        // msgLogger.recover();
        msgLogger.replayRecords(dataRecordReplay);

        this.fireConnectionRecovered();

    }
565550
protected final <T> T executeQuery(final String sql, final StatementWithReturnBlock<T> queryBlock) throws Exception {
        checkState(initialized);

        setupConnection();
        checkNotNull(connection);
        boolean committed = false;
        try {
            T returnValue = withStatement(connection, sql, queryBlock);
            connection.commit();
            committed = true;
            return returnValue;
        } finally {
            if (!committed) {
                connection.rollback();
                cleanupConnection();
            }
        }
    }
28198
public function replayTransactionLog($fromDate=null, $toDate=null)
    {

        $cursor = $this->getTransactionLog()->getCompletedTransactions($this->storeName, $this->podName, $fromDate, $toDate);
        foreach($cursor as $result)
        {
            $this->applyTransaction($result);
        }

        return true;
    }
240988
public void reconnect() throws SQLException {
    SearchFilter filter;
    boolean inTransaction = false;
    if (currentReadOnlyAsked) {
      filter = new SearchFilter(true, true);
    } else {
      inTransaction = masterProtocol != null && masterProtocol.inTransaction();
      filter = new SearchFilter(true, urlParser.getOptions().failOnReadOnly);
    }
    reconnectFailedConnection(filter);
    handleFailLoop();
    if (inTransaction) {
      throw new ReconnectDuringTransactionException(
          "Connection reconnect automatically during an active transaction", 1401, "25S03");
    }
  }
1234924
@Deprecated
    @Override
    public SQLTransaction beginTransaction(IsolationLevel isolationLevel, boolean forUpdateOnly) {
        return super.beginTransaction(isolationLevel, forUpdateOnly);
    }
1360655
public void rollbackTransaction() throws HibernateException
    {
        Transaction tx = threadTransaction.get();
        try
        {
            threadTransaction.set(null);
            if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack())
            {
                tx.rollback();
            }
        }
        finally
        {
            closeSession();
        }
    }
630364
private static <T> Observable<Boolean> commitOrRollbackOnNext(final boolean isCommit,
            final Database db, Observable<T> source) {
        return source.concatMap(new Func1<T, Observable<Boolean>>() {
            @Override
            public Observable<Boolean> call(T t) {
                if (isCommit)
                    return db.commit();
                else
                    return db.rollback();
            }
        });
    }
553641
private Blog blogFromResultSet(final ResultSet rs) throws SQLException {

      long registeredTimestamp = 0L;
      long lastUpdatedTimestamp = 0L;

      try {
         registeredTimestamp = rs.getTimestamp(5).getTime();
      } catch(SQLException se) {
         //Deal with possible java.sql.SQLException: Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp
         registeredTimestamp = 0L;
      }

      try {
         lastUpdatedTimestamp = rs.getTimestamp(6).getTime();
      } catch(SQLException se) {
         //Deal with possible java.sql.SQLException: Value '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp
         lastUpdatedTimestamp = 0L;
      }

      return new Blog(rs.getLong(1), rs.getLong(2), rs.getString(3), rs.getString(4), registeredTimestamp, lastUpdatedTimestamp);
   }
610923
public int executeRefresh(DatabaseConnection databaseConnection, T data, ObjectCache objectCache)
			throws SQLException {
		@SuppressWarnings("unchecked")
		ID id = (ID) idField.extractJavaFieldValue(data);
		// we don't care about the cache here
		T result = super.execute(databaseConnection, id, null);
		if (result == null) {
			return 0;
		}
		// copy each field from the result into the passed in object
		for (FieldType fieldType : resultsFieldTypes) {
			if (fieldType != idField) {
				fieldType.assignField(connectionSource, data, fieldType.extractJavaFieldValue(result), false,
						objectCache);
			}
		}
		return 1;
	}
135156
public DomainQuery replayQuery(RecordedQuery recordedQuery, IDomainAccess domainAccess) {
		Boolean br_old = null;
		DomainQuery query;
		try {
			if (!Settings.TEST_MODE) {
				br_old = QueryRecorder.blockRecording.get();
				if (this.createNew)
					QueryRecorder.blockRecording.set(Boolean.FALSE);
				else
					QueryRecorder.blockRecording.set(Boolean.TRUE);
			}
			this.generic = false;
			this.replayedQueryContext = new ReplayedQueryContext(recordedQuery);
			query = ((IIntDomainAccess)domainAccess).getInternalDomainAccess().createRecordedQuery(this.replayedQueryContext,
					this.createNew); // do record
			this.id2ObjectMap.put(QueryRecorder.QUERY_ID, query);
			
			for (Statement stmt : recordedQuery.getStatements()) {
				replayStatement(stmt);
			}
			Map<String, Parameter> params = recordedQuery.getParameters();
			if (params != null) {
				QueryExecutor qe = InternalAccess.getQueryExecutor(query);
				Iterator<Parameter> pit = params.values().iterator();
				while(pit.hasNext()) {
					Parameter param = pit.next();
					qe.addParameter(param);
				}
			}
		} finally {
			if (!Settings.TEST_MODE)
				QueryRecorder.blockRecording.set(br_old);
		}
		
		return query;
	}
275373
public PlaybackState getFurthestPlaybackState() {
        PlaybackState result = null;
        for (PlaybackState state : playbackStateMap.values()) {
            if (result == null || result.position < state.position) {
                result = state;
            }
        }
        return result;
    }
1143197
public void restoreOldProperties(Map<String,String> oldProperties, Record record)
    {
        this.restoreOldProperty(oldProperties, record.getDatabaseName() + BaseDatabase.DBSHARED_PARAM_SUFFIX);
        this.restoreOldProperty(oldProperties, record.getDatabaseName() + BaseDatabase.DBUSER_PARAM_SUFFIX);
        this.restoreOldProperty(oldProperties, DBConstants.DB_USER_PREFIX);
        this.restoreOldProperty(oldProperties, DBConstants.SYSTEM_NAME);
        this.restoreOldProperty(oldProperties, DBParams.LANGUAGE);
    }
289298
private void seekToCurrentPlayback() {
        if (engine.isPullMode()) {
            try {
                // TODO: figure out if this is the correct position to seek to
                final long delta = System.currentTimeMillis() - engine.getPlaybackStart();
                engine.seek((int) delta);
            } catch (OperationNotSupportedException err) {
                // Ignore error, should not happen for pullMode engines
            }
        }
    }
986408
public synchronized void playMethodCalls(Memento memento, String [] savePoints)
   {
	String savePoint = null;
	
	MethodCallFact methodCallFact = null;
	SummaryException exceptions = new SummaryException();
	
	//loop thru savepoints
	for (int i = 0; i < savePoints.length; i++)
	{
	   savePoint = savePoints[i];
	   
	   if(savePoint == null || savePoint.length() == 0 || savePoint.trim().length() == 0)
		continue;
	   
	   Debugger.println(this,"processing savepoint="+savePoint);
	   
	   //get method call fact
	   methodCallFact = (MethodCallFact)memento.restore(savePoint, MethodCallFact.class);
	   try
	   {
		ObjectProxy.executeMethod(prepareObject(methodCallFact,savePoint), methodCallFact);
	   }
	   catch(Exception e)
	   {
		exceptions.addException(new SystemException("savePoint="+savePoint+" methodCallFact="+methodCallFact+" exception="+Debugger.stackTrace(e)));
		throw new SystemException(e); // TODO: 
	   }
	}
	
	if(!exceptions.isEmpty())
	   throw exceptions;
   }
1067
@Override
    public synchronized int executeUpdate(final Expression query) throws DatabaseEngineException {
        /*
         * Reconnection is already assured by "void executeUpdate(final String query)".
         */
        final String trans = translate(query);
        logger.trace(trans);
        return executeUpdate(trans);
    }
247318
@Deprecated
    @Override
    @SuppressWarnings("deprecation")
    protected void rollbackRuntime(OperationContext context, ModelNode operation, ModelNode model, List<ServiceController<?>> controllers) {
        revertReload(context);
    }