/**
   * Read a chunk of repository connections.
   *
   * @param rval is the place to put the read policies.
   * @param returnIndex is a map from the object id (resource id) and the rval index.
   * @param params is the set of parameters.
   */
  protected void getRepositoryConnectionsChunk(
      RepositoryConnection[] rval, Map returnIndex, ArrayList params) throws ManifoldCFException {
    ArrayList list = new ArrayList();
    String query =
        buildConjunctionClause(list, new ClauseDescription[] {new MultiClause(nameField, params)});
    IResultSet set =
        performQuery("SELECT * FROM " + getTableName() + " WHERE " + query, list, null, null);
    int i = 0;
    while (i < set.getRowCount()) {
      IResultRow row = set.getRow(i++);
      String name = row.getValue(nameField).toString();
      int index = ((Integer) returnIndex.get(name)).intValue();
      RepositoryConnection rc = new RepositoryConnection();
      rc.setIsNew(false);
      rc.setName(name);
      rc.setDescription((String) row.getValue(descriptionField));
      rc.setClassName((String) row.getValue(classNameField));
      rc.setACLAuthority((String) row.getValue(groupNameField));
      rc.setMaxConnections((int) ((Long) row.getValue(maxCountField)).longValue());
      String xml = (String) row.getValue(configField);
      if (xml != null && xml.length() > 0) rc.getConfigParams().fromXML(xml);
      rval[index] = rc;
    }

    // Do throttle part
    throttleSpecManager.getRows(rval, returnIndex, params);
  }
 /** Uninstall the manager. */
 public void deinstall() throws ManifoldCFException {
   beginTransaction();
   try {
     throttleSpecManager.deinstall();
     historyManager.deinstall();
     performDrop(null);
   } catch (ManifoldCFException e) {
     signalRollback();
     throw e;
   } catch (Error e) {
     signalRollback();
     throw e;
   } finally {
     endTransaction();
   }
 }
  /**
   * 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);
    }
  }
  /** Install the manager. */
  public void install() throws ManifoldCFException {
    // First, get the authority manager table name and name column
    IAuthorityGroupManager authMgr = AuthorityGroupManagerFactory.make(threadContext);

    // Always use a loop, and no transaction, as we may need to retry due to upgrade
    while (true) {
      Map existing = getTableSchema(null, null);
      if (existing == null) {
        // Install the "objects" table.
        HashMap map = new HashMap();
        map.put(nameField, new ColumnDescription("VARCHAR(32)", true, false, null, null, false));
        map.put(
            descriptionField,
            new ColumnDescription("VARCHAR(255)", false, true, null, null, false));
        map.put(
            classNameField, new ColumnDescription("VARCHAR(255)", false, false, null, null, false));
        map.put(
            groupNameField,
            new ColumnDescription(
                "VARCHAR(32)",
                false,
                true,
                authMgr.getTableName(),
                authMgr.getGroupNameColumn(),
                false));
        map.put(maxCountField, new ColumnDescription("BIGINT", false, false, null, null, false));
        map.put(configField, new ColumnDescription("LONGTEXT", false, true, null, null, false));
        performCreate(map, null);
      } else {
        // Upgrade code
        ColumnDescription cd = (ColumnDescription) existing.get(groupNameField);
        if (cd == null) {
          Map addMap = new HashMap();
          addMap.put(
              groupNameField,
              new ColumnDescription(
                  "VARCHAR(32)",
                  false,
                  true,
                  authMgr.getTableName(),
                  authMgr.getGroupNameColumn(),
                  false));
          performAlter(addMap, null, null, null);
        }
        // Get rid of the authorityName field.  When we do this we need to copy into the group name
        // field, adding groups if they don't yet exist first
        cd = (ColumnDescription) existing.get(authorityNameField);
        if (cd != null) {
          ArrayList params = new ArrayList();
          IResultSet set =
              performQuery(
                  "SELECT " + nameField + "," + authorityNameField + " FROM " + getTableName(),
                  null,
                  null,
                  null);
          for (int i = 0; i < set.getRowCount(); i++) {
            IResultRow row = set.getRow(i);
            String repoName = (String) row.getValue(nameField);
            String authName = (String) row.getValue(authorityNameField);
            if (authName != null && authName.length() > 0) {
              // Attempt to create a matching auth group.  This will fail if the group
              // already exists
              IAuthorityGroup grp = authMgr.create();
              grp.setName(authName);
              try {
                authMgr.save(grp);
              } catch (ManifoldCFException e) {
                if (e.getErrorCode() == ManifoldCFException.INTERRUPTED) throw e;
                // Fall through; the row exists already
              }
              Map<String, String> map = new HashMap<String, String>();
              map.put(groupNameField, authName);
              params.clear();
              String query =
                  buildConjunctionClause(
                      params, new ClauseDescription[] {new UnitaryClause(nameField, repoName)});
              performUpdate(map, " WHERE " + query, params, null);
            }
          }
          List<String> deleteList = new ArrayList<String>();
          deleteList.add(authorityNameField);
          performAlter(null, null, deleteList, null);
        }
      }

      // Install dependent tables.
      historyManager.install(getTableName(), nameField);
      throttleSpecManager.install(getTableName(), nameField);

      // Index management
      IndexDescription authorityIndex = new IndexDescription(false, new String[] {groupNameField});
      IndexDescription classIndex = new IndexDescription(false, new String[] {classNameField});

      // Get rid of indexes that shouldn't be there
      Map indexes = getTableIndexes(null, null);
      Iterator iter = indexes.keySet().iterator();
      while (iter.hasNext()) {
        String indexName = (String) iter.next();
        IndexDescription id = (IndexDescription) indexes.get(indexName);

        if (authorityIndex != null && id.equals(authorityIndex)) authorityIndex = null;
        else if (classIndex != null && id.equals(classIndex)) classIndex = null;
        else if (indexName.indexOf("_pkey") == -1)
          // This index shouldn't be here; drop it
          performRemoveIndex(indexName);
      }

      // Add the ones we didn't find
      if (authorityIndex != null) performAddIndex(null, authorityIndex);

      if (classIndex != null) performAddIndex(null, classIndex);

      break;
    }
  }
 /** Calculate how many repository connections to get at once. */
 protected int maxClauseGetRepositoryConnectionsChunk() {
   return Math.min(
       findConjunctionClauseMax(new ClauseDescription[] {}),
       throttleSpecManager.maxClauseGetRows());
 }
  /**
   * 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);
      }
    }
  }