/**
   * Delete a repository connection.
   *
   * @param name is the name of the connection to delete. If the name does not exist, no error is
   *     returned.
   */
  public void delete(String name) throws ManifoldCFException {
    // Grab a job manager handle.  We will need to check if any jobs refer to this connection.
    IJobManager jobManager = JobManagerFactory.make(threadContext);

    StringSetBuffer ssb = new StringSetBuffer();
    ssb.add(getRepositoryConnectionsKey());
    ssb.add(getRepositoryConnectionKey(name));
    StringSet cacheKeys = new StringSet(ssb);
    ICacheHandle ch = cacheManager.enterCache(null, cacheKeys, getTransactionID());
    try {
      beginTransaction();
      try {
        // Check if any jobs refer to this connection name
        if (jobManager.checkIfReference(name))
          throw new ManifoldCFException(
              "Can't delete repository connection '" + name + "': existing jobs refer to it");
        ManifoldCF.noteConfigurationChange();
        throttleSpecManager.deleteRows(name);
        historyManager.deleteOwner(name);
        ArrayList params = new ArrayList();
        String query =
            buildConjunctionClause(
                params, new ClauseDescription[] {new UnitaryClause(nameField, name)});
        performDelete("WHERE " + query, params, null);
        cacheManager.invalidateKeys(ch);
      } catch (ManifoldCFException e) {
        signalRollback();
        throw e;
      } catch (Error e) {
        signalRollback();
        throw e;
      } finally {
        endTransaction();
      }
    } finally {
      cacheManager.leaveCache(ch);
    }
  }
  protected void localCleanUp() throws Exception {
    IThreadContext tc = ThreadContextFactory.make();

    Exception currentException = null;
    // First, tear down all jobs, connections, authority connections, and output connections.
    try {
      IRepositoryConnectionManager connMgr = RepositoryConnectionManagerFactory.make(tc);
      IAuthorityConnectionManager authConnMgr = AuthorityConnectionManagerFactory.make(tc);
      IOutputConnectionManager outputMgr = OutputConnectionManagerFactory.make(tc);

      // Now, get a list of the repository connections
      IRepositoryConnection[] connections = connMgr.getAllConnections();
      int i = 0;
      while (i < connections.length) {
        connMgr.delete(connections[i++].getName());
      }

      // Get a list of authority connections
      IAuthorityConnection[] authorities = authConnMgr.getAllConnections();
      i = 0;
      while (i < authorities.length) {
        authConnMgr.delete(authorities[i++].getName());
      }

      // Finally, get rid of output connections
      IOutputConnection[] outputs = outputMgr.getAllConnections();
      i = 0;
      while (i < outputs.length) {
        outputMgr.delete(outputs[i++].getName());
      }

    } catch (Exception e) {
      currentException = e;
    }
    try {
      IDBInterface database =
          DBInterfaceFactory.make(
              tc,
              ManifoldCF.getMasterDatabaseName(),
              ManifoldCF.getMasterDatabaseUsername(),
              ManifoldCF.getMasterDatabasePassword());

      IConnectorManager mgr = ConnectorManagerFactory.make(tc);
      IAuthorityConnectorManager authMgr = AuthorityConnectorManagerFactory.make(tc);
      IOutputConnectorManager outputMgr = OutputConnectorManagerFactory.make(tc);
      IOutputConnectionManager outputConnManager = OutputConnectionManagerFactory.make(tc);
      IJobManager jobManager = JobManagerFactory.make(tc);
      IRepositoryConnectionManager connManager = RepositoryConnectionManagerFactory.make(tc);

      // Deregistration should be done in a transaction
      database.beginTransaction();
      try {
        int i;

        String[] connectorClasses = getConnectorClasses();

        i = 0;
        while (i < connectorClasses.length) {
          // Find the connection names that come with this class
          String[] connectionNames = connManager.findConnectionsForConnector(connectorClasses[i]);
          // For each connection name, modify the jobs to note that the connector is no longer
          // installed
          jobManager.noteConnectorDeregistration(connectionNames);
          // Now that all jobs have been placed into an appropriate state, actually do the
          // deregistration itself.
          mgr.unregisterConnector(connectorClasses[i]);
          i++;
        }

        String[] authorityClasses = getAuthorityClasses();

        i = 0;
        while (i < authorityClasses.length) {
          authMgr.unregisterConnector(authorityClasses[i]);
          i++;
        }

        String[] outputClasses = getOutputClasses();

        i = 0;
        while (i < outputClasses.length) {
          // Find the connection names that come with this class
          String[] connectionNames =
              outputConnManager.findConnectionsForConnector(outputClasses[i]);
          // For all connection names, notify all agents of the deregistration
          AgentManagerFactory.noteOutputConnectorDeregistration(tc, connectionNames);
          // Now that all jobs have been placed into an appropriate state, actually do the
          // deregistration itself.
          outputMgr.unregisterConnector(outputClasses[i]);
          i++;
        }

      } catch (ManifoldCFException e) {
        database.signalRollback();
        throw e;
      } catch (Error e) {
        database.signalRollback();
        throw e;
      } finally {
        database.endTransaction();
      }
    } catch (Exception e) {
      if (currentException != null) currentException = e;
    }
    try {
      super.localCleanUp();
    } catch (Exception e) {
      if (currentException != null) currentException = e;
    }
    if (currentException != null) throw currentException;
  }
  protected void localSetUp() throws Exception {

    super.localSetUp();

    IThreadContext tc = ThreadContextFactory.make();

    IDBInterface database =
        DBInterfaceFactory.make(
            tc,
            ManifoldCF.getMasterDatabaseName(),
            ManifoldCF.getMasterDatabaseUsername(),
            ManifoldCF.getMasterDatabasePassword());

    IConnectorManager mgr = ConnectorManagerFactory.make(tc);
    IAuthorityConnectorManager authMgr = AuthorityConnectorManagerFactory.make(tc);
    IJobManager jobManager = JobManagerFactory.make(tc);
    IRepositoryConnectionManager connManager = RepositoryConnectionManagerFactory.make(tc);
    IOutputConnectorManager outputMgr = OutputConnectorManagerFactory.make(tc);
    IOutputConnectionManager outputConnManager = OutputConnectionManagerFactory.make(tc);

    // Deregistration should be done in a transaction
    database.beginTransaction();
    try {
      int i;

      String[] connectorClasses = getConnectorClasses();
      String[] connectorNames = getConnectorNames();

      i = 0;
      while (i < connectorClasses.length) {
        // First, register connector
        mgr.registerConnector(connectorNames[i], connectorClasses[i]);
        // Then, signal to all jobs that might depend on this connector that they can switch state
        // Find the connection names that come with this class
        String[] connectionNames = connManager.findConnectionsForConnector(connectorClasses[i]);
        // For each connection name, modify the jobs to note that the connector is now installed
        jobManager.noteConnectorRegistration(connectionNames);
        i++;
      }

      String[] authorityClasses = getAuthorityClasses();
      String[] authorityNames = getAuthorityNames();

      i = 0;
      while (i < authorityClasses.length) {
        authMgr.registerConnector(authorityNames[i], authorityClasses[i]);
        i++;
      }

      String[] outputClasses = getOutputClasses();
      String[] outputNames = getOutputNames();

      i = 0;
      while (i < outputClasses.length) {
        // First, register connector
        outputMgr.registerConnector(outputNames[i], outputClasses[i]);
        // Then, signal to all jobs that might depend on this connector that they can switch state
        // Find the connection names that come with this class
        String[] connectionNames = outputConnManager.findConnectionsForConnector(outputClasses[i]);
        // For all connection names, notify all agents of the registration
        AgentManagerFactory.noteOutputConnectorRegistration(tc, connectionNames);
        i++;
      }

    } catch (ManifoldCFException e) {
      database.signalRollback();
      throw e;
    } catch (Error e) {
      database.signalRollback();
      throw e;
    } finally {
      database.endTransaction();
    }
  }
  /**
   * Save a repository connection object.
   *
   * @param object is the object to save.
   * @return true if the object was created, false otherwise.
   */
  public boolean save(IRepositoryConnection object) throws ManifoldCFException {
    StringSetBuffer ssb = new StringSetBuffer();
    ssb.add(getRepositoryConnectionsKey());
    ssb.add(getRepositoryConnectionKey(object.getName()));
    StringSet cacheKeys = new StringSet(ssb);
    while (true) {
      // Catch deadlock condition
      long sleepAmt = 0L;
      try {
        ICacheHandle ch = cacheManager.enterCache(null, cacheKeys, getTransactionID());
        try {
          beginTransaction();
          try {
            // performLock();
            // Notify of a change to the configuration
            ManifoldCF.noteConfigurationChange();
            boolean isNew = object.getIsNew();
            // See whether the instance exists
            ArrayList params = new ArrayList();
            String query =
                buildConjunctionClause(
                    params,
                    new ClauseDescription[] {new UnitaryClause(nameField, object.getName())});
            IResultSet set =
                performQuery(
                    "SELECT * FROM " + getTableName() + " WHERE " + query + " FOR UPDATE",
                    params,
                    null,
                    null);
            HashMap values = new HashMap();
            values.put(descriptionField, object.getDescription());
            values.put(classNameField, object.getClassName());
            values.put(groupNameField, object.getACLAuthority());
            values.put(maxCountField, new Long((long) object.getMaxConnections()));
            String configXML = object.getConfigParams().toXML();
            values.put(configField, configXML);
            boolean notificationNeeded = false;
            boolean isCreated;

            if (set.getRowCount() > 0) {
              // If the object is supposedly new, it is bad that we found one that already exists.
              if (isNew)
                throw new ManifoldCFException(
                    "Repository connection '" + object.getName() + "' already exists");
              isCreated = false;
              IResultRow row = set.getRow(0);
              String oldXML = (String) row.getValue(configField);
              if (oldXML == null || !oldXML.equals(configXML)) notificationNeeded = true;

              // Update
              params.clear();
              query =
                  buildConjunctionClause(
                      params,
                      new ClauseDescription[] {new UnitaryClause(nameField, object.getName())});
              performUpdate(values, " WHERE " + query, params, null);
              throttleSpecManager.deleteRows(object.getName());
            } else {
              // If the object is not supposed to be new, it is bad that we did not find one.
              if (!isNew)
                throw new ManifoldCFException(
                    "Repository connection '" + object.getName() + "' no longer exists");
              isCreated = true;
              // Insert
              values.put(nameField, object.getName());
              // We only need the general key because this is new.
              performInsert(values, null);
            }

            // Write secondary table stuff
            throttleSpecManager.writeRows(object.getName(), object);

            // If notification required, do it.
            if (notificationNeeded) {
              IJobManager jobManager = JobManagerFactory.make(threadContext);
              jobManager.noteConnectionChange(object.getName());
            }

            cacheManager.invalidateKeys(ch);
            return isCreated;
          } catch (ManifoldCFException e) {
            signalRollback();
            throw e;
          } catch (Error e) {
            signalRollback();
            throw e;
          } finally {
            endTransaction();
          }
        } finally {
          cacheManager.leaveCache(ch);
        }
      } catch (ManifoldCFException e) {
        // Is this a deadlock exception?  If so, we want to try again.
        if (e.getErrorCode() != ManifoldCFException.DATABASE_TRANSACTION_ABORT) throw e;
        sleepAmt = getSleepAmt();
      } finally {
        sleepFor(sleepAmt);
      }
    }
  }