/** Opens a dialog that displays the operational attributes of the current entry. */
  public void displayOperationalAttributes() {
    JXplorerBrowser jx = null;

    if (owner instanceof JXplorerBrowser) jx = (JXplorerBrowser) owner;
    else return;

    showingOperationalAttributes = !showingOperationalAttributes;

    // EJP 17 August 2010.
    // CB 14 August 2012 - some directories (looking at you Active Directory) don't support the '+'
    // operator... so do it manually as well...
    String[] opAttrs = {
      "+",
      "createTimeStamp",
      "creatorsName",
      "entryFlags",
      "federationBoundary",
      "localEntryID",
      "modifiersName",
      "modifyTimeStamp",
      "structuralObjectClass",
      "subordinateCount",
      "subschemaSubentry"
    };
    DXEntry entry = null;

    if (showingOperationalAttributes) {
      try {
        entry = (jx.getSearchBroker()).unthreadedReadEntry(currentDN, opAttrs);
        StringBuffer buffy = new StringBuffer("DN: " + currentDN.toString() + "\n\n");

        // Get the attribute values...
        // EJP 17 August 2010: use the actual attributes returned.
        NamingEnumeration ne = null;

        try {
          ne = entry.getAll();
          while (ne.hasMore()) {
            DXAttribute att = (DXAttribute) ne.next();
            buffy.append(att.getName() + ": " + att.get().toString() + "\n");

            tableData.insertOperationalAttribute(att);
          }
        } finally {
          if (ne != null) ne.close();
        }

        tableData.fireTableDataChanged();
      } catch (NamingException e) {
        CBUtility.error(
            TableAttributeEditor.this, CBIntText.get("Unable to read entry " + currentDN), e);
      }
    } else {
      tableData.removeOperationalAttributes();
      tableData.fireTableDataChanged();
    }
  }
  /**
   * Normally called by the 'Yes' button listener of the virtual entry dialog. This method opens the
   * New Entry dialog in simple mode (or Change Classes dialog). If the user selects one or more
   * object classes they are added to the entry and displayed in the table editor.
   */
  public void processVirtualEntry() {

    ChangeObjectClassWin userData = null;
    if (dataSource.getSchemaOps() == null) {
      JOptionPane.showMessageDialog(
          owner,
          CBIntText.get(
              "Because there is no schema currently published by the\ndirectory, changing an entry's object class is unavailable."),
          CBIntText.get("No Schema"),
          JOptionPane.INFORMATION_MESSAGE);
      return;
    } else {
      shutVirtualEntryDialog(); // TE: kill the prompt window.
      userData =
          new ChangeObjectClassWin(dataSource, currentEntry.getDN(), null, this, owner, true);
      userData.setSize(400, 250);
      CBUtility.center(userData, owner); // TE: centres window.
      userData.setVisible(true);

      while (userData.isVisible()) // TE: don't do anything until the New Entry window is closed.
      {
        try {
          wait();
        } catch (Exception e) {
          userData.dispose();
        }
      }
    }

    if (userData.newObjectClasses
        != null) // TE: if the user has selected one or more object classes - add them to the entry
                 // in the directory.
    {
      try {
        DXOps dxOps = new DXOps(dataSource.getLdapContext());
        dxOps.addAttribute(currentEntry.getDN(), userData.newObjectClasses);
        dataSource.getEntry(
            currentEntry
                .getDN()); // TE: hack??  forces the entry to be read again - otherwise we don't
                           // display the naming value.
      } catch (NamingException e) {
        CBUtility.error(
            TableAttributeEditor.this,
            CBIntText.get(
                "Unable to add new object classes to {0}.",
                new String[] {currentEntry.getDN().toString()}),
            e);
      }
    }
  }
  protected void setReadWrite(boolean writeable, DXEntry entry) {
    submit.setEnabled(writeable);
    reset.setEnabled(writeable);
    changeClass.setEnabled(writeable);
    opAttrs.setEnabled(writeable);
    myEditor.setEnabled(writeable);
    popupTableTool.setReadWrite(writeable);

    if (entry != null
        && entry.get("objectclass") != null) // only allow class changes if we can find
    changeClass.setEnabled(true); // some to start with!
  }
  /** Writes the data currently in the table editor to the directory. */
  public void writeTableData() {

    myEditor.stopCellEditing();

    if (dataSource == null) // if ds is null, data is not modifiable...
    {
      CBUtility.error("no datasource to write data to in writeTableData()");
      return;
    } // shouldn't happen

    DXEntry oldEntry = tableData.getOldEntry();

    DXEntry newEntry = tableData.getNewEntry();

    /*   Check to see if major surgery is needed - whether the user has been
     *   messing with the object class list. */

    if (classChangedOriginalEntry != null) {

      // use the saved state of the pre-class-changed entry as the 'old entry'
      // state.
      oldEntry = classChangedOriginalEntry;
      classChangedOriginalEntry =
          null; // this is only used once! (either the object class change will
      // now succeed, or fail - either way, the entry state is reset to
      // match what's in the directory.)

      if (objectClassesChanged(oldEntry, newEntry)) {
        oldEntry.removeEmptyAttributes();

        newEntry.setStatus(oldEntry.getStatus());

        Object[] delSet =
            CBArray.difference(oldEntry.toIDStringArray(), newEntry.toIDStringArray());

        /* if there *are* attributes that should no longer exist, delete them by adding them (blanked)
         * to the complete 'newAtts' set of *all* known attributes. */

        if ((delSet != null) && (delSet.length > 0)) {
          for (int i = 0; i < delSet.length; i++) {
            newEntry.put(
                new DXAttribute(
                    delSet[i].toString())); // overwrite old values with an empty attribute
          }
        }
      }
    }

    dataSource.modifyEntry(oldEntry, newEntry);
  }
  private void displayEntry(
      DXEntry entry, DataBrokerQueryInterface ds, boolean storeOriginalEntry) {
    myEditor.stopCellEditing();

    //        checkedDN = null; // hack - resets promptForSave.
    // Store original Entry for reset
    if (entry != null && storeOriginalEntry && entry.getStatus() == DXEntry.NORMAL)
      originalEntry = new DXEntry(entry);

    // Set the globals...
    currentEntry = entry;
    dataSource = ds;

    if (entry != null && entry.size() == 0) {
      // If there is an entry and its size is zero - it's probably a virtual entry.
      // We need to give the user the option of adding an object class to it i.e. so that
      // it can be added to the directory as a real entry.
      //
      // Disable all the buttons except the 'Change Class' button - but rename this button
      // to 'Add Class' so the user hopefully has a bit more of an idea about what is going on.

      // Sets editor to a blank screen...
      tableData.clear();

      // Disable all buttons except the 'Change Class' button - rename this one...
      submit.setEnabled(false);
      reset.setEnabled(false);
      changeClass.setText(CBIntText.get("Add Class"));
      changeClass.setEnabled(true);
      opAttrs.setEnabled(false);

      virtualEntry = true;

      return;
    }

    virtualEntry = false;

    // Isn't a virtual entry...
    if (entry != null) currentDN = entry.getDN();

    // May have been changed to 'Add Class'...
    changeClass.setText(CBIntText.get("Change Class"));

    // Some quick faffing around, to see if we're coming back from a
    // change classes operation.
    if (classChangedOriginalEntry != null) {
      // If they have the same name, then we're reviewing the same entry - otherwise we've moved on
      if (entry == null || entry.getDN().equals(classChangedOriginalEntry.getDN()) == false)
        classChangedOriginalEntry = null;
    }

    /*
     *    Check that we're not displaying a new entry, and leaving unsaved changes
     *    behind.
     *
     *    This turns out to be quite tricky, and involves a bunch 'o special cases.
     *
     *    First check whether the table data has changed (if not, do nothing)
     *    ->  if the new entry is null, prompt user to save
     *    ->  OR if the DN has changed, and it wasn't due to a rename, prompt user to save
     *
     */
    if (tableData.changedByUser()) // user made changes - were they saved?  (i.e., are we
    { // displaying the result of those changes?)
      boolean prompt = false;

      DXEntry oldEntry = tableData.getOldEntry();

      if (oldEntry != null) {
        /*
         *    The code below is simply checking to see if the name of the
         *    new entry is different from the old entry, and if it is,
         *    whether that's due to the old entry being renamed.
         */
        if (entry == null) {
          prompt = true;
        }
        // TE: added the isEmpty check see bug: 3194.
        else if (!oldEntry.getDN().isEmpty() && entry.getDN().equals(oldEntry.getDN()) == false) {
          DN oldParent = oldEntry.getDN().getParent();

          DN newParent = entry.getDN().getParent();

          if (oldParent.equals(newParent) == false) {
            prompt = true;
          } else {
            if (entry.getDN().getLowestRDN().equals(tableData.getRDN()) == false) {
              prompt = true;
            }
          }
        }

        if (prompt) // yes, there is a risk of data loss - prompt the user.
        {
          checkForUnsavedChanges(); // see if the user wants to save their data
        }
      }
    }

    myEditor.setDataSource(
        ds); // Sets the DataBrokerQueryInterface in AttributeValueCellEditor used to get the syntax
             // of attributes.

    // only enable buttons if DataBrokerQueryInterface
    // is valid *and* we can modify data...

    if (dataSource == null || entry == null || dataSource.isModifiable() == false) {
      setReadWrite(false, entry);
    } else {
      setReadWrite(true, entry);
    }

    //        myEditor.stopCellEditing();

    if (entry != null) {
      entry.expandAllAttributes();
      currentDN = entry.getDN();

      tableData.insertAttributes(entry);
      popupTableTool.setDN(currentDN); // Sets the DN in SmartPopupTableTool.
      myEditor.setDN(
          currentDN); // Sets the DN in the attributeValueCellEditor which can be used to identify
                      // the entry that is being modified/
    } else {
      tableData.clear(); // Sets editor to a blank screen.
    }

    tableScroller.getVerticalScrollBar().setValue(0); // Sets the scroll bar back to the top.
  }
  /** Opens the change class dialog. */
  public void changeClass() { // JPanel mainPanel
    /*
     *    MINOR MAGIC
     *
     *    This code reuses the 'new entry window'.  In order to make things
     *    sane, we prompt the user to save any serious changes before continuing.
     *    (Things can get really wierd if the user changes the name and then
     *    tries to change the objectclass - best to avoid the whole issue.)
     */
    myEditor.stopCellEditing();

    if (virtualEntry) {
      doVirtualEntryDisplay();
      return;
    }

    /*
     *    classChangedOriginalEntry saves the original state of the entry
     *    between visits to NewEntryWin.  (- I wonder if it would be neater
     *    to just reset the 'oldEntry' state of the table every time? ).
     *    Check it's not been set already (i.e. Pathological User is paying
     *    multiple visits to the NewEntryWin.)
     */
    if (classChangedOriginalEntry == null) classChangedOriginalEntry = tableData.getOldEntry();

    DXEntry newEntry = tableData.getNewEntry();
    DN newDN = newEntry.getDN();

    /*
     *    Pathalogical user has messed with the name, *and* wants to
     *    change the object classes...
     */
    if (newDN.equals(classChangedOriginalEntry.getDN()) == false) {
      checkForUnsavedChanges();
      /*
      if (promptForSave() == false)  // we may need to reset the 'newEntry' data
      {                                   // if the user discards their changes.

          tableData.reset();              // resets the table before going on.

          newEntry = tableData.getNewEntry();
          newDN = newEntry.getDN();
      }
      else // user has saved data - so now we need to reset the 'classChangedOriginalEntry'
      {
      */
      // to the changed (and hopefully saved!) data.
      // NB: If the directory write fails, then the change classes will also fail...
      classChangedOriginalEntry = tableData.getNewEntry();
    }

    /*
     *    Open NewEntryWin, allowing the user to reset the objectclass attribute.
     */

    /*
            NewEntryWin userData = new NewEntryWin(newDN.parentDN(), newDN,
                                    dataSource,
                                    newEntry.getAsNonNullAttributes(),
                                    newDN.getLowestRDN().toString(), TableAttributeEditor.this,
                                    CBUtility.getParentFrame(mainPanel));
    */
    if (dataSource.getSchemaOps() == null) {
      JOptionPane.showMessageDialog(
          owner,
          CBIntText.get(
              "Because there is no schema currently published by the\ndirectory, changing an entry's object class is unavailable."),
          CBIntText.get("No Schema"),
          JOptionPane.INFORMATION_MESSAGE);
      return;
    } else {
      ChangeObjectClassWin userData =
          new ChangeObjectClassWin(
              dataSource,
              newDN,
              newEntry.getAsNonNullAttributes(),
              this,
              CBUtility.getParentFrame(this),
              false);
      userData.setSize(400, 250);
      CBUtility.center(userData, owner); // TE: centres window.
      userData.setVisible(true);
    }
  }
  /**
   * Clear out all the old editors, and get new editors corresponding to the new object classes.
   *
   * @param entry the entry to be displayed by all the editors
   * @param ds the datasource the editors may use for more info
   * @param ocs the object classes (in order) to find editors for.
   */
  protected void setEditors(DXEntry entry, DataBrokerQueryInterface ds, Vector ocs) {

    try {
      clearPluggableEditors(); // clear all extra editors

      // search for unique structural editors...

      if ("false".equalsIgnoreCase(JXConfig.getProperty("plugins.ignoreUniqueness"))) {
        if (ocs == null) // TE: may happen if virtual entry.
        return;

        int size = ocs.size();

        for (int i = 0; i < size; i++) {
          Object objectClass = ocs.get(i);
          if (objectClass != null) {
            PluggableEditor ed = getEditor(objectClass.toString());
            if (ed != null && ed.isUnique() == true) // found a unique editor
            { // so clear old ones,
              addUniqueEditor(ed); // and use the unique one
              refreshEditors(entry, ds); // to display the data
              setCurrentEditor(ed);
              return; // ... and exit.
            }
          }
        }
      } else log.warning("skipping uniqueness test for pluggable editors");

      boolean newEdSet = false;

      // search for non-unique structural editors
      for (int i = 0; i < ocs.size(); i++) {
        Object objectClass = ocs.get(i);
        if (objectClass != null) {
          PluggableEditor ed = getEditor(objectClass.toString());
          if (ed != null) {
            addEditor(ed);

            // Force the displayed editor to be the first pluggable one...
            if (newEdSet == false) {
              setCurrentEditor(ed);
              newEdSet = true;
            }
          }
        }
      }

      // search for non-structural editors
      try {
        Attribute allOCs = entry.getAllObjectClasses();
        if (allOCs != null) {
          Enumeration vals = allOCs.getAll();
          while (vals.hasMoreElements()) {
            Object oc = vals.nextElement();
            if (oc != null) {
              String ocName = oc.toString();
              if (ocs.contains(ocName)
                  == false) // don't bother with struct objectclasses dealt with above
              {
                PluggableEditor ed = getEditor(ocName);

                if (ed != null) {
                  addEditor(ed);

                  if (ed.isUnique()) // a special service to users...
                  log.warning(
                        "WARNING: Illegal unique editor defined for oc: "
                            + ocName
                            + " not allowed - (oc not in primary structural inheritance chain)");
                }
              }
            }
          }
        }
      } catch (NamingException e) {
        log.log(
            Level.WARNING,
            "WARNING: non-fatal exception getting object classes for plugin editors. ",
            e);
      }

      addEditor(templateDisplay); // and always add old faithfulls...
      // XXX
      if (entry.getStatus() != DXEntry.NEW) // well, almost always...
      addEditor(tableDisplay);
    } catch (Exception e) {
      log.warning("Unexpected Exception in AttributeDisplay\n" + e);
      e.printStackTrace();
    }
  }
  public void displayEntry(DXEntry dxentry, DataBrokerQueryInterface ds) {
    // Set the local data variables.

    dataSource = ds;
    entry = dxentry;

    // check that the default editors have been initialised.

    if (tableDisplay == null) initTableEditor();
    if (templateDisplay == null) initHTMLEditor();

    // check for a 'no data' display - if there is no data, revert
    // to the default html 'no data' template.

    if (entry
        == null) // || entry.size() == 0) //TE: This is commented out to allow virtual nodes to be
                 // edited.
    {
      if (oldOCSig != null) {
        clearPluggableEditors();

        if (activeEditors.size() == 0) {
          addEditor(templateDisplay);
        }
        oldOCSig = null;
      }
      refreshEditors(null, ds);
    } else {
      dataSource = ds; // may be null...
      Vector ocs = entry.getOrderedOCs();

      // try to create a unique 'signature' for a group of object classes
      // This relies on them being delivered in the same order though.  (Less
      // efficient if they aren't, but otherwise shouldn't be a big problem).
      String newOCSig = new String();

      if (ocs != null)
        for (int i = 0; i < ocs.size(); i++) {
          Object ocSig = ocs.get(i);
          if (ocSig != null) newOCSig += ocSig.toString();
        }

      // Check if signiture hasn't changed.  If it *has* changed,
      // reset the editors using 'setEditors', and update
      // the 'old object class signiture' variable.
      if (newOCSig.equals(oldOCSig) == false) {
        setEditors(entry, ds, ocs);
        oldOCSig = newOCSig;
      }

      // Some quick sanity checks...
      if (entry.getStatus() == DXEntry.NEW) // check for new entries (but *not* NEW_WRITTEN)...
      {
        // don't allow editors to appear that can't edit a new entry
        trimNonNewEntryEditors();
        suggestPluggableEditor();
      } else {
        // make sure that the html template display is around...
        // XXX (a bit of a hack - this should really check that *all*
        // XXX editor that can't handle new entries have been added back...
        // XXX (maybe set flag?)
        // TE: added '&& !currentEditor.isUnique()' b/c this code always made sure the HTML
        // TE: editor is visible, whereas with a unique plugin we only want that one visible...
        // TE: unless of course I am totally confused!  See bug 674.
        if (activeEditors.contains(templateDisplay) == false && !currentEditor.isUnique()) {
          add((PluggableEditor) templateDisplay, 0);
          if (currentEditor != null) // XXX hack hack.
          setCurrentEditor(currentEditor);
        }
      }

      if (activeEditors.contains(currentEditor) == false) {
        suggestPluggableEditor();
      }

      // now that the editor set we're using has been sorted out,
      // actually go and update the editors!  (Nb. this triggers an usaved changes check)
      refreshEditors(entry, ds);
    }
  }