/**
   * This method takes all the children of the passed-in category (both {@link
   * arlut.csd.ganymede.server.DBObjectBase DBObjectBase} objects and contained {@link
   * arlut.csd.ganymede.server.DBBaseCategory DBBaseCategory} objects) and makes copies under this.
   */
  private void recurseDown(DBBaseCategory category, Hashtable baseHash, DBSchemaEdit editor)
      throws RemoteException {
    Vector<CategoryNode> children = category.getNodes();
    DBObjectBase oldBase, newBase;
    DBBaseCategory oldCategory, newCategory;

    /* -- */

    if (debug) {
      Ganymede.debug("** recurseDown");

      if (editor == null) {
        Ganymede.debug("**#?!?!!! DBBaseCategory.recurseDown(): editor == null!!!");
      }
    }

    for (CategoryNode node : children) {
      if (node instanceof DBObjectBase) {
        oldBase = (DBObjectBase) node;

        // a new copy, with the same objects under it

        newBase = new DBObjectBase(oldBase, editor);
        baseHash.put(newBase.getKey(), newBase);

        if (false) {
          Ganymede.debug(
              "Created newBase " + newBase.getName() + " in recursive category tree duplication");
        }

        // we want this base to be added to the current end of this category

        addNodeAfter(newBase, null);

        if (false) {
          Ganymede.debug("Added " + newBase.getName() + " to new category tree");
        }
      } else if (node instanceof DBBaseCategory) {
        oldCategory = (DBBaseCategory) node;
        newCategory = (DBBaseCategory) newSubCategory(oldCategory.getName());
        newCategory.editor = editor;

        if (false) {
          Ganymede.debug(
              "Created newCategory "
                  + newCategory.getName()
                  + " in recursive category tree duplication");
        }

        newCategory.recurseDown(oldCategory, baseHash, editor);
      }
    }
  }
  /** This method emits this delta rec to a file */
  public void emit(DataOutput out) throws IOException {
    DBObjectBase baseDef;
    DBObjectBaseField fieldDef;

    /* -- */

    // write the object id

    baseDef = Ganymede.db.getObjectBase(invid.getType());

    if (debug) {
      System.err.println("Emitting delta rec for invid " + invid.toString());
    }

    invid.emit(out);

    // write the fieldrec count

    out.writeInt(fieldRecs.size());

    if (debug) {
      System.err.println(
          "Emitting " + fieldRecs.size() + " field records for invid " + invid.toString());
    }

    // now let's write out the fields

    fieldDeltaRec fdRec;
    Object value;

    for (int i = 0; i < fieldRecs.size(); i++) {
      fdRec = (fieldDeltaRec) fieldRecs.elementAt(i);

      // write out our field code.. this will be used by the loader
      // code to determine what kind of field this is, and what
      // kind of data types need to be loaded.

      if (debug) {
        System.err.println("Emitting fieldDeltaRec:\n\t" + fdRec.toString());
      }

      out.writeShort(fdRec.fieldcode);

      // are we deleting?

      if (!fdRec.vector && fdRec.scalarValue == null) {
        // yes, we're deleting this field
        out.writeBoolean(true);
        continue;
      }

      // no, we're redefining this field

      out.writeBoolean(false);

      // write out our field type code.. this will be used by the loader
      // to verify that the schema hasn't undergone an incompatible
      // change since the journal was written.

      fieldDef = (DBObjectBaseField) baseDef.getField(fdRec.fieldcode);

      out.writeShort(fieldDef.getType());

      if (fdRec.scalarValue != null) {
        out.writeBoolean(true); // scalar redefinition
        fdRec.scalarValue.emit(out);
        continue;
      }

      out.writeBoolean(false); // vector mod

      // write out what is being added to this vector

      if (debug) {
        System.err.println("====== Emitting " + fdRec.addValues.size() + " addition elements");
      }

      if (fdRec.addValues == null) {
        out.writeInt(0);
      } else {
        out.writeInt(fdRec.addValues.size());

        for (int j = 0; j < fdRec.addValues.size(); j++) {
          value = fdRec.addValues.elementAt(j);

          // we only support 3 vector field types

          if (value instanceof String) {
            out.writeUTF((String) value);
          } else if (value instanceof Invid) {
            ((Invid) value).emit(out);
          } else if (value instanceof IPwrap) {
            Byte[] bytes = ((IPwrap) value).address;

            out.writeByte(bytes.length);

            for (int k = 0; k < bytes.length; k++) {
              out.writeByte(bytes[k].byteValue());
            }
          } else {
            Ganymede.debug("DBObjectDeltaRec.emit(): Error!  Unrecognized element in vector!");
          }
        }
      }

      // write out what is being removed from this vector

      if (fdRec.delValues == null) {
        out.writeInt(0);
      } else {
        out.writeInt(fdRec.delValues.size());

        for (int j = 0; j < fdRec.delValues.size(); j++) {
          value = fdRec.delValues.elementAt(j);

          // we only support 3 vector field types

          if (value instanceof String) {
            out.writeUTF((String) value);
          } else if (value instanceof Invid) {
            Invid invid = (Invid) value;

            out.writeShort(invid.getType());
            out.writeInt(invid.getNum());
          } else if (value instanceof IPwrap) {
            Byte[] bytes = ((IPwrap) value).address;

            out.writeByte(bytes.length);

            for (int k = 0; k < bytes.length; k++) {
              out.writeByte(bytes[k].byteValue());
            }
          }
        }
      }
    }
  }
  /**
   * This method is used to remove a Category Node from under us.
   *
   * @see arlut.csd.ganymede.rmi.Category
   */
  public synchronized void removeNode(CategoryNode node) throws RemoteException {
    int i, index = -1;

    /* -- */

    if (node == null) {
      throw new IllegalArgumentException("Can't remove a null node");
    }

    // find our deletion point

    if (debug) {
      try {
        Ganymede.debug("DBBaseCategory (" + getName() + ").removeNode(" + node.getPath() + ")");
      } catch (RemoteException ex) {
        Ganymede.logError(ex);
        throw new RuntimeException("rmi local failure?" + ex.getMessage());
      }
    }

    for (i = 0; i < contents.size(); i++) {
      if (debug) {
        try {
          Ganymede.debug(" examining: " + ((CategoryNode) contents.elementAt(i)).getPath());
        } catch (RemoteException ex) {
          Ganymede.logError(ex);
          throw new RuntimeException("rmi local failure?" + ex.getMessage());
        }
      }

      if (contents.elementAt(i).equals(node)) {
        index = i;
      }
    }

    if (index == -1) {
      throw new IllegalArgumentException("can't delete a node that's not in the category");
    }

    // remove our node from our content list

    contents.removeElementAt(index);

    if (false) {
      if (node instanceof DBObjectBase) {
        DBObjectBase base = (DBObjectBase) node;

        if (!base.isEditing()) {
          System.err.println(
              "DBBaseCategory.removeNode(): " + base.getName() + " has a null editor!");
        } else {
          System.err.println(
              "DBBaseCategory.removeNode(): " + base.getName() + " has a non-null editor!");
        }
      }
    }

    // Sorry, kid, yer on your own now!

    node.setCategory(null);
  }
  /**
   * This method is used to remove a Category Node from under us.
   *
   * @see arlut.csd.ganymede.rmi.Category
   */
  public synchronized void removeNode(String name) throws RemoteException {
    int i, index = -1;

    CategoryNode node = null;

    /* -- */

    if (name == null) {
      throw new IllegalArgumentException("Can't remove a null name");
    }

    // find our deletion point

    if (debug) {
      Ganymede.debug("DBBaseCategory (" + getName() + ").removeNode(" + name + ")");
    }

    for (i = 0; i < contents.size() && (index == -1); i++) {
      if (debug) {
        Ganymede.debug(" examining: " + contents.elementAt(i));
      }

      node = (CategoryNode) contents.elementAt(i);

      try {
        if (node.getName().equals(name)) {
          index = i;
        }
      } catch (RemoteException ex) {
        throw new RuntimeException("caught remote: " + ex);
      }
    }

    if (index == -1) {
      throw new IllegalArgumentException("can't delete a name that's not in the category");
    } else if (debug) {
      System.err.println("DBBaseCategory.removeNode(): found node " + node);

      if (node instanceof DBObjectBase) {
        System.err.println("DBBaseCategory.removeNode(): node is DBObjectBase");
      } else if (node instanceof Base) {
        System.err.println("DBBaseCategory.removeNode(): node is Base");
      } else if (node instanceof DBBaseCategory) {
        System.err.println("DBBaseCategory.removeNode(): node is DBBaseCategory");
      } else if (node instanceof Category) {
        System.err.println("DBBaseCategory.removeNode(): node is Category");
      } else {
        System.err.println("DBBaseCategory.removeNode(): node is <unrecognized>");
      }
    }

    // remove our node from our content list

    contents.removeElementAt(index);

    if (debug) {
      if (node instanceof DBObjectBase) {
        DBObjectBase base = (DBObjectBase) node;

        if (!base.isEditing()) {
          System.err.println(
              "DBBaseCategory.removeNode(2): " + base.getName() + " has a null editor!");
        } else {
          System.err.println(
              "DBBaseCategory.removeNode(2): " + base.getName() + " has a non-null editor!");
        }
      }
    }

    // Sorry, kid, yer on your own now!

    node.setCategory(null);
  }
  /**
   * This method is used to scan the persistent log storage for log events that match invid and that
   * have occurred since sinceTime.
   *
   * @param invid If not null, retrieveHistory() will only return events involving this object
   *     invid.
   * @param sinceTime if not null, retrieveHistory() will only return events occuring on or after
   *     the time specified in this Date object.
   * @param beforeTime if not null, retrieveHistory() will only return events occurring on or before
   *     the time specified in this Date object.
   * @param keyOnAdmin if true, rather than returning a string containing events that involved
   *     &lt;invid&gt;, retrieveHistory() will return a string containing events performed on behalf
   *     of the administrator with invid &lt;invid&gt;.
   * @param fullTransactions if true, the buffer returned will include all events in any
   *     transactions that involve the given invid. if false, only those events in a transaction
   *     directly affecting the given invid will be returned.
   * @param getLoginEvents if true, this method will return only login and logout events. if false,
   *     this method will return no login and logout events.
   * @return A human-readable multiline string containing a list of history events
   */
  public StringBuffer retrieveHistory(
      Invid invid,
      Date sinceTime,
      Date beforeTime,
      boolean keyOnAdmin,
      boolean fullTransactions,
      boolean getLoginEvents) {
    if (con == null) {
      throw new IllegalArgumentException("no connection to postgres database");
    }

    StringBuffer buffer = new StringBuffer();

    Date transDate = null;
    String prevTransID = null;
    String transAdmin = null;

    ResultSet rs = null;

    /* -- */

    try {
      if (keyOnAdmin) {
        rs = queryEventsByAdmin(invid, sinceTime, beforeTime);
      } else if (fullTransactions) {
        rs = queryEventsByTransactions(invid, sinceTime, beforeTime);
      } else {
        rs = queryEvents(invid, sinceTime, beforeTime);
      }

      while (rs.next()) {
        long time = rs.getLong(1);
        String token = rs.getString(2);
        String adminName = rs.getString(3);
        String text = rs.getString(4);
        String transactionID = rs.getString(5);

        if (invid.getType() == SchemaConstants.UserBase) {
          if (token.equals("normallogin")
              || token.equals("normallogout")
              || token.equals("abnormallogout")) {
            if (!getLoginEvents) {
              continue; // we don't want to show login/logout activity here
            }
          } else if (getLoginEvents) {
            continue; // we don't want to show non-login/logout activity here
          }
        }

        if (prevTransID != null && !prevTransID.equals(transactionID)) {
          buffer.append(
              "---------- End Transaction "
                  + transDate.toString()
                  + ": "
                  + transAdmin
                  + " ----------\n\n");

          transAdmin = null;
          transDate = null;
          prevTransID = null;
        }

        if (token.equals("starttransaction")) {
          transDate = new Date(time);

          String tmp2 =
              "---------- Transaction " + transDate.toString() + ": " + adminName + " ----------\n";

          // remember our admin name and transaction id so we
          // can put out a notice about closing the previous
          // transaction when we see it

          transAdmin = adminName;
          prevTransID = transactionID;

          buffer.append(tmp2);
        } else if (token.equals("finishtransaction")) {
          String tmp2 =
              "---------- End Transaction "
                  + new Date(time).toString()
                  + ": "
                  + adminName
                  + " ----------\n\n";

          prevTransID = null;
          transAdmin = null;
          transDate = null;

          buffer.append(tmp2);
        } else {
          String tmp = token + "\n" + WordWrap.wrap(text, 78, "\t") + "\n";

          buffer.append(tmp);
        }
      }
    } catch (SQLException ex) {
      Ganymede.debug("SQLException in retrieveHistory: " + ex.getMessage());
      Ganymede.debug("** SQLState: " + ex.getSQLState());
      Ganymede.debug("** SQL Error Code: " + ex.getErrorCode());
      Ganymede.debug(Ganymede.stackTrace(ex));
      return buffer;
    } finally {
      try {
        if (rs != null) {
          rs.close();

          Statement st = rs.getStatement();

          if (st != null) {
            st.close();
          }
        }
      } catch (SQLException ex) {
      }
    }

    return buffer;
  }
  /**
   * This method writes the given event to the persistent storage managed by this controller.
   *
   * @param event The DBLogEvent to be recorded
   */
  public synchronized void writeEvent(DBLogEvent event) {
    if (con == null) {
      throw new IllegalArgumentException("no connection to postgres database");
    }

    try {
      if (statement == null) {
        statement =
            con.prepareStatement(
                "insert into event (event_id, javatime, sqltime, classtoken, "
                    + "admin_invid, admin_name, trans_id, text) "
                    + "values (?,?,?,?,?,?,?,?)");
      }

      if (event.eventClassToken.equals("starttransaction")) {
        transactionID = event.transactionID;
      }

      primaryKey++;
      statement.setInt(1, primaryKey);
      statement.setLong(2, event.time.getTime());
      statement.setTimestamp(3, new java.sql.Timestamp(event.time.getTime()));
      statement.setString(4, event.eventClassToken);

      if (event.admin != null) {
        statement.setString(5, event.admin.toString());
      } else {
        statement.setNull(5, java.sql.Types.VARCHAR);
      }

      if (event.adminName != null) {
        statement.setString(6, event.adminName);
      } else {
        statement.setNull(5, java.sql.Types.VARCHAR);
      }

      if (event.transactionID != null) {
        statement.setString(7, event.transactionID);
      } else {
        statement.setNull(5, java.sql.Types.VARCHAR);
      }

      if (event.description != null) {
        statement.setString(8, event.description);
      } else {
        statement.setNull(5, java.sql.Types.VARCHAR);
      }

      statement.addBatch();

      for (String address : event.getMailTargets()) {
        statement.addBatch(
            "insert into email (event_id, address) values(" + primaryKey + ", '" + address + "')");
      }

      for (Invid invid : event.getInvids()) {
        statement.addBatch(
            "insert into invids (invid, event_id) values('"
                + invid.toString()
                + "',"
                + primaryKey
                + ")");
      }

      // if we had successfully logged our entire transaction,
      // record a mapping in the transactions table from each
      // invid in the transaction (which are recorded in the
      // starttransaction line) to the transaction id
      //
      // if we get a transactionID mismatch we won't record anything
      //
      // we reset the transactionID and transInvids List
      // pointer in any event

      if (event.eventClassToken.equals("finishtransaction")) {
        if (transactionID != null && transactionID.equals(event.transactionID)) {
          for (Invid invid : event.getInvids()) {
            statement.addBatch(
                "insert into transactions (invid, trans_id) values('"
                    + invid.toString()
                    + "','"
                    + transactionID
                    + "')");
          }
        }

        transactionID = null;
      }

      statement.executeBatch();
      statement.clearParameters();
    } catch (SQLException ex) {
      Ganymede.debug("SQLException in spinLog: " + ex.getMessage());
      Ganymede.debug("** SQLState: " + ex.getSQLState());
      Ganymede.debug("** SQL Error Code: " + ex.getErrorCode());
      Ganymede.debug(Ganymede.stackTrace(ex));
      Ganymede.debug("Event was " + event.toString());
      return;
    }
  }