/**
   * 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);
  }
 /**
  * Check if underlying connector exists.
  *
  * @param name is the name of the connection to check.
  * @return true if the underlying connector is registered.
  */
 @Override
 public boolean checkConnectorExists(String name) throws ManifoldCFException {
   beginTransaction();
   try {
     StringSetBuffer ssb = new StringSetBuffer();
     ssb.add(getRepositoryConnectionKey(name));
     StringSet localCacheKeys = new StringSet(ssb);
     ArrayList params = new ArrayList();
     String query =
         buildConjunctionClause(
             params, new ClauseDescription[] {new UnitaryClause(nameField, name)});
     IResultSet set =
         performQuery(
             "SELECT " + classNameField + " FROM " + getTableName() + " WHERE " + query,
             params,
             localCacheKeys,
             null);
     if (set.getRowCount() == 0)
       throw new ManifoldCFException("No such connection: '" + name + "'");
     IResultRow row = set.getRow(0);
     String className = (String) row.getValue(classNameField);
     IConnectorManager cm = ConnectorManagerFactory.make(threadContext);
     return cm.isInstalled(className);
   } catch (ManifoldCFException e) {
     signalRollback();
     throw e;
   } catch (Error e) {
     signalRollback();
     throw e;
   } finally {
     endTransaction();
   }
 }
 /**
  * Get a list of repository connections that share the same connector.
  *
  * @param className is the class name of the connector.
  * @return the repository connections that use that connector.
  */
 @Override
 public String[] findConnectionsForConnector(String className) throws ManifoldCFException {
   StringSetBuffer ssb = new StringSetBuffer();
   ssb.add(getRepositoryConnectionsKey());
   StringSet localCacheKeys = new StringSet(ssb);
   ArrayList params = new ArrayList();
   String query =
       buildConjunctionClause(
           params, new ClauseDescription[] {new UnitaryClause(classNameField, className)});
   IResultSet set =
       performQuery(
           "SELECT " + nameField + " FROM " + getTableName() + " WHERE " + query,
           params,
           localCacheKeys,
           null);
   String[] rval = new String[set.getRowCount()];
   int i = 0;
   while (i < rval.length) {
     IResultRow row = set.getRow(i);
     rval[i] = (String) row.getValue(nameField);
     i++;
   }
   java.util.Arrays.sort(rval);
   return rval;
 }
 /**
  * Obtain a list of the repository connections, ordered by name.
  *
  * @return an array of connection objects.
  */
 public IRepositoryConnection[] getAllConnections() throws ManifoldCFException {
   beginTransaction();
   try {
     // Read all the tools
     StringSetBuffer ssb = new StringSetBuffer();
     ssb.add(getRepositoryConnectionsKey());
     StringSet localCacheKeys = new StringSet(ssb);
     IResultSet set =
         performQuery(
             "SELECT "
                 + nameField
                 + ",lower("
                 + nameField
                 + ") AS sortfield FROM "
                 + getTableName()
                 + " ORDER BY sortfield ASC",
             null,
             localCacheKeys,
             null);
     String[] names = new String[set.getRowCount()];
     int i = 0;
     while (i < names.length) {
       IResultRow row = set.getRow(i);
       names[i] = row.getValue(nameField).toString();
       i++;
     }
     return loadMultiple(names);
   } catch (ManifoldCFException e) {
     signalRollback();
     throw e;
   } catch (Error e) {
     signalRollback();
     throw e;
   } finally {
     endTransaction();
   }
 }
  /** 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;
    }
  }
  /**
   * 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);
      }
    }
  }