/**
  * Test of onList method, of class JsonRosterSocketService.
  *
  * @throws java.io.IOException this is an error, not a failure, in the test
  * @throws jmri.JmriException this is an error, not a failure, in the test
  * @throws jmri.server.json.JsonException this is an error, not a failure, in the test
  */
 @Test
 public void testOnList() throws IOException, JmriException, JsonException {
   JsonNode data = null;
   Locale locale = Locale.ENGLISH;
   JsonRosterSocketService instance = new JsonRosterSocketService(this.connection);
   // assert we have not been listening
   Assert.assertEquals(0, Roster.getDefault().getPropertyChangeListeners().length);
   Roster.getDefault()
       .getEntriesInGroup(Roster.ALLENTRIES)
       .stream()
       .forEach(
           (entry) -> {
             Assert.assertEquals(1, entry.getPropertyChangeListeners().length);
           });
   // onList should cause listening to start if it hasn't already
   instance.onList(JsonRoster.ROSTER, data, locale);
   Assert.assertNotNull(this.connection.getMessage());
   Assert.assertEquals(Roster.getDefault().numEntries(), this.connection.getMessage().size());
   // assert we are listening
   Assert.assertEquals(1, Roster.getDefault().getPropertyChangeListeners().length);
   Roster.getDefault()
       .getEntriesInGroup(Roster.ALLENTRIES)
       .stream()
       .forEach(
           (entry) -> {
             Assert.assertEquals(2, entry.getPropertyChangeListeners().length);
           });
 }
 /** Test of onClose method, of class JsonRosterSocketService. */
 @Test
 public void testOnClose() {
   JsonRosterSocketService instance =
       new JsonRosterSocketService(new JsonMockConnection((DataOutputStream) null));
   // listen to the roster, since onClose stops listening to the roster
   instance.listen();
   // assert we are listening
   Assert.assertEquals(1, Roster.getDefault().getPropertyChangeListeners().length);
   Roster.getDefault()
       .getEntriesInGroup(Roster.ALLENTRIES)
       .stream()
       .forEach(
           (entry) -> {
             Assert.assertEquals(2, entry.getPropertyChangeListeners().length);
           });
   // the connection is closing, stop listening
   instance.onClose();
   // assert we are not listening
   Assert.assertEquals(0, Roster.getDefault().getPropertyChangeListeners().length);
   Roster.getDefault()
       .getEntriesInGroup(Roster.ALLENTRIES)
       .stream()
       .forEach(
           (entry) -> {
             Assert.assertEquals(1, entry.getPropertyChangeListeners().length);
           });
 }
Example #3
0
  /** Rebuild the Roster index and store it. */
  public void reindex() {
    Roster roster = new Roster();
    for (String fileName : Roster.getAllFileNames()) {
      // Read file
      try {
        Element loco =
            (new LocoFile())
                .rootFromName(LocoFile.getFileLocation() + fileName)
                .getChild("locomotive");
        if (loco != null) {
          RosterEntry re = new RosterEntry(loco);
          re.setFileName(fileName);
          roster.addEntry(re);
        }
      } catch (JDOMException | IOException ex) {
        log.error("Exception while loading loco XML file: {} execption: {}", fileName, ex);
      }
    }

    this.makeBackupFile(this.getRosterIndexPath());
    try {
      roster.writeFile(this.getRosterIndexPath());
    } catch (IOException ex) {
      log.error("Exception while writing the new roster file, may not be complete: {}", ex);
    }
    this.reloadRosterFile();
    log.info("Roster rebuilt, stored in {}", this.getRosterIndexPath());
  }
Example #4
0
 @Override
 public void propertyChange(PropertyChangeEvent e) {
   if (e.getPropertyName().equals(Roster.ADD)) {
     fireTableDataChanged();
   } else if (e.getPropertyName().equals(Roster.REMOVE)) {
     fireTableDataChanged();
   } else if (e.getPropertyName().equals(Roster.SAVED)) {
     // TODO This really needs to do something like find the index of the roster entry here
     if (e.getSource() instanceof RosterEntry) {
       int row = Roster.getDefault().getGroupIndex(rosterGroup, (RosterEntry) e.getSource());
       fireTableRowsUpdated(row, row);
     } else {
       fireTableDataChanged();
     }
   } else if (e.getPropertyName().equals(RosterGroupSelector.SELECTED_ROSTER_GROUP)) {
     setRosterGroup((e.getNewValue() != null) ? e.getNewValue().toString() : null);
   } else if (e.getPropertyName().startsWith("attribute")
       && e.getSource() instanceof RosterEntry) { // NOI18N
     int row = Roster.getDefault().getGroupIndex(rosterGroup, (RosterEntry) e.getSource());
     fireTableRowsUpdated(row, row);
   } else if (e.getPropertyName().equals(Roster.ROSTER_GROUP_ADDED)
       && e.getNewValue().equals(rosterGroup)) {
     fireTableDataChanged();
   }
 }
Example #5
0
 public final void setRosterGroup(String rosterGroup) {
   for (RosterEntry re : Roster.getDefault().getEntriesInGroup(rosterGroup)) {
     re.removePropertyChangeListener(this);
   }
   this.rosterGroup = rosterGroup;
   for (RosterEntry re : Roster.getDefault().getEntriesInGroup(rosterGroup)) {
     re.addPropertyChangeListener(this);
   }
   fireTableDataChanged();
 }
Example #6
0
 /** Editable state must be set in ctor. */
 @Override
 public boolean isCellEditable(int row, int col) {
   if (col == ADDRESSCOL) {
     return false;
   }
   if (col == PROTOCOL) {
     return false;
   }
   if (col == DECODERCOL) {
     return false;
   }
   if (col == ICONCOL) {
     return false;
   }
   if (col == DATEUPDATECOL) {
     return false;
   }
   if (editable) {
     RosterEntry re = Roster.getDefault().getGroupEntry(rosterGroup, row);
     if (re != null) {
       return (!re.isOpen());
     }
   }
   return editable;
 }
Example #7
0
 public List<RosterEntry> getEntriesInGroup(String group) {
   if (group == null || group.equals(Roster.ALLENTRIES) || group.isEmpty()) {
     return this.matchingList(null, null, null, null, null, null, null);
   } else {
     return this.getEntriesWithAttributeKeyValue(
         Roster.getRosterGroupProperty(group), "yes"); // NOI18N
   }
 }
 /**
  * Test of onMessage method INVALID on a ROSTER
  *
  * @throws java.io.IOException this is an error, not a failure, in the test
  * @throws jmri.JmriException this is an error, not a failure, in the test
  * @throws jmri.server.json.JsonException this is an error, not a failure, in the test
  */
 @Test
 public void testOnMessageInvalidRoster() throws IOException, JmriException, JsonException {
   JsonNode data =
       this.connection.getObjectMapper().createObjectNode().put(JSON.METHOD, "Invalid");
   Locale locale = Locale.ENGLISH;
   JsonRosterSocketService instance = new JsonRosterSocketService(this.connection);
   instance.onMessage(JsonRoster.ROSTER, data, locale);
   Assert.assertNotNull(this.connection.getMessage());
   Assert.assertEquals(Roster.getDefault().numEntries(), this.connection.getMessage().size());
 }
Example #9
0
 /**
  * @param group The group being queried or null for all entries in the roster.
  * @return The Number of roster entries in the specified group or 0 if the group does not exist.
  */
 public int numGroupEntries(String group) {
   if (group != null
       && !group.equals(Roster.ALLENTRIES)
       && !group.equals(Roster.AllEntries(Locale.getDefault()))) {
     return (this.rosterGroups.get(group) != null)
         ? this.rosterGroups.get(group).getEntries().size()
         : 0;
   } else {
     return this.numEntries();
   }
 }
Example #10
0
  /**
   * Create the panel used to select an existing entry
   *
   * @return a JPanel for handling the entry-selection GUI
   */
  protected JPanel layoutRosterSelection() {
    JPanel pane2a = new JPanel();
    pane2a.setLayout(new BoxLayout(pane2a, BoxLayout.X_AXIS));
    pane2a.add(new JLabel(Bundle.getMessage("USE LOCOMOTIVE SETTINGS FOR: ")));
    locoBox.setNonSelectedItem(Bundle.getMessage("<NONE - NEW LOCO>"));
    Roster.getDefault().addPropertyChangeListener(this);
    pane2a.add(locoBox);
    locoBox.addPropertyChangeListener(
        RosterEntrySelector.SELECTED_ROSTER_ENTRIES,
        new PropertyChangeListener() {

          @Override
          public void propertyChange(PropertyChangeEvent pce) {
            if (locoBox.getSelectedRosterEntries().length != 0) {
              // reset and disable decoder selection
              setDecoderSelectionFromLoco(locoBox.getSelectedRosterEntries()[0].titleString());
              go2.setEnabled(true);
              go2.setRequestFocusEnabled(true);
              go2.requestFocus();
              go2.setToolTipText(Bundle.getMessage("CLICK TO OPEN THE PROGRAMMER"));
            } else {
              go2.setEnabled(false);
              go2.setToolTipText(Bundle.getMessage("SELECT A LOCOMOTIVE OR DECODER TO ENABLE"));
            }
          }
        });
    idloco = new JToggleButton(Bundle.getMessage("IDENT"));
    idloco.setToolTipText(
        Bundle.getMessage(
            "READ THE LOCOMOTIVE'S ADDRESS AND ATTEMPT TO SELECT THE RIGHT SETTINGS"));
    if (jmri.InstanceManager.getNullableDefault(jmri.ProgrammerManager.class) != null
        && jmri.InstanceManager.getDefault(jmri.ProgrammerManager.class).getGlobalProgrammer()
            != null
        && !jmri.InstanceManager.getDefault(jmri.ProgrammerManager.class)
            .getGlobalProgrammer()
            .getCanRead()) {
      // can't read, disable the button
      idloco.setEnabled(false);
      idloco.setToolTipText(
          Bundle.getMessage("BUTTON DISABLED BECAUSE CONFIGURED COMMAND STATION CAN'T READ CVS"));
    }
    idloco.addActionListener(
        new ActionListener() {
          public void actionPerformed(java.awt.event.ActionEvent e) {
            if (log.isDebugEnabled()) {
              log.debug("Identify locomotive pressed");
            }
            startIdentifyLoco();
          }
        });
    pane2a.add(idloco);
    pane2a.setAlignmentX(JLabel.RIGHT_ALIGNMENT);
    return pane2a;
  }
Example #11
0
 /**
  * Delete a roster group, notifying all listeners of the change.
  *
  * <p>This method fires the property change notification "{@value #ROSTER_GROUP_REMOVED}".
  *
  * @param rg The group to be deleted
  */
 public void delRosterGroupList(String rg) {
   RosterGroup group = this.rosterGroups.remove(rg);
   String str = Roster.getRosterGroupProperty(rg);
   group
       .getEntries()
       .stream()
       .forEach(
           (re) -> {
             re.deleteAttribute(str);
           });
   firePropertyChange(ROSTER_GROUP_REMOVED, rg, null);
 }
 /** Test of listen method, of class JsonRosterSocketService. */
 @Test
 public void testListen() {
   JsonRosterSocketService instance = new JsonRosterSocketService(this.connection);
   Assert.assertEquals(0, Roster.getDefault().getPropertyChangeListeners().length);
   Roster.getDefault()
       .getEntriesInGroup(Roster.ALLENTRIES)
       .stream()
       .forEach(
           (entry) -> {
             Assert.assertEquals(1, entry.getPropertyChangeListeners().length);
           });
   // add the first time
   instance.listen();
   Assert.assertEquals(1, Roster.getDefault().getPropertyChangeListeners().length);
   Roster.getDefault()
       .getEntriesInGroup(Roster.ALLENTRIES)
       .stream()
       .forEach(
           (entry) -> {
             Assert.assertEquals(2, entry.getPropertyChangeListeners().length);
           });
   // don't add the second time
   instance.listen();
   Assert.assertEquals(1, Roster.getDefault().getPropertyChangeListeners().length);
   Roster.getDefault()
       .getEntriesInGroup(Roster.ALLENTRIES)
       .stream()
       .forEach(
           (entry) -> {
             Assert.assertEquals(2, entry.getPropertyChangeListeners().length);
           });
 }
Example #13
0
  /**
   * Check if an entry is consistent with specific properties.
   *
   * <p>A null String argument always matches. Strings are used for convenience in GUI building.
   *
   * @param r the roster entry being checked
   * @param roadName road name of entry or null for any road name
   * @param roadNumber road number of entry of null for any number
   * @param dccAddress address of entry or null for any address
   * @param mfg manufacturer of entry or null for any manufacturer
   * @param decoderModel decoder model of entry or null for any model
   * @param decoderFamily decoder family of entry or null for any family
   * @param id id of entry or null for any id
   * @param group group entry is member of or null for any group
   * @return True if the entry matches
   */
  public boolean checkEntry(
      RosterEntry r,
      String roadName,
      String roadNumber,
      String dccAddress,
      String mfg,
      String decoderModel,
      String decoderFamily,
      String id,
      String group) {

    if (id != null && !id.equals(r.getId())) {
      return false;
    }
    if (roadName != null && !roadName.equals(r.getRoadName())) {
      return false;
    }
    if (roadNumber != null && !roadNumber.equals(r.getRoadNumber())) {
      return false;
    }
    if (dccAddress != null && !dccAddress.equals(r.getDccAddress())) {
      return false;
    }
    if (mfg != null && !mfg.equals(r.getMfg())) {
      return false;
    }
    if (decoderModel != null && !decoderModel.equals(r.getDecoderModel())) {
      return false;
    }
    if (decoderFamily != null && !decoderFamily.equals(r.getDecoderFamily())) {
      return false;
    }
    if (group != null
        && !Roster.ALLENTRIES.equals(group)
        && (r.getAttribute(Roster.getRosterGroupProperty(group)) == null
            || !r.getAttribute(Roster.getRosterGroupProperty(group)).equals("yes"))) { // NOI18N
      return false;
    }
    return true;
  }
Example #14
0
  public void actionPerformed(ActionEvent e) {
    // obtain a HardcopyWriter to do this
    Roster r = Roster.instance();
    String title = "DecoderPro Roster";
    String rosterGroup = r.getDefaultRosterGroup();
    // rosterGroup may legitimately be null
    // but getProperty returns null if the property cannot be found, so
    // we test that the property exists before attempting to get its value
    if (Beans.hasProperty(wi, RosterGroupSelector.SELECTED_ROSTER_GROUP)) {
      rosterGroup = (String) Beans.getProperty(wi, RosterGroupSelector.SELECTED_ROSTER_GROUP);
    }
    if (rosterGroup == null) {
      title = title + " All Entries";
    } else {
      title = title + " Group " + rosterGroup + " Entires";
    }
    HardcopyWriter writer = null;
    try {
      writer = new HardcopyWriter(mFrame, title, 10, .5, .5, .5, .5, isPreview);
    } catch (HardcopyWriter.PrintCanceledException ex) {
      log.debug("Print cancelled");
      return;
    }

    // add the image
    ImageIcon icon =
        new ImageIcon(FileUtil.findURL("resources/decoderpro.gif", FileUtil.Location.INSTALLED));
    // we use an ImageIcon because it's guaranteed to have been loaded when ctor is complete
    writer.write(icon.getImage(), new JLabel(icon));
    // Add a number of blank lines, so that the roster entry starts below the decoderpro logo
    int height = icon.getImage().getHeight(null);
    int blanks = (height - writer.getLineAscent()) / writer.getLineHeight();

    try {
      for (int i = 0; i < blanks; i++) {
        String s = "\n";
        writer.write(s, 0, s.length());
      }
    } catch (IOException ex) {
      log.warn("error during printing: " + ex);
    }

    // Loop through the Roster, printing as needed
    List<RosterEntry> l = r.matchingList(null, null, null, null, null, null, null); // take all
    log.debug("Roster list size: " + l.size());
    for (RosterEntry re : l) {
      if (rosterGroup != null) {
        if (re.getAttribute(Roster.getRosterGroupProperty(rosterGroup)) != null
            && re.getAttribute(Roster.getRosterGroupProperty(rosterGroup)).equals("yes")) {
          re.printEntry(writer);
        }
      } else {
        re.printEntry(writer);
      }
    }

    // and force completion of the printing
    writer.close();
  }
Example #15
0
 /**
  * Copy a roster group, adding every entry in the roster group to the new group.
  *
  * <p>If a roster group with the target name already exists, this method silently fails to rename
  * the roster group. The GUI method CopyRosterGroupAction.performAction() catches this error and
  * informs the user. This method fires the property change "{@value #ROSTER_GROUP_ADDED}".
  *
  * @param oldName Name of the roster group to be copied
  * @param newName Name of the new roster group
  * @see jmri.jmrit.roster.swing.RenameRosterGroupAction
  */
 public void copyRosterGroupList(String oldName, String newName) {
   if (this.rosterGroups.containsKey(newName)) {
     return;
   }
   this.rosterGroups.put(newName, new RosterGroup(newName));
   String newGroup = Roster.getRosterGroupProperty(newName);
   this.rosterGroups
       .get(oldName)
       .getEntries()
       .stream()
       .forEach(
           (re) -> {
             re.putAttribute(newGroup, "yes"); // NOI18N
           });
   this.addRosterGroup(new RosterGroup(newName));
 }
Example #16
0
 // cache selectedRosterEntries so that multiple calls to this
 // between selection changes will not require the creation of a new array
 @Override
 @edu.umd.cs.findbugs.annotations.SuppressWarnings(
     value = "EI_EXPOSE_REP",
     justification = "Want to give access to mutable, original roster objects")
 public RosterEntry[] getSelectedRosterEntries() {
   if (selectedRosterEntries == null) {
     int[] rows = dataTable.getSelectedRows();
     selectedRosterEntries = new RosterEntry[rows.length];
     for (int idx = 0; idx < rows.length; idx++) {
       selectedRosterEntries[idx] =
           Roster.instance()
               .getEntryForId(sorter.getValueAt(rows[idx], RosterTableModel.IDCOL).toString());
     }
   }
   return selectedRosterEntries;
 }
Example #17
0
  /** Start with a decoder selected, so we're going to create a new RosterEntry. */
  protected void openNewLoco() {
    // find the decoderFile object
    DecoderFile decoderFile = DecoderIndexFile.instance().fileFromTitle(selectedDecoderType());
    if (log.isDebugEnabled()) {
      log.debug("decoder file: " + decoderFile.getFilename());
    }

    // create a dummy RosterEntry with the decoder info
    RosterEntry re = new RosterEntry();
    re.setDecoderFamily(decoderFile.getFamily());
    re.setDecoderModel(decoderFile.getModel());
    re.setId(Bundle.getMessage("LabelNewDecoder"));
    // note that we're leaving the filename null
    // add the new roster entry to the in-memory roster
    Roster.getDefault().addEntry(re);

    startProgrammer(decoderFile, re, (String) programmerBox.getSelectedItem());
  }
Example #18
0
 /** Provides the empty String if attribute doesn't exist. */
 @Override
 public Object getValueAt(int row, int col) {
   // get roster entry for row
   RosterEntry re = Roster.getDefault().getGroupEntry(rosterGroup, row);
   if (re == null) {
     log.debug("roster entry is null!");
     return null;
   }
   switch (col) {
     case IDCOL:
       return re.getId();
     case ADDRESSCOL:
       return re.getDccLocoAddress().getNumber();
     case DECODERCOL:
       return re.getDecoderModel();
     case MODELCOL:
       return re.getModel();
     case ROADNAMECOL:
       return re.getRoadName();
     case ROADNUMBERCOL:
       return re.getRoadNumber();
     case MFGCOL:
       return re.getMfg();
     case ICONCOL:
       return getIcon(re);
     case OWNERCOL:
       return re.getOwner();
     case DATEUPDATECOL:
       return re.getDateUpdated();
     case PROTOCOL:
       return re.getProtocolAsString();
     default:
       break;
   }
   String value = re.getAttribute(getColumnName(col).replaceAll("\\s", "")); // NOI18N
   if (value != null) {
     return value;
   }
   return "";
 }
Example #19
0
 /**
  * Identify locomotive complete, act on it by setting the GUI. This will fire "GUI changed" events
  * which will reset the decoder GUI.
  */
 protected void selectLoco(int dccAddress) {
   // raise the button again
   idloco.setSelected(false);
   // locate that loco
   List<RosterEntry> l =
       Roster.getDefault()
           .matchingList(null, null, Integer.toString(dccAddress), null, null, null, null);
   if (log.isDebugEnabled()) {
     log.debug("selectLoco found " + l.size() + " matches");
   }
   if (l.size() > 0) {
     RosterEntry r = l.get(0);
     if (log.isDebugEnabled()) {
       log.debug("Loco id is " + r.getId());
     }
     locoBox.setSelectedItem(r);
   } else {
     log.warn("Read address " + dccAddress + ", but no such loco in roster");
     _statusLabel.setText(
         Bundle.getMessage("READ ADDRESS ")
             + dccAddress
             + Bundle.getMessage(", BUT NO SUCH LOCO IN ROSTER"));
   }
 }
  @Override
  public void actionPerformed(ActionEvent event) {

    Roster roster = Roster.instance();
    String rosterGroup = Roster.instance().getDefaultRosterGroup();
    RosterEntry[] entries;
    // rosterGroup may legitimately be null
    // but getProperty returns null if the property cannot be found, so
    // we test that the property exists before attempting to get its value
    if (Beans.hasProperty(wi, RosterGroupSelector.SELECTED_ROSTER_GROUP)) {
      rosterGroup = (String) Beans.getProperty(wi, RosterGroupSelector.SELECTED_ROSTER_GROUP);
      log.debug("selectedRosterGroup was {}", rosterGroup);
    }
    if (Beans.hasProperty(wi, "selectedRosterEntries")) {
      entries = (RosterEntry[]) Beans.getProperty(wi, "selectedRosterEntries");
      if (entries != null) {
        log.debug("selectedRosterEntries found {} entries", entries.length);
      } else {
        log.debug("selectedRosterEntries left entries null");
      }
    } else {
      entries = selectRosterEntry(rosterGroup);
      if (entries != null) {
        log.debug("selectRosterEntry(rosterGroup) found {} entries", entries.length);
      } else {
        log.debug("selectRosterEntry(rosterGroup) left entries null");
      }
    }
    if (entries == null) {
      return;
    }
    // get parent object if there is one
    // Component parent = null;
    // if ( event.getSource() instanceof Component) parent = (Component)event.getSource();

    // find the file for the selected entry
    for (RosterEntry re : entries) {
      String filename = roster.fileFromTitle(re.titleString());
      String fullFilename = LocoFile.getFileLocation() + filename;
      log.debug("resolves to [{}], [{}]", filename, fullFilename);

      // prompt for one last chance
      log.debug("rosterGroup now {}", rosterGroup);
      if (rosterGroup == null) {
        if (!userOK(re.titleString(), filename, fullFilename)) {
          return;
        }
        // delete it from roster
        roster.removeEntry(re);
      } else {
        String group = Roster.getRosterGroupProperty(rosterGroup);
        log.debug("removing {} group from entry", group);
        re.deleteAttribute(group);
        re.updateFile();
      }
      Roster.writeRosterFile();

      // backup the file & delete it
      if (rosterGroup == null) {
        try {
          // ensure preferences will be found
          FileUtil.createDirectory(LocoFile.getFileLocation());

          // move original file to backup
          LocoFile df = new LocoFile(); // need a dummy object to do this operation in next line
          df.makeBackupFile(LocoFile.getFileLocation() + filename);

        } catch (Exception ex) {
          log.error("error during locomotive file output: " + ex);
        }
      }
    }
  }
Example #21
0
 /**
  * Locate the single instance of Roster, loading it if need be.
  *
  * <p>Calls {@link #getDefault() } to provide the single instance.
  *
  * @deprecated 4.5.1
  * @return The valid Roster object
  */
 @Deprecated
 public static synchronized Roster instance() {
   return Roster.getDefault();
 }
Example #22
0
 @Override
 public int getRowCount() {
   return Roster.getDefault().numGroupEntries(rosterGroup);
 }
Example #23
0
 /**
  * Store the roster in the default place, including making a backup if needed.
  *
  * <p>Uses writeFile(String), a protected method that can write to a specific location.
  *
  * @deprecated Since 4.0 Use Roster.getDefault().writeRoster() instead
  * @see #writeRoster()
  */
 @Deprecated
 public static void writeRosterFile() {
   Roster.getDefault().writeRoster();
 }
Example #24
0
 public RosterTableModel(boolean editable) {
   this.editable = editable;
   Roster.getDefault().addPropertyChangeListener(this);
 }
Example #25
0
  public RosterTable(boolean editable, int selectionMode) {
    super();
    dataModel = new RosterTableModel(editable);
    sorter = new TableSorter(dataModel);
    dataTable = new JTable(sorter);
    sorter.setTableHeader(dataTable.getTableHeader());
    dataScroll = new JScrollPane(dataTable);

    // set initial sort
    TableSorter tmodel = ((TableSorter) dataTable.getModel());
    tmodel.setSortingStatus(RosterTableModel.ADDRESSCOL, TableSorter.ASCENDING);

    // Use a "Numeric, if not, Alphanumeric" comparator
    tmodel.setColumnComparator(String.class, new jmri.util.PreferNumericComparator());

    // allow reordering of the columns
    dataTable.getTableHeader().setReorderingAllowed(true);

    // have to shut off autoResizeMode to get horizontal scroll to work (JavaSwing p 541)
    dataTable.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);

    dataTable.setColumnModel(columnModel);
    dataModel.setColumnModel(columnModel);
    dataTable.createDefaultColumnsFromModel();
    dataTable.setAutoCreateColumnsFromModel(false);

    TableColumn tc = columnModel.getColumnByModelIndex(RosterTableModel.PROTOCOL);
    columnModel.setColumnVisible(tc, false);

    for (String s : Roster.instance().getAllAttributeKeys()) {
      if (!s.contains("RosterGroup")
          && !s.toLowerCase().startsWith("sys")
          && !s.toUpperCase().startsWith("VSD")) { // NOI18N
        String[] r = s.split("(?=\\p{Lu})"); // NOI18N
        StringBuilder sb = new StringBuilder();
        sb.append(r[0].trim());
        // System.out.println("'"+r[0]+",");
        for (int j = 1; j < r.length; j++) {
          // System.out.println("'"+r[j]+",");
          sb.append(" ");
          sb.append(r[j].trim());
        }
        TableColumn c = new TableColumn(dataModel.getColumnCount());
        c.setHeaderValue((sb.toString()).trim());
        dataTable.addColumn(c);
        dataModel.addColumn(c.getHeaderValue());
        columnModel.setColumnVisible(c, false);
      }
    }

    // resize columns as requested
    resetColumnWidths();

    // general GUI config
    setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));

    // install items in GUI
    add(dataScroll);

    // set Viewport preferred size from size of table
    java.awt.Dimension dataTableSize = dataTable.getPreferredSize();
    // width is right, but if table is empty, it's not high
    // enough to reserve much space.
    dataTableSize.height = Math.max(dataTableSize.height, 400);
    dataTableSize.width = Math.max(dataTableSize.width, 400);
    dataScroll.getViewport().setPreferredSize(dataTableSize);

    dataTable.setSelectionMode(selectionMode);
    MouseListener mouseHeaderListener = new tableHeaderListener();
    dataTable.getTableHeader().addMouseListener(mouseHeaderListener);

    dataTable.setDefaultEditor(Object.class, new RosterCellEditor());

    dataTable
        .getSelectionModel()
        .addListSelectionListener(
            tableSelectionListener =
                new ListSelectionListener() {
                  @Override
                  public void valueChanged(ListSelectionEvent e) {
                    if (!e.getValueIsAdjusting()) {
                      selectedRosterEntries = null; // clear cached list of selections
                      if (dataTable.getSelectedRowCount() == 1) {
                        re =
                            Roster.instance()
                                .getEntryForId(
                                    sorter
                                        .getValueAt(
                                            dataTable.getSelectedRow(), RosterTableModel.IDCOL)
                                        .toString());
                      } else if (dataTable.getSelectedRowCount() > 1) {
                        re = null;
                      } // leave last selected item visible if no selection
                    } else if (e.getFirstIndex() == -1) {
                      // A reorder of the table might of occured therefore we are going to make sure
                      // that the selected item is still in view
                      moveTableViewToSelected();
                    }
                  }
                });
  }
Example #26
0
 @Override
 public void setValueAt(Object value, int row, int col) {
   // get roster entry for row
   RosterEntry re = Roster.getDefault().getGroupEntry(rosterGroup, row);
   if (re == null) {
     log.warn("roster entry is null!");
     return;
   }
   if (re.isOpen()) {
     log.warn("Entry is already open");
     return;
   }
   String valueToSet = (String) value;
   switch (col) {
     case IDCOL:
       if (re.getId().equals(valueToSet)) {
         return;
       }
       re.setId(valueToSet);
       break;
     case ROADNAMECOL:
       if (re.getRoadName().equals(valueToSet)) {
         return;
       }
       re.setRoadName(valueToSet);
       break;
     case ROADNUMBERCOL:
       if (re.getRoadNumber().equals(valueToSet)) {
         return;
       }
       re.setRoadNumber(valueToSet);
       break;
     case MFGCOL:
       if (re.getMfg().equals(valueToSet)) {
         return;
       }
       re.setMfg(valueToSet);
       break;
     case MODELCOL:
       if (re.getModel().equals(valueToSet)) {
         return;
       }
       re.setModel(valueToSet);
       break;
     case OWNERCOL:
       if (re.getOwner().equals(valueToSet)) {
         return;
       }
       re.setOwner(valueToSet);
       break;
     default:
       String attributeName = (getColumnName(col)).replaceAll("\\s", "");
       if (re.getAttribute(attributeName) != null
           && re.getAttribute(attributeName).equals(valueToSet)) {
         return;
       }
       if ((valueToSet == null) || valueToSet.isEmpty()) {
         re.deleteAttribute(attributeName);
       } else {
         re.putAttribute(attributeName, valueToSet);
       }
       break;
   }
   // need to mark as updated
   re.changeDateUpdated();
   re.updateFile();
 }