Method called when a new secondary connection is found after a fallback.

@param newSecondaryProtocol the new active connection
@throws SQLException if switch failed
345850
public void foundActiveSecondary(Protocol newSecondaryProtocol) throws SQLException {
    if (isSecondaryHostFail()) {
      if (isExplicitClosed()) {
        newSecondaryProtocol.close();
        return;
      }

      if (proxy.lock.tryLock()) {
        try {
          lockAndSwitchSecondary(newSecondaryProtocol);
        } finally {
          proxy.lock.unlock();
        }
      } else {
        if (!waitNewSecondaryProtocol.compareAndSet(null, newSecondaryProtocol)) {
          newSecondaryProtocol.close();
        }
      }
    } else {
      newSecondaryProtocol.close();
    }
  }
789317
@Override
	public void rollback() {
		if (conn != null) {
			try {
				conn.rollback();
			} catch (SQLException e) {
				throw new UroborosqlSQLException(e);
			}
		}
	}
946786
protected void reConnectAsync(IOException originalExcep) {
        setAllowReconnect(false);
        this.reconnecting = true;
        this.reconnectException = originalExcep;
        connectAsynch(getTargetAddress());
    }
319547
protected void closeConnection() throws SQLException {
        if (connection != null && !connection.isClosed()) {
            connection.close();
            connection = null;
        }

    }
1130137
public void reconnect() throws SQLException {
    try {
      listener.reconnect();
    } catch (SQLException e) {
      ExceptionMapper.throwException(e, null, null);
    }
  }
1258260
public void processConnectionClosedEvent(WSJdbcConnection handle) 
    throws ResourceException {
        //A connection handle was closed - must notify the connection manager
        // of the close on the handle.  JDBC connection handles
        // which are closed are not allowed to be reused because there is no
        // guarantee that the user will not try to reuse an already closed JDBC handle.

        // Only send the event if the application is requesting the close. 
        if (cleaningUpHandles)
            return;

        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();

        // Fill in the ConnectionEvent only if needed. 
        connEvent.recycle(ConnectionEvent.CONNECTION_CLOSED, null, handle);

        if (isTraceOn && tc.isEventEnabled())
            Tr.event(this, tc, "Firing CONNECTION CLOSED", handle);

        try {
            removeHandle(handle); 

            // - Remove resetting autocommit in connection close time
        } catch (NullPointerException nullX) {
            // No FFDC code needed.  ManagedConnection is already closed.

            // A ConnectionError situation may
            // trigger a ManagedConnection close before the handle sends the ConnectionClosed
            // event.  When the event is sent the ManagedConnection is already closed.  If so,
            // just do a no-op here.
            if (handlesInUse == null) {
                if (isTraceOn && tc.isEventEnabled())
                    Tr.event(this, tc, "ManagedConnection already closed"); 
                return;
            } else
                throw nullX;
        }

        if (numHandlesInUse == 0) 
        {
            if (haveVendorConnectionPropertiesChanged) {
                try {

                    helper.doConnectionVendorPropertyReset(this.sqlConn, CONNECTION_VENDOR_DEFAULT_PROPERTIES);
                } catch (SQLException sqle) {
                    FFDCFilter.processException(sqle, getClass().getName(), "1905", this);
                    throw new DataStoreAdapterException("DSA_ERROR", sqle, getClass());
                }

                haveVendorConnectionPropertiesChanged = false;
            }
        } 

        // loop through the listeners
        // Not synchronized because of contract that listeners will only be changed on
        // ManagedConnection create/destroy. 

        for (int i = 0; i < numListeners; i++) {
            // send Connection Closed event to the current listener
            ivEventListeners[i].connectionClosed(connEvent); 
        }

        // Replace ConnectionEvent caching with a single reusable instance per
        // ManagedConnection. 
    }
1184962
public static void rollbackAndClose(Connection conn) throws SQLException {
        if (conn != null) {
            try {
                conn.rollback();
            } finally {
                conn.close();
            }
        }
    }
1318035
@Override
  public void initializeConnection() throws SQLException {
    super.initializeConnection();
    try {
      reconnectFailedConnection(new SearchFilter(true));
    } catch (SQLException e) {
      //initializeConnection failed
      checkInitialConnection(e);
    }
  }
500088
private void closeConnectionAfterBatch(Connection conn, int initialIsolation) throws SQLException {
        if (_isDB2)
        {
            if (Connection.TRANSACTION_REPEATABLE_READ != initialIsolation && Connection.TRANSACTION_SERIALIZABLE != initialIsolation)
                try
                {
                    conn.setTransactionIsolation(initialIsolation);
                } catch (Exception e)
                {
                    if (tc.isDebugEnabled())
                        Tr.debug(tc, "setTransactionIsolation threw Exception. Specified transaction isolation level was " + initialIsolation + " ", e);
                    FFDCFilter.processException(e, "com.ibm.ws.recoverylog.spi.SQLMultiScopeRecoveryLog.closeConnectionAfterBatch", "3696", this);
                    if (!isolationFailureReported)
                    {
                        isolationFailureReported = true;
                        Tr.warning(tc, "CWRLS0024_EXC_DURING_RECOVERY", e);
                    }
                }
        }
        conn.close();
    }
251525
@Override
  public void cancelCurrentQuery() throws SQLException {
    try (MasterProtocol copiedProtocol = new MasterProtocol(urlParser, new GlobalStateInfo(),
        new ReentrantLock())) {
      copiedProtocol.setHostAddress(getHostAddress());
      copiedProtocol.connect();
      //no lock, because there is already a query running that possessed the lock.
      copiedProtocol.executeQuery("KILL QUERY " + serverThreadId);
    }
    interrupted = true;
  }
379710
private Connection getConnection() throws JspException, SQLException {
	// Fix: Add all other mechanisms
	Connection conn = null;
	isPartOfTransaction = false;

        TransactionTagSupport parent = (TransactionTagSupport)
	    findAncestorWithClass(this, TransactionTagSupport.class);
	if (parent != null) {
            if (dataSourceSpecified) {
                throw new JspTagException(
                    Resources.getMessage("ERROR_NESTED_DATASOURCE"));
            }
	    conn = parent.getSharedConnection();
            isPartOfTransaction = true;
	} else {
	    if ((rawDataSource == null) && dataSourceSpecified) {
		throw new JspException(
		    Resources.getMessage("SQL_DATASOURCE_NULL"));
	    }
	    DataSource dataSource = DataSourceUtil.getDataSource(rawDataSource,
								 pageContext);
            try {
                conn = dataSource.getConnection();
            } catch (Exception ex) {
                throw new JspException(
                    Resources.getMessage("DATASOURCE_INVALID",
					 ex.toString()));
            }
	}

	return conn;
    }
1206030
public final void setAutoCommit(boolean value) throws SQLException 
    {
        if (value != currentAutoCommit || helper.alwaysSetAutoCommit()) 
        {
            if( (dsConfig.get().isolationLevel == Connection.TRANSACTION_NONE) && (value == false) )
                throw new SQLException(AdapterUtil.getNLSMessage("DSRA4010.tran.none.autocommit.required", dsConfig.get().id));
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(this, tc, "Set AutoCommit to " + value); 

            // Don't update values until AFTER the operation completes successfully on the
            // underlying Connection. 

            sqlConn.setAutoCommit(value); 
            currentAutoCommit = value; 
        }
        if (cachedConnection != null) 
            cachedConnection.setCurrentAutoCommit(currentAutoCommit, key);
    }
1176307
void connectDBConn(DBConn dbConn) throws DBNotAvailableException, RuntimeException {
        // If we're using failover hosts, see if it's time to try primary hosts again.
        if (m_bUseSecondaryHosts &&
            (System.currentTimeMillis() - m_lastPrimaryHostCheckTimeMillis) > getParamInt("primary_host_recheck_millis", 60000)) {
            m_bUseSecondaryHosts = false;
        }
        
        // Try all primary hosts first if possible.
        DBNotAvailableException lastException = null;
        if (!m_bUseSecondaryHosts) {
            String[] dbHosts = getParamString("dbhost").split(",");
            for (int attempt = 1; !dbConn.isOpen() && attempt <= dbHosts.length; attempt++) {
                try {
                    dbConn.connect(chooseHost(dbHosts));
                } catch (DBNotAvailableException ex) {
                    lastException = ex;
                } catch (RuntimeException ex) {
                    throw ex;   // bad keyspace; abort connection attempts
                }
            }
            m_lastPrimaryHostCheckTimeMillis = System.currentTimeMillis();
        }
        
        // Try secondary hosts if needed and if configured.
        if (!dbConn.isOpen() && !Utils.isEmpty(getParamString("secondary_dbhost"))) {
            if (!m_bUseSecondaryHosts) {
                m_logger.info("All connections to 'dbhost' failed; trying 'secondary_dbhost'");
            }
            String[] dbHosts = getParamString("secondary_dbhost").split(",");
            for (int attempt = 1; !dbConn.isOpen() && attempt <= dbHosts.length; attempt++) {
                try {
                    dbConn.connect(chooseHost(dbHosts));
                } catch (DBNotAvailableException e) {
                    lastException = e;
                } catch (RuntimeException ex) {
                    throw ex;   // bad keyspace; abort connection attempts
                }
            }
            if (dbConn.isOpen()) {
                m_bUseSecondaryHosts = true; // stick with secondary hosts for now.
            }
        }
        
        if (!dbConn.isOpen()) {
            m_logger.error("All Thrift connection attempts failed.", lastException);
            throw lastException;
        }
    }
181390
protected boolean saveSpecial(DatabaseConnection connection) throws SQLException {
		// check for a connection already saved
		NestedConnection currentSaved = specialConnection.get();
		if (currentSaved == null) {
			specialConnection.set(new NestedConnection(connection));
			return true;
		} else {
			if (currentSaved.connection != connection) {
				throw new SQLException("trying to save connection " + connection
						+ " but already have saved connection " + currentSaved.connection);
			}
			// we must have a save call within another save
			currentSaved.increment();
			return false;
		}
	}
474429
private void cmdExecuteActionPerformed(java.awt.event.ActionEvent evt) {
		if (selectedSource == null) {
			DialogUtils.showQuickErrorDialog(this, new Exception("Data source has not been defined."));
		}
		else {
			String sqlString = txtQueryEditor.getText();
			if (sqlString.isEmpty()) {

				JOptionPane.showMessageDialog(this, "SQL query cannot be blank", "Warning", JOptionPane.WARNING_MESSAGE);
			}
			else
			{
				executeQuery();
				txtClassUriTemplate.requestFocus();
			}
		}

	}
129564
public void lockAndSwitchMaster(Protocol newMasterProtocol)
      throws ReconnectDuringTransactionException {
    if (masterProtocol != null && !masterProtocol.isClosed()) {
      masterProtocol.close();
    }

    if (!currentReadOnlyAsked || isSecondaryHostFail()) {
      //actually on a secondary read-only because master was unknown.
      //So select master as currentConnection
      if (currentProtocol != null) {
        try {
          syncConnection(currentProtocol, newMasterProtocol);
        } catch (Exception e) {
          //Some error append during connection parameter synchronisation
        }
      }
      //switching current connection to master connection
      currentProtocol = newMasterProtocol;
    }

    boolean inTransaction = this.masterProtocol != null && this.masterProtocol.inTransaction();
    this.masterProtocol = newMasterProtocol;
    resetMasterFailoverData();
    if (inTransaction) {
      //master connection was down, so has been change for a new active connection
      //problem was there was an active connection -> must throw exception so client known it
      throw new ReconnectDuringTransactionException(
          "Connection reconnect automatically during an active transaction", 1401, "25S03");
    }
  }
221094
public static void returnConnection(Connection conn) throws SQLException {
        if (conn == null) {
            return;
        }
        String dsName = openConnDsName.get().get(conn);
        OpenConnStats connStats = dsName != null ? openConnStats.get().get(dsName) : null;
        if (connStats == null) {
            conn.close();
        } else {
            long value = connStats.counter.decrementAndGet();
            if (value <= 0) {
                try {
                    try {
                        if (connStats.inTransaction) {
                            conn.commit();
                        }
                    } catch (Exception e) {
                        conn.rollback();
                    } finally {
                        try {
                            conn.setAutoCommit(true);
                        } finally {
                            connStats.inTransaction = false;
                            conn.close();
                        }
                    }
                } finally {
                    openConnStats.get().remove(dsName);
                    openConnDsName.get().remove(conn);
                }
            }
        }
    }