From 00176081fc90737ea8561e888bdfe2ff7d7a21a6 Mon Sep 17 00:00:00 2001 From: Mike Neilson Date: Thu, 11 May 2023 13:57:51 -0700 Subject: [PATCH] General cleanup in prep for future work. Remove commented out code with no explanation. Altered formatting to new standard. --- .../java/decodes/decoder/NumberParser.java | 6 - src/main/java/lrgs/ddsrecv/DdsRecv.java | 1112 +-- .../java/lrgs/ddsrecv/DdsRecvConnection.java | 1004 ++- src/main/java/lrgs/ddsserver/DdsServer.java | 662 +- src/main/java/lrgs/ddsserver/JLddsThread.java | 291 +- src/main/java/lrgs/gui/MessageBrowser.java | 2672 ++++--- .../java/lrgs/ldds/GetHostnameThread.java | 294 +- src/main/java/lrgs/ldds/LddsClient.java | 4513 ++++++------ src/main/java/lrgs/ldds/LddsCommand.java | 4 - src/main/java/lrgs/ldds/LddsInputStream.java | 38 +- src/main/java/lrgs/ldds/LddsLoggerThread.java | 520 +- src/main/java/lrgs/ldds/LddsMessage.java | 234 +- src/main/java/lrgs/ldds/LddsThread.java | 1025 +-- src/main/java/lrgs/ldds/ProtocolError.java | 31 +- .../lrgs/lrgsmain/JavaLrgsStatusProvider.java | 1167 ++-- src/main/java/lrgs/lrgsmain/LrgsConfig.java | 1177 ++-- .../lrgs/lrgsmain/LrgsInputException.java | 18 +- .../java/lrgs/rtstat/DdsRecvConDialog.java | 65 +- .../java/lrgs/rtstat/LrgsConfigDialog.java | 6189 ++++++++--------- .../java/lrgs/rtstat/RtStatCmdLineArgs.java | 1 - src/main/java/lrgs/rtstat/RtStatFrame.java | 227 +- src/main/java/lrgs/rtstat/RtStatPanel.java | 11 - .../java/lrgs/rtstat/RtSummaryStatFrame.java | 17 - .../java/lrgs/rtstat/RtSummaryStatPanel.java | 40 +- 24 files changed, 10543 insertions(+), 10775 deletions(-) diff --git a/src/main/java/decodes/decoder/NumberParser.java b/src/main/java/decodes/decoder/NumberParser.java index 423759582..a013a4b86 100644 --- a/src/main/java/decodes/decoder/NumberParser.java +++ b/src/main/java/decodes/decoder/NumberParser.java @@ -101,11 +101,6 @@ public void setDataType( char type ) /** @return the data type code */ public char getDataType() { return dataType; } - /** - Do not call this method. - */ - public void setMask(int m) { pbinaryMask = m; } - /** Parses an integer value from the passed field data. @param field the raw data extracted from the message. @@ -1070,4 +1065,3 @@ public static void main(String args[]) System.out.println("BIN_UNSIGNED_LSB Parsed '" + args[0] + "' to: " + v); } } - diff --git a/src/main/java/lrgs/ddsrecv/DdsRecv.java b/src/main/java/lrgs/ddsrecv/DdsRecv.java index e9c7d5a6a..897405459 100644 --- a/src/main/java/lrgs/ddsrecv/DdsRecv.java +++ b/src/main/java/lrgs/ddsrecv/DdsRecv.java @@ -6,7 +6,7 @@ * source code for your own purposes, except that no part of the information * contained in this file may be claimed to be proprietary. * - * Except for specific contractual terms between ILEX and the federal + * Except for specific contractual terms between ILEX and the federal * government, this source code is provided completely without warranty. * For more information contact: info@ilexeng.com */ @@ -46,557 +46,563 @@ */ public class DdsRecv extends Thread implements LrgsInputInterface { - /** Module name */ - public static String module = "DdsRecv"; - - /** Event num meaning that no connections are configured. */ - public static final int EVT_NO_CONNECTIONS = 1; - - /** Event num meaning that connection failed. */ - public static final int EVT_CONNECTION_FAILED = 2; - - /** Event num meaning that connection failed. */ - public static final int EVT_BAD_CONFIG = 3; - - /** Manages the primary group connections */ - protected DdsRecvConList recvConList; - - /** Shutdown flag */ - protected boolean isShutdown; - - /** We check for config changes this often. */ - protected static final long cfgCheckTime = 30000L; - - /** The configuration is stored in this 'settings' object. */ - protected DdsRecvSettings ddsRecvSettings; - - /** Last time that settings were read, used to detect changes. */ - protected long lastConfigRead; - - /** LrgsMain provides links to other modules. */ - protected LrgsMain lrgsMain; - - /** Last time that a message was retrieved. */ - protected long lastMsgRecvTime; - - /** Messages are archived here. */ - protected MsgArchive msgArchive; - - /** Slot number for the parent DDS receiver. */ - protected int slot; - - /** current status code (see LrgsInputInterface) */ - protected int statusCode; - - /** Explanatory status string */ - protected String status; - - /** secondary flag */ - private boolean isSecondary = false; - - /** Manages the secondary group connections */ - protected DdsRecvConList recvSeconConList; - - private long enableTime = 0L; - private long lastStatusTime = 0L; - private int numLastHour = 0, numThisHour = 0; - - /** - * Constructor - * - * @param lrgsMain - * the program main object. - * @param msgArchive - * used to store incoming messages. - */ - public DdsRecv(LrgsMain lrgsMain, MsgArchive msgArchive) - { - this.lrgsMain = lrgsMain; - this.msgArchive = msgArchive; - recvConList = new DdsRecvConList(lrgsMain); - // recvSeconConList = new DdsRecvConList(lrgsMain); - isShutdown = false; - ddsRecvSettings = DdsRecvSettings.instance(); - lastConfigRead = 0L; - slot = -1; - statusCode = DL_INIT; - status = "Initializing"; - lastMsgRecvTime = System.currentTimeMillis() - 3600000L; - } - - /** Causes the entire DdsRecv module to shut down. */ - public void shutdown() - { - isShutdown = true; - recvConList.shutdown(); - statusCode = DL_DISABLED; - status = "Shutdown"; - } - - /** - * Sets the last receive time. Called once prior to starting the thread. - * - * @param rt - * the last receive time, usually retrieved from the quality log. - */ - public void setLastMsgRecvTime(long rt) - { - if (rt <= 0) - rt = System.currentTimeMillis() - 3600000L; - lastMsgRecvTime = rt; - Logger.instance().debug1("LastMsgRecvTime set to " + lastMsgRecvTime); - } - - /** - * Thread run method - */ - public void run() - { - Logger.instance().debug1(module + " starting."); - - checkConfig(); - - recvConList.start(); - long lastCfgCheck = 0L; - statusCode = DL_STRSTAT; - status = "Active"; - while (!isShutdown) - { - if (System.currentTimeMillis() - lastCfgCheck > cfgCheckTime) - { - checkConfig(); - - lastCfgCheck = System.currentTimeMillis(); - } - if (LrgsConfig.instance().enableDdsRecv) - { - status = "Active"; - statusCode = DL_STRSTAT; - getSomeData(); - } - else - { - status = "Disabled"; - statusCode = DL_DISABLED; - // Logger.instance().debug3(module + " not enabled."); - try { sleep(1000L); } catch (InterruptedException ex) {} - } - } - } - - /** - * Internal method to get the next message and archive it. - */ - protected void getSomeData() - { - // If we don't currently have a connection, get the highest priority - // one from the list that's ready-to-go. - DdsRecvConnection con = recvConList.currentConnection; - if (con == null) - { - con = getConnection(); - if (con == null) - { - if (isSecondary) - Logger.instance().debug3( - module + ":" + EVT_NO_CONNECTIONS - + " No 'Secondary Group' DDS Connections available to receive data."); - else - Logger.instance().debug3( - module + ":" + EVT_NO_CONNECTIONS - + " No 'Primary Group' DDS Connections available to receive data."); - - try { sleep(1000L); } catch (InterruptedException ex) {} - return; - } - Logger.instance().debug3( - module + ":" + (-EVT_NO_CONNECTIONS) + " DDS Connections ARE available to receive data."); - // We now have a new connection. Send it the search criteria. - SearchCriteria searchCrit = buildSearchCrit(); - Logger.instance().debug1( - module + " Sending searchcrit to connection '" + con.getName() + "': " - + searchCrit.toString()); - if (!con.sendSearchCriteria(searchCrit)) - { - recvConList.currentConnection = null; - return; - } - } - try - { - // Logger.instance().info("trying getDcpMsg from " + con.getName()); - DcpMsg dcpMsg = con.getDcpMsg(); - if (dcpMsg != null) - { - lastMsgRecvTime = System.currentTimeMillis(); - archiveMsg(dcpMsg, con); - numThisHour++; - } - else - // all caught up, pause for 1 sec. - { - // Logger.instance().info("All Caught Up from " + - // con.getName()); - allCaughtUp(); - } - } - catch (LrgsInputException ex) - { - if (!isShutdown) - { - String msg = "- Connection to " + con.getName() - + " failed -- will switch to different connection."; - Logger.instance().warning(module + ":" + EVT_CONNECTION_FAILED + msg); - } - recvConList.currentConnection = null; - } - } - - /** - * Template method to get a connection. - * - * @return a connection from the pool. - */ - protected DdsRecvConnection getConnection() - { - return recvConList.getCurrentConnection(); - } - - /** - * Template method to archive a message. - * - * @param dcpMsg - * the message - * @param slotNum - * the input interface's slot number - */ - protected void archiveMsg(DcpMsg dcpMsg, DdsRecvConnection con) - { - msgArchive.archiveMsg(dcpMsg, con); - } - - /** - * Template method to take action when server reports that we are all caught - * up. This base-class implementation just pauses 1 second. - */ - protected void allCaughtUp() - { - try { sleep(1000L); } catch (InterruptedException ex) {} - } - - /** - * Builds a new search criteria to initialize a new connection. - */ - protected SearchCriteria buildSearchCrit() - { - // We now have a new connection. Send it the search criteria. - SearchCriteria searchCrit = new SearchCriteria(); - try - { - searchCrit.setLrgsSince(IDateFormat.time_t2string((int) (lastMsgRecvTime / 1000L) - 60)); - for (NetlistGroupAssoc nga : ddsRecvSettings.getNetlistGroupAssociations()) - { - String netlistGroup = nga.getGroupName(); - - if (netlistGroup.equalsIgnoreCase("both") - || (isSecondary && netlistGroup.equalsIgnoreCase("secondary")) - || (!isSecondary && netlistGroup.equalsIgnoreCase("primary"))) - { - if (nga.getNetlistName().toLowerCase().startsWith("source=") - && nga.getNetlistName().length() > 7) - { - String t = nga.getNetlistName().substring(7); - int tn = DcpMsgFlag.sourceName2Value(t); - if (tn != -1) - searchCrit.addSource(tn); - else - Logger.instance().warning(module + " invalid source specified '" - + nga.getNetlistName() + "'"); - } - else if (nga.getNetworkList() != null) - searchCrit.addNetworkList(nga.getNetworkList().makeFileName()); - } - } - if (ddsRecvSettings.decodesAll) - searchCrit.addNetworkList(""); - if (ddsRecvSettings.decodesProduction) - searchCrit.addNetworkList(""); - } - - catch (Exception e) - { - // TODO: handle exception - } - return searchCrit; - } - - /** - * Check the configuration file to see if it has changed. If so, reload it - * and put the changes into effect. - */ - protected void checkConfig() - { - Logger.instance().debug3(module + " checkConfig"); - String fn = EnvExpander.expand(LrgsConfig.instance().ddsRecvConfig); - File cf = new File(fn); - - if (cf.lastModified() > lastConfigRead || ddsRecvSettings.networkListsHaveChanged()) - { - - lastConfigRead = System.currentTimeMillis(); - if (!isSecondary) - { // reloads configuration from file if primary - // group thread. - try - { - synchronized (ddsRecvSettings) - { - ddsRecvSettings.setFromFile(fn); - ddsRecvSettings.setReloaded(true); - Logger.instance().info( - module + ":" + (-EVT_BAD_CONFIG) + " Loaded Config File '" + cf + "'"); - - } - - } - catch (BadConfigException ex) - { - Logger.instance().failure( - module + ":" + EVT_BAD_CONFIG + " Cannot read DDS Recv Config File '" + cf + "': " - + ex); - } - } - - else - // secondary group thread waits for the configuration to be reloaded - { - while (!ddsRecvSettings.isReloaded()) - { - try - { - sleep(5000L); - } - catch (Exception ex2) - { - - Logger.instance().failure( - module + ":" + EVT_BAD_CONFIG + " Cannot read DDS Recv Config File '" + cf - + "': " + ex2); - } - continue; - } - synchronized (ddsRecvSettings) - { - ddsRecvSettings.setReloaded(false); - } - - } - - synchronized (recvConList) - { - recvConList.removeAll(); - for (Iterator it = ddsRecvSettings.getConnectConfigs(); it.hasNext();) - { - DdsRecvConnectCfg ddsCfg = (DdsRecvConnectCfg) it.next(); - - if (isSecondary) - { // adds to secondary group list - if (ddsCfg.group != null && ddsCfg.group.equalsIgnoreCase("secondary")) - recvConList.addConnection(ddsCfg); - } - else - { // adds to primary group list - if (ddsCfg.group == null || ddsCfg.group.equalsIgnoreCase("primary")) - recvConList.addConnection(ddsCfg); - - } - } - } - } - } - - // ===================================================================== - // Methods from LrgsInputInterface - // ===================================================================== - - /** - * @return the type of this input interface. - */ - public int getType() - { - if (isSecondary) - return DL_DDS_SECONDRAY; - else - return DL_DDS; - } - - /** - * All inputs must keep track of their 'slot', which is a unique index into - * the LrgsMain's vector of all input interfaces. - * - * @param slot - * the slot number. - */ - public void setSlot(int slot) - { - this.slot = slot; - } - - /** @return the slot numbery that this interface was given at startup */ - public int getSlot() - { - return this.slot; - } - - /** - * @return the name of this interface. - */ - public String getInputName() - { - if (isSecondary) - return "DDS-Recv:Main(Secondary)"; - else - return "DDS-Recv:Main"; - } - - /** - * Initializes the interface. May throw LrgsInputException when an - * unrecoverable error occurs. - */ - public void initLrgsInput() throws LrgsInputException - { - } - - /** - * Shuts down the interface. Any errors encountered should be handled within - * this method. - */ - public void shutdownLrgsInput() - { - } - - /** - * Enable or Disable the interface. The interface should only attempt to - * archive messages when enabled. - * - * @param enabled - * true if the interface is to be enabled, false if disabled. - */ - public void enableLrgsInput(boolean enabled) - { - if (enabled) - enableTime = System.currentTimeMillis(); - else - enableTime = 0L; - } - - /** - * @return true if this downlink can report a Bit Error Rate. - */ - public boolean hasBER() - { - return false; - } - - /** - * @return the Bit Error Rate as a string. - */ - public String getBER() - { - return ""; - } - - /** - * @return true if this downlink assigns a sequence number to each msg. - */ - public boolean hasSequenceNums() - { - return false; - } - - /** - * @return the numeric code representing the current status. - */ - public int getStatusCode() - { - return statusCode; - } - - private static final long MS_PER_HR = 3600*1000L; - - /** - * @return a short string description of the current status. - */ - public String getStatus() - { - long now = System.currentTimeMillis(); - if (now/MS_PER_HR > lastStatusTime/MS_PER_HR) // Hour just changed - { - String s = "ddsMinHourly"; -Logger.instance().debug3("Looking for property '" + s + "'"); - int minHourly = LrgsConfig.instance().ddsMinHourly; - if (minHourly > 0 // Feature Enabled - && enableTime != 0L // Currently Enabled - && (now - enableTime > 3*MS_PER_HR)) // Have been up for at least 3 hours - { - if (numThisHour < minHourly) - { - Logger.instance().warning(module + " " + getInputName() - + " for hour ending " + new Date((now / MS_PER_HR) * MS_PER_HR) - + " number of messages received=" + numThisHour - + " which is under minimum threshold of " + minHourly); - } - if (numThisHour < (numLastHour/2)) - { - Logger.instance().warning(module + " " + getInputName() - + " for hour ending " + new Date((now / MS_PER_HR) * MS_PER_HR) - + " number of messages received=" + numThisHour - + " which is under half previous hour's total of " + numLastHour); - } - } - - // Rollover the counts. - numLastHour = numThisHour; - numThisHour = 0; - } - - lastStatusTime = now; - return status; - } - - public int getDataSourceId() - { - return -1; - } - - /** @return true if this interface receives APR messages */ - public boolean getsAPRMessages() - { - return true; - } - - /** - * @return the isSecondary - */ - public boolean isSecondary() - { - return isSecondary; - } - - /** - * @param isSecondary - * the isSecondary to set - */ - public void setSecondary(boolean isSecondary) - { - this.isSecondary = isSecondary; - } - - @Override - public String getGroup() - { - // TODO Auto-generated method stub - return null; - } + /** Module name */ + public static String module = "DdsRecv"; + + /** Event num meaning that no connections are configured. */ + public static final int EVT_NO_CONNECTIONS = 1; + + /** Event num meaning that connection failed. */ + public static final int EVT_CONNECTION_FAILED = 2; + + /** Event num meaning that connection failed. */ + public static final int EVT_BAD_CONFIG = 3; + + /** Manages the primary group connections */ + protected DdsRecvConList recvConList; + + /** Shutdown flag */ + protected boolean isShutdown; + + /** We check for config changes this often. */ + protected static final long cfgCheckTime = 30000L; + + /** The configuration is stored in this 'settings' object. */ + protected DdsRecvSettings ddsRecvSettings; + + /** Last time that settings were read, used to detect changes. */ + protected long lastConfigRead; + + /** LrgsMain provides links to other modules. */ + protected LrgsMain lrgsMain; + + /** Last time that a message was retrieved. */ + protected long lastMsgRecvTime; + + /** Messages are archived here. */ + protected MsgArchive msgArchive; + + /** Slot number for the parent DDS receiver. */ + protected int slot; + + /** current status code (see LrgsInputInterface) */ + protected int statusCode; + + /** Explanatory status string */ + protected String status; + + /** secondary flag */ + private boolean isSecondary = false; + + /** Manages the secondary group connections */ + protected DdsRecvConList recvSeconConList; + + private long enableTime = 0L; + private long lastStatusTime = 0L; + private int numLastHour = 0, numThisHour = 0; + + /** + * Constructor + * + * @param lrgsMain + * the program main object. + * @param msgArchive + * used to store incoming messages. + */ + public DdsRecv(LrgsMain lrgsMain, MsgArchive msgArchive) + { + this.lrgsMain = lrgsMain; + this.msgArchive = msgArchive; + recvConList = new DdsRecvConList(lrgsMain); + isShutdown = false; + ddsRecvSettings = DdsRecvSettings.instance(); + lastConfigRead = 0L; + slot = -1; + statusCode = DL_INIT; + status = "Initializing"; + lastMsgRecvTime = System.currentTimeMillis() - 3600000L; + } + + /** Causes the entire DdsRecv module to shut down. */ + public void shutdown() + { + isShutdown = true; + recvConList.shutdown(); + statusCode = DL_DISABLED; + status = "Shutdown"; + } + + /** + * Sets the last receive time. Called once prior to starting the thread. + * + * @param rt + * the last receive time, usually retrieved from the quality log. + */ + public void setLastMsgRecvTime(long rt) + { + if (rt <= 0) + { + rt = System.currentTimeMillis() - 3600000L; + } + lastMsgRecvTime = rt; + Logger.instance().debug1("LastMsgRecvTime set to " + lastMsgRecvTime); + } + + /** + * Thread run method + */ + public void run() + { + Logger.instance().debug1(module + " starting."); + + checkConfig(); + + recvConList.start(); + long lastCfgCheck = 0L; + statusCode = DL_STRSTAT; + status = "Active"; + while (!isShutdown) + { + if (System.currentTimeMillis() - lastCfgCheck > cfgCheckTime) + { + checkConfig(); + + lastCfgCheck = System.currentTimeMillis(); + } + if (LrgsConfig.instance().enableDdsRecv) + { + status = "Active"; + statusCode = DL_STRSTAT; + getSomeData(); + } + else + { + status = "Disabled"; + statusCode = DL_DISABLED; + // Logger.instance().debug3(module + " not enabled."); + try { sleep(1000L); } catch (InterruptedException ex) {} + } + } + } + + /** + * Internal method to get the next message and archive it. + */ + protected void getSomeData() + { + // If we don't currently have a connection, get the highest priority + // one from the list that's ready-to-go. + DdsRecvConnection con = recvConList.currentConnection; + if (con == null) + { + con = getConnection(); + if (con == null) + { + if (isSecondary) + Logger.instance().debug3( + module + ":" + EVT_NO_CONNECTIONS + + " No 'Secondary Group' DDS Connections available to receive data."); + else + Logger.instance().debug3( + module + ":" + EVT_NO_CONNECTIONS + + " No 'Primary Group' DDS Connections available to receive data."); + + try { sleep(1000L); } catch (InterruptedException ex) {} + return; + } + Logger.instance().debug3( + module + ":" + (-EVT_NO_CONNECTIONS) + " DDS Connections ARE available to receive data."); + // We now have a new connection. Send it the search criteria. + SearchCriteria searchCrit = buildSearchCrit(); + Logger.instance().debug1( + module + " Sending searchcrit to connection '" + con.getName() + "': " + + searchCrit.toString()); + if (!con.sendSearchCriteria(searchCrit)) + { + recvConList.currentConnection = null; + return; + } + } + try + { + // Logger.instance().info("trying getDcpMsg from " + con.getName()); + DcpMsg dcpMsg = con.getDcpMsg(); + if (dcpMsg != null) + { + lastMsgRecvTime = System.currentTimeMillis(); + archiveMsg(dcpMsg, con); + numThisHour++; + } + else + // all caught up, pause for 1 sec. + { + allCaughtUp(); + } + } + catch (LrgsInputException ex) + { + if (!isShutdown) + { + String msg = "- Connection to " + con.getName() + + " failed -- will switch to different connection."; + Logger.instance().warning(module + ":" + EVT_CONNECTION_FAILED + msg); + } + recvConList.currentConnection = null; + } + } + + /** + * Template method to get a connection. + * + * @return a connection from the pool. + */ + protected DdsRecvConnection getConnection() + { + return recvConList.getCurrentConnection(); + } + + /** + * Template method to archive a message. + * + * @param dcpMsg + * the message + * @param slotNum + * the input interface's slot number + */ + protected void archiveMsg(DcpMsg dcpMsg, DdsRecvConnection con) + { + msgArchive.archiveMsg(dcpMsg, con); + } + + /** + * Template method to take action when server reports that we are all caught + * up. This base-class implementation just pauses 1 second. + */ + protected void allCaughtUp() + { + try { sleep(1000L); } catch (InterruptedException ex) {} + } + + /** + * Builds a new search criteria to initialize a new connection. + */ + protected SearchCriteria buildSearchCrit() + { + // We now have a new connection. Send it the search criteria. + SearchCriteria searchCrit = new SearchCriteria(); + try + { + searchCrit.setLrgsSince(IDateFormat.time_t2string((int) (lastMsgRecvTime / 1000L) - 60)); + for (NetlistGroupAssoc nga : ddsRecvSettings.getNetlistGroupAssociations()) + { + String netlistGroup = nga.getGroupName(); + + if (netlistGroup.equalsIgnoreCase("both") + || (isSecondary && netlistGroup.equalsIgnoreCase("secondary")) + || (!isSecondary && netlistGroup.equalsIgnoreCase("primary"))) + { + if (nga.getNetlistName().toLowerCase().startsWith("source=") + && nga.getNetlistName().length() > 7) + { + String t = nga.getNetlistName().substring(7); + int tn = DcpMsgFlag.sourceName2Value(t); + if (tn != -1) + searchCrit.addSource(tn); + else + Logger.instance().warning(module + " invalid source specified '" + + nga.getNetlistName() + "'"); + } + else if (nga.getNetworkList() != null) + searchCrit.addNetworkList(nga.getNetworkList().makeFileName()); + } + } + if (ddsRecvSettings.decodesAll) + searchCrit.addNetworkList(""); + if (ddsRecvSettings.decodesProduction) + searchCrit.addNetworkList(""); + } + + catch (Exception e) + { + // TODO: handle exception + } + return searchCrit; + } + + /** + * Check the configuration file to see if it has changed. If so, reload it + * and put the changes into effect. + */ + protected void checkConfig() + { + Logger.instance().debug3(module + " checkConfig"); + String fn = EnvExpander.expand(LrgsConfig.instance().ddsRecvConfig); + File cf = new File(fn); + + if (cf.lastModified() > lastConfigRead || ddsRecvSettings.networkListsHaveChanged()) + { + + lastConfigRead = System.currentTimeMillis(); + if (!isSecondary) + { // reloads configuration from file if primary + // group thread. + try + { + synchronized (ddsRecvSettings) + { + ddsRecvSettings.setFromFile(fn); + ddsRecvSettings.setReloaded(true); + Logger.instance().info( + module + ":" + (-EVT_BAD_CONFIG) + " Loaded Config File '" + cf + "'"); + + } + + } + catch (BadConfigException ex) + { + Logger.instance().failure( + module + ":" + EVT_BAD_CONFIG + " Cannot read DDS Recv Config File '" + cf + "': " + + ex); + } + } + + else + // secondary group thread waits for the configuration to be reloaded + { + while (!ddsRecvSettings.isReloaded()) + { + try + { + sleep(5000L); + } + catch (Exception ex2) + { + + Logger.instance().failure( + module + ":" + EVT_BAD_CONFIG + " Cannot read DDS Recv Config File '" + cf + + "': " + ex2); + } + continue; + } + synchronized (ddsRecvSettings) + { + ddsRecvSettings.setReloaded(false); + } + + } + + synchronized (recvConList) + { + recvConList.removeAll(); + for (Iterator it = ddsRecvSettings.getConnectConfigs(); it.hasNext();) + { + DdsRecvConnectCfg ddsCfg = (DdsRecvConnectCfg) it.next(); + + if (isSecondary) + { // adds to secondary group list + if (ddsCfg.group != null && ddsCfg.group.equalsIgnoreCase("secondary")) + recvConList.addConnection(ddsCfg); + } + else + { // adds to primary group list + if (ddsCfg.group == null || ddsCfg.group.equalsIgnoreCase("primary")) + recvConList.addConnection(ddsCfg); + + } + } + } + } + } + + // ===================================================================== + // Methods from LrgsInputInterface + // ===================================================================== + + /** + * @return the type of this input interface. + */ + public int getType() + { + if (isSecondary) + return DL_DDS_SECONDRAY; + else + return DL_DDS; + } + + /** + * All inputs must keep track of their 'slot', which is a unique index into + * the LrgsMain's vector of all input interfaces. + * + * @param slot + * the slot number. + */ + public void setSlot(int slot) + { + this.slot = slot; + } + + /** @return the slot numbery that this interface was given at startup */ + public int getSlot() + { + return this.slot; + } + + /** + * @return the name of this interface. + */ + public String getInputName() + { + if (isSecondary) + { + return "DDS-Recv:Main(Secondary)"; + } + else + { + return "DDS-Recv:Main"; + } + } + + /** + * Initializes the interface. May throw LrgsInputException when an + * unrecoverable error occurs. + */ + public void initLrgsInput() throws LrgsInputException + { + } + + /** + * Shuts down the interface. Any errors encountered should be handled within + * this method. + */ + public void shutdownLrgsInput() + { + } + + /** + * Enable or Disable the interface. The interface should only attempt to + * archive messages when enabled. + * + * @param enabled + * true if the interface is to be enabled, false if disabled. + */ + public void enableLrgsInput(boolean enabled) + { + if (enabled) + { + enableTime = System.currentTimeMillis(); + } + else + { + enableTime = 0L; + } + } + + /** + * @return true if this downlink can report a Bit Error Rate. + */ + public boolean hasBER() + { + return false; + } + + /** + * @return the Bit Error Rate as a string. + */ + public String getBER() + { + return ""; + } + + /** + * @return true if this downlink assigns a sequence number to each msg. + */ + public boolean hasSequenceNums() + { + return false; + } + + /** + * @return the numeric code representing the current status. + */ + public int getStatusCode() + { + return statusCode; + } + + private static final long MS_PER_HR = 3600*1000L; + + /** + * @return a short string description of the current status. + */ + public String getStatus() + { + long now = System.currentTimeMillis(); + if (now/MS_PER_HR > lastStatusTime/MS_PER_HR) // Hour just changed + { + String s = "ddsMinHourly"; + Logger.instance().debug3("Looking for property '" + s + "'"); + int minHourly = LrgsConfig.instance().ddsMinHourly; + if (minHourly > 0 // Feature Enabled + && enableTime != 0L // Currently Enabled + && (now - enableTime > 3*MS_PER_HR)) // Have been up for at least 3 hours + { + if (numThisHour < minHourly) + { + Logger.instance().warning(module + " " + getInputName() + + " for hour ending " + new Date((now / MS_PER_HR) * MS_PER_HR) + + " number of messages received=" + numThisHour + + " which is under minimum threshold of " + minHourly); + } + if (numThisHour < (numLastHour/2)) + { + Logger.instance().warning(module + " " + getInputName() + + " for hour ending " + new Date((now / MS_PER_HR) * MS_PER_HR) + + " number of messages received=" + numThisHour + + " which is under half previous hour's total of " + numLastHour); + } + } + + // Rollover the counts. + numLastHour = numThisHour; + numThisHour = 0; + } + + lastStatusTime = now; + return status; + } + + public int getDataSourceId() + { + return -1; + } + + /** @return true if this interface receives APR messages */ + public boolean getsAPRMessages() + { + return true; + } + + /** + * @return the isSecondary + */ + public boolean isSecondary() + { + return isSecondary; + } + + /** + * @param isSecondary + * the isSecondary to set + */ + public void setSecondary(boolean isSecondary) + { + this.isSecondary = isSecondary; + } + + @Override + public String getGroup() + { + return null; + } } diff --git a/src/main/java/lrgs/ddsrecv/DdsRecvConnection.java b/src/main/java/lrgs/ddsrecv/DdsRecvConnection.java index b893bcae6..e228f1736 100644 --- a/src/main/java/lrgs/ddsrecv/DdsRecvConnection.java +++ b/src/main/java/lrgs/ddsrecv/DdsRecvConnection.java @@ -6,7 +6,7 @@ * source code for your own purposes, except that no part of the information * contained in this file may be claimed to be proprietary. * -* Except for specific contractual terms between ILEX and the federal +* Except for specific contractual terms between ILEX and the federal * government, this source code is provided completely without warranty. * For more information contact: info@ilexeng.com */ @@ -35,520 +35,500 @@ This class encapsulates a connection to a remote DDS server for the purpose of retrieving DCP data for my own local archive. */ -public class DdsRecvConnection - implements LrgsInputInterface +public class DdsRecvConnection implements LrgsInputInterface { - /** My status */ - String status; - - /** My slot number */ - private int slot; - - /** My configuration */ - private DdsRecvConnectCfg config; - - private long lastActivityTime; - private long lastMessageTime; - - private LddsClient lddsClient; - - private int dataSourceId; - - private LrgsMain lrgsMain; - - /** Dds Receive group: primary/secondary. Used to display group on rtstat screen */ - private String group; - - /** - * Constructor. - * @param config the configuration for this connection. - */ - public DdsRecvConnection(DdsRecvConnectCfg config, LrgsMain lrgsMain) - { - lddsClient = new LddsClient(config.host, config.port); - lddsClient.enableMultiMessageMode(true); - lddsClient.enableExtMessageMode(true); - lddsClient.setModule(DdsRecv.module); - - this.config = config; - slot = -1; - status = "Unused"; - lastActivityTime = 0L; - lastMessageTime = 0L; - dataSourceId = lrgs.db.LrgsConstants.undefinedId; - this.lrgsMain = lrgsMain; - group = config.group; - } - - /** - * @return the configuration for this connection. - */ - public DdsRecvConnectCfg getConfig() - { - return config; - } - - /** - * From LrgsInputInterface. - * @return the type of this input interface. - */ - public int getType() - { - return DL_DDSCON; - } - - /** - * From LrgsInputInterface. - * All inputs must keep track of their 'slot', which is a unique index - * into the LrgsMain's vector of all input interfaces. - * @param slot the slot number. - */ - public void setSlot(int slot) - { - this.slot = slot; - } - - /** - * From LrgsInputInterface. - * @return the name of this interface. - */ - public String getInputName() - { - return "DDS:" + config.name; - } - - /** - * From LrgsInputInterface. - * Initializes the interface by connecting to the server and sending - * the (authenticated or anonymous) hello message. - * @throws LrgsInputException when an unrecoverable error occurs. - */ - public void initLrgsInput() - throws LrgsInputException - { - status = "Initializing"; - Logger.instance().info(DdsRecv.module - + " Initializing DDS recv connection to " + lddsClient.getName()); - lastActivityTime = System.currentTimeMillis(); - lastMessageTime = System.currentTimeMillis(); - try - { - lddsClient.connect(); - status = "Ready"; - Logger.instance().info(DdsRecv.module - + " Connection established to " + lddsClient.getName()); - } - catch(UnknownHostException ex) - { - status = "Unknown Host"; - String msg = "Can't connect to " - + lddsClient.getName() + ": " + ex; - Logger.instance().warning( - DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " - + msg); - throw new LrgsInputException(msg); - } - catch(IOException ex) - { - status = "IO Error"; - String msg = "IO Error on connection to " - + lddsClient.getName() + ": " + ex; - Logger.instance().warning( - DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " - + msg); - throw new LrgsInputException(msg); - } - - if (config.authenticate) - { - PasswordFileEntry pfe; - try - { - pfe = CmdAuthHello.getPasswordFileEntry(config.username); - } - catch (UnknownUserException e) - { - pfe = null; - } -// PasswordFile pf; -// try -// { -// pf = new PasswordFile(new File( -// EnvExpander.expand("$LRGSHOME/.lrgs.passwd"))); -// pf.read(); -// } -// catch(IOException ex) -// { -// status = "Auth Error"; -// throw new LrgsInputException("Connection to " -// + lddsClient.getName() -// + " calls for authenticated connection " -// + "but can't read local password file: " + ex); -// } -// PasswordFileEntry pfe = pf.getEntryByName(config.username); - if (pfe == null) - throw new LrgsInputException("Connection to " - + lddsClient.getName() - + " calls for authenticated connection " - + "but no entry for username '" + config.username - + "'"); - try - { - lddsClient.sendAuthHello(pfe, AuthenticatorString.ALGO_SHA); - } - catch(IOException ex) - { - status = "IO Error"; - throw new LrgsInputException("IO Error on connection to " - + lddsClient.getName() + ": " + ex); - } - catch(ServerError ex) - { - status = "Rejected by Svr"; - throw new LrgsInputException("Server at " - + lddsClient.getName() + " rejected connection: " + ex); - } - catch(ProtocolError ex) - { - status = "Proto Error"; - throw new LrgsInputException("Protocol Error on connection to " - + lddsClient.getName() + ": " + ex); - } - } - else - { - try - { - lddsClient.sendHello(config.username); - } - catch(IOException ex) - { - status = "IO Error"; - throw new LrgsInputException("IO Error on connection to " - + lddsClient.getName() + ": " + ex); - } - catch(ServerError ex) - { - status = "Rejected by Svr"; - throw new LrgsInputException("Server at " - + lddsClient.getName() + " rejected connection: " + ex); - } - catch(ProtocolError ex) - { - status = "Proto Error"; - throw new LrgsInputException("Protocol Error on connection to " - + lddsClient.getName() + ": " + ex); - } - } - dataSourceId = + /** My status */ + String status; + + /** My slot number */ + private int slot; + + /** My configuration */ + private DdsRecvConnectCfg config; + + private long lastActivityTime; + private long lastMessageTime; + + private LddsClient lddsClient; + + private int dataSourceId; + + private LrgsMain lrgsMain; + + /** Dds Receive group: primary/secondary. Used to display group on rtstat screen */ + private String group; + + /** + * Constructor. + * @param config the configuration for this connection. + */ + public DdsRecvConnection(DdsRecvConnectCfg config, LrgsMain lrgsMain) + { + lddsClient = new LddsClient(config.host, config.port); + lddsClient.enableMultiMessageMode(true); + lddsClient.enableExtMessageMode(true); + lddsClient.setModule(DdsRecv.module); + + this.config = config; + slot = -1; + status = "Unused"; + lastActivityTime = 0L; + lastMessageTime = 0L; + dataSourceId = lrgs.db.LrgsConstants.undefinedId; + this.lrgsMain = lrgsMain; + group = config.group; + } + + /** + * @return the configuration for this connection. + */ + public DdsRecvConnectCfg getConfig() + { + return config; + } + + /** + * From LrgsInputInterface. + * @return the type of this input interface. + */ + public int getType() + { + return DL_DDSCON; + } + + /** + * From LrgsInputInterface. + * All inputs must keep track of their 'slot', which is a unique index + * into the LrgsMain's vector of all input interfaces. + * @param slot the slot number. + */ + public void setSlot(int slot) + { + this.slot = slot; + } + + /** + * From LrgsInputInterface. + * @return the name of this interface. + */ + public String getInputName() + { + return "DDS:" + config.name; + } + + /** + * From LrgsInputInterface. + * Initializes the interface by connecting to the server and sending + * the (authenticated or anonymous) hello message. + * @throws LrgsInputException when an unrecoverable error occurs. + */ + public void initLrgsInput() + throws LrgsInputException + { + status = "Initializing"; + Logger.instance().info(DdsRecv.module + + " Initializing DDS recv connection to " + lddsClient.getName()); + lastActivityTime = System.currentTimeMillis(); + lastMessageTime = System.currentTimeMillis(); + try + { + lddsClient.connect(); + status = "Ready"; + Logger.instance().info(DdsRecv.module + + " Connection established to " + lddsClient.getName()); + } + catch(UnknownHostException ex) + { + status = "Unknown Host"; + String msg = "Can't connect to " + + lddsClient.getName() + ": " + ex; + Logger.instance().warning( + DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " + + msg); + throw new LrgsInputException(msg); + } + catch(IOException ex) + { + status = "IO Error"; + String msg = "IO Error on connection to " + + lddsClient.getName() + ": " + ex; + Logger.instance().warning( + DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " + + msg); + throw new LrgsInputException(msg); + } + + if (config.authenticate) + { + PasswordFileEntry pfe; + try + { + pfe = CmdAuthHello.getPasswordFileEntry(config.username); + } + catch (UnknownUserException e) + { + pfe = null; + } + if (pfe == null) + throw new LrgsInputException("Connection to " + + lddsClient.getName() + + " calls for authenticated connection " + + "but no entry for username '" + config.username + + "'"); + try + { + lddsClient.sendAuthHello(pfe, AuthenticatorString.ALGO_SHA); + } + catch(IOException ex) + { + status = "IO Error"; + throw new LrgsInputException("IO Error on connection to " + + lddsClient.getName() + ": " + ex); + } + catch(ServerError ex) + { + status = "Rejected by Svr"; + throw new LrgsInputException("Server at " + + lddsClient.getName() + " rejected connection: " + ex); + } + catch(ProtocolError ex) + { + status = "Proto Error"; + throw new LrgsInputException("Protocol Error on connection to " + + lddsClient.getName() + ": " + ex); + } + } + else + { + try + { + lddsClient.sendHello(config.username); + } + catch(IOException ex) + { + status = "IO Error"; + throw new LrgsInputException("IO Error on connection to " + + lddsClient.getName() + ": " + ex); + } + catch(ServerError ex) + { + status = "Rejected by Svr"; + throw new LrgsInputException("Server at " + + lddsClient.getName() + " rejected connection: " + ex); + } + catch(ProtocolError ex) + { + status = "Proto Error"; + throw new LrgsInputException("Protocol Error on connection to " + + lddsClient.getName() + ": " + ex); + } + } + dataSourceId = lrgsMain.getDbThread().getDataSourceId(DL_DDS_TYPESTR, config.host); - } - - /** - * Sends a noop command to keep the connection alive. - */ - public void noop() - throws LrgsInputException - { - try - { - lddsClient.sendNoop(); - status = "Ready"; - lastActivityTime = System.currentTimeMillis(); - } - catch(Exception ex) - { - status = "Error"; - throw new LrgsInputException("Error sending NOOP: " + ex); - } - } - - /** - * @return true if this connection is enabled in the configuration. - */ - public boolean isEnabled() - { - return config.enabled; - } - - /** - * From LrgsInputInterface. - * Shuts down the interface. - * Any errors encountered should be handled within this method. - */ - public void shutdownLrgsInput() - { - lddsClient.disconnect(); - status = "Disconnected"; - } - - /** - * @return true if this connection is currently connected. - */ - public boolean isConnected() - { - return lddsClient.isConnected(); - } - - /** - * Enable or Disable the interface. - * The interface should only attempt to archive messages when enabled. - * @param enabled true if the interface is to be enabled, false if disabled. - */ - public void enableLrgsInput(boolean enabled) - { - if (enabled && !config.enabled) - { - Logger.instance().info("Enabling DDS-Recv connection to " - + config.host); - config.enabled = true; - } - else if (!enabled && config.enabled) - { - Logger.instance().info("Disabling DDS-Recv connection to " - + config.host); - config.enabled = false; - shutdownLrgsInput(); - status = "Disabled"; - } - } - - /** - * @return true if this downlink can report a Bit Error Rate. - */ - public boolean hasBER() - { - return false; - } - - /** - * @return the Bit Error Rate as a string. - */ - public String getBER() - { - return ""; - } - - /** - * @return true if this downlink assigns a sequence number to each msg. - */ - public boolean hasSequenceNums() - { - return false; - } - - /** - * @return the numeric code representing the current status. - */ - public int getStatusCode() - { - return DL_STRSTAT; - } - - /** - * @return a short string description of the current status. - */ - public String getStatus() - { - return status; - } - - /** - * @return slot number assigned to this interface. - */ - public int getSlot() - { - return slot; - } - - /** - * Sends a search criteria to the connection. - * @param searchCrit the search criteria. - * @return true on success, false on failure. - */ - public boolean sendSearchCriteria(SearchCriteria searchCrit) - { - DdsRecvSettings settings = DdsRecvSettings.instance(); - for(NetlistGroupAssoc nga : settings.getNetlistGroupAssociations()) - { - if (!TextUtil.strEqualIgnoreCase(nga.getGroupName(), group)) - continue; - if (nga.getNetworkList() == null) - { - if (!nga.getNetlistName().toLowerCase().startsWith("source=")) - Logger.instance().warning(DdsRecv.module + - " No network list found for group=" + nga.getGroupName() - + " list='" + nga.getNetlistName() + "' -- ignored."); - continue; - } - try - { - lddsClient.sendNetList(nga.getNetworkList(), null); - } - catch(ServerError ex) - { - Logger.instance().warning(DdsRecv.module + - "Server at " + lddsClient.getName() - + " rejected network list '" + nga.getNetworkList().makeFileName() - + "': " + ex + " -- ignored."); - } - catch(Exception ex) - { - String msg = DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " - + " Error sending network list to " - + lddsClient.getName() + ": " + ex; - Logger.instance().warning(msg); - System.err.println(msg); - ex.printStackTrace(System.err); - shutdownLrgsInput(); - status = "Error"; - return false; - } - } - searchCrit.DapsStatus = - config.acceptARMs ? SearchCriteria.ACCEPT : SearchCriteria.REJECT; - try - { -// Logger.instance().info(DdsRecv.module + -// " sending search crit '" + searchCrit.toString() + "'" -// + " to " + lddsClient.getName()); - lddsClient.sendSearchCrit(searchCrit); - status = "Catch-up"; - return true; - } - catch(Exception ex) - { - Logger.instance().warning( - DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " - + " Error sending search criteria to " - + lddsClient.getName() + ": " + ex); - shutdownLrgsInput(); - status = "Error"; - return false; - } - } - - /** - * @return a DCP message from the connection, or null if caught-up. - * @throws LrgsInputException if the connection has failed. - */ - public DcpMsg getDcpMsg() - throws LrgsInputException - { - try - { - DcpMsg msg = lddsClient.getDcpMsg(60); - long now = System.currentTimeMillis(); - lastActivityTime = now; - if (msg != null) - { - if (System.currentTimeMillis() - msg.getDapsTime().getTime() - < 30000L) - status = "Real-Time"; - lastMessageTime = now; - msg.setDataSourceId(dataSourceId); - } - else if (now - lastMessageTime > - DdsRecvSettings.instance().timeout * 1000L) - { - String errmsg = DdsRecv.module + - " timeout on connection to " + lddsClient.getName(); - Logger.instance().warning( - DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " - + errmsg); - lddsClient.disconnect(); - status = "Timeout"; - throw new LrgsInputException(errmsg); - } - return msg; - } - catch(Exception ex) - { - if (ex instanceof ServerError) - { - ServerError se = (ServerError)ex; - if (se.Derrno == LrgsErrorCode.DMSGTIMEOUT - || se.Derrno == LrgsErrorCode.DUNTIL) - { - long now = System.currentTimeMillis(); - if (now - lastMessageTime > - (DdsRecvSettings.instance().timeout * 1000L)) - { - String errmsg = DdsRecv.module + - " timeout on connection to " + lddsClient.getName(); - Logger.instance().warning( - DdsRecv.module + ":" - + DdsRecv.EVT_CONNECTION_FAILED + "- " - + errmsg); - lddsClient.disconnect(); - status = "Timeout"; - throw new LrgsInputException(errmsg); - } - else - { - Logger.instance().debug3(DdsRecv.module - + " caught up on connection " + getName()); - status = "Real-Time"; - return null; - } - } - } - String msg = DdsRecv.module + - " Error getting message from " + lddsClient.getName() - + ": " + ex; - Logger.instance().warning( - DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " - + msg); - lddsClient.disconnect(); - if (!(ex instanceof IOException) - && !(ex instanceof ServerError - && ((ServerError)ex).Derrno == LrgsErrorCode.DDDSINTERNAL - && ex.getMessage().contains("not currently usable"))) - { - System.err.println(msg); - ex.printStackTrace(System.err); - } - status = "Error"; - throw new LrgsInputException(msg); - } - } - - /** - * @return name of this connection. - */ - public String getName() - { - return lddsClient.getName(); - } - - public long getLastActivityTime() - { - return lastActivityTime; - } - - public void flush() - { - lddsClient.flushBufferedMessages(); - } - - public int getDataSourceId() { return dataSourceId; } - - /** @return true if this interface receives APR messages */ - public boolean getsAPRMessages() { return true; } + } + + /** + * Sends a noop command to keep the connection alive. + */ + public void noop() + throws LrgsInputException + { + try + { + lddsClient.sendNoop(); + status = "Ready"; + lastActivityTime = System.currentTimeMillis(); + } + catch(Exception ex) + { + status = "Error"; + throw new LrgsInputException("Error sending NOOP: " + ex); + } + } + + /** + * @return true if this connection is enabled in the configuration. + */ + public boolean isEnabled() + { + return config.enabled; + } + + /** + * From LrgsInputInterface. + * Shuts down the interface. + * Any errors encountered should be handled within this method. + */ + public void shutdownLrgsInput() + { + lddsClient.disconnect(); + status = "Disconnected"; + } + + /** + * @return true if this connection is currently connected. + */ + public boolean isConnected() + { + return lddsClient.isConnected(); + } + + /** + * Enable or Disable the interface. + * The interface should only attempt to archive messages when enabled. + * @param enabled true if the interface is to be enabled, false if disabled. + */ + public void enableLrgsInput(boolean enabled) + { + if (enabled && !config.enabled) + { + Logger.instance().info("Enabling DDS-Recv connection to " + + config.host); + config.enabled = true; + } + else if (!enabled && config.enabled) + { + Logger.instance().info("Disabling DDS-Recv connection to " + + config.host); + config.enabled = false; + shutdownLrgsInput(); + status = "Disabled"; + } + } + + /** + * @return true if this downlink can report a Bit Error Rate. + */ + public boolean hasBER() + { + return false; + } + + /** + * @return the Bit Error Rate as a string. + */ + public String getBER() + { + return ""; + } + + /** + * @return true if this downlink assigns a sequence number to each msg. + */ + public boolean hasSequenceNums() + { + return false; + } + + /** + * @return the numeric code representing the current status. + */ + public int getStatusCode() + { + return DL_STRSTAT; + } + + /** + * @return a short string description of the current status. + */ + public String getStatus() + { + return status; + } + + /** + * @return slot number assigned to this interface. + */ + public int getSlot() + { + return slot; + } + + /** + * Sends a search criteria to the connection. + * @param searchCrit the search criteria. + * @return true on success, false on failure. + */ + public boolean sendSearchCriteria(SearchCriteria searchCrit) + { + DdsRecvSettings settings = DdsRecvSettings.instance(); + for(NetlistGroupAssoc nga : settings.getNetlistGroupAssociations()) + { + if (!TextUtil.strEqualIgnoreCase(nga.getGroupName(), group)) + continue; + if (nga.getNetworkList() == null) + { + if (!nga.getNetlistName().toLowerCase().startsWith("source=")) + Logger.instance().warning(DdsRecv.module + + " No network list found for group=" + nga.getGroupName() + + " list='" + nga.getNetlistName() + "' -- ignored."); + continue; + } + try + { + lddsClient.sendNetList(nga.getNetworkList(), null); + } + catch(ServerError ex) + { + Logger.instance().warning(DdsRecv.module + + "Server at " + lddsClient.getName() + + " rejected network list '" + nga.getNetworkList().makeFileName() + + "': " + ex + " -- ignored."); + } + catch(Exception ex) + { + String msg = DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " + + " Error sending network list to " + + lddsClient.getName() + ": " + ex; + Logger.instance().warning(msg); + System.err.println(msg); + ex.printStackTrace(System.err); + shutdownLrgsInput(); + status = "Error"; + return false; + } + } + searchCrit.DapsStatus = + config.acceptARMs ? SearchCriteria.ACCEPT : SearchCriteria.REJECT; + try + { + lddsClient.sendSearchCrit(searchCrit); + status = "Catch-up"; + return true; + } + catch(Exception ex) + { + Logger.instance().warning( + DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " + + " Error sending search criteria to " + + lddsClient.getName() + ": " + ex); + shutdownLrgsInput(); + status = "Error"; + return false; + } + } + + /** + * @return a DCP message from the connection, or null if caught-up. + * @throws LrgsInputException if the connection has failed. + */ + public DcpMsg getDcpMsg() + throws LrgsInputException + { + try + { + DcpMsg msg = lddsClient.getDcpMsg(60); + long now = System.currentTimeMillis(); + lastActivityTime = now; + if (msg != null) + { + if (System.currentTimeMillis() - msg.getDapsTime().getTime() + < 30000L) + status = "Real-Time"; + lastMessageTime = now; + msg.setDataSourceId(dataSourceId); + } + else if (now - lastMessageTime > + DdsRecvSettings.instance().timeout * 1000L) + { + String errmsg = DdsRecv.module + + " timeout on connection to " + lddsClient.getName(); + Logger.instance().warning( + DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " + + errmsg); + lddsClient.disconnect(); + status = "Timeout"; + throw new LrgsInputException(errmsg); + } + return msg; + } + catch(Exception ex) + { + if (ex instanceof ServerError) + { + ServerError se = (ServerError)ex; + if (se.Derrno == LrgsErrorCode.DMSGTIMEOUT + || se.Derrno == LrgsErrorCode.DUNTIL) + { + long now = System.currentTimeMillis(); + if (now - lastMessageTime > + (DdsRecvSettings.instance().timeout * 1000L)) + { + String errmsg = DdsRecv.module + + " timeout on connection to " + lddsClient.getName(); + Logger.instance().warning( + DdsRecv.module + ":" + + DdsRecv.EVT_CONNECTION_FAILED + "- " + + errmsg); + lddsClient.disconnect(); + status = "Timeout"; + throw new LrgsInputException(errmsg); + } + else + { + Logger.instance().debug3(DdsRecv.module + + " caught up on connection " + getName()); + status = "Real-Time"; + return null; + } + } + } + String msg = DdsRecv.module + + " Error getting message from " + lddsClient.getName() + + ": " + ex; + Logger.instance().warning( + DdsRecv.module + ":" + DdsRecv.EVT_CONNECTION_FAILED + "- " + + msg); + lddsClient.disconnect(); + if (!(ex instanceof IOException) + && !(ex instanceof ServerError + && ((ServerError)ex).Derrno == LrgsErrorCode.DDDSINTERNAL + && ex.getMessage().contains("not currently usable"))) + { + System.err.println(msg); + ex.printStackTrace(System.err); + } + status = "Error"; + throw new LrgsInputException(msg); + } + } + + /** + * @return name of this connection. + */ + public String getName() + { + return lddsClient.getName(); + } + + public long getLastActivityTime() + { + return lastActivityTime; + } + + public void flush() + { + lddsClient.flushBufferedMessages(); + } + + public int getDataSourceId() { return dataSourceId; } + + /** @return true if this interface receives APR messages */ + public boolean getsAPRMessages() { return true; } // TODO: Make the APR setting configurable for each connection. - /** - * @return the group - */ - public String getGroup() { - return group; - } - - /** - * @param group the group to set - */ - public void setGroup(String group) { - this.group = group; - } + /** + * @return the group + */ + public String getGroup() { + return group; + } + + /** + * @param group the group to set + */ + public void setGroup(String group) { + this.group = group; + } } diff --git a/src/main/java/lrgs/ddsserver/DdsServer.java b/src/main/java/lrgs/ddsserver/DdsServer.java index 47f3e7617..9d701d675 100644 --- a/src/main/java/lrgs/ddsserver/DdsServer.java +++ b/src/main/java/lrgs/ddsserver/DdsServer.java @@ -6,7 +6,7 @@ * source code for your own purposes, except that no part of this source * code may be claimed to be proprietary. * -* Except for specific contractual terms between ILEX and the federal +* Except for specific contractual terms between ILEX and the federal * government, this source code is provided completely without warranty. * For more information contact: info@ilexeng.com */ @@ -33,285 +33,272 @@ /** Main class for the LRGS DDS server that uses the Java-Only-Archive. */ -public class DdsServer extends BasicServer - implements Runnable +public class DdsServer extends BasicServer + implements Runnable { - public static final String module = "DdsSvr"; - - /** Event number meaning server disabled */ - public static final int EVT_SVR_DISABLED = 1; - - /** Event number meaning can't make client */ - public static final int EVT_INTERNAL_CLIENT = 2; - - /** Event number meaning we already have max clients. */ - public static final int EVT_MAX_CLIENTS = 3; - - /** Event number meaning error on listening socket. */ - public static final int EVT_LISTEN = 4; - - /** Control switch used by main to enable/disable the server. */ - private boolean enabled; - - /** Logs statistics for each client-thread each minute: */ - public static LddsLoggerThread statLoggerThread; - - /** Internal shutdown flag */ - boolean shutdownFlag; - - private String status; - - /** Passed from parent, allows clients to retrieve event messages from Q */ - private QueueLogger qlog; - - /** The archive object from which to serve dcp messages. */ - public MsgArchive msgArchive; - - /** Global mapper for DCP names. */ - NetlistDcpNameMapper globalMapper; - - /** Provides status to clients. */ - public JavaLrgsStatusProvider statusProvider; - - /** Server uses a FileCounter to assign unique ID to each connection. */ - public static final String counterName = "$LRGSHOME/dds-counter"; - - private Counter conIdCounter; - - /** - Constructor. - @param port the listening port. - @param bindaddr indicates the NIC to listen on if there are more than one. - @param archive the MsgArchive object to serve data from. - @param qlog the QueueLogger to serve event messages from. - @throws IOException on invalid port number or socket already bound. - */ - public DdsServer(int port, InetAddress bindaddr, MsgArchive msgArchive, - QueueLogger qlog, JavaLrgsStatusProvider statusProvider) - throws IOException - { - super(port, bindaddr); - enabled = false; - shutdownFlag = false; - this.msgArchive = msgArchive; - this.qlog = qlog; - globalMapper = new NetlistDcpNameMapper( - new File(EnvExpander.expand(LrgsConfig.instance().ddsNetlistDir)), - null); - this.statusProvider = statusProvider; - conIdCounter = null; - setModuleName(module); - } - - /** - Used by main as a switch to coordinate archive and DDS. - When disabled, hangup on all clients and don't accept new ones. - @param tf true if enabling the DDS server. - */ - public void setEnabled(boolean tf) - { - if (tf != enabled) - { - if (enabled) - { - killAllSvrThreads(); - } - enabled = tf; - } - } - - /** Initializes the application. */ - public void init() - throws ArchiveUnavailableException - { - status = "R"; - BackgroundStuff bs = new BackgroundStuff(this); - bs.start(); - statLoggerThread = new LddsLoggerThread(this, - LrgsConfig.instance().ddsUsageLog); - statLoggerThread.start(); - Logger.instance().debug1("Starting DDS Listening thread."); - GetHostnameThread.instance().start(); - Thread listenThread = new Thread(this); - listenThread.start(); - try { conIdCounter = new FileCounter(EnvExpander.expand(counterName));} - catch(IOException ex) - { - Logger.instance().warning("Cannot create File-conIdCounter: " + ex); - conIdCounter = new SimpleCounter(1); - } - } - - /** Updates the status in the LRGS client slot. */ - public void updateStatus() - { - switch(status.length()) - { - case 0: - case 10: - status = "R"; break; - case 1: status = "Ru"; break; - case 2: status = "Run"; break; - case 3: status = "Runn"; break; - case 4: status = "Runni"; break; - case 5: status = "Runnin"; break; - case 6: status = "Running"; break; - case 7: status = "Running-"; break; - case 8: status = "Running--"; break; - case 9: status = "Running---"; break; - } - } - - /** Shuts the application down. */ - public void shutdown() - { - Logger.instance().info(module + " shutting down."); - shutdownFlag = true; - statLoggerThread.shutdown(); - setEnabled(false); - super.shutdown(); - } - - /** - Overloaded from BasicServer, this constructs a new LddsThread - to handle this client connection. - @param sock the client connection socket - */ - protected BasicSvrThread newSvrThread(Socket sock) - throws IOException - { - try - { -// sock.setTcpNoDelay(true); -// sock.setSoTimeout(LddsParams.ServerHangupSeconds * 1000); - -// Experimenting with this. -// Setting linger to 0 will tell the server to immediatly drop connections on -// close without the normal ack/nak tcp mechanism. -// sock.setSoLinger(true, 0); - - Logger.instance().debug1(module + " New DDS client. " - + " KeepAlive=" + sock.getKeepAlive() - + " SoLinger=" + sock.getSoLinger() - + " SoTimeout=" + sock.getSoTimeout() - + " TcpNoDelay=" + sock.getTcpNoDelay() - + " ReuseAddress=" + sock.getReuseAddress()); - } - catch(Exception ex) - { - Logger.instance().warning(module - + " Exception setting or printing socket options: " + ex); - } - - if (!enabled) - { - Logger.instance().warning(module + ":" + EVT_SVR_DISABLED - + "- Cannot accept new client, Server disabled."); - sock.close(); - return null; - } - - int numcli = getNumSvrThreads(); - int maxcli = LrgsConfig.instance().ddsMaxClients; - if (maxcli > 0 && numcli >= maxcli) - { - Logger.instance().warning(module + ":" + EVT_MAX_CLIENTS - + " Cannot accept new client, already have max of " - + maxcli + " connected."); - sock.close(); - return null; - } - - AttachedProcess ap = statusProvider.getFreeClientSlot(); - if (ap == null) - { - Logger.instance().warning(module + ":" + EVT_MAX_CLIENTS - + " Cannot get free client data structure, already have max of " - + maxcli + " connected."); - sock.close(); - } - else - Logger.instance().debug1(module + ":" + (-EVT_MAX_CLIENTS) - + " New client accepted"); - - - try - { - int id = conIdCounter.getNextValue(); - //Work around for when file is bad - if (id == -1) - { - conIdCounter.setNextValue(1); - Logger.instance().warning(module + ":" + - "Re-setting "+ - EnvExpander.expand(counterName) + - " to 1."); - } - id = conIdCounter.getNextValue(); - //End work around - LddsThread ret = new JLddsThread(this, sock, id, msgArchive, - globalMapper, ap); - ret.statLogger = statLoggerThread; - ret.setQueueLogger(qlog); - ret.setStatusProvider(statusProvider); - return ret; - } - catch(IOException ex) - { - throw ex; - } - catch(Exception ex) - { - String msg = "- Unexpected exception creating new client thread: " - + ex; - Logger.instance().failure(module + " " + EVT_INTERNAL_CLIENT - + msg); - System.err.println(msg); - ex.printStackTrace(System.err); - return null; - } - } - - /** From java.lang.Runnable interface. */ - public void run() - { - try - { - Logger.instance().info(module - + " ServerSocket.getSoTimeout=" + listeningSocket.getSoTimeout()); - Logger.instance().info(module - + " ServerSocket.getReceiveBufferSize=" - + listeningSocket.getReceiveBufferSize()); - Logger.instance().info(module - + " ServerSocket.getReuseAddress=" - + listeningSocket.getReuseAddress()); - } - catch(Exception ex) - { - Logger.instance().warning(module - + " Error getting or setting server socket params: " + ex); - } - try { listen(); } - catch(IOException ex) - { - Logger.instance().failure(module + ":" + EVT_LISTEN - + "- Error on listening socket: " + ex); - } - } - - protected void listenTimeout() - { - Logger.instance().info(module + " listen timeout"); - } - -// /** -// Log status for an LddsThread object. -// @param lt the thread object -// */ -// public void logStat(LddsThread lt) -// { -// statLoggerThread.logStat(lt); -// } + public static final String module = "DdsSvr"; + + /** Event number meaning server disabled */ + public static final int EVT_SVR_DISABLED = 1; + + /** Event number meaning can't make client */ + public static final int EVT_INTERNAL_CLIENT = 2; + + /** Event number meaning we already have max clients. */ + public static final int EVT_MAX_CLIENTS = 3; + + /** Event number meaning error on listening socket. */ + public static final int EVT_LISTEN = 4; + + /** Control switch used by main to enable/disable the server. */ + private boolean enabled; + + /** Logs statistics for each client-thread each minute: */ + public static LddsLoggerThread statLoggerThread; + + /** Internal shutdown flag */ + boolean shutdownFlag; + + private String status; + + /** Passed from parent, allows clients to retrieve event messages from Q */ + private QueueLogger qlog; + + /** The archive object from which to serve dcp messages. */ + public MsgArchive msgArchive; + + /** Global mapper for DCP names. */ + NetlistDcpNameMapper globalMapper; + + /** Provides status to clients. */ + public JavaLrgsStatusProvider statusProvider; + + /** Server uses a FileCounter to assign unique ID to each connection. */ + public static final String counterName = "$LRGSHOME/dds-counter"; + + private Counter conIdCounter; + + /** + Constructor. + @param port the listening port. + @param bindaddr indicates the NIC to listen on if there are more than one. + @param archive the MsgArchive object to serve data from. + @param qlog the QueueLogger to serve event messages from. + @throws IOException on invalid port number or socket already bound. + */ + public DdsServer(int port, InetAddress bindaddr, MsgArchive msgArchive, + QueueLogger qlog, JavaLrgsStatusProvider statusProvider) + throws IOException + { + super(port, bindaddr); + enabled = false; + shutdownFlag = false; + this.msgArchive = msgArchive; + this.qlog = qlog; + globalMapper = new NetlistDcpNameMapper( + new File(EnvExpander.expand(LrgsConfig.instance().ddsNetlistDir)), + null); + this.statusProvider = statusProvider; + conIdCounter = null; + setModuleName(module); + } + + /** + Used by main as a switch to coordinate archive and DDS. + When disabled, hangup on all clients and don't accept new ones. + @param tf true if enabling the DDS server. + */ + public void setEnabled(boolean tf) + { + if (tf != enabled) + { + if (enabled) + { + killAllSvrThreads(); + } + enabled = tf; + } + } + + /** Initializes the application. */ + public void init() + throws ArchiveUnavailableException + { + status = "R"; + BackgroundStuff bs = new BackgroundStuff(this); + bs.start(); + statLoggerThread = new LddsLoggerThread(this, + LrgsConfig.instance().ddsUsageLog); + statLoggerThread.start(); + Logger.instance().debug1("Starting DDS Listening thread."); + GetHostnameThread.instance().start(); + Thread listenThread = new Thread(this); + listenThread.start(); + try + { + conIdCounter = new FileCounter(EnvExpander.expand(counterName)); + } + catch(IOException ex) + { + Logger.instance().warning("Cannot create File-conIdCounter: " + ex); + conIdCounter = new SimpleCounter(1); + } + } + + /** Updates the status in the LRGS client slot. */ + public void updateStatus() + { + switch(status.length()) + { + case 0: + case 10: + status = "R"; break; + case 1: status = "Ru"; break; + case 2: status = "Run"; break; + case 3: status = "Runn"; break; + case 4: status = "Runni"; break; + case 5: status = "Runnin"; break; + case 6: status = "Running"; break; + case 7: status = "Running-"; break; + case 8: status = "Running--"; break; + case 9: status = "Running---"; break; + } + } + + /** Shuts the application down. */ + public void shutdown() + { + Logger.instance().info(module + " shutting down."); + shutdownFlag = true; + statLoggerThread.shutdown(); + setEnabled(false); + super.shutdown(); + } + + /** + Overloaded from BasicServer, this constructs a new LddsThread + to handle this client connection. + @param sock the client connection socket + */ + protected BasicSvrThread newSvrThread(Socket sock) + throws IOException + { + try + { + Logger.instance().debug1(module + " New DDS client. " + + " KeepAlive=" + sock.getKeepAlive() + + " SoLinger=" + sock.getSoLinger() + + " SoTimeout=" + sock.getSoTimeout() + + " TcpNoDelay=" + sock.getTcpNoDelay() + + " ReuseAddress=" + sock.getReuseAddress()); + } + catch(Exception ex) + { + Logger.instance().warning(module + + " Exception setting or printing socket options: " + ex); + } + + if (!enabled) + { + Logger.instance().warning(module + ":" + EVT_SVR_DISABLED + + "- Cannot accept new client, Server disabled."); + sock.close(); + return null; + } + + int numcli = getNumSvrThreads(); + int maxcli = LrgsConfig.instance().ddsMaxClients; + if (maxcli > 0 && numcli >= maxcli) + { + Logger.instance().warning(module + ":" + EVT_MAX_CLIENTS + + " Cannot accept new client, already have max of " + + maxcli + " connected."); + sock.close(); + return null; + } + + AttachedProcess ap = statusProvider.getFreeClientSlot(); + if (ap == null) + { + Logger.instance().warning(module + ":" + EVT_MAX_CLIENTS + + " Cannot get free client data structure, already have max of " + + maxcli + " connected."); + sock.close(); + } + else + { + Logger.instance().debug1(module + ":" + (-EVT_MAX_CLIENTS) + + " New client accepted"); + } + + try + { + int id = conIdCounter.getNextValue(); + //Work around for when file is bad + if (id == -1) + { + conIdCounter.setNextValue(1); + Logger.instance().warning(module + ":" + + "Re-setting "+ + EnvExpander.expand(counterName) + + " to 1."); + } + id = conIdCounter.getNextValue(); + //End work around + LddsThread ret = new JLddsThread(this, sock, id, msgArchive, + globalMapper, ap); + ret.statLogger = statLoggerThread; + ret.setQueueLogger(qlog); + ret.setStatusProvider(statusProvider); + return ret; + } + catch(IOException ex) + { + throw ex; + } + catch(Exception ex) + { + String msg = "- Unexpected exception creating new client thread: " + + ex; + Logger.instance().failure(module + " " + EVT_INTERNAL_CLIENT + + msg); + System.err.println(msg); + ex.printStackTrace(System.err); + return null; + } + } + + /** From java.lang.Runnable interface. */ + public void run() + { + try + { + Logger.instance().info(module + + " ServerSocket.getSoTimeout=" + listeningSocket.getSoTimeout()); + Logger.instance().info(module + + " ServerSocket.getReceiveBufferSize=" + + listeningSocket.getReceiveBufferSize()); + Logger.instance().info(module + + " ServerSocket.getReuseAddress=" + + listeningSocket.getReuseAddress()); + } + catch(Exception ex) + { + Logger.instance().warning(module + + " Error getting or setting server socket params: " + ex); + } + try { listen(); } + catch(IOException ex) + { + Logger.instance().failure(module + ":" + EVT_LISTEN + + "- Error on listening socket: " + ex); + } + } + + protected void listenTimeout() + { + Logger.instance().info(module + " listen timeout"); + } } @@ -320,63 +307,62 @@ protected void listenTimeout() */ class BackgroundStuff extends Thread { - DdsServer svr; - - BackgroundStuff(DdsServer svr) - { - this.svr = svr; - } - - public void run() - { - long lastNetlistCheck = System.currentTimeMillis(); - - try { sleep((long)2000); } - catch (InterruptedException ie) {} - while(svr.shutdownFlag == false) - { - svr.updateStatus(); - - // Hangup on clients who have gone catatonic. - long now = System.currentTimeMillis(); - LddsThread badClient = null; - - synchronized(svr) - { - for(@SuppressWarnings("rawtypes") - Iterator it = svr.getSvrThreads(); it.hasNext(); ) - { - LddsThread lt = (LddsThread)it.next(); - if ((now - lt.getLastActivity().getTime()) - > (LddsParams.ServerHangupSeconds*1000L)) - { - badClient = lt; - break; - // Can't disconnect inside this loop because it will - // cause a modification to the vector we're iterating! - } - } - } - if (badClient != null) // Found one to hang up on? - { - Logger.instance().debug1(DdsServer.module + - " Hanging up on client '" + badClient.getClientName() - + "' due to inactivity for more than " - + LddsParams.ServerHangupSeconds + " seconds."); - badClient.disconnect(); - badClient = null; - } - - // Check global network lists for change once per minute. - if (now - lastNetlistCheck > 60000L) - { - lastNetlistCheck = now; - svr.globalMapper.check(); - } - - try { sleep((long)2000); } - catch (InterruptedException ie) {} - } - } + DdsServer svr; + + BackgroundStuff(DdsServer svr) + { + this.svr = svr; + } + + public void run() + { + long lastNetlistCheck = System.currentTimeMillis(); + + try { sleep((long)2000); } + catch (InterruptedException ie) {} + while(svr.shutdownFlag == false) + { + svr.updateStatus(); + + // Hangup on clients who have gone catatonic. + long now = System.currentTimeMillis(); + LddsThread badClient = null; + + synchronized(svr) + { + for(@SuppressWarnings("rawtypes") + Iterator it = svr.getSvrThreads(); it.hasNext(); ) + { + LddsThread lt = (LddsThread)it.next(); + if ((now - lt.getLastActivity().getTime()) + > (LddsParams.ServerHangupSeconds*1000L)) + { + badClient = lt; + break; + // Can't disconnect inside this loop because it will + // cause a modification to the vector we're iterating! + } + } + } + if (badClient != null) // Found one to hang up on? + { + Logger.instance().debug1(DdsServer.module + + " Hanging up on client '" + badClient.getClientName() + + "' due to inactivity for more than " + + LddsParams.ServerHangupSeconds + " seconds."); + badClient.disconnect(); + badClient = null; + } + + // Check global network lists for change once per minute. + if (now - lastNetlistCheck > 60000L) + { + lastNetlistCheck = now; + svr.globalMapper.check(); + } + + try { sleep((long)2000); } + catch (InterruptedException ie) {} + } + } } - diff --git a/src/main/java/lrgs/ddsserver/JLddsThread.java b/src/main/java/lrgs/ddsserver/JLddsThread.java index 6f2cab812..0f225136f 100644 --- a/src/main/java/lrgs/ddsserver/JLddsThread.java +++ b/src/main/java/lrgs/ddsserver/JLddsThread.java @@ -74,150 +74,149 @@ */ public class JLddsThread extends LddsThread { - /** The one and only archive object. */ - private MsgArchive msgArchive; - - /** The global name mapper. */ - private DcpNameMapper globalMapper; - - /** The AttachedProcess structure for tracking status info. */ - private AttachedProcess attachedProcess; - - /** - Constructor. - @param parent the server object - @param socket the socket to the client - @param ID unique integer ID for this client. - @param msgArchive the archive from which to serve data. - */ - public JLddsThread(BasicServer parent, Socket socket, int id, - MsgArchive msgArchive, DcpNameMapper globalMapper, AttachedProcess ap) - throws IOException - { - super(parent, socket, id); - this.msgArchive = msgArchive; - this.globalMapper = globalMapper; - this.attachedProcess = ap; - attachedProcess.pid = id; - attachedProcess.type = "DDS-CLI"; - attachedProcess.user = "(unknown)"; - attachedProcess.status = "user?"; - } - - /** - Template method to create the name mapper. - This version is for the Java-Only DDS server. It returns a name - mapper that first looks for a mapping in network lists in the user's - sandbox directory, and then in the global directory. - */ - protected DcpNameMapper makeDcpNameMapper() - { - // This can happen if user disconnects in the middle of Hello sequence. - if (user == null) - return null; - - return new NetlistDcpNameMapper(user.getDirectory(), globalMapper); - } - - /** - Template method to create the DcpMsgSource object. - This version creates a MessageArchiveRetriever, which acts as both - the source and the retriever. - */ - protected DcpMsgSource makeDcpMsgSource() - throws ArchiveUnavailableException - { - LinkedList clients = parent.getAllSvrThreads(); - String myhostname = getHostName(); -if (user == null) System.err.println("JLddsThread: makeDcpMsgSrc, user is null!"); - String myusername = user.getName(); - int nsame = 0; - Date oldestDate = null; - JLddsThread oldestPeer = null; - for(Object ob : clients) - { - JLddsThread peer = (JLddsThread)ob; - if (peer == this) - continue; - String peerhostname = peer.getHostName(); - String peerusername = peer.user != null ? peer.user.getName():null; - Date peerLastActivity = peer.getLastActivity(); - if (peerLastActivity == null) - peerLastActivity = new Date(0L); - if (myhostname != null - && peerhostname != null - && myhostname.equalsIgnoreCase(peerhostname) - && myusername != null - && peerusername != null - && myusername.equals(peerusername)) - { - nsame++; - if (oldestDate == null - || peerLastActivity.compareTo(oldestDate) < 0) - { - oldestDate = peerLastActivity; - oldestPeer = peer; - } - } - } - if (nsame > 50) - { - Logger.instance().warning("More than 50 connections with same " - + "user/host = " + myusername + "/" + myhostname - + " -- Hanging up oldest."); - oldestPeer.disconnect(); - } - MessageArchiveRetriever ret = - new MessageArchiveRetriever(msgArchive, attachedProcess); - ret.setForceAscending(user.getDisableBackLinkSearch()); - ret.setGoodOnly(user.isGoodOnly()); - return ret; - } - - /** - Template method to create the DcpMsgRetriever object. - The source is created first. This method just returns the source - object, which also acts as the retriever. - */ - protected DcpMsgRetriever makeDcpMsgRetriever() - { - return (DcpMsgRetriever)msgacc; - } - - /** - * @return true if authentication is required by this server. - */ - public boolean isAuthRequired() - { - return LrgsConfig.instance().ddsRequireAuth; - } - - /** - * @return true if same user is allowed multiple connections. - */ - public boolean isSameUserMultAttachOK() - { - return true; - } - - /** - * @return the root directory for user sandbox directories. - */ -// public String getDdsUserRootDir() -// { -// return LrgsConfig.instance().ddsUserRootDir; -// } - - public void disconnect() - { - attachedProcess.pid = -1; - super.disconnect(); - } - - public void setHostName(String hostname) - { - super.setHostName(hostname); - if (attachedProcess != null) - attachedProcess.setName(hostname); - } + /** The one and only archive object. */ + private MsgArchive msgArchive; + + /** The global name mapper. */ + private DcpNameMapper globalMapper; + + /** The AttachedProcess structure for tracking status info. */ + private AttachedProcess attachedProcess; + + /** + Constructor. + @param parent the server object + @param socket the socket to the client + @param ID unique integer ID for this client. + @param msgArchive the archive from which to serve data. + */ + public JLddsThread(BasicServer parent, Socket socket, int id, + MsgArchive msgArchive, DcpNameMapper globalMapper, AttachedProcess ap) + throws IOException + { + super(parent, socket, id); + this.msgArchive = msgArchive; + this.globalMapper = globalMapper; + this.attachedProcess = ap; + attachedProcess.pid = id; + attachedProcess.type = "DDS-CLI"; + attachedProcess.user = "(unknown)"; + attachedProcess.status = "user?"; + } + + /** + Template method to create the name mapper. + This version is for the Java-Only DDS server. It returns a name + mapper that first looks for a mapping in network lists in the user's + sandbox directory, and then in the global directory. + */ + protected DcpNameMapper makeDcpNameMapper() + { + // This can happen if user disconnects in the middle of Hello sequence. + if (user == null) + return null; + + return new NetlistDcpNameMapper(user.getDirectory(), globalMapper); + } + + /** + Template method to create the DcpMsgSource object. + This version creates a MessageArchiveRetriever, which acts as both + the source and the retriever. + */ + protected DcpMsgSource makeDcpMsgSource() + throws ArchiveUnavailableException + { + LinkedList clients = parent.getAllSvrThreads(); + String myhostname = getHostName(); + if (user == null) + { + System.err.println("JLddsThread: makeDcpMsgSrc, user is null!"); + } + String myusername = user.getName(); + int nsame = 0; + Date oldestDate = null; + JLddsThread oldestPeer = null; + for(Object ob : clients) + { + JLddsThread peer = (JLddsThread)ob; + if (peer == this) + continue; + String peerhostname = peer.getHostName(); + String peerusername = peer.user != null ? peer.user.getName():null; + Date peerLastActivity = peer.getLastActivity(); + if (peerLastActivity == null) + { + peerLastActivity = new Date(0L); + } + if (myhostname != null + && peerhostname != null + && myhostname.equalsIgnoreCase(peerhostname) + && myusername != null + && peerusername != null + && myusername.equals(peerusername)) + { + nsame++; + if (oldestDate == null + || peerLastActivity.compareTo(oldestDate) < 0) + { + oldestDate = peerLastActivity; + oldestPeer = peer; + } + } + } + if (nsame > 50) + { + Logger.instance().warning("More than 50 connections with same " + + "user/host = " + myusername + "/" + myhostname + + " -- Hanging up oldest."); + oldestPeer.disconnect(); + } + MessageArchiveRetriever ret = + new MessageArchiveRetriever(msgArchive, attachedProcess); + ret.setForceAscending(user.getDisableBackLinkSearch()); + ret.setGoodOnly(user.isGoodOnly()); + return ret; + } + + /** + Template method to create the DcpMsgRetriever object. + The source is created first. This method just returns the source + object, which also acts as the retriever. + */ + protected DcpMsgRetriever makeDcpMsgRetriever() + { + return (DcpMsgRetriever)msgacc; + } + + /** + * @return true if authentication is required by this server. + */ + public boolean isAuthRequired() + { + return LrgsConfig.instance().ddsRequireAuth; + } + + /** + * @return true if same user is allowed multiple connections. + */ + public boolean isSameUserMultAttachOK() + { + return true; + } + + public void disconnect() + { + attachedProcess.pid = -1; + super.disconnect(); + } + + public void setHostName(String hostname) + { + super.setHostName(hostname); + if (attachedProcess != null) + { + attachedProcess.setName(hostname); + } + } } diff --git a/src/main/java/lrgs/gui/MessageBrowser.java b/src/main/java/lrgs/gui/MessageBrowser.java index 525f23c1e..4d5eba945 100644 --- a/src/main/java/lrgs/gui/MessageBrowser.java +++ b/src/main/java/lrgs/gui/MessageBrowser.java @@ -66,1360 +66,1324 @@ and save them to a file. It uses DDS (not CORBA) to pull DCP messages from */ @SuppressWarnings("serial") public class MessageBrowser extends MenuFrame - implements DcpMsgOutputMonitor, SearchCritEditorParent + implements DcpMsgOutputMonitor, SearchCritEditorParent { - private static ResourceBundle labels = null; - private static ResourceBundle genericLabels = null; - - public static final int DEFAULT_PORT_NUM = LddsParams.DefaultPort; - public static final int StartHeight = 620; - public static final int StartWidth = 950;//900; - - private static final String TITLE = "DCP Message Browser"; - private String hostName, userName; - private int portNum; - private SearchCriteria searchcrit; - private SearchCriteriaEditorIF scedit; - - private JComboBox hostField; - private JTextField portField = new JTextField(15), userField = new JTextField(15); - private JPasswordField passwordField = new JPasswordField(15); - private JButton connectButton; - private JTextField scfileField; - private JButton scSelectButton, scEditButton; - private JTextField prefixField, suffixField; - private JTextField beforeDataField, afterDataField; - private JCheckBox wrapCheck; -// private JCheckBox decodeCheck; - private JTextArea messageArea; - private JScrollPane messagePane; - private MessageAreaOutputStream msgDisplayStream; - private DcpMsgOutputThread msgOutputThread; - private boolean displayPaused; - private JButton nextMessageButton, saveToFileButton, clearButton; - private JButton displayAllButton; - private JLabel statusBar; -// private JButton abortButton; - - private Properties connectionList; - - private static JFileChooser filechooser; - private static final String[] scExtensions = { "sc" }; - - private LddsClient client; - private boolean firstAfterConnect; - private boolean wrapLines; -// private boolean doDecode; - private boolean showRaw, doDecode; - private String lastSearchCrit; - private boolean displayingAll; - - private static String[] showChoices; - private JComboBox showCombo; - private JComboBox outCombo; + private static ResourceBundle labels = null; + private static ResourceBundle genericLabels = null; + + public static final int DEFAULT_PORT_NUM = LddsParams.DefaultPort; + public static final int StartHeight = 620; + public static final int StartWidth = 950;//900; + + private static final String TITLE = "DCP Message Browser"; + private String hostName, userName; + private int portNum; + private SearchCriteria searchcrit; + private SearchCriteriaEditorIF scedit; + + private JComboBox hostField; + private JTextField portField = new JTextField(15), userField = new JTextField(15); + private JPasswordField passwordField = new JPasswordField(15); + private JButton connectButton; + private JTextField scfileField; + private JButton scSelectButton, scEditButton; + private JTextField prefixField, suffixField; + private JTextField beforeDataField, afterDataField; + private JCheckBox wrapCheck; + + private JTextArea messageArea; + private JScrollPane messagePane; + private MessageAreaOutputStream msgDisplayStream; + private DcpMsgOutputThread msgOutputThread; + private boolean displayPaused; + private JButton nextMessageButton, saveToFileButton, clearButton; + private JButton displayAllButton; + private JLabel statusBar; + + private Properties connectionList; + + private static JFileChooser filechooser; + private static final String[] scExtensions = { "sc" }; + + private LddsClient client; + private boolean firstAfterConnect; + private boolean wrapLines; + + private boolean showRaw, doDecode; + private String lastSearchCrit; + private boolean displayingAll; + + private static String[] showChoices; + private JComboBox showCombo; + private JComboBox outCombo; private static String[] outFmts; - private static boolean canDecode = true; - - - /** - Construct new MessageBrowser frame. - @param hostName DDS server host to connect to - @param portNum DDS port number - @userName user name to use in connection - */ - public MessageBrowser(String hostName, int portNum, String userName) - { - - super(TITLE); - - try - { - ResourceFactory.instance().initDbResources(); - } - catch (DatabaseException e1) - { - // TODO Auto-generated catch block - e1.printStackTrace(); - } - - ClassLoader cl = Thread.currentThread().getContextClassLoader(); - try { cl.loadClass("lrgs.ddsrecv.DdsRecvConnectCfg"); } - catch(ClassNotFoundException ex) - { - canDecode = false; - showRaw = true; - doDecode = false; - } - - - getMyLabelDescriptions(); - setTitle(labels.getString("MessageBrowser.frameTitle")); - filechooser = new JFileChooser(); - - if (canDecode) - { - showChoices = new String[3]; - showChoices[0] = labels.getString("MessageBrowser.rawCombo"); - showChoices[1] = labels.getString("MessageBrowser.rawDecodedCombo"); - showChoices[2] = labels.getString("MessageBrowser.decodedCombo"); - } - - this.hostName = hostName != null ? hostName : ""; - this.portNum = portNum == 0 ? DEFAULT_PORT_NUM : portNum; - this.userName = userName != null ? userName : ""; - scedit = null; - msgOutputThread = null; - displayingAll = false; - - searchcrit = new SearchCriteria(); - - initProperties(); - MessageOutput.initProperties(); - buildMenuBar(); - initConnectionList(); - - Container contpane = getContentPane(); - contpane.setLayout(new BorderLayout()); - - statusBar = new JLabel( - labels.getString("MessageBrowser.initializingLabel")); - statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED)); - contpane.add(statusBar, BorderLayout.SOUTH); - - // West contains Server, Search Criteria and Output Format Groups: - JPanel west = new JPanel(new GridBagLayout()); - contpane.add(west, BorderLayout.WEST); - - // NorthWest contains Server group - JPanel northwest = new JPanel(new GridBagLayout()); - northwest.setBorder(new TitledBorder( - labels.getString("MessageBrowser.serverTitle"))); - - northwest.add(new JLabel( - labels.getString("MessageBrowser.hostName")), - new GridBagConstraints(0, 0, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - - hostField = new JComboBox(); - hostField.setEditable(true); - hostField.addActionListener( - new ActionListener() - { - public void actionPerformed(ActionEvent ae) - { - RtStatFrame.setFieldsFromHostSelection(hostField, connectionList, portField, - userField, passwordField); - } - }); - RtStatFrame.loadConnectionsField(hostField, connectionList, ""); - northwest.add(hostField, - new GridBagConstraints(1, 0, 1, 1, 0.8, 1.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - - northwest.add(new JLabel(labels.getString("MessageBrowser.port")), - new GridBagConstraints(0, 1, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - northwest.add(portField, - new GridBagConstraints(1, 1, 1, 1, 0.8, 1.0, - GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - portField.setText(GuiApp.getProperty("MessageBrowser.Port")); - - Dimension d = portField.getPreferredSize(); - hostField.setPreferredSize(d); - - northwest.add(new JLabel( - labels.getString("MessageBrowser.userName")), - new GridBagConstraints(0, 2, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - northwest.add(userField, - new GridBagConstraints(1, 2, 1, 1, 0.8, 1.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - if(this.userName.length()>0) - userField.setText(this.userName); - else - userField.setText(GuiApp.getProperty("MessageBrowser.User")); - - northwest.add(new JLabel( - labels.getString("MessageBrowser.password")), - new GridBagConstraints(0, 3, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - //northwest.add(passwordField = new JTextField(15), - northwest.add(passwordField, - new GridBagConstraints(1, 3, 1, 1, 0.8, 1.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - - // Connect button across bottom: - connectButton = - new SingleClickButton(labels.getString("MessageBrowser.connect")) - { - public void buttonPressed(AWTEvent event) - { - connectButtonPress(); - } - }; - northwest.add(connectButton, - new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0, - GridBagConstraints.CENTER, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - - // Finally, add northwest to the west panel. - west.add(northwest, - new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, - GridBagConstraints.NORTH, GridBagConstraints.BOTH, - new Insets(2, 5, 2, 5), 0, 0)); - - - // Midwest contains Search Criteria Group. - JPanel midwest = new JPanel(new BorderLayout()); - midwest.setBorder(new TitledBorder( - labels.getString("MessageBrowser.searchCriteria"))); - west.add(midwest, - new GridBagConstraints(0, 1, 1, 1, 0.0, 0.2, - GridBagConstraints.NORTH, GridBagConstraints.BOTH, - new Insets(2, 5, 2, 5), 0, 0)); - JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT)); - p.add(new JLabel(labels.getString("MessageBrowser.fileName"))); - p.add(scfileField = new JTextField(15)); - scfileField.setText( - GuiApp.getProperty("MessageBrowser.DefaultSearchCrit")); - - midwest.add(p, BorderLayout.NORTH); - p = new JPanel(new FlowLayout(FlowLayout.CENTER)); - scSelectButton = - new SingleClickButton(genericLabels.getString("select")) - { - public void buttonPressed(AWTEvent event) - { - scSelectButtonPress(); - } - }; - p.add(scSelectButton); - scEditButton = - new SingleClickButton( - " " + genericLabels.getString("edit") + " ") - { - public void buttonPressed(AWTEvent event) - { - scEditButtonPress(); - } - }; - p.add(scEditButton); - midwest.add(p, BorderLayout.CENTER); - p = new JPanel(new FlowLayout(FlowLayout.CENTER)); - midwest.add(p, BorderLayout.SOUTH); - - - - // Center contains big messge display area with buttons on bottom. - JPanel center = new JPanel(new BorderLayout()); - contpane.add(center, BorderLayout.CENTER); - messageArea = new JTextArea(); - msgDisplayStream = new MessageAreaOutputStream(); - - messagePane = new JScrollPane(messageArea); - messagePane.setBorder(new BevelBorder(BevelBorder.LOWERED)); - messageArea.setLineWrap(wrapLines); - messageArea.setEditable(false); - Font oldfont = messageArea.getFont(); - messageArea.setFont(new Font("Monospaced", Font.PLAIN, oldfont.getSize())); - - center.add(messagePane, BorderLayout.CENTER); - p = new JPanel(new GridBagLayout()); -// p = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 4)); - nextMessageButton = new JButton( - labels.getString("MessageBrowser.displayNext")); - nextMessageButton.addActionListener( - new ActionListener() - { - public void actionPerformed(ActionEvent av) - { - nextMessageButtonPress(); - } - }); - p.add(nextMessageButton, - new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 0, 2, 5), 0, 0)); - -//here - displayAllButton = new JButton( - labels.getString("MessageBrowser.displayAll")); - displayAllButton.addActionListener( - new ActionListener() - { - public void actionPerformed(ActionEvent av) - { - displayAllButtonPress(); - } - }); - p.add(displayAllButton, - new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 0, 2, 5), 0, 0)); - - - clearButton = new JButton(" " + - genericLabels.getString("clear")+ " "); - clearButton.addActionListener( - new ActionListener() - { - public void actionPerformed(ActionEvent av) - { - clearButtonPress(); - } - }); - p.add(clearButton, - new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - - saveToFileButton = - new SingleClickButton( - labels.getString("MessageBrowser.saveToFile")) - { - public void buttonPressed(AWTEvent event) - { - saveToFileButtonPress(); - } - }; - - - p.add(saveToFileButton, - new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 0), 0, 0)); - -// abortButton = new JButton(" Abort Request "); -// abortButton.addActionListener( -// new ActionListener() -// { -// public void actionPerformed(ActionEvent av) -// { -// abortButtonPress(); -// } -// }); -// p.add(abortButton); - - center.add(p, BorderLayout.SOUTH); - - // Southwest contains Output Format group. - JPanel southwest = new JPanel(new GridBagLayout()); - southwest.setBorder(new TitledBorder( - labels.getString("MessageBrowser.displayFormat"))); - - southwest.add(new JLabel( - labels.getString("MessageBrowser.beforeMsg")), - new GridBagConstraints(0, 0, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - - southwest.add(prefixField = new JTextField(16), - new GridBagConstraints(1, 0, 1, 1, 0.8, 1.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - prefixField.setText(GuiApp.getProperty("MessageBrowser.Prefix")); - southwest.add(new JLabel(labels.getString("MessageBrowser.afterMsg")), - new GridBagConstraints(0, 1, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - southwest.add(suffixField = new JTextField(16), - new GridBagConstraints(1, 1, 1, 1, 0.8, 1.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - suffixField.setText(GuiApp.getProperty("MessageBrowser.Suffix")); - - - if (canDecode) - { - southwest.add(new JLabel(labels.getString("MessageBrowser.show")), - new GridBagConstraints(0, 2, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - showCombo = new JComboBox(showChoices); - showCombo.setSelectedItem( - GuiApp.getProperty("MessageBrowser.Show", "Raw")); - southwest.add(showCombo, - new GridBagConstraints(1, 2, 1, 1, 1.0, 1.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - - showCombo.addActionListener( - new ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - int i = showCombo.getSelectedIndex(); - showRaw = (i == 0 || i == 1); - doDecode = (i == 1 || i == 2); - GuiApp.setProperty("MessageBrowser.Show", showChoices[i]); - } - }); - - //========= - southwest.add(new JLabel(labels.getString("MessageBrowser.outFormat")), - new GridBagConstraints(0, 3, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - outFmts = DecodesInterface.getOutputFormats(); - if (outFmts == null) - { - String[] thisFmt = new String[1]; - thisFmt[0] = "human-readable"; - outCombo = new JComboBox(thisFmt); - } else { - - outCombo = new JComboBox(outFmts); - } - outCombo.setSelectedItem( - GuiApp.getProperty("MessageBrowser.OutputFormat", "human-readable")); - southwest.add(outCombo, - new GridBagConstraints(1, 3, 1, 1, 1.0, 1.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - - outCombo.addActionListener( - new ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - int i = outCombo.getSelectedIndex(); - GuiApp.setProperty("MessageBrowser.OutputFormat", outFmts[i]); - } - }); - //========= - - southwest.add(new JLabel( - labels.getString("MessageBrowser.beforeData")), - new GridBagConstraints(0, 4, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - southwest.add(beforeDataField = new JTextField(16), - new GridBagConstraints(1, 4, 1, 1, 0.8, 1.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - - southwest.add(new JLabel(labels.getString("MessageBrowser.afterData")), - new GridBagConstraints(0, 5, 1, 1, 0.2, 1.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 5, 2, 5), 0, 0)); - southwest.add(afterDataField = new JTextField(16), - new GridBagConstraints(1, 5, 1, 1, 0.8, 1.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 5, 2, 5), 0, 0)); - } - - wrapCheck = new JCheckBox( - labels.getString("MessageBrowser.wraplonglines"), - GuiApp.getBooleanProperty("MessageBrowser.WrapLongLines", false)); - southwest.add(wrapCheck, - new GridBagConstraints(0, (canDecode ? 6 : 2), 2, 1, 1.0, 1.0, - GridBagConstraints.CENTER, GridBagConstraints.NONE, - new Insets(2, 6, 2, 5), 0, 0)); - wrapLines = wrapCheck.isSelected(); - messageArea.setLineWrap(wrapLines); - wrapCheck.addItemListener( - new ItemListener() - { - public void itemStateChanged(ItemEvent ev) - { - wrapLines = ev.getStateChange() == ItemEvent.SELECTED; - messageArea.setLineWrap(wrapLines); - GuiApp.setProperty("MessageBrowser.WrapLongLines", - wrapLines ? "true" : "false"); - } - }); - - west.add(southwest, - new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, - GridBagConstraints.NORTH, GridBagConstraints.BOTH, - new Insets(2, 5, 2, 5), 0, 0)); - - String dir = System.getProperty("user.dir"); - filechooser.setCurrentDirectory(new File(dir)); - filechooser.addChoosableFileFilter(new ExtensionFileFilter( - scExtensions, "Search Criteria")); -// filechooser.addChoosableFileFilter(new AllFiles_FileFilter()); - - // Copy DECODES properties into the GUI controls -// decodeCheck.setSelected(GuiApp.getBooleanProperty( -// "MessageBrowser.Decode", false)); - if (canDecode) - { - beforeDataField.setText( - GuiApp.getProperty("MessageBrowser.BeforeData", "----\\n")); - afterDataField.setText( - GuiApp.getProperty("MessageBrowser.AfterData", "")); - - int i = showCombo.getSelectedIndex(); - showRaw = (i == 0 || i == 1); - doDecode = (i == 1 || i == 2); - } - } - - /** - * Queries the GuiApp singleton for all the properties used by this - * display. This makes sure they're in the property set and initializes - * default values. - */ - @SuppressWarnings({ "rawtypes", "unchecked" }) - public static void initProperties() - { -// GuiApp.getProperty("MessageBrowser.Help", "http://www.ilexeng.com/" -// + LrgsApp.SubDir + "/help/MessageBrowser.html"); - GuiApp.getProperty("MessageBrowser.Prefix", "\\n"); - GuiApp.getProperty("MessageBrowser.Suffix", "\\n"); - String u = System.getProperty("user.name"); - GuiApp.getProperty("MessageBrowser.User", u != null ? u : ""); - GuiApp.getProperty("MessageBrowser.Port", - "" + LddsParams.DefaultPort); - GuiApp.getProperty("MessageBrowser.Timeout", "60"); - GuiApp.getProperty("MessageBrowser.DefaultSearchCrit", - "$DCSTOOL_USERDIR/MessageBrowser.sc"); - String nm = "MessageBrowser.WrapLongLines"; - GuiApp.getProperty(nm, "true"); - EditPropsAction.registerEditor(nm, - new JComboBox(new String[] { "true", "false" })); - nm = "MessageBrowser.showMsgMetaData"; - GuiApp.getProperty(nm, "false"); - EditPropsAction.registerEditor(nm, - new JComboBox(new String[] { "true", "false" })); - -// GuiApp.getProperty("MessageBrowser.ConnectionsFile", -// LddsClient.getLddsConnectionsFile()); - - // Try to initialize DECODES: - String dpf = GuiApp.getProperty("MessageBrowser.DecodesPropFile", - "$DECODES_INSTALL_DIR/decodes.properties"); - dpf = EnvExpander.expand(dpf, System.getProperties()); - - try - { -// DecodesInterface.initDecodesMinimal(dpf); - DecodesInterface.initDecodes(dpf); - if (canDecode) - DecodesInterface.initializeForDecoding(); - - } - catch(decodes.util.DecodesException ex) - { - Logger.instance().log(Logger.E_FAILURE, - "Error initializing DECODES (Decoding functions disabled): " - + ex); - return; - } - catch(NoClassDefFoundError ex) - { - Logger.instance().log(Logger.E_FAILURE, - "Cannot find DECODES classes. " - + "Check CLASSPATH and software installation: " + ex); - return; - } - - if (canDecode) - { - nm = "MessageBrowser.PresentationGroup"; - String pgs[] = DecodesInterface.getPresentationGroups(); - GuiApp.getProperty(nm, "empty-presentation"); - if (pgs != null && pgs.length > 0) - EditPropsAction.registerEditor(nm, new JComboBox(pgs)); - - nm = "MessageBrowser.OutputFormat"; - String fmts[] = DecodesInterface.getOutputFormats(); - GuiApp.getProperty(nm, "human-readable"); - if (fmts != null && fmts.length > 0) - EditPropsAction.registerEditor(nm, new JComboBox(fmts)); - - GuiApp.getProperty("MessageBrowser.TimeZone", "UTC"); - - nm = "MessageBrowser.EnableEquations"; - GuiApp.getProperty(nm, "true"); - EditPropsAction.registerEditor(nm, - new JComboBox(new String[] { "true", "false" })); - - nm = "MessageBrowser.Show"; - GuiApp.getProperty(nm, "Raw"); - EditPropsAction.registerEditor(nm, new JComboBox(showChoices)); - - // nm = "MessageBrowser.Decode"; - // GuiApp.getProperty(nm, "false"); - // EditPropsAction.registerEditor(nm, - // new JComboBox(new String[] { "true", "false" })); - - GuiApp.getProperty("MessageBrowser.BeforeData", "----\\n"); - - GuiApp.getProperty("MessageBrowser.AfterData", ""); - } - } - - /** - Opens the file specified by the MessageBrowser.ConnectionsFile - property and load the connection combo box. - */ - private void initConnectionList() - { - connectionList = new Properties(); -// String fn = GuiApp.getProperty("MessageBrowser.ConnectionsFile"); - String fn = LddsClient.getLddsConnectionsFile(); - fn = EnvExpander.expand(fn, System.getProperties()); - File file = new File(fn); - try - { - FileInputStream fis = new FileInputStream(file); - connectionList.load(fis); - fis.close(); - } - catch(IOException ioe) - { - System.out.println("No previously recorded connections"); - } - } - -// /** -// Updates the file specified by the MessageBrowser.ConnectionsFile -// with a newly selected connection. -// */ -// private void updateConnectionList(String host, String port, String user) -// { -// connectionList.setProperty(host, port + " " + user + " " + System.currentTimeMillis()); -// String fn = LddsClient.getLddsConnectionsFile(); -// File file = new File(fn); -// try -// { -// FileOutputStream fos = new FileOutputStream(file); -// connectionList.store(fos, "Recent LRGS Connections"); -// fos.close(); -// } -// catch(IOException ioe) -// { -// System.out.println("Cannot save connections"); -// } -// } - -// private void loadConnectionsField() -// { -// -// Enumeration enames = connectionList.propertyNames(); -// int selected = -1; -// int i = 0; -// hostField.removeAllItems(); -// for(; enames.hasMoreElements(); i++) -// { -// String s = (String)enames.nextElement(); -// if (hostName != null && hostName.compareToIgnoreCase(s) == 0) -// selected = i; -// hostField.addItem(s); -// } -// if (selected == -1) -// { -// hostField.addItem(hostName); -// selected = i; -// } -// hostField.setSelectedIndex(selected); -// } - -// private void setPortFromHostSelection() -// { -// String host = (String)hostField.getSelectedItem(); -// if (host == null || host.length() == 0) -// return; -// -// String hl = connectionList.getProperty(host); -// if (hl == null || hl.length() == 0) -// { -// portField.setText("16003"); -// return; -// } -// StringTokenizer st = new StringTokenizer(hl); -// if (st.hasMoreTokens()) -// portField.setText(st.nextToken()); -// else -// portField.setText("16003"); -// if (st.hasMoreTokens()) -// userField.setText(st.nextToken()); -// } - - /** Sets the screen size. */ - public void setSize(Dimension d) - { - GuiApp.setProperty("MessageBrowser.height", ""+d.height); - GuiApp.setProperty("MessageBrowser.width", ""+d.width); - } - - /** Called when screen moved. Saves location in properties. */ - public void movedTo(Point p) - { - GuiApp.setProperty("MessageBrowser.x", ""+p.x); - GuiApp.setProperty("MessageBrowser.y", ""+p.y); - } - - /** Starts the GUI at the specified location. */ - public void startup(int x, int y) - { - int width = GuiApp.getIntProperty("MessageBrowser.width", StartWidth); - int height = GuiApp.getIntProperty("MessageBrowser.height", StartHeight); - x = GuiApp.getIntProperty("MessageBrowser.x", x); - y = GuiApp.getIntProperty("MessageBrowser.y", y); - launch(x, y, width, height); - statusBar.setText(labels.getString("MessageBrowser.notConnectedLabel")); - } - - /** - @return array of 1 action, which starts the properties edit dialog. - */ - protected AbstractAction[] getFileMenuActions() - { - AbstractAction[] ret = new AbstractAction[1]; - - ret[0] = new EditPropsAction(this, "Message Browser ", - new String[] { "General", "MessageBrowser", "MessageOutput" }); - - return ret; - } - - /** @return null -- don't need an Edit menu. */ - protected AbstractAction[] getEditMenuActions() - { - return null; - } - - /** - @return true - we do want a Help menu. - */ - protected boolean isHelpMenuEnabled() - { - return true; - } - - /** @return the name for the help page "MessageBrowser.html" */ - protected String getHelpFileName() { return "MessageBrowser.html"; } - - /** - * Performs clean up before TopLevel exits. - * Override this method in your subclass. It is called when the user selects - * 'Exit' from the file menu. Do any cleanup and resource releasing necessary. - * The default implementation here does nothing. - */ - public void cleanupBeforeExit() - { - if (displayingAll) - stopDisplayAll(); - if (client != null) - { - try - { - client.sendGoodbye(); - client.disconnect(); - client = null; - } - catch(Exception e) {} - } - } - - /** - Called when connect button pressed. - Uses current info from the hostname, port, user, and password fields - to open the DDS connection and send the inital "Hello" message. - */ - public void connectButtonPress() - { - statusBar.setText(labels.getString("MessageBrowser.connectingLabel")); - if (client != null) - client.disconnect(); - client = null; - if (msgOutputThread != null) - msgOutputThread.cleanupAndDie(); - msgOutputThread = null; - nextMessageButton.setEnabled(true); - - int port; - try { port = Integer.parseInt(portField.getText()); } - catch(NumberFormatException nfe) - { - port = LddsParams.DefaultPort; - } - - String errmsg = null; - hostName = (String)hostField.getSelectedItem(); - String pw = new String(passwordField.getPassword()); - - try - { - client = new LddsClient(hostName, port); - client.connect(); - - //String pw = passwordField.getText().trim(); - if (pw.length() > 0) - client.sendAuthHello(userField.getText(), pw); - else - client.sendHello(userField.getText()); - - msgOutputThread = new DcpMsgOutputThread(this, client, - msgDisplayStream, 5, "", ""); - displayPaused = true; - msgOutputThread.start(); - statusBar.setText(LoadResourceBundle.sprintf( - labels.getString("MessageBrowser.connectedToLabel"), - hostName, port)); - } - catch(UnknownHostException uhe) - { - errmsg = LoadResourceBundle.sprintf( - labels.getString("MessageBrowser.unknownHostErr"), - hostName) + uhe; - } - catch(IOException ioe) - { - errmsg = labels.getString("MessageBrowser.ioConnectErr") + ioe; - } - catch(ProtocolError pe) - { - errmsg = pe.toString(); - } - catch(ServerError se) - { - errmsg = se.toString(); - } - if (errmsg != null) - { - showError(errmsg); - client = null; - statusBar.setText( - labels.getString("MessageBrowser.notConnectedLabel")); - } - else - { - statusBar.setText(LoadResourceBundle.sprintf( - labels.getString("MessageBrowser.connectedToAsUserLabel"), - hostName, port, userField.getText())); - - firstAfterConnect = true; - RtStatFrame.updateConnectionList(hostName, portField.getText(), - userField.getText(), connectionList, pw); - RtStatFrame.loadConnectionsField(hostField, connectionList, hostName); - } - } - - /** - Called when Search Criteria Select button is pressed. Opens a - FileChooser dialog. - */ - public void scSelectButtonPress() - { - if (filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) - scfileField.setText(filechooser.getSelectedFile().getPath()); - } - - /** - Called when Search Criteria Edit button is pressed. - If an SC Edit dialog is already active, just switch to it. Otherwise - start one on the currently selected criteria. - */ - public void scEditButtonPress() - { - if (scedit != null) - { - scedit.toFront(); - return; - } - - String s = scfileField.getText(); - s = EnvExpander.expand(s, System.getProperties()); - - decodes.util.ResourceFactory rf = - decodes.util.ResourceFactory.instance(); - try - { - if (s == null || s.length() == 0) - scedit = rf.getSearchCriteriaEditor(null); - else - { - scedit = rf.getSearchCriteriaEditor(new File(s)); - } - } - catch(IOException ioe) - { - showError(LoadResourceBundle.sprintf( - labels.getString("MessageBrowser.cannotEditErr"), - s) + ioe); - return; - } - scedit.setParent((SearchCritEditorParent)this); - scedit.startup(x+40, y+40); - scedit.setAutoSave(true); - lastSearchCrit = ""; - } - - /** - * Checks to make sure search criteria is up to date and whether - * or not it needs to be sent to the server. - * If a search criteria editor window is up, check the contents - * of the GUI window, rather than the file on disk. - * After calling this function the local variable 'searchcrit' will - * be guaranteed to be up-to-date. - * @return true if search criteria needs to be sent to the server. - */ - private boolean checkSearchCriteria() - { - if (lastSearchCrit == null) - lastSearchCrit = ""; - String curSCName = scfileField.getText().trim(); - curSCName = EnvExpander.expand(curSCName, System.getProperties()); - - // Determine if search criteria needs to be sent. - boolean needToSendSC = false; - - // If a search-criteria-editor window is up, send the crit if - // anything has been changed in it. - if (scedit != null) - { - //String lastscstring = searchcrit.toString(); - //SearchCriteria testsc = new SearchCriteria(); - //testsc = scedit.fillSearchCrit(); - if (firstAfterConnect || scedit.isChanged()) - { - // They are different! - searchcrit = new SearchCriteria(); - scedit.fillSearchCrit(searchcrit); - needToSendSC = true; - } - // Else no changes have been made in the editor. - else - needToSendSC = false; - } - // Else no editor active, just go by the filename specified. - else if (curSCName.length() > 0 - && (firstAfterConnect || !curSCName.equals(lastSearchCrit))) - { - File f = new File(curSCName); - try { searchcrit.parseFile(f); } - catch(Exception ioe) - { - if (ioe instanceof FileNotFoundException - && curSCName.endsWith("MessageBrowser.sc")) - { - try - { - f.createNewFile(); - try { searchcrit.parseFile(f); } - catch(Exception ex) {} - } - catch(IOException ex2) - { - showError(LoadResourceBundle.sprintf( - labels.getString( - "MessageBrowser.cannotReadCreateErr"), - f.getPath()) + ex2.toString()); - return false; - } - } - else - { - showError(LoadResourceBundle.sprintf( - labels.getString("MessageBrowser.cannotOpenErr"), - curSCName) + ioe.toString()); - return false; - } - } - needToSendSC = true; - lastSearchCrit = curSCName; - } - - return needToSendSC; - } - - /** - Called when 'Clear' button pressed at bottom of screen. - Clears the messgae area. - */ - public void clearButtonPress() - { - messageArea.setText(""); - } - - /** - Called when 'Next Message' button pressed at bottom of screen. - If searchcrit needs to be sent, send it. - Tell the background msgOutputThread to start & retrieve 1 message. - */ - public void nextMessageButtonPress() - { - if (client == null) - { - connectButtonPress(); - if (client == null) // unsuccessful connect? - return; - } - - if (checkSearchCriteria()) - { - if (!sendSearchCriteria(searchcrit)) - return; - } - msgOutputThread.prefix = prefixField.getText(); - msgOutputThread.suffix = suffixField.getText(); - msgOutputThread.timeout = - GuiApp.getIntProperty("MessageBrowser.Timeout", 5); - msgOutputThread.showRaw = showRaw; - msgOutputThread.doDecode = doDecode; - msgOutputThread.beforeData = canDecode ? beforeDataField.getText() : null; - msgOutputThread.afterData = canDecode ? afterDataField.getText() : null; - msgOutputThread.showMetaData = - GuiApp.getBooleanProperty("MessageBrowser.showMsgMetaData", false); - - displayPaused = false; - nextMessageButton.setEnabled(false); - } - - /** - Called if the 'send network lists' checkbox is checked right after - the search criiteria is sent. - Finds the network lists referenced in the search criteria and sends - them to the server. - */ - public void sendNetworkLists(SearchCriteria searchcrit) - { - if (searchcrit.NetlistFiles == null - || searchcrit.NetlistFiles.size() == 0) - { - Logger.instance().debug3("No lists to send."); - return; // no lists to send. - } - - for(String s : searchcrit.NetlistFiles) - { - if (s.equalsIgnoreCase("") - || s.equalsIgnoreCase("")) - continue; - - File f = NetlistFinder.find(s); - if (f != null) - { - try { client.sendNetList(f, s); } - catch(Exception e) - { - System.err.println("Error sending network list " - + s + ": " + e); - } - } - else - Logger.instance().warning("Cannot find netlist '" + s + "'"); - } - } - - /** - Sends the search criteria to the DDS server. - @return true if success and we should continue with message display. - */ - public boolean sendSearchCriteria(SearchCriteria searchcrit) - { - firstAfterConnect = false; - - - Logger.instance().debug3("Sending network lists."); - sendNetworkLists(searchcrit); - - String errmsg = null; - try { client.sendSearchCrit(searchcrit); } - catch(IOException ioe) - { - // Probably means socket error. - errmsg = labels.getString("MessageBrowser.ioSendingSCErr") + ioe; - firstAfterConnect = true; - client = null; // Force reconnect - } - catch(ProtocolError pe) - { - errmsg = pe.toString(); - client = null; // Force reconnect - } - catch(ServerError se) - { - errmsg = se.toString(); - } - if (errmsg != null) - { - showError(errmsg); - return false; - } - - return true; - } - - - /** - From the SearchCritEditorParent interface, informs us that the user - has closed the search criiteria editor. - */ - public void closingSearchCritEditor() - { - scedit = null; - } - - /** - Called when Save To File button is pressed. - Starts a new MessageOutput dialog with the current connection & - search crit parameters. - */ - public void saveToFileButtonPress() - { - // Get port number - int port; - try { port = Integer.parseInt(portField.getText()); } - catch(NumberFormatException nfe) - { - port = LddsParams.DefaultPort; - } - - // Make sure current 'searchcrit' object is up-to-date and make - // a copy for the output thread to use. - checkSearchCriteria(); - SearchCriteria outputcrit = new SearchCriteria(searchcrit); - - MessageOutput output = new MessageOutput( - (String)hostField.getSelectedItem(), port, userField.getText(), - outputcrit, prefixField.getText(), suffixField.getText(), - true, doDecode, - (canDecode ? beforeDataField.getText() : null), - (canDecode ? afterDataField.getText() : null), showRaw); - //String s = passwordField.getText().trim(); - String s = new String(passwordField.getPassword()); - if (s.length() > 0) - output.setPassword(s); - - output.startup(x+40, y+40); - } - - /** - DcpMsgOutputMonitor methods telling us a message was just displayed. - Make sure that the text area is scrolled to the bottom. - */ - public void dcpMsgOutputStatus(DcpMsg msg) - { - messageArea.setCaretPosition(messageArea.getText().length()); - if (!displayingAll) - { - displayPaused = true; - nextMessageButton.setEnabled(true); - } - } - - /** - DcpMsgOutputMonitor method: Normally we allow one message to display - then we return false, causing the output thread to pause after each - message is displayed. - */ - public boolean dcpMsgOutputIsPaused() - { - return displayPaused; - } - - /** - Called when output thread encounters an error. Display it in a dialog. - @param msg the error message - */ - public void dcpMsgOutputError(String msg) - { - showError(msg); - displayPaused = true; - nextMessageButton.setEnabled(true); - // Close connection so that reconnect is forced next time. - client.disconnect(); - statusBar.setText( - labels.getString("MessageBrowser.notConnectedLabel")); - client = null; - if (displayingAll) - stopDisplayAll(); - } - - /** - Called from the output thread when the until time is reached. - Terminates the 'display all' function. - */ - public void dcpMsgOutputDone() - { - JOptionPane.showMessageDialog(this, - labels.getString("MessageBrowser.untilTimeReachedInfo")); - displayPaused = true; - nextMessageButton.setEnabled(true); - if (displayingAll) - stopDisplayAll(); - } - - /** - Called from the output thread when the DDS server times out. - Display error message. - */ - public void dcpMsgTimeout() - { - showError(labels.getString("MessageBrowser.timeoutErr")); - displayPaused = true; - nextMessageButton.setEnabled(true); - if (displayingAll) - stopDisplayAll(); - } - - - - static CmdLineArgs cmdLineArgs = new CmdLineArgs(true, "util.log"); - static StringToken searchcrit_arg= new StringToken( - "f", "Search Crit File", "", TokenOptions.optSwitch, ""); - static IntegerToken port_arg = new IntegerToken( - "p", "Port Number", "", TokenOptions.optSwitch, DEFAULT_PORT_NUM); - static StringToken user_arg = new StringToken( - "u", "User Name", "", TokenOptions.optSwitch, ""); - static - { - cmdLineArgs.addToken(searchcrit_arg); - cmdLineArgs.addToken(port_arg); - cmdLineArgs.addToken(user_arg); - } - - /** - Main method for stand-alone operation. - Usage: -
    -
  • -h hostname (required)
  • -
  • -p port (optional default=16003)
  • -
  • -u username (required)
  • -
  • -P password (optional)
  • -
  • -f search criteria (optional default = get all messages)
  • -
  • -l log file name (optional)
  • -
- */ - public static void main(String args[]) - throws Exception - { - Logger.setLogger(new StderrLogger("MessageBrowser")); - DecodesInterface.setGUI(true); - - // Parse command line args & get argument values: - cmdLineArgs.parseArgs(args); - - getMyLabelDescriptions(); - - Logger.instance().debug1("MessageBrowser Starting."); - - GuiApp.setAppName(LrgsApp.ShortID); - GeneralProperties.init(); - MessageBrowser me = new MessageBrowser( - cmdLineArgs.getHostName(), port_arg.getValue(), user_arg.getValue()); - - DecodesInterface.maintainGoesPdt(); - - GuiApp.setTopFrame(me); - me.startup(100, 100); - } - - public static void getMyLabelDescriptions() - { - DecodesSettings settings = DecodesSettings.instance(); - //Load the generic properties file - includes labels that are used - //in multiple screens - genericLabels = LoadResourceBundle.getLabelDescriptions( - "decodes/resources/generic", - settings.language); - //Return the main label descriptions for Message Browser App - labels = LoadResourceBundle.getLabelDescriptions( - "decodes/resources/msgaccess", - settings.language); - } - - public static ResourceBundle getLabels() - { - if (labels == null) - getMyLabelDescriptions(); - return labels; - } - - public static ResourceBundle getGenericLabels() - { - if (genericLabels == null) - getMyLabelDescriptions(); - return genericLabels; - } - - // Inner class to handle outputs to the JTextArea on the screen. - class MessageAreaOutputStream extends OutputStream - { - public synchronized void write(int b) - { - b &= 0xff; - char c = (char)b; - messageArea.append(String.valueOf(c)); - } - - public synchronized void write(byte[] data, int offset, int length) - { - messageArea.append( new String(data, offset, length) ); - } - } - - - /** - Called when display all button is pressed. - */ - public void displayAllButtonPress() - { - if (!displayingAll) - startDisplayAll(); - else - stopDisplayAll(); - } - - public void startDisplayAll() - { - if (client == null) - { - connectButtonPress(); - if (client == null) // unsuccessful connect? - return; - } - - client.enableMultiMessageMode(true); - - if (checkSearchCriteria()) - { - SearchCriteria toSend = new SearchCriteria(searchcrit); - String s = toSend.getLrgsUntil(); - if (s == null || s.trim().length() == 0) - toSend.setLrgsUntil("now"); - if (!sendSearchCriteria(toSend)) - return; - } - - msgOutputThread.prefix = prefixField.getText(); - msgOutputThread.suffix = suffixField.getText(); - msgOutputThread.timeout = - GuiApp.getIntProperty("MessageBrowser.Timeout", 30); - msgOutputThread.doDecode = doDecode; - msgOutputThread.showRaw = showRaw; - msgOutputThread.beforeData = canDecode ? beforeDataField.getText() : null; - msgOutputThread.afterData = canDecode ? afterDataField.getText() : null; - msgOutputThread.showMetaData = - GuiApp.getBooleanProperty("MessageBrowser.showMsgMetaData", false); - - displayPaused = false; - - displayAllButton.setText( - labels.getString("MessageBrowser.stopButton")); - displayingAll = true; - nextMessageButton.setEnabled(false); - } - - public void stopDisplayAll() - { - displayAllButton.setText( - labels.getString("MessageBrowser.displayAll")); - displayingAll = false; - nextMessageButton.setEnabled(true); - client.enableMultiMessageMode(false); - } + private static boolean canDecode = true; + + + /** + Construct new MessageBrowser frame. + @param hostName DDS server host to connect to + @param portNum DDS port number + @userName user name to use in connection + */ + public MessageBrowser(String hostName, int portNum, String userName) + { + + super(TITLE); + + try + { + ResourceFactory.instance().initDbResources(); + } + catch (DatabaseException e1) + { + // TODO Auto-generated catch block + e1.printStackTrace(); + } + + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + try { cl.loadClass("lrgs.ddsrecv.DdsRecvConnectCfg"); } + catch(ClassNotFoundException ex) + { + canDecode = false; + showRaw = true; + doDecode = false; + } + + + getMyLabelDescriptions(); + setTitle(labels.getString("MessageBrowser.frameTitle")); + filechooser = new JFileChooser(); + + if (canDecode) + { + showChoices = new String[3]; + showChoices[0] = labels.getString("MessageBrowser.rawCombo"); + showChoices[1] = labels.getString("MessageBrowser.rawDecodedCombo"); + showChoices[2] = labels.getString("MessageBrowser.decodedCombo"); + } + + this.hostName = hostName != null ? hostName : ""; + this.portNum = portNum == 0 ? DEFAULT_PORT_NUM : portNum; + this.userName = userName != null ? userName : ""; + scedit = null; + msgOutputThread = null; + displayingAll = false; + + searchcrit = new SearchCriteria(); + + initProperties(); + MessageOutput.initProperties(); + buildMenuBar(); + initConnectionList(); + + Container contpane = getContentPane(); + contpane.setLayout(new BorderLayout()); + + statusBar = new JLabel( + labels.getString("MessageBrowser.initializingLabel")); + statusBar.setBorder(new BevelBorder(BevelBorder.LOWERED)); + contpane.add(statusBar, BorderLayout.SOUTH); + + // West contains Server, Search Criteria and Output Format Groups: + JPanel west = new JPanel(new GridBagLayout()); + contpane.add(west, BorderLayout.WEST); + + // NorthWest contains Server group + JPanel northwest = new JPanel(new GridBagLayout()); + northwest.setBorder(new TitledBorder( + labels.getString("MessageBrowser.serverTitle"))); + + northwest.add(new JLabel( + labels.getString("MessageBrowser.hostName")), + new GridBagConstraints(0, 0, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + + hostField = new JComboBox(); + hostField.setEditable(true); + hostField.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent ae) + { + RtStatFrame.setFieldsFromHostSelection(hostField, connectionList, portField, + userField, passwordField); + } + }); + RtStatFrame.loadConnectionsField(hostField, connectionList, ""); + northwest.add(hostField, + new GridBagConstraints(1, 0, 1, 1, 0.8, 1.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + + northwest.add(new JLabel(labels.getString("MessageBrowser.port")), + new GridBagConstraints(0, 1, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + northwest.add(portField, + new GridBagConstraints(1, 1, 1, 1, 0.8, 1.0, + GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + portField.setText(GuiApp.getProperty("MessageBrowser.Port")); + + Dimension d = portField.getPreferredSize(); + hostField.setPreferredSize(d); + + northwest.add(new JLabel( + labels.getString("MessageBrowser.userName")), + new GridBagConstraints(0, 2, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + northwest.add(userField, + new GridBagConstraints(1, 2, 1, 1, 0.8, 1.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + if(this.userName.length()>0) + userField.setText(this.userName); + else + userField.setText(GuiApp.getProperty("MessageBrowser.User")); + + northwest.add(new JLabel( + labels.getString("MessageBrowser.password")), + new GridBagConstraints(0, 3, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + //northwest.add(passwordField = new JTextField(15), + northwest.add(passwordField, + new GridBagConstraints(1, 3, 1, 1, 0.8, 1.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + + // Connect button across bottom: + connectButton = + new SingleClickButton(labels.getString("MessageBrowser.connect")) + { + public void buttonPressed(AWTEvent event) + { + connectButtonPress(); + } + }; + northwest.add(connectButton, + new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0, + GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + + // Finally, add northwest to the west panel. + west.add(northwest, + new GridBagConstraints(0, 0, 1, 1, 0.0, 1.0, + GridBagConstraints.NORTH, GridBagConstraints.BOTH, + new Insets(2, 5, 2, 5), 0, 0)); + + + // Midwest contains Search Criteria Group. + JPanel midwest = new JPanel(new BorderLayout()); + midwest.setBorder(new TitledBorder( + labels.getString("MessageBrowser.searchCriteria"))); + west.add(midwest, + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.2, + GridBagConstraints.NORTH, GridBagConstraints.BOTH, + new Insets(2, 5, 2, 5), 0, 0)); + JPanel p = new JPanel(new FlowLayout(FlowLayout.RIGHT)); + p.add(new JLabel(labels.getString("MessageBrowser.fileName"))); + p.add(scfileField = new JTextField(15)); + scfileField.setText( + GuiApp.getProperty("MessageBrowser.DefaultSearchCrit")); + + midwest.add(p, BorderLayout.NORTH); + p = new JPanel(new FlowLayout(FlowLayout.CENTER)); + scSelectButton = + new SingleClickButton(genericLabels.getString("select")) + { + public void buttonPressed(AWTEvent event) + { + scSelectButtonPress(); + } + }; + p.add(scSelectButton); + scEditButton = + new SingleClickButton( + " " + genericLabels.getString("edit") + " ") + { + public void buttonPressed(AWTEvent event) + { + scEditButtonPress(); + } + }; + p.add(scEditButton); + midwest.add(p, BorderLayout.CENTER); + p = new JPanel(new FlowLayout(FlowLayout.CENTER)); + midwest.add(p, BorderLayout.SOUTH); + + + + // Center contains big messge display area with buttons on bottom. + JPanel center = new JPanel(new BorderLayout()); + contpane.add(center, BorderLayout.CENTER); + messageArea = new JTextArea(); + msgDisplayStream = new MessageAreaOutputStream(); + + messagePane = new JScrollPane(messageArea); + messagePane.setBorder(new BevelBorder(BevelBorder.LOWERED)); + messageArea.setLineWrap(wrapLines); + messageArea.setEditable(false); + Font oldfont = messageArea.getFont(); + messageArea.setFont(new Font("Monospaced", Font.PLAIN, oldfont.getSize())); + + center.add(messagePane, BorderLayout.CENTER); + p = new JPanel(new GridBagLayout()); + nextMessageButton = new JButton( + labels.getString("MessageBrowser.displayNext")); + nextMessageButton.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent av) + { + nextMessageButtonPress(); + } + }); + p.add(nextMessageButton, + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 0, 2, 5), 0, 0)); + + displayAllButton = new JButton( + labels.getString("MessageBrowser.displayAll")); + displayAllButton.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent av) + { + displayAllButtonPress(); + } + }); + p.add(displayAllButton, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 0, 2, 5), 0, 0)); + + + clearButton = new JButton(" " + + genericLabels.getString("clear")+ " "); + clearButton.addActionListener( + new ActionListener() + { + public void actionPerformed(ActionEvent av) + { + clearButtonPress(); + } + }); + p.add(clearButton, + new GridBagConstraints(2, 0, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + + saveToFileButton = + new SingleClickButton( + labels.getString("MessageBrowser.saveToFile")) + { + public void buttonPressed(AWTEvent event) + { + saveToFileButtonPress(); + } + }; + + + p.add(saveToFileButton, + new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 0), 0, 0)); + + center.add(p, BorderLayout.SOUTH); + + // Southwest contains Output Format group. + JPanel southwest = new JPanel(new GridBagLayout()); + southwest.setBorder(new TitledBorder( + labels.getString("MessageBrowser.displayFormat"))); + + southwest.add(new JLabel( + labels.getString("MessageBrowser.beforeMsg")), + new GridBagConstraints(0, 0, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + + southwest.add(prefixField = new JTextField(16), + new GridBagConstraints(1, 0, 1, 1, 0.8, 1.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + prefixField.setText(GuiApp.getProperty("MessageBrowser.Prefix")); + southwest.add(new JLabel(labels.getString("MessageBrowser.afterMsg")), + new GridBagConstraints(0, 1, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + southwest.add(suffixField = new JTextField(16), + new GridBagConstraints(1, 1, 1, 1, 0.8, 1.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + suffixField.setText(GuiApp.getProperty("MessageBrowser.Suffix")); + + + if (canDecode) + { + southwest.add(new JLabel(labels.getString("MessageBrowser.show")), + new GridBagConstraints(0, 2, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + showCombo = new JComboBox(showChoices); + showCombo.setSelectedItem( + GuiApp.getProperty("MessageBrowser.Show", "Raw")); + southwest.add(showCombo, + new GridBagConstraints(1, 2, 1, 1, 1.0, 1.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + + showCombo.addActionListener( + new ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + int i = showCombo.getSelectedIndex(); + showRaw = (i == 0 || i == 1); + doDecode = (i == 1 || i == 2); + GuiApp.setProperty("MessageBrowser.Show", showChoices[i]); + } + }); + + //========= + southwest.add(new JLabel(labels.getString("MessageBrowser.outFormat")), + new GridBagConstraints(0, 3, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + outFmts = DecodesInterface.getOutputFormats(); + if (outFmts == null) + { + String[] thisFmt = new String[1]; + thisFmt[0] = "human-readable"; + outCombo = new JComboBox(thisFmt); + } else { + + outCombo = new JComboBox(outFmts); + } + outCombo.setSelectedItem( + GuiApp.getProperty("MessageBrowser.OutputFormat", "human-readable")); + southwest.add(outCombo, + new GridBagConstraints(1, 3, 1, 1, 1.0, 1.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + + outCombo.addActionListener( + new ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + int i = outCombo.getSelectedIndex(); + GuiApp.setProperty("MessageBrowser.OutputFormat", outFmts[i]); + } + }); + //========= + + southwest.add(new JLabel( + labels.getString("MessageBrowser.beforeData")), + new GridBagConstraints(0, 4, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + southwest.add(beforeDataField = new JTextField(16), + new GridBagConstraints(1, 4, 1, 1, 0.8, 1.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + + southwest.add(new JLabel(labels.getString("MessageBrowser.afterData")), + new GridBagConstraints(0, 5, 1, 1, 0.2, 1.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 5, 2, 5), 0, 0)); + southwest.add(afterDataField = new JTextField(16), + new GridBagConstraints(1, 5, 1, 1, 0.8, 1.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 5, 2, 5), 0, 0)); + } + + wrapCheck = new JCheckBox( + labels.getString("MessageBrowser.wraplonglines"), + GuiApp.getBooleanProperty("MessageBrowser.WrapLongLines", false)); + southwest.add(wrapCheck, + new GridBagConstraints(0, (canDecode ? 6 : 2), 2, 1, 1.0, 1.0, + GridBagConstraints.CENTER, GridBagConstraints.NONE, + new Insets(2, 6, 2, 5), 0, 0)); + wrapLines = wrapCheck.isSelected(); + messageArea.setLineWrap(wrapLines); + wrapCheck.addItemListener( + new ItemListener() + { + public void itemStateChanged(ItemEvent ev) + { + wrapLines = ev.getStateChange() == ItemEvent.SELECTED; + messageArea.setLineWrap(wrapLines); + GuiApp.setProperty("MessageBrowser.WrapLongLines", + wrapLines ? "true" : "false"); + } + }); + + west.add(southwest, + new GridBagConstraints(0, 2, 1, 1, 0.0, 1.0, + GridBagConstraints.NORTH, GridBagConstraints.BOTH, + new Insets(2, 5, 2, 5), 0, 0)); + + String dir = System.getProperty("user.dir"); + filechooser.setCurrentDirectory(new File(dir)); + filechooser.addChoosableFileFilter(new ExtensionFileFilter( + scExtensions, "Search Criteria")); + + if (canDecode) + { + beforeDataField.setText( + GuiApp.getProperty("MessageBrowser.BeforeData", "----\\n")); + afterDataField.setText( + GuiApp.getProperty("MessageBrowser.AfterData", "")); + + int i = showCombo.getSelectedIndex(); + showRaw = (i == 0 || i == 1); + doDecode = (i == 1 || i == 2); + } + } + + /** + * Queries the GuiApp singleton for all the properties used by this + * display. This makes sure they're in the property set and initializes + * default values. + */ + @SuppressWarnings({ "rawtypes", "unchecked" }) + public static void initProperties() + { + GuiApp.getProperty("MessageBrowser.Prefix", "\\n"); + GuiApp.getProperty("MessageBrowser.Suffix", "\\n"); + String u = System.getProperty("user.name"); + GuiApp.getProperty("MessageBrowser.User", u != null ? u : ""); + GuiApp.getProperty("MessageBrowser.Port", + "" + LddsParams.DefaultPort); + GuiApp.getProperty("MessageBrowser.Timeout", "60"); + GuiApp.getProperty("MessageBrowser.DefaultSearchCrit", + "$DCSTOOL_USERDIR/MessageBrowser.sc"); + String nm = "MessageBrowser.WrapLongLines"; + GuiApp.getProperty(nm, "true"); + EditPropsAction.registerEditor(nm, + new JComboBox(new String[] { "true", "false" })); + nm = "MessageBrowser.showMsgMetaData"; + GuiApp.getProperty(nm, "false"); + EditPropsAction.registerEditor(nm, + new JComboBox(new String[] { "true", "false" })); + + // Try to initialize DECODES: + String dpf = GuiApp.getProperty("MessageBrowser.DecodesPropFile", + "$DECODES_INSTALL_DIR/decodes.properties"); + dpf = EnvExpander.expand(dpf, System.getProperties()); + + try + { + DecodesInterface.initDecodes(dpf); + if (canDecode) + { + DecodesInterface.initializeForDecoding(); + } + } + catch(decodes.util.DecodesException ex) + { + Logger.instance().log(Logger.E_FAILURE, + "Error initializing DECODES (Decoding functions disabled): " + + ex); + return; + } + catch(NoClassDefFoundError ex) + { + Logger.instance().log(Logger.E_FAILURE, + "Cannot find DECODES classes. " + + "Check CLASSPATH and software installation: " + ex); + return; + } + + if (canDecode) + { + nm = "MessageBrowser.PresentationGroup"; + String pgs[] = DecodesInterface.getPresentationGroups(); + GuiApp.getProperty(nm, "empty-presentation"); + if (pgs != null && pgs.length > 0) + EditPropsAction.registerEditor(nm, new JComboBox(pgs)); + + nm = "MessageBrowser.OutputFormat"; + String fmts[] = DecodesInterface.getOutputFormats(); + GuiApp.getProperty(nm, "human-readable"); + if (fmts != null && fmts.length > 0) + EditPropsAction.registerEditor(nm, new JComboBox(fmts)); + + GuiApp.getProperty("MessageBrowser.TimeZone", "UTC"); + + nm = "MessageBrowser.EnableEquations"; + GuiApp.getProperty(nm, "true"); + EditPropsAction.registerEditor(nm, + new JComboBox(new String[] { "true", "false" })); + + nm = "MessageBrowser.Show"; + GuiApp.getProperty(nm, "Raw"); + EditPropsAction.registerEditor(nm, new JComboBox(showChoices)); + + GuiApp.getProperty("MessageBrowser.BeforeData", "----\\n"); + + GuiApp.getProperty("MessageBrowser.AfterData", ""); + } + } + + /** + Opens the file specified by the MessageBrowser.ConnectionsFile + property and load the connection combo box. + */ + private void initConnectionList() + { + connectionList = new Properties(); + String fn = LddsClient.getLddsConnectionsFile(); + fn = EnvExpander.expand(fn, System.getProperties()); + File file = new File(fn); + try + { + FileInputStream fis = new FileInputStream(file); + connectionList.load(fis); + fis.close(); + } + catch(IOException ioe) + { + System.out.println("No previously recorded connections"); + } + } + + /** Sets the screen size. */ + public void setSize(Dimension d) + { + GuiApp.setProperty("MessageBrowser.height", ""+d.height); + GuiApp.setProperty("MessageBrowser.width", ""+d.width); + } + + /** Called when screen moved. Saves location in properties. */ + public void movedTo(Point p) + { + GuiApp.setProperty("MessageBrowser.x", ""+p.x); + GuiApp.setProperty("MessageBrowser.y", ""+p.y); + } + + /** Starts the GUI at the specified location. */ + public void startup(int x, int y) + { + int width = GuiApp.getIntProperty("MessageBrowser.width", StartWidth); + int height = GuiApp.getIntProperty("MessageBrowser.height", StartHeight); + x = GuiApp.getIntProperty("MessageBrowser.x", x); + y = GuiApp.getIntProperty("MessageBrowser.y", y); + launch(x, y, width, height); + statusBar.setText(labels.getString("MessageBrowser.notConnectedLabel")); + } + + /** + @return array of 1 action, which starts the properties edit dialog. + */ + protected AbstractAction[] getFileMenuActions() + { + AbstractAction[] ret = new AbstractAction[1]; + + ret[0] = new EditPropsAction(this, "Message Browser ", + new String[] { "General", "MessageBrowser", "MessageOutput" }); + + return ret; + } + + /** @return null -- don't need an Edit menu. */ + protected AbstractAction[] getEditMenuActions() + { + return null; + } + + /** + @return true - we do want a Help menu. + */ + protected boolean isHelpMenuEnabled() + { + return true; + } + + /** @return the name for the help page "MessageBrowser.html" */ + protected String getHelpFileName() { return "MessageBrowser.html"; } + + /** + * Performs clean up before TopLevel exits. + * Override this method in your subclass. It is called when the user selects + * 'Exit' from the file menu. Do any cleanup and resource releasing necessary. + * The default implementation here does nothing. + */ + public void cleanupBeforeExit() + { + if (displayingAll) + { + stopDisplayAll(); + } + if (client != null) + { + try + { + client.sendGoodbye(); + client.disconnect(); + client = null; + } + catch(Exception e) {} + } + } + + /** + Called when connect button pressed. + Uses current info from the hostname, port, user, and password fields + to open the DDS connection and send the inital "Hello" message. + */ + public void connectButtonPress() + { + statusBar.setText(labels.getString("MessageBrowser.connectingLabel")); + if (client != null) + { + client.disconnect(); + } + client = null; + if (msgOutputThread != null) + { + msgOutputThread.cleanupAndDie(); + } + msgOutputThread = null; + nextMessageButton.setEnabled(true); + + int port; + try + { + port = Integer.parseInt(portField.getText()); + } + catch(NumberFormatException nfe) + { + port = LddsParams.DefaultPort; + } + + String errmsg = null; + hostName = (String)hostField.getSelectedItem(); + String pw = new String(passwordField.getPassword()); + + try + { + client = new LddsClient(hostName, port); + client.connect(); + + if (pw.length() > 0) + { + client.sendAuthHello(userField.getText(), pw); + } + else + { + client.sendHello(userField.getText()); + } + + msgOutputThread = new DcpMsgOutputThread(this, client, + msgDisplayStream, 5, "", ""); + displayPaused = true; + msgOutputThread.start(); + statusBar.setText(LoadResourceBundle.sprintf( + labels.getString("MessageBrowser.connectedToLabel"), + hostName, port)); + } + catch(UnknownHostException uhe) + { + errmsg = LoadResourceBundle.sprintf( + labels.getString("MessageBrowser.unknownHostErr"), + hostName) + uhe; + } + catch(IOException ioe) + { + errmsg = labels.getString("MessageBrowser.ioConnectErr") + ioe; + } + catch(ProtocolError pe) + { + errmsg = pe.toString(); + } + catch(ServerError se) + { + errmsg = se.toString(); + } + if (errmsg != null) + { + showError(errmsg); + client = null; + statusBar.setText( + labels.getString("MessageBrowser.notConnectedLabel")); + } + else + { + statusBar.setText(LoadResourceBundle.sprintf( + labels.getString("MessageBrowser.connectedToAsUserLabel"), + hostName, port, userField.getText())); + + firstAfterConnect = true; + RtStatFrame.updateConnectionList(hostName, portField.getText(), + userField.getText(), connectionList, pw); + RtStatFrame.loadConnectionsField(hostField, connectionList, hostName); + } + } + + /** + Called when Search Criteria Select button is pressed. Opens a + FileChooser dialog. + */ + public void scSelectButtonPress() + { + if (filechooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) + { + scfileField.setText(filechooser.getSelectedFile().getPath()); + } + } + + /** + Called when Search Criteria Edit button is pressed. + If an SC Edit dialog is already active, just switch to it. Otherwise + start one on the currently selected criteria. + */ + public void scEditButtonPress() + { + if (scedit != null) + { + scedit.toFront(); + return; + } + + String s = scfileField.getText(); + s = EnvExpander.expand(s, System.getProperties()); + + decodes.util.ResourceFactory rf = + decodes.util.ResourceFactory.instance(); + try + { + if (s == null || s.length() == 0) + { + scedit = rf.getSearchCriteriaEditor(null); + } + else + { + scedit = rf.getSearchCriteriaEditor(new File(s)); + } + } + catch(IOException ioe) + { + showError(LoadResourceBundle.sprintf( + labels.getString("MessageBrowser.cannotEditErr"), + s) + ioe); + return; + } + scedit.setParent((SearchCritEditorParent)this); + scedit.startup(x+40, y+40); + scedit.setAutoSave(true); + lastSearchCrit = ""; + } + + /** + * Checks to make sure search criteria is up to date and whether + * or not it needs to be sent to the server. + * If a search criteria editor window is up, check the contents + * of the GUI window, rather than the file on disk. + * After calling this function the local variable 'searchcrit' will + * be guaranteed to be up-to-date. + * @return true if search criteria needs to be sent to the server. + */ + private boolean checkSearchCriteria() + { + if (lastSearchCrit == null) + { + lastSearchCrit = ""; + } + String curSCName = scfileField.getText().trim(); + curSCName = EnvExpander.expand(curSCName, System.getProperties()); + + // Determine if search criteria needs to be sent. + boolean needToSendSC = false; + + // If a search-criteria-editor window is up, send the crit if + // anything has been changed in it. + if (scedit != null) + { + if (firstAfterConnect || scedit.isChanged()) + { + // They are different! + searchcrit = new SearchCriteria(); + scedit.fillSearchCrit(searchcrit); + needToSendSC = true; + } + // Else no changes have been made in the editor. + else + { + needToSendSC = false; + } + } + // Else no editor active, just go by the filename specified. + else if (curSCName.length() > 0 + && (firstAfterConnect || !curSCName.equals(lastSearchCrit))) + { + File f = new File(curSCName); + try + { + searchcrit.parseFile(f); + } + catch(Exception ioe) + { + if (ioe instanceof FileNotFoundException + && curSCName.endsWith("MessageBrowser.sc")) + { + try + { + f.createNewFile(); + try + { + searchcrit.parseFile(f); + } + catch(Exception ex) {} + } + catch(IOException ex2) + { + showError(LoadResourceBundle.sprintf( + labels.getString( + "MessageBrowser.cannotReadCreateErr"), + f.getPath()) + ex2.toString()); + return false; + } + } + else + { + showError(LoadResourceBundle.sprintf( + labels.getString("MessageBrowser.cannotOpenErr"), + curSCName) + ioe.toString()); + return false; + } + } + needToSendSC = true; + lastSearchCrit = curSCName; + } + + return needToSendSC; + } + + /** + Called when 'Clear' button pressed at bottom of screen. + Clears the messgae area. + */ + public void clearButtonPress() + { + messageArea.setText(""); + } + + /** + Called when 'Next Message' button pressed at bottom of screen. + If searchcrit needs to be sent, send it. + Tell the background msgOutputThread to start & retrieve 1 message. + */ + public void nextMessageButtonPress() + { + if (client == null) + { + connectButtonPress(); + if (client == null) // unsuccessful connect? + { + return; + } + } + + if (checkSearchCriteria()) + { + if (!sendSearchCriteria(searchcrit)) + { + return; + } + } + msgOutputThread.prefix = prefixField.getText(); + msgOutputThread.suffix = suffixField.getText(); + msgOutputThread.timeout = + GuiApp.getIntProperty("MessageBrowser.Timeout", 5); + msgOutputThread.showRaw = showRaw; + msgOutputThread.doDecode = doDecode; + msgOutputThread.beforeData = canDecode ? beforeDataField.getText() : null; + msgOutputThread.afterData = canDecode ? afterDataField.getText() : null; + msgOutputThread.showMetaData = + GuiApp.getBooleanProperty("MessageBrowser.showMsgMetaData", false); + + displayPaused = false; + nextMessageButton.setEnabled(false); + } + + /** + Called if the 'send network lists' checkbox is checked right after + the search criiteria is sent. + Finds the network lists referenced in the search criteria and sends + them to the server. + */ + public void sendNetworkLists(SearchCriteria searchcrit) + { + if (searchcrit.NetlistFiles == null + || searchcrit.NetlistFiles.size() == 0) + { + Logger.instance().debug3("No lists to send."); + return; // no lists to send. + } + + for(String s : searchcrit.NetlistFiles) + { + if (s.equalsIgnoreCase("") + || s.equalsIgnoreCase("")) + { + continue; + } + + File f = NetlistFinder.find(s); + if (f != null) + { + try + { + client.sendNetList(f, s); + } + catch(Exception e) + { + System.err.println("Error sending network list " + + s + ": " + e); + } + } + else + { + Logger.instance().warning("Cannot find netlist '" + s + "'"); + } + } + } + + /** + Sends the search criteria to the DDS server. + @return true if success and we should continue with message display. + */ + public boolean sendSearchCriteria(SearchCriteria searchcrit) + { + firstAfterConnect = false; + + Logger.instance().debug3("Sending network lists."); + sendNetworkLists(searchcrit); + + String errmsg = null; + try + { + client.sendSearchCrit(searchcrit); + } + catch(IOException ioe) + { + // Probably means socket error. + errmsg = labels.getString("MessageBrowser.ioSendingSCErr") + ioe; + firstAfterConnect = true; + client = null; // Force reconnect + } + catch(ProtocolError pe) + { + errmsg = pe.toString(); + client = null; // Force reconnect + } + catch(ServerError se) + { + errmsg = se.toString(); + } + if (errmsg != null) + { + showError(errmsg); + return false; + } + + return true; + } + + + /** + From the SearchCritEditorParent interface, informs us that the user + has closed the search criiteria editor. + */ + public void closingSearchCritEditor() + { + scedit = null; + } + + /** + Called when Save To File button is pressed. + Starts a new MessageOutput dialog with the current connection & + search crit parameters. + */ + public void saveToFileButtonPress() + { + // Get port number + int port; + try + { + port = Integer.parseInt(portField.getText()); + } + catch(NumberFormatException nfe) + { + port = LddsParams.DefaultPort; + } + + // Make sure current 'searchcrit' object is up-to-date and make + // a copy for the output thread to use. + checkSearchCriteria(); + SearchCriteria outputcrit = new SearchCriteria(searchcrit); + + MessageOutput output = new MessageOutput( + (String)hostField.getSelectedItem(), port, userField.getText(), + outputcrit, prefixField.getText(), suffixField.getText(), + true, doDecode, + (canDecode ? beforeDataField.getText() : null), + (canDecode ? afterDataField.getText() : null), showRaw); + //String s = passwordField.getText().trim(); + String s = new String(passwordField.getPassword()); + if (s.length() > 0) + { + output.setPassword(s); + } + + output.startup(x+40, y+40); + } + + /** + DcpMsgOutputMonitor methods telling us a message was just displayed. + Make sure that the text area is scrolled to the bottom. + */ + public void dcpMsgOutputStatus(DcpMsg msg) + { + messageArea.setCaretPosition(messageArea.getText().length()); + if (!displayingAll) + { + displayPaused = true; + nextMessageButton.setEnabled(true); + } + } + + /** + DcpMsgOutputMonitor method: Normally we allow one message to display + then we return false, causing the output thread to pause after each + message is displayed. + */ + public boolean dcpMsgOutputIsPaused() + { + return displayPaused; + } + + /** + Called when output thread encounters an error. Display it in a dialog. + @param msg the error message + */ + public void dcpMsgOutputError(String msg) + { + showError(msg); + displayPaused = true; + nextMessageButton.setEnabled(true); + // Close connection so that reconnect is forced next time. + client.disconnect(); + statusBar.setText( + labels.getString("MessageBrowser.notConnectedLabel")); + client = null; + if (displayingAll) + { + stopDisplayAll(); + } + } + + /** + Called from the output thread when the until time is reached. + Terminates the 'display all' function. + */ + public void dcpMsgOutputDone() + { + JOptionPane.showMessageDialog(this, + labels.getString("MessageBrowser.untilTimeReachedInfo")); + displayPaused = true; + nextMessageButton.setEnabled(true); + if (displayingAll) + stopDisplayAll(); + } + + /** + Called from the output thread when the DDS server times out. + Display error message. + */ + public void dcpMsgTimeout() + { + showError(labels.getString("MessageBrowser.timeoutErr")); + displayPaused = true; + nextMessageButton.setEnabled(true); + if (displayingAll) + stopDisplayAll(); + } + + + + static CmdLineArgs cmdLineArgs = new CmdLineArgs(true, "util.log"); + static StringToken searchcrit_arg= new StringToken( + "f", "Search Crit File", "", TokenOptions.optSwitch, ""); + static IntegerToken port_arg = new IntegerToken( + "p", "Port Number", "", TokenOptions.optSwitch, DEFAULT_PORT_NUM); + static StringToken user_arg = new StringToken( + "u", "User Name", "", TokenOptions.optSwitch, ""); + static + { + cmdLineArgs.addToken(searchcrit_arg); + cmdLineArgs.addToken(port_arg); + cmdLineArgs.addToken(user_arg); + } + + /** + Main method for stand-alone operation. + Usage: +
    +
  • -h hostname (required)
  • +
  • -p port (optional default=16003)
  • +
  • -u username (required)
  • +
  • -P password (optional)
  • +
  • -f search criteria (optional default = get all messages)
  • +
  • -l log file name (optional)
  • +
+ */ + public static void main(String args[]) + throws Exception + { + Logger.setLogger(new StderrLogger("MessageBrowser")); + DecodesInterface.setGUI(true); + + // Parse command line args & get argument values: + cmdLineArgs.parseArgs(args); + + getMyLabelDescriptions(); + + Logger.instance().debug1("MessageBrowser Starting."); + + GuiApp.setAppName(LrgsApp.ShortID); + GeneralProperties.init(); + MessageBrowser me = new MessageBrowser( + cmdLineArgs.getHostName(), port_arg.getValue(), user_arg.getValue()); + + DecodesInterface.maintainGoesPdt(); + + GuiApp.setTopFrame(me); + me.startup(100, 100); + } + + public static void getMyLabelDescriptions() + { + DecodesSettings settings = DecodesSettings.instance(); + //Load the generic properties file - includes labels that are used + //in multiple screens + genericLabels = LoadResourceBundle.getLabelDescriptions( + "decodes/resources/generic", + settings.language); + //Return the main label descriptions for Message Browser App + labels = LoadResourceBundle.getLabelDescriptions( + "decodes/resources/msgaccess", + settings.language); + } + + public static ResourceBundle getLabels() + { + if (labels == null) + { + getMyLabelDescriptions(); + } + return labels; + } + + public static ResourceBundle getGenericLabels() + { + if (genericLabels == null) + { + getMyLabelDescriptions(); + } + return genericLabels; + } + + // Inner class to handle outputs to the JTextArea on the screen. + class MessageAreaOutputStream extends OutputStream + { + public synchronized void write(int b) + { + b &= 0xff; + char c = (char)b; + messageArea.append(String.valueOf(c)); + } + + public synchronized void write(byte[] data, int offset, int length) + { + messageArea.append( new String(data, offset, length) ); + } + } + + + /** + Called when display all button is pressed. + */ + public void displayAllButtonPress() + { + if (!displayingAll) + { + startDisplayAll(); + } + else + { + stopDisplayAll(); + } + } + + public void startDisplayAll() + { + if (client == null) + { + connectButtonPress(); + if (client == null) // unsuccessful connect? + { + return; + } + } + + client.enableMultiMessageMode(true); + + if (checkSearchCriteria()) + { + SearchCriteria toSend = new SearchCriteria(searchcrit); + String s = toSend.getLrgsUntil(); + if (s == null || s.trim().length() == 0) + { + toSend.setLrgsUntil("now"); + } + if (!sendSearchCriteria(toSend)) + { + return; + } + } + + msgOutputThread.prefix = prefixField.getText(); + msgOutputThread.suffix = suffixField.getText(); + msgOutputThread.timeout = + GuiApp.getIntProperty("MessageBrowser.Timeout", 30); + msgOutputThread.doDecode = doDecode; + msgOutputThread.showRaw = showRaw; + msgOutputThread.beforeData = canDecode ? beforeDataField.getText() : null; + msgOutputThread.afterData = canDecode ? afterDataField.getText() : null; + msgOutputThread.showMetaData = + GuiApp.getBooleanProperty("MessageBrowser.showMsgMetaData", false); + + displayPaused = false; + + displayAllButton.setText( + labels.getString("MessageBrowser.stopButton")); + displayingAll = true; + nextMessageButton.setEnabled(false); + } + + public void stopDisplayAll() + { + displayAllButton.setText( + labels.getString("MessageBrowser.displayAll")); + displayingAll = false; + nextMessageButton.setEnabled(true); + client.enableMultiMessageMode(false); + } } diff --git a/src/main/java/lrgs/ldds/GetHostnameThread.java b/src/main/java/lrgs/ldds/GetHostnameThread.java index 7529ec8ec..45d4c8e74 100644 --- a/src/main/java/lrgs/ldds/GetHostnameThread.java +++ b/src/main/java/lrgs/ldds/GetHostnameThread.java @@ -1,5 +1,5 @@ /** - * + * */ package lrgs.ldds; @@ -12,7 +12,6 @@ import java.net.UnknownHostException; import java.util.concurrent.LinkedBlockingQueue; -import lrgs.ddsserver.DdsServer; import lrgs.lrgsmain.LrgsConfig; /** @@ -22,159 +21,166 @@ public class GetHostnameThread extends Thread { - private static int max=20; - private LinkedBlockingQueue ltq - = new LinkedBlockingQueue(); - public static final String module = "GetHostnameThread"; - private static GetHostnameThread _instance = null; - private String localIpMask = null; - private int localIpMaskInt = 0; - private int localIpAddr = 0; - - public static GetHostnameThread instance() - { - if (_instance == null) - _instance = new GetHostnameThread(); - return _instance; - } - - public GetHostnameThread() - { - super("GetHostnameThread"); - setLocalIpMask(LrgsConfig.instance().getMiscProp("localIpMask")); - } - - private void setLocalIpMask(String lim) - { - localIpMask = lim; - if (localIpMask == null || localIpMask.trim().length() == 0) + private static int max=20; + private LinkedBlockingQueue ltq + = new LinkedBlockingQueue(); + public static final String module = "GetHostnameThread"; + private static GetHostnameThread _instance = null; + private String localIpMask = null; + private int localIpMaskInt = 0; + private int localIpAddr = 0; + + public static GetHostnameThread instance() + { + if (_instance == null) { - localIpMaskInt = 0; - localIpAddr = 0; + _instance = new GetHostnameThread(); } - else - { - String ipaddr = localIpMask.trim(); - int slash = ipaddr.indexOf('/'); - int nbits=32; - if (slash > 0) - { - try { nbits = Integer.parseInt(ipaddr.substring(slash+1)); } - catch(Exception ex) - { - Logger.instance().warning(module + " bad localIpMask setting '" + localIpMask + "': '" - + ex + " -- ignored."); - localIpMaskInt = 0; - localIpAddr = 0; - return; - } - ipaddr = ipaddr.substring(0, slash); - } - - try - { - Inet4Address a; - a = (Inet4Address) InetAddress.getByName(ipaddr); - byte[] b = a.getAddress(); - int ai = ((b[0] & 0xFF) << 24) | - ((b[1] & 0xFF) << 16) | - ((b[2] & 0xFF) << 8) | - ((b[3] & 0xFF) << 0); - localIpMaskInt = -1<<(32-nbits); - localIpAddr = ai & localIpMaskInt; - } - catch (UnknownHostException ex) - { - Logger.instance().warning(module + " unusable localIpMask setting '" + localIpMask + "': " - + ex + " -- ignored."); - localIpMaskInt = 0; - localIpAddr = 0; - return; - } - } - } - - - public synchronized void enqueue(LddsThread lt) - { - String lim = LrgsConfig.instance().getMiscProp("localIpMask"); - if (!TextUtil.strEqualIgnoreCase(localIpMask, lim)) - setLocalIpMask(lim); - - if (localIpAddr != 0) - { - try - { - byte[] b = lt.getSocket().getInetAddress().getAddress(); - int ia = ((b[0] & 0xFF) << 24) | - ((b[1] & 0xFF) << 16) | - ((b[2] & 0xFF) << 8) | - ((b[3] & 0xFF) << 0); - - if ((ia & localIpMaskInt) == localIpAddr) + return _instance; + } + + public GetHostnameThread() + { + super("GetHostnameThread"); + setLocalIpMask(LrgsConfig.instance().getMiscProp("localIpMask")); + } + + private void setLocalIpMask(String lim) + { + localIpMask = lim; + if (localIpMask == null || localIpMask.trim().length() == 0) + { + localIpMaskInt = 0; + localIpAddr = 0; + } + else + { + String ipaddr = localIpMask.trim(); + int slash = ipaddr.indexOf('/'); + int nbits=32; + if (slash > 0) + { + try { - int toDisplay = ia & (~localIpMaskInt); - String hostname = "local." + toDisplay; - lt.setHostName(hostname); - return; + nbits = Integer.parseInt(ipaddr.substring(slash+1)); } - } - catch(Exception ex) - { - Logger.instance().warning(module + ".enqueue 1: " + ex); - } - } - - try - { - while (ltq.size() >= max) - { - ltq.take(); - } - ltq.put(lt); - } - catch(InterruptedException ex) + catch(Exception ex) + { + Logger.instance().warning(module + " bad localIpMask setting '" + localIpMask + "': '" + + ex + " -- ignored."); + localIpMaskInt = 0; + localIpAddr = 0; + return; + } + ipaddr = ipaddr.substring(0, slash); + } + + try + { + Inet4Address a; + a = (Inet4Address) InetAddress.getByName(ipaddr); + byte[] b = a.getAddress(); + int ai = ((b[0] & 0xFF) << 24) | + ((b[1] & 0xFF) << 16) | + ((b[2] & 0xFF) << 8) | + ((b[3] & 0xFF) << 0); + localIpMaskInt = -1<<(32-nbits); + localIpAddr = ai & localIpMaskInt; + } + catch (UnknownHostException ex) + { + Logger.instance().warning(module + " unusable localIpMask setting '" + localIpMask + "': " + + ex + " -- ignored."); + localIpMaskInt = 0; + localIpAddr = 0; + return; + } + } + } + + + public synchronized void enqueue(LddsThread lt) + { + String lim = LrgsConfig.instance().getMiscProp("localIpMask"); + if (!TextUtil.strEqualIgnoreCase(localIpMask, lim)) { - Logger.instance().warning(module + ".enqueue 2: " + ex); + setLocalIpMask(lim); } - } - - private LddsThread dequeue() - { - try + + if (localIpAddr != 0) + { + try + { + byte[] b = lt.getSocket().getInetAddress().getAddress(); + int ia = ((b[0] & 0xFF) << 24) | + ((b[1] & 0xFF) << 16) | + ((b[2] & 0xFF) << 8) | + ((b[3] & 0xFF) << 0); + + if ((ia & localIpMaskInt) == localIpAddr) + { + int toDisplay = ia & (~localIpMaskInt); + String hostname = "local." + toDisplay; + lt.setHostName(hostname); + return; + } + } + catch(Exception ex) + { + Logger.instance().warning(module + ".enqueue 1: " + ex); + } + } + + try + { + while (ltq.size() >= max) + { + ltq.take(); + } + ltq.put(lt); + } + catch(InterruptedException ex) { - Logger.instance().debug1(module + - ".dequeue getting LddsThread qsize=" + ltq.size() - + "..."); - return ltq.take(); + Logger.instance().warning(module + ".enqueue 2: " + ex); + } + } + + private LddsThread dequeue() + { + try + { + Logger.instance().debug1(module + + ".dequeue getting LddsThread qsize=" + ltq.size() + + "..."); + return ltq.take(); } catch (InterruptedException ex) { - Logger.instance().warning(module + ".dequeue " + ex); - return null; + Logger.instance().warning(module + ".dequeue " + ex); + return null; } - } + } - public void run() - { - while(true) - { - LddsThread lt = dequeue(); - if (lt != null) - { - Socket sock = lt.getSocket(); - InetAddress ia = - sock != null ? sock.getInetAddress() : null; - Logger.instance().debug1(module + - " Trying name lookup for " + ia.toString()); - - lt.setHostName(ia.getHostName()); - Logger.instance().debug1(module + - " Done. Set name to '" + lt.getHostName() + "'"); - } - else - Logger.instance().warning(module + ".dequeue returned null"); - } - } + public void run() + { + while(true) + { + LddsThread lt = dequeue(); + if (lt != null) + { + Socket sock = lt.getSocket(); + InetAddress ia = + sock != null ? sock.getInetAddress() : null; + Logger.instance().debug1(module + + " Trying name lookup for " + ia.toString()); + + lt.setHostName(ia.getHostName()); + Logger.instance().debug1(module + + " Done. Set name to '" + lt.getHostName() + "'"); + } + else + Logger.instance().warning(module + ".dequeue returned null"); + } + } } diff --git a/src/main/java/lrgs/ldds/LddsClient.java b/src/main/java/lrgs/ldds/LddsClient.java index 6b51a9176..d90f75a6e 100644 --- a/src/main/java/lrgs/ldds/LddsClient.java +++ b/src/main/java/lrgs/ldds/LddsClient.java @@ -34,2243 +34,2280 @@ and the LRGS DCP Data Server (LDDS). Construct the LddsClient object */ public class LddsClient extends BasicClient { - /** Input stream coming from the server */ - private LddsInputStream linput; - - /** The server's protocol version number */ - private int serverProtoVersion; - private String serverProtoVersionStr; - - /** True if I should request messages in multi-mode. */ - private boolean multiMessageModeEnabled; - - /** True if I should request messages in extended-multi-mode. */ - private boolean extMessageModeEnabled; - - /** Buffer holding last multi-message response. */ - private DcpMsg multiMsg[]; - - /** Index into multi-message response buffer */ - private int multiMsgIdx; - - /** The session key if an authenticated hello was done. */ - protected byte[] sessionKey = null; - - /** Optional module name to pre-pend to all log messages. */ - protected String module; - - ExtBlockXmlParser extBlockXmlParser; - - private SimpleDateFormat outageDateFormat; - private SimpleDateFormat goesDateFormat; - private OutageXmlParser outageXmlParser = null; - public boolean implicitAllUsed = false; - - SearchCritLocalFilter searchCritLocalFilter = null; - - // The user name used in the last call to hello or auth. - private String userName = null; - private boolean strongOnly = false; - - - /** - Constructs client for LDDS at specified host. - Use default port number. - The connection is not made until the 'connect()' method is called. - @param host the remote host - */ - public LddsClient(String host) - { - this(host, LddsParams.DefaultPort); - } - - /** - Constructs client for LDDS at specified port on specified host. - The connection is not made until the 'connect()' method is called. - @param host the remote host - @param port the remote port - */ - public LddsClient(String host, int port) - { - super(host, port); - - goesDateFormat = new SimpleDateFormat("yyDDDHHmmss"); - TimeZone jtz = TimeZone.getTimeZone("UTC"); - goesDateFormat.setTimeZone(jtz); - - outageDateFormat = new SimpleDateFormat("yyyy/DDD-HH:mm:ss"); - outageDateFormat.setTimeZone(jtz); - - linput = null; - serverProtoVersion = DdsVersion.version_unknown; // Not set until connected to a server. - - /// Client must explicitely enable multi-mode. - multiMessageModeEnabled = false; - extMessageModeEnabled = true; - multiMsg = null; - multiMsgIdx = 0; - module = ""; - extBlockXmlParser = null; - } - - /** - Multi-message mode allows the client to attempt to receive several - messages from the server in a single request. Approximately 80K worth - of message data can be retrieved in a single request. - Even if enabled, it will only be used if the server supports it. - @param tf true if you want to use multi-mode - */ - public void enableMultiMessageMode(boolean tf) - { - multiMessageModeEnabled = tf; - } - - /** - Extended-message mode allows the client to attempt to receive several - messages from the server in a single request with extended status info - on each message. - Even if enabled, it will only be used if the server supports it. - @param tf true if you want to use multi-mode - */ - public void enableExtMessageMode(boolean tf) - { - extMessageModeEnabled = tf; -//Logger.instance().info("extMessageModeEnabled=" + extMessageModeEnabled); - } - - /** - Connects to the specified host and port. - @throws IOException on socket error. - @throws UnknownHostException if can't resolve specified host name. - */ - public void connect() throws IOException, UnknownHostException - { - Logger.instance().debug2(module + - "Connecting to '" + host + "', port " + port); - super.connect(); - socket.setTcpNoDelay(true); - socket.setSoTimeout(60000); - linput = new LddsInputStream(input); - } - - /** - Disconnects from the server. - Close input & output streams and release all socket resources. - - This function should be called when any of the other methods throws - an exception. You can then call connect() again to reconnect to the - server. - */ - public void disconnect() - { - try - { - if (linput != null) - { - Logger.instance().debug2(module + - "Disconnecting from '" + host + "', port " + port); - linput.close(); - } - else - Logger.instance().debug2(module + - "Already disconnected from '" + host + "', port " + port); - super.disconnect(); - } - catch(Exception e) {} - finally - { - linput = null; - } - } - - /** - * @return true if this is currently connected to a server. - */ - public boolean isConnected() - { - return linput != null; - } - - /** - * @return true if successfully authenticated to the server. - */ - public boolean isAuthenticated() - { - return sessionKey != null; - } - - /** - Sends a Hello message with the specified user name. - Then awaits the response from the server. If an exception is not thrown, - then the login was successful. - - @param name the user name to send to the server - - @throws ServerError if the server rejected this request. In the case - of the hello message this means that the username is not known. - @throws ProtocolError if the server response could not be parsed - or it was of an unexpected type. - @throws IOException indicates that the socket is no longer usable. - */ - public void sendHello(String name) - throws ServerError, ProtocolError, IOException - { - // Send hello - if (debug != null) - debug.println("sendHello("+name+")"); - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") sendHello(" - + name + ")"); - - LddsMessage msg = new LddsMessage(LddsMessage.IdHello, - name + " " + DdsVersion.getVersion()); - sendData(msg.getBytes()); - - // Read the response message - It should be same type ID. - msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdHello) - throw new ProtocolError("Unexpected response '" + - msg.MsgId + "' - expected '" + LddsMessage.IdHello - + "' (hello)"); - - String resp = ByteUtil.getCString(msg.MsgData, 0); - if (debug != null) - debug.println("Hello response '" + resp + "'"); - - // '?' means that server refused the login. - if (resp.length() > 0 && resp.charAt(0) == '?') - throw new ServerError(resp); - else if (resp.length() >= 9 && resp.substring(0,9).equals("HELLO ???")) - throw new ServerError(resp); - - // Try to parse the protocol version out of the response. - serverProtoVersion = DdsVersion.version_1; // Default assumption - StringTokenizer st = new StringTokenizer(resp); - if (st.countTokens() >= 2) - { - st.nextToken(); // skip name echo - String s = st.nextToken(); - try { serverProtoVersion = Integer.parseInt(s); } - catch(NumberFormatException ex) - { - Logger.instance().warning(module + - "Invalid protocol version '" + s - + "' returned by server. Assuming protoVersion=3"); - serverProtoVersion = DdsVersion.version_1; - } - } - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") Hello response '" - + resp+ "', protocolVersion=" + serverProtoVersion); - userName = name; - - } - - /** - Sends an Authenticated Hello message with the specified user name and - password. - Then awaits the response from the server. If an exception is not thrown, - then the login was successful. - - @param name the user name to send to the server - @param passwd the password to send to the server - - @throws ServerError if the server rejected this request. In the case - of the this message this means that the authentication failed. - @throws ProtocolError if the server response could not be parsed - or it was of an unexpected type. - @throws IOException indicates that the socket is no longer usable. - */ - public void sendAuthHello(String name, String passwd) - throws ServerError, ProtocolError, IOException - { - // Send hello - if (debug != null) - debug.println("sendAuthHello("+name+")"); - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") sendAuthHello(" - + name + ")"); - - if (name == null || TextUtil.isAllWhitespace(name)) - throw new ServerError( - "Client-side reject: username cannot be blank", 0, 0); - - if (passwd == null || TextUtil.isAllWhitespace(passwd)) - throw new ServerError( - "Client-side reject: password cannot be blank", 0, 0); - - try - { - PasswordFileEntry pfe = new PasswordFileEntry(name, passwd); -//System.out.println("sendAuthHello user='" + name + "' pw='" + passwd + "', authStr='" -//+ ByteUtil.toHexString(pfe.getShaPassword()) + "'"); - sendAuthHello(pfe, strongOnly ? AuthenticatorString.ALGO_SHA256 : AuthenticatorString.ALGO_SHA); - } - catch(AuthException ex) - { - throw new ProtocolError("Invalid username or password: " + ex); - } - userName = name; - - } - - /** - * Sends an authenticated hello, using a prepared password file entry. - * @param pfe the password file entry. - */ - public void sendAuthHello(PasswordFileEntry pfe, String algo) - throws ServerError, ProtocolError, IOException - { - Date now = new Date(); - int timet = (int)(now.getTime() / 1000); - AuthenticatorString auth; - try - { - auth = new AuthenticatorString(timet, pfe, algo); - - // Construct a 1-time session key for admin functions. - sessionKey = AuthenticatorString.makeAuthenticator( - auth.getString().getBytes(), pfe.getShaPassword(), timet, algo); - } - catch(Exception ex) - { - sessionKey = null; - throw new ServerError( - "Client-side reject: cannot build authenticator: " + ex); - } - String tstr = goesDateFormat.format(now); - - String body = pfe.getUsername() + " " + tstr + " " + auth.getString() - + " " + DdsVersion.getVersion(); - - LddsMessage msg = new LddsMessage(LddsMessage.IdAuthHello, body); - sendData(msg.getBytes()); - - // Read the response message - It should be same type ID. - msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdAuthHello) - { - sessionKey = null; - throw new ProtocolError("Unexpected response '" + - msg.MsgId + "' - expected '" + LddsMessage.IdAuthHello - + "' (auth-hello)"); - } - - String resp = ByteUtil.getCString(msg.MsgData, 0); - Logger.instance().debug1("AuthHello response '" + resp + "'"); - - // '?' means that server refused the login. - if (resp.length() > 0 && resp.charAt(0) == '?') - { - sessionKey = null; - ServerError serverError = new ServerError(resp); - if (serverError.Derrno == LrgsErrorCode.DSTRONGREQUIRED - && algo == AuthenticatorString.ALGO_SHA) - { - // We tried with SHA, but server requires SHA-256. Try again. - sendAuthHello(pfe, AuthenticatorString.ALGO_SHA256); - return; - } - throw serverError; - } - StringTokenizer st = new StringTokenizer(resp); - if (st.countTokens() < 3) - { - sessionKey = null; - throw new ProtocolError("Invalid response '" + resp - + "' to AuthHello request"); - } - st.nextToken(); // skip name echo - st.nextToken(); // skip time echo - serverProtoVersionStr = st.nextToken(); - - try - { - int i=0; - while(i < serverProtoVersionStr.length() - && Character.isDigit(serverProtoVersionStr.charAt(i))) - i++; - serverProtoVersion = Integer.parseInt( - serverProtoVersionStr.substring(0, i)); - } - catch(NumberFormatException ex) - { - Logger.instance().warning(module + - "Invalid protocol version '" + serverProtoVersionStr - + "' returned by server. Assuming protoVersion=3"); - serverProtoVersion = DdsVersion.version_3; - } - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") AuthHello response '" - + resp+ "', protocolVersion=" + serverProtoVersion); - - userName = pfe.getUsername(); - - } - - /** - Sends a goodbye message to server. Then waits for response. - - @throws IOException if the socket is no longer usable. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - */ - public void sendGoodbye() - throws IOException, ProtocolError - { - if (debug != null) - debug.println("sendGoodbye()"); - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") sendGoodbye()"); - - LddsMessage msg = new LddsMessage(LddsMessage.IdGoodbye, null); - sendData(msg.getBytes()); - - // Read the response message - It should be same type ID. - msg = getAbortResponse(); - if (msg == null) - throw new ProtocolError("No response received for GOODBYE"); - else if (msg.MsgId != LddsMessage.IdGoodbye) - throw new ProtocolError( - "Unexpected response '" + msg.MsgId + "'" - + " - Expected '" + LddsMessage.IdGoodbye + "' (Goodbye)"); - - if (debug != null) - debug.println("Goodbye action complete"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") Goodbye response OK"); - } - - - /** - Retrieves a search criteria file from the server. The file is always - called 'searchcrit' on the server and is always stored in the user's - home directory. The filename passed to this function is the local - file that will be created to hold the retrieved searchcrit. -

- If the 'localfile' argument is left blank, a file called 'searchcrit' - will be created in the current directory. - - @param localfile the name of the local file to write SC data to. - - @throws IOException if the socket is no longer usable. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - @throws ServerError if the server returned an error response for - the request. - */ - public void getSearchCrit(String localfile) - throws IOException, ProtocolError, ServerError - { - if (localfile == null) - localfile = "searchcrit"; - - if (debug != null) - debug.println("getSearchCrit("+localfile+")"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") getSearchCrit(" - + localfile + ")"); - - // Send request - LddsMessage msg = new LddsMessage(LddsMessage.IdCriteria, "?"); - sendData(msg.getBytes()); - - // Read the response message - It should be same type ID. - msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdCriteria) - throw new ProtocolError( - "Unexpected response to getSearchCrit '" + msg.MsgId + "'"); - - // Validate response - if ((char)msg.MsgData[0] == '?') - throw new ServerError(new String(msg.MsgData)); - - if (msg.MsgData.length < 50) - throw new ProtocolError("No searchcrit data returned"); - - // Save data. - if (debug != null) - debug.println("Saving " + (msg.MsgData.length - 50) - + " bytes to " + localfile); - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") Saving " - + (msg.MsgData.length - 50) + " bytes to " + localfile); - - File file = new File(localfile); - FileOutputStream fos = new FileOutputStream(file); - fos.write(ArrayUtil.getField(msg.MsgData, 50, msg.MsgData.length-50)); - } - - /** - Sends a search criteria file to the server. The file is always - called 'searchcrit' on the server and is always stored in the user's - sandbox directory. The filename passed to this function is the local - file that will be read and transferred to the server. -

- If the 'localfile' argument is left blank, a file called 'searchcrit' - will be read from the current directory. - - @param localfile the name of the local sc file to send. - - @throws IOException if either the socket is no longer usable, or - that the specified localfile could not be read. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - @throws ServerError if the server returned an error response for - the request. - */ - public void sendSearchCrit(String localfile) - throws IOException, ProtocolError, ServerError - { - if (localfile == null) - localfile = "searchcrit"; - - if (debug != null) - debug.println("sendSearchCrit("+localfile+")"); - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") sendSearchCrit(" - + localfile + ")"); - - // Read contents of specified searchcrit file into memory. - File f = new File(localfile); - try - { - SearchCriteria sc = new SearchCriteria(f); - sendSearchCrit(sc); - } - catch(SearchSyntaxException ex) - { - throw new IOException("Bad SearchCriteria format: " + ex); - } - } - - /** - Sends search criteria from an existing SearchCriteria object rather - than a file. - -

- New feature in LRGS 6: if the LRGS_SINCE field contains a string of - the form filetime(filename), then this method attempts to find the - local file, get its last-modify-time, and send that to the server. - If the file does not exist locally, it is equivalent to no SINCE - time being sent. - - @param searchcrit the SearchCriteria object to send to the server - @throws IOException if either the socket is no longer usable. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - @throws ServerError if the server returned an error response for - the request. - */ - public void sendSearchCrit(SearchCriteria searchcrit) - throws IOException, ProtocolError, ServerError - { - if (debug != null) - debug.println("sendSearchCrit(OBJECT)"); - - // Make a copy, preprocess, and send the copy. - SearchCriteria toSend = new SearchCriteria(searchcrit); - - // If single-mode then set in search-crit. - // Thus for a V11 server, we will still get expanded-mode data. - if (!multiMessageModeEnabled) - toSend.single = true; - - // Expand filetime for since, if used. - String st = toSend.getLrgsSince(); - if (st != null) - { - st = st.trim(); - if (TextUtil.startsWithIgnoreCase(st,"filetime(")) - { - st = st.substring(9); - int idx = st.indexOf(")"); - if (idx != -1) - st = st.substring(0, idx); - String fn = EnvExpander.expand(st); - File f = new File(fn); - long t; - if (!f.exists() - || (t = f.lastModified()) <= 0) - toSend.setLrgsSince(null); - else - { - toSend.setLrgsSince( - IDateFormat.toString(new Date(t-60000L), false)); - } - } - } - - // MJM - The following added in Nov, 2007. Try to convert the - // DCP name to an address before sending to the server. This goes - // with the strategy of trying to void persistent client context - // on the server. - // Try to find a matching site name in the DECODES database. - if (toSend.DcpNames != null && toSend.DcpNames.size() > 0 - && Database.getDb() != null - && Database.getDb().platformList != null) - { - PlatformList platList = Database.getDb().platformList; - for (Iterator nmIt = toSend.DcpNames.iterator(); nmIt.hasNext(); ) - { - String nm = nmIt.next(); - Platform plat = platList.getByFileName(nm); - if (plat == null) - plat = platList.getBySiteNameValue(nm); - if (plat != null) - { - String dcpaddr = plat.getDcpAddress(); - if (dcpaddr != null) - { - toSend.addDcpAddress(new DcpAddress(dcpaddr)); - nmIt.remove(); - } - } - } - } - - - implicitAllUsed = false; - // MJM 2008 09/25 Implement the implicit and network - // lists. If these are used, build a dynamic list from the DECODES - // platform list containing all non-expired GOES IDs. - for(int i = 0; i") - || nlname.equalsIgnoreCase("")) - { - implicitAllUsed = true; - boolean productionOnly = nlname.equalsIgnoreCase(""); - decodes.db.Database db = decodes.db.Database.getDb(); - if (db == null) - { - toSend.NetlistFiles.remove(i--); - continue; - } - NetworkList nl = new NetworkList(); - for(Platform plat : db.platformList.getPlatformVector()) - { - if (plat.expiration != null) - continue; - if (productionOnly && !plat.isProduction) - continue; - for(TransportMedium tm : plat.transportMedia) - if (tm.isGoes() - || tm.getMediumType().equalsIgnoreCase(Constants.medium_IRIDIUM)) - { - DcpAddress addr = new DcpAddress(tm.getMediumId()); - if (!nl.containsDcpAddr(addr)) - nl.add(new NetworkListItem(addr, - plat.getDisplayName(), - plat.getDescription())); - } - } - String listname = productionOnly ? - "decodes_production.nl" : "decodes_all.nl"; - sendNetList(nl, listname); - toSend.NetlistFiles.set(i, listname); - } - } - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") sendSearchCrit(OBJECT)"); - - // If there are too many explicit DCP addresses, convert them to - // temporary network lists and send them first. - int listnum = 1; - while(toSend.ExplicitDcpAddrs.size() > 500) - { - NetworkList tmpNl = new NetworkList(); - for(int idx = 0; idx < 500; idx++) - tmpNl.add(new NetworkListItem(toSend.ExplicitDcpAddrs.get(idx),"","")); - String nlName = "searchcrit_" + (listnum++) + ".nl"; - sendNetList(tmpNl, nlName); - toSend.addNetworkList(nlName); - ArrayList tl = new ArrayList(toSend.ExplicitDcpAddrs.size()-500); - for(int idx = 500; idx < toSend.ExplicitDcpAddrs.size(); idx++) - tl.add(toSend.ExplicitDcpAddrs.get(idx)); - toSend.ExplicitDcpAddrs = tl; - } - - // Put searchcrit into a byte array. - byte data[] = toSend.toString(serverProtoVersion).getBytes(); - searchCritLocalFilter = toSend.getSearchCritLocalFilter(); - sendSearchCrit("OBJECT", data); - } - - /** - Sends search criteria from an in-memory byte array. - @param filename the name of the searchcrit to pass to the server - @param data the search criteria data - @throws IOException if either the socket is no longer usable. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - @throws ServerError if the server returned an error response for - the request. - */ - private void sendSearchCrit(String filename, byte data[]) - throws IOException, ProtocolError, ServerError - { - // Construct an empty criteria message big enought for this file. - LddsMessage msg = new LddsMessage(LddsMessage.IdCriteria, ""); - msg.MsgLength = data.length + 50; - msg.MsgData = new byte[msg.MsgLength]; - - // Create the 'header' portion containing the searchcrit filename. - // (First 40 bytes is filename) - int i; - for(i = 0; i<40 && i 0 && (char)msg.MsgData[0] == '?') - { - String s = new String(msg.MsgData); - throw new ServerError(s); - } - - if (debug != null) - debug.println("Successfully sent searchcrit."); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "Successfully sent searchcrit."); - - // MJM 20080619 - Just sent new crit, clear any buffered messages. - flushBufferedMessages(); - } - - - /** - * Requests the next DCP message from the server. - * If a search criteria file has previously been transfered - * (either to or from the server), then the server will only pass messages - * that meet the specified criteria. - *

- * The timeout argument specifies the number of seconds to wait for a - * response from the server. - *

- * Returns a DcpMsg or null if no response was received from the server - * within the specified # of seconds. - *

- * @param timeout number of seconds to wait - * @throws IOException if socket is no longer usable. - * @throws ProtocolError if an unexpected response was received. - * (i.e. the wrong message type). - * @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if - * no message arrived at the server within the specified timeout - * period. This typically indicates that you are already caught-up - * to the present time. - * @throws ServerError with other Derrno codes to indicate other errors - * on the server which are not recoverable. When this happens, call - * disconnect() and then start the session over. - */ - public DcpMsg getDcpMsg(int timeout) - throws IOException, ProtocolError, ServerError - { - if (!this.multiMessageModeEnabled) //Single mode - { - return getDcpMsgSingle(timeout); - } - else if (this.multiMessageModeEnabled && serverProtoVersion >= DdsVersion.version_11) - { - //Proto V11, single mode is sent in searchcrit. - return getDcpMsgExt(timeout); - } - else if (this.extMessageModeEnabled && serverProtoVersion >= DdsVersion.version_8) - { - return getDcpMsgExt(timeout); - } - else if (this.multiMessageModeEnabled && serverProtoVersion >= DdsVersion.version_5) - { - return getDcpMsgMulti(timeout); - } - else - { - return getDcpMsgSingle(timeout); - } - } - - /** - Gets the next message from the server (single-mode). - Requests the next DCP message from the server. - If a search criteria file has previously been transfered - (either to or from the server), then the server will only pass messages - that meet the specified criteria. -

- The timeout argument specifies the number of seconds to wait for a - response from the server. -

- @param timeout number of seconds to wait - - @return a DcpMsg or null if no response was received from the server - within the specified # of seconds. - - @throws IOException if socket is no longer usable. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if - no message arrived at the server within the specified timeout - period. This typically indicates that you are already caught-up - to the present time. - @throws ServerError with other Derrno codes to indicate other errors - on the server which are not recoverable. When this happens, call - disconnect() and then start the session over. - */ - public DcpMsg getDcpMsgSingle(int timeout) - throws IOException, ProtocolError, ServerError - { - boolean requestAgain = true; - DcpMsg ret = null; - while(requestAgain) - { - requestDcpMsg(); - ret = receiveDcpMsg(timeout); - if (ret == null) - ret = abortDcpMsgRequest(); - - // If we have a local filter (i.e. we are talking to a legacy - // server and must do some of the filtering locally)... - requestAgain = ret != null - && searchCritLocalFilter != null - && !searchCritLocalFilter.passesCrit(ret); - } - - return ret; - } - - /** - Most clients can call the synchronous getDcpMsg() function. If you - need the ability to abort a request, call the requestDcpMsg method - followed by the receiveDcpMsg method. - - Request the next DCP message from the server. If your client process - needs the ability to abort a request in progress, you will have to - call requestDcpMsg followed by repeated calls to receiveDcpMsg. - - @throws IOException if the socket is no longer usable. - */ - public void requestDcpMsg() throws IOException - { - if (debug != null) - debug.println("Requesting DCP Message..."); - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "Requesting DCP Message..."); - - // Request Dcp Message - LddsMessage msg = new LddsMessage(LddsMessage.IdDcp, ""); - sendData(msg.getBytes()); - } - - /** - * Receives a DCP Message after calling requestDcpMsg. - * If a message is received within timeout seconds, it will be returned. - * Otherwise null will be returned. - *

- * Note: One message is returned by the server for each request. Once - * a message has been received you need to call requestDcpMsg again - * before calling this method. - *

- * @throws IOException if the socket is no longer usable. - * @throws ProtocolError if an unexpected response was received. - * (i.e. the wrong message type). - * @throws ServerError with a Derrno equal to (DUNTIL) if the specified - * until time was reached. - * @throws ServerError with other codes for other errors on the server - * (probably not recoverable). - */ - public DcpMsg receiveDcpMsg(int timeout) - throws IOException, ProtocolError, ServerError - { - // Check for asynchronous disconnection. - if (linput == null) - return null; - - socket.setSoTimeout((timeout+1)*1000); - - // Get response. - LddsMessage msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdDcp) - throw new - ProtocolError("Unexpected responses '" + msg.MsgId + "'"); - if (msg.MsgData[0] == (byte)'?') - throw new ServerError(new String(msg.MsgData)); - - return lddsMsg2DcpMsg(msg); - } - - private DcpMsg lddsMsg2DcpMsg(LddsMessage msg) - throws ProtocolError - { - if (msg.MsgLength < 40 + DcpMsg.DCP_MSG_MIN_LENGTH) - { - if (debug != null) - { - debug.println("Too-Short DCP message response: id='" - + msg.MsgId + "' length=" + msg.MsgLength); - if (msg.MsgLength > 40) - { - String d = new String(ArrayUtil.getField(msg.MsgData, - 40, msg.MsgLength - 40)); - debug.println("data: " + d); - } - } - - Logger.instance().warning(module + - "DDS Connection (" + host + ":" + port + ") " - + "Too-Short DCP message response: id='" - + msg.MsgId + "' length=" + msg.MsgLength + " -- skipped."); - - if (msg.MsgLength > 40) - { - String d = new String( - ArrayUtil.getField(msg.MsgData, 40, msg.MsgLength - 40)); - Logger.instance().warning(module + - "Complete response '" + d + "'"); - } - - throw new ProtocolError("Too-Short DCP message response received"); - } -// DcpMsg ret = -// new DcpMsg(ArrayUtil.getField(msg.MsgData, 40, msg.MsgLength-40), -// msg.MsgLength - 40); - DcpMsg ret = new DcpMsg(msg.MsgData, msg.MsgLength-40, 40); - ret.flagbits = DcpMsgFlag.MSG_PRESENT | DcpMsgFlag.SRC_DDS - | DcpMsgFlag.MSG_NO_SEQNUM; - - // Get sequence filename from first 40 bytes of message. - ret.setSeqFileName(ByteUtil.getCString(msg.MsgData, 0)); - if (debug != null) - { - debug.println("Response received: fn = " + - ret.getSeqFileName() + ", length = " + (msg.MsgLength - 40)); - } - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "Response received: fn = " + - ret.getSeqFileName() + ", length = " + (msg.MsgLength - 40)); - - return ret; - } - - /** - In order to be able to abort DCP message requests. You will need to - first call requestDcpMsg(). Then in a loop, repeatedly call - receiveDcpMsg with a brief timeout. When you want to stop, call - abortDcpMsgRequest(). This tells the server to abort the request. - - A race condition exists. The server might be just sending the - Dcp message response when I send the abort. If this happens, this - method will return the DCP message. Otherwise, null is returned. - - Failure to abort an outstanding DCP Message request will render the - socket unusable for other operations. - - @throws IOException if the socket is no longer usable. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - */ - public DcpMsg abortDcpMsgRequest() - throws IOException, ProtocolError - { - if (debug != null) - debug.println("abortDcpMsgRequest()"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "abortDcpMsgRequest()"); - - if (linput == null) - return null; - - LddsMessage msg = new LddsMessage(LddsMessage.IdStop, null); - sendData(msg.getBytes()); - - msg = getAbortResponse(); - - // There is a race condition here. The server may have just - // sent the message out when I sent it an abort. If the message I - // just read is a DCP message return it to the client. - DcpMsg ret = null; - if (msg != null && msg.MsgId == LddsMessage.IdDcp) - { - ret = lddsMsg2DcpMsg(msg); - - // Now read the response to the Abort request. - msg = getAbortResponse(); - } - - if (msg == null) - throw new ProtocolError( - "No response to abort request received"); - else if (msg.MsgId != LddsMessage.IdStop) - throw new ProtocolError( - "Unexpected response '" + msg.MsgId + "'" - + " - Expected '" + LddsMessage.IdStop + "' (Stop)"); - - return ret; - } - - private LddsMessage getAbortResponse() - throws IOException, ProtocolError - { - // Wait up to 10 seconds for the response to the abort. - // If none received, we'll just abort anyway. - socket.setSoTimeout(10000); - - return linput.getMessage(); - } - - /** - The getNetList method retrieves a network list file from the server. - The first argument (serverfile) specifies the name of the network - list file on the server. The second argument (localfile) specifies - the name of the file on the local system that will be created. - - @param serverfile name of network list on the server - @param localfile name of network list on the local computer - - @throws IOException if a network socket error or local file error. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - @throws ServerError if the server responded to the request with an - error message. This most likely means that that the requested - network list file does not exist on the server. - - */ - public void getNetList(String serverfile, File localfile) - throws IOException, ProtocolError, ServerError - { - if (debug != null) - debug.println("getNetList("+serverfile+ ", " - + localfile.getName() + ")"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "getNetList("+serverfile+ ", " + localfile.getName() + ")"); - - // Send request - LddsMessage msg = new LddsMessage(LddsMessage.IdGetNetlist, - serverfile); - sendData(msg.getBytes()); - - // Read the response message - It should be same type ID. - msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdGetNetlist) - throw new ProtocolError("Unexpected responses '" + msg.MsgId + "'"); - - // Validate response - if ((char)msg.MsgData[0] == '?') - throw new ServerError(new String(msg.MsgData)); - if (msg.MsgLength < 64) - throw new ServerError("?0,0,No file data returned"); - - // Save data. - if (debug != null) - debug.println("Saving " + (msg.MsgLength - 64) - + " bytes to " + localfile.getName()); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "Saving " + (msg.MsgLength - 64) - + " bytes to " + localfile.getName()); - - FileOutputStream fos = new FileOutputStream(localfile); - fos.write( ArrayUtil.getField(msg.MsgData, 64, msg.MsgData.length-64)); - fos.close(); - } - - /** - sends a network list file to the server. - - @param serverfile name of network list on the server - @param localfile name of network list on the local computer - - @throws IOException on network socket error or local file error. - @throws ProtocolError if an unexpected response was received. - (i.e. the wrong message type). - @throws ServerError if the server responded to the request with an - error message. This most likely means that that the named - file could not be created on the server. - */ - public void sendNetList(File localfile, String serverfile) - throws IOException, ProtocolError, ServerError - { - if (debug != null) - debug.println("sendNetList("+localfile.getName() - +", " + serverfile + ")"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "sendNetList("+localfile.getName() +", " + serverfile + ")"); - - // Read contents of specified searchcrit file into memory. - FileInputStream fis = new FileInputStream(localfile); - byte data[] = new byte[(int)localfile.length()]; - fis.read(data); - fis.close(); - - // Construct an empty criteria message big enought for this file. - LddsMessage msg = new LddsMessage(LddsMessage.IdPutNetlist, ""); - msg.MsgLength = data.length + 64; - msg.MsgData = new byte[msg.MsgLength]; - - // Create the 'header' portion, which contains 64 char filename - int i; - for(i = 0; i<64 && i - * The timeout argument specifies the number of seconds to wait for a - * response from the server. - *

- * Returns an array DcpMsg objects, or null if no response was received - * from the server within the specified # of seconds. - *

- * @param timeout number of seconds to wait - - * @throws IOException if socket is no longer usable. - * @throws ProtocolError if an unexpected response was received. - * (i.e. the wrong message type). - * @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if - * the server indicates that you are already caught-up to the present - * time. When this happens, pause and try again later. - * @throws ServerError with other Derrno codes to indicate other errors - * on the server which are not recoverable. When this happens, call - * disconnect() and then start the session over. - */ - public DcpMsg[] getDcpMsgBlock(int timeout) - throws IOException, ProtocolError, ServerError - { - requestDcpMsgBlock(); - DcpMsg ret[] = receiveDcpMsgBlock(timeout); - if (ret == null) - ret = abortDcpMsgBlockRequest(); - return ret; - } - - public void requestDcpMsgBlock() throws IOException - { - if (debug != null) - debug.println("Requesting DCP Message Block..."); - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "Requesting DCP Message Block..."); - - // Request Dcp Message - LddsMessage msg = new LddsMessage(LddsMessage.IdDcpBlock, ""); - sendData(msg.getBytes()); - } - - /** - * Receives a DCP Message Block after calling requestDcpMsg. - * The block is parsed into an array of DcpMsg objects and returned. - * Returns null if no response is received from server in timeout seconds. - *

- * @throws IOException if the socket is no longer usable. - * @throws ProtocolError if an unexpected response was received. - * (i.e. the wrong message type). - * @throws ServerError with a Derrno equal to (DUNTIL) if the specified - * until time was reached. - * @throws ServerError with other codes for other errors on the server - * (probably not recoverable). - */ - public DcpMsg[] receiveDcpMsgBlock(int timeout) - throws IOException, ProtocolError, ServerError - { - // Check for asynchronous disconnection. - if (linput == null) - { - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "receiveDcpMsgBlock asynchronous disconect, aborting."); - return null; - } - - socket.setSoTimeout((timeout+1) * 1000); - - // Get response. - LddsMessage msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdDcpBlock) - throw new - ProtocolError("Unexpected response '" + msg.MsgId - + "', expected type '" + LddsMessage.IdDcpBlock + "'"); - - if (msg.MsgData[0] == (byte)'?') - { - String err = new String(msg.MsgData); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") ServerError: " - + err); - throw new ServerError(err); - } - - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "received block response, length=" + msg.MsgLength); - - return lddsMsg2DcpMsgBlock(msg); - } - - private DcpMsg[] lddsMsg2DcpMsgBlock(LddsMessage msg) - throws ProtocolError - { - Logger.instance().debug3(module + - "Parsing block response. Total length = " + msg.MsgLength); - - // Got response, parse it into an array of DCP Messages. - ArrayList v = new ArrayList(); - boolean garbled = false; - int msgnum = 0; - for(int msgStart=0; msgStart= multiMsg.length) - { - // get next block of data - int numFiltered = 0; - do - { - multiMsgIdx = 0; - multiMsg = getDcpMsgBlock(timeout); - if (multiMsg == null) - throw new ProtocolError( - "Timeout waiting for block response from server."); - // If we have a local filter (i.e. we are talking to a legacy - // server and must do some of the filtering locally)... - if (searchCritLocalFilter != null) - { - numFiltered = 0; - for(int idx = 0; idx < multiMsg.length; idx++) - if (!searchCritLocalFilter.passesCrit(multiMsg[idx])) - { - multiMsg[idx] = null; - numFiltered++; - } - if (numFiltered > 0) - { - DcpMsg fret[] = new DcpMsg[multiMsg.length - numFiltered]; - int fidx = 0; - for(int idx = 0; idx < multiMsg.length; idx++) - if (multiMsg[idx] != null) - fret[fidx++] = multiMsg[idx]; - multiMsg = fret; - } - } - } while(multiMsg != null && multiMsg.length == 0 && - searchCritLocalFilter != null && numFiltered > 0); - } - if (multiMsg != null && multiMsgIdx < multiMsg.length) - return multiMsg[multiMsgIdx++]; - else - return null; - } - - /** - * @return the number of messages already received and buffered. - */ - public int getNumberBuffered() - { - if (multiMsg != null) - return multiMsg.length - multiMsgIdx; - else - return 0; - } - - /** - * Deletes any buffered messages, forcing next retrieve to send request - * to server. - */ - public void flushBufferedMessages() - { - multiMsgIdx = 0; - multiMsg = null; - } - - /** - Retrieves the status from the server. - @return byte array containing an XML block representing the server's - current status. - */ - public byte[] getStatus() - throws IOException, ProtocolError, ServerError - { - if (debug != null) - debug.println("getStatus"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") getStatus"); - - // Send request - LddsMessage msg = new LddsMessage(LddsMessage.IdStatus, "?"); - sendData(msg.getBytes()); - - // Read the response message - It should be same type ID. - msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdStatus) - throw new ProtocolError( - "Unexpected response to getStatus '" + msg.MsgId + "'"); - - // Validate response - if ((char)msg.MsgData[0] == '?') - throw new ServerError(new String(msg.MsgData)); - - // Some servers throw a null byte at the end. If so, convert to LF. - if (msg.MsgData[msg.MsgData.length-1] == 0) - msg.MsgData[msg.MsgData.length-1] = (byte)'\n'; - - return msg.MsgData; - } - - /** - Retrieve the next block of events from the server. - return an array of Strings, each represeting a single formated text - event. - @return array of event strings - */ - public String[] getEvents() - throws IOException, ProtocolError, ServerError - { - if (serverProtoVersion < DdsVersion.version_6) - return new String[0]; - - if (debug != null) - debug.println("getEvent"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") getEvents"); - - // Send request - LddsMessage msg = new LddsMessage(LddsMessage.IdEvents, "?"); - sendData(msg.getBytes()); - - // Read the response message - It should be same type ID. - msg = linput.getMessage(); - if (msg.MsgId != LddsMessage.IdEvents) - throw new ProtocolError( - "Unexpected response to getEvents '" + msg.MsgId + "'"); - - // Validate response - if (msg.MsgData.length == 0) - return new String[0]; - - if ((char)msg.MsgData[0] == '?') - throw new ServerError(new String(msg.MsgData)); - - // Some servers throw a null byte at the end. If so, convert to space. - if (msg.MsgData[msg.MsgData.length-1] == 0) - msg.MsgData[msg.MsgData.length-1] = (byte)' '; - - int numEvents = 0; - for(int i=0; i < msg.MsgData.length; i++) - if (msg.MsgData[i] == (byte)'\n') - numEvents++; - if (numEvents == 0) - return null; - - String ret[] = new String[numEvents]; - int num = 0; - int sidx = 0; - for(int i=0; i 0 && (char)msg.MsgData[0] == '?') - throw new ServerError(new String(msg.MsgData)); - if (msg.MsgLength < 64) - throw new ServerError("?0,0,No file data returned"); - - return ArrayUtil.getField(msg.MsgData, 64, msg.MsgLength - 64); - } - - /** - * Installs a configuration on the server. - * @throws AuthException if you are not authenticated, or on any - * server-side error. - */ - public void installConfig(String cfgType, byte[] data) - throws AuthException - { - if (debug != null) - debug.println("installConfig(" + cfgType + ")"); - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "installConfig(" + cfgType + ")"); - - // Construct an empty criteria message big enought for this file. - LddsMessage msg = new LddsMessage(LddsMessage.IdInstConfig, ""); - msg.MsgLength = 64 + (data != null ? data.length : 0); - msg.MsgData = new byte[msg.MsgLength]; - - // Create the 'header' portion, which contains 64 char cfg type - int i; - for(i = 0; i<64 && i - * The timeout argument specifies the number of seconds to wait for a - * response from the server. - * - * @return uncompressed byte-array response to the Extended Block Request. - * from the server within the specified # of seconds. - * @param timeout number of seconds to wait - - * @throws IOException if socket is no longer usable. - * @throws ProtocolError if an unexpected response was received. - * (i.e. the wrong message type). - * @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if - * the server indicates that you are already caught-up to the present - * time. When this happens, pause and try again later. - * @throws ServerError with other Derrno codes to indicate other errors - * on the server which are not recoverable. When this happens, call - * disconnect() and then start the session over. - */ - public byte[] getMsgBlockExtXml(int timeout) - throws IOException, ProtocolError, ServerError - { - Logger.instance().debug2(module + - "DDS Connection (" + host + ":" + port + ") " - + "Requesting DCP Message Block Ext (timeout=" - + timeout + ")..."); - - LddsMessage req = new LddsMessage(LddsMessage.IdDcpBlockExt, ""); - - LddsMessage resp = serverExec(req); - if (resp.MsgId != LddsMessage.IdDcpBlockExt) - throw new ProtocolError("Unexpected response '" + resp.MsgId - + "', expected type '" + LddsMessage.IdDcpBlockExt + "'"); - - // Message contains compressed byte-array of XML. Uncompress it. - try - { - ByteArrayInputStream bais = new ByteArrayInputStream(resp.MsgData); - GZIPInputStream gzis = new GZIPInputStream(bais); - ByteArrayOutputStream baos = - new ByteArrayOutputStream(resp.MsgData.length); - byte buf[] = new byte[4096]; - int len; - while ((len = gzis.read(buf)) > 0) - baos.write(buf, 0, len); - gzis.close(); - bais.close(); - baos.close(); - byte ret[] = baos.toByteArray(); -//Logger.instance().info("orig response len=" + resp.MsgData.length -//+ " after unzip=" + ret.length); - return ret; - } - catch(IOException ex) - { - throw new ProtocolError("Error unpacking compressed block: " + ex); - } - } - - /** - * Gets the next extended mode block and converts the XML into an array - * of DcpMsg objects. - */ - public DcpMsg[] getMsgBlockExt(int timeout) - throws IOException, ProtocolError, ServerError - { - DcpMsg ret[] = null; - int numFiltered = 0; - do - { - byte[] xmldata = getMsgBlockExtXml(timeout); - if (extBlockXmlParser == null) - extBlockXmlParser = new ExtBlockXmlParser(DcpMsgFlag.SRC_DDS); - ret = extBlockXmlParser.parseMsgBlock(xmldata); - // If we have a local filter (i.e. we are talking to a legacy - // server and must do some of the filtering locally)... - if (searchCritLocalFilter != null && ret != null) - { - numFiltered = 0; - for(int idx = 0; idx < ret.length; idx++) - if (!searchCritLocalFilter.passesCrit(ret[idx])) - { - ret[idx] = null; - numFiltered++; - } - if (numFiltered > 0) - { - DcpMsg fret[] = new DcpMsg[ret.length - numFiltered]; - int fidx = 0; - for(int idx = 0; idx < ret.length; idx++) - if (ret[idx] != null) - fret[fidx++] = ret[idx]; - ret = fret; - } - } - } while(ret != null && ret.length == 0 && - searchCritLocalFilter != null && numFiltered > 0); - return ret; - } - - /** - Get the next DCP message using extended-mode. - - @param timeout number of seconds to wait - @return DcpMsg object - */ - private DcpMsg getDcpMsgExt(int timeout) - throws IOException, ProtocolError, ServerError - { - if (multiMsg == null || multiMsgIdx >= multiMsg.length) - { - // get next block of data - multiMsgIdx = 0; - multiMsg = null; - multiMsg = getMsgBlockExt(timeout); - if (multiMsg == null) - throw new ProtocolError( - "Timeout waiting for ext block response from server."); - } - if (multiMsg != null && multiMsgIdx < multiMsg.length) - return multiMsg[multiMsgIdx++]; - else - return null; - } - - /** - * Returns the array of outages, optionally within a time range. - * If both start and end are null, all outages are returned. - * Else if only end is null, all outages since the start time are returned. - */ - public ArrayList getOutages(Date start, Date end) - throws IOException, ProtocolError, ServerError - { - String txt = ""; - if (start != null) - { - txt = outageDateFormat.format(start); - if (end != null) - txt = txt + " " + outageDateFormat.format(end); - } - LddsMessage msg = new LddsMessage(LddsMessage.IdGetOutages, txt); - LddsMessage resp = serverExec(msg); - // Response contains GZipped array of XML Outages. First unzip it. - - byte respData[] = null; - try - { - ByteArrayInputStream bais = new ByteArrayInputStream(resp.MsgData); - GZIPInputStream gzis = new GZIPInputStream(bais); - ByteArrayOutputStream baos = - new ByteArrayOutputStream(resp.MsgData.length); - byte buf[] = new byte[4096]; - int len; - while ((len = gzis.read(buf)) > 0) - baos.write(buf, 0, len); - gzis.close(); - bais.close(); - baos.close(); - respData = baos.toByteArray(); -//Logger.instance().info("orig response len=" + resp.MsgData.length -//+ " after unzip=" + respData.length); - } - catch(IOException ex) - { - throw new ProtocolError("Error unpacking compressed outages: "+ex); - } - - try { return getOutageXmlParser().parse(respData); } - catch(IOException ex) - { - Logger.instance().warning("Unparsable outages: " + ex); - return new ArrayList(); - } - } - -//============================ -// /** -// * Receives a DCP Message Block after calling requestDcpMsg. -// * The block is parsed into an array of DcpMsg objects and returned. -// * Returns null if no response is received from server in timeout seconds. -// *

-// * @throws IOException if the socket is no longer usable. -// * @ProtocolError if an unexpected response was received. -// * (i.e. the wrong message type). -// * @throws ServerError with a Derrno equal to (DUNTIL) if the specified -// * until time was reached. -// * @throws ServerError with other codes for other errors on the server -// * (probably not recoverable). -// */ -// public DcpMsg[] receiveDcpMsgBlock(int timeout) -// throws IOException, ProtocolError, ServerError -// { -// // Check for asynchronous disconnection. -// if (linput == null) -// { -// Logger.instance().debug2(module + -// "DDS Connection (" + host + ":" + port + ") " -// + "receiveDcpMsgBlock asynchronous disconect, aborting."); -// return null; -// } -// -// socket.setSoTimeout((timeout+1) * 1000); -// -// // Get response. -// LddsMessage msg = linput.getMessage(); -// if (msg.MsgId != LddsMessage.IdDcpBlock) -// throw new -// ProtocolError("Unexpected response '" + msg.MsgId -// + "', expected type '" + LddsMessage.IdDcpBlock + "'"); -// -// if (msg.MsgData[0] == (byte)'?') -// { -// String err = new String(msg.MsgData); -// Logger.instance().debug2(module + -// "DDS Connection (" + host + ":" + port + ") ServerError: " -// + err); -// throw new ServerError(err); -// } -// -// Logger.instance().debug2(module + -// "DDS Connection (" + host + ":" + port + ") " -// + "received block response, length=" + msg.MsgLength); -// -// return lddsMsg2DcpMsgBlock(msg); -// } -// -// private DcpMsg[] lddsMsg2DcpMsgBlock(LddsMessage msg) -// throws ProtocolError -// { -// Logger.instance().debug3(module + -// "Parsing block response. Total length = " + msg.MsgLength); -// -// // Got response, parse it into an array of DCP Messages. -// Vector v = new Vector(); -// boolean garbled = false; -// int msgnum = 0; -// for(int msgStart=0; msgStart userList = new ArrayList(); - while(st.hasMoreTokens()) - { - String line = st.nextToken(); - try - { - userList.add(new DdsUser(line)); - } - catch(BadConfigException ex) - { - Logger.instance().warning(module + " Ignoring user spec '" - + line + "': " + ex); - } - } - return userList; - } - catch(Exception ex) - { - String m = "Cannot list users: " + ex; - Logger.instance().warning(m); - System.err.println(m); - ex.printStackTrace(); - throw new AuthException(m); - } - } - - /** - * Sends a request to add or edit a user on the DDS server. - * @param ddsUser the user data - * @param pw the password, or null to leave password unchanged on server. - * @throws AuthException if you are not authenticated, or on any - * server-side error. - */ - public void modUser(DdsUser ddsUser, String pw) - throws AuthException - { - byte[] sk = getSessionKey(); - if (sk == null) - throw new AuthException( - "Modify user requires authenticated connection."); - String sks = ByteUtil.toHexString(sk); - - String cmd = "set " + ddsUser.userName + " "; - - // If not setting pw, or if v13, put placeholder in pw field. - if (pw == null || pw.length() == 0 - || serverProtoVersion >= DdsVersion.version_13) - cmd += "-"; - else - { - PasswordFileEntry pfe = new PasswordFileEntry(ddsUser.userName); - pfe.setPassword(pw); - pw = ByteUtil.toHexString(pfe.getShaPassword()); - DesEncrypter de = new DesEncrypter(sks); - pw = de.encrypt(pw); - cmd += pw; - } - - // Syntax: set username DES(pw) perms props - // No field may have embedded blanks. - cmd = cmd + " " + ddsUser.permsString() + " " + ddsUser.propsString(); -//System.out.println("LddsClient.modUser sending '" + cmd + "'"); - try - { - LddsMessage msg = new LddsMessage(LddsMessage.IdUser, cmd); - LddsMessage resp = serverExec(msg); - } - catch(Exception ex) - { - throw new AuthException("Cannot set user info: " + ex); - } - - if (pw != null && pw.length() > 0 && serverProtoVersion >= DdsVersion.version_13) - { - cmd = "pw " + ddsUser.userName + " "; - DesEncrypter de = new DesEncrypter(sks); - cmd += de.encrypt(pw); - try - { - LddsMessage msg = new LddsMessage(LddsMessage.IdUser, cmd); - LddsMessage resp = serverExec(msg); - } - catch(Exception ex) - { - throw new AuthException("Cannot set user password: " + ex); - } - } - } - - /** - * Removes a user on the server. - * @param userName the user name to remove. - * @throws AuthException on any server-side error. - */ - public void rmUser(String userName) - throws AuthException - { - String cmd = "rm " + userName; - try - { - LddsMessage msg = new LddsMessage(LddsMessage.IdUser, cmd); - LddsMessage resp = serverExec(msg); - } - catch(Exception ex) - { - throw new AuthException("Cannot remove DDS user: " + ex); - } - } - - public OutageXmlParser getOutageXmlParser() - { - if (outageXmlParser == null) - outageXmlParser = new OutageXmlParser(); - return outageXmlParser; - } - - - /** find the LddsConnections file and return path */ - public static String getLddsConnectionsFile() - { - String dirs[] = { "DCSTOOL_USERDIR", "DCSTOOL_HOME", "user.home" }; - for(String p : dirs) - { - String dir = System.getProperty(p); - if (dir != null && dir.length() > 0) - return dir + "/LddsConnections"; - } - return "LddsConnections"; - } - - public String getUserName() - { - return userName; - } - - public void setStrongOnly(boolean strongOnly) - { - this.strongOnly = strongOnly; - } + /** Input stream coming from the server */ + private LddsInputStream linput; + + /** The server's protocol version number */ + private int serverProtoVersion; + private String serverProtoVersionStr; + + /** True if I should request messages in multi-mode. */ + private boolean multiMessageModeEnabled; + + /** True if I should request messages in extended-multi-mode. */ + private boolean extMessageModeEnabled; + + /** Buffer holding last multi-message response. */ + private DcpMsg multiMsg[]; + + /** Index into multi-message response buffer */ + private int multiMsgIdx; + + /** The session key if an authenticated hello was done. */ + protected byte[] sessionKey = null; + + /** Optional module name to pre-pend to all log messages. */ + protected String module; + + ExtBlockXmlParser extBlockXmlParser; + + private SimpleDateFormat outageDateFormat; + private SimpleDateFormat goesDateFormat; + private OutageXmlParser outageXmlParser = null; + public boolean implicitAllUsed = false; + + SearchCritLocalFilter searchCritLocalFilter = null; + + // The user name used in the last call to hello or auth. + private String userName = null; + private boolean strongOnly = false; + + + /** + Constructs client for LDDS at specified host. + Use default port number. + The connection is not made until the 'connect()' method is called. + @param host the remote host + */ + public LddsClient(String host) + { + this(host, LddsParams.DefaultPort); + } + + /** + Constructs client for LDDS at specified port on specified host. + The connection is not made until the 'connect()' method is called. + @param host the remote host + @param port the remote port + */ + public LddsClient(String host, int port) + { + super(host, port); + + goesDateFormat = new SimpleDateFormat("yyDDDHHmmss"); + TimeZone jtz = TimeZone.getTimeZone("UTC"); + goesDateFormat.setTimeZone(jtz); + + outageDateFormat = new SimpleDateFormat("yyyy/DDD-HH:mm:ss"); + outageDateFormat.setTimeZone(jtz); + + linput = null; + serverProtoVersion = DdsVersion.version_unknown; // Not set until connected to a server. + + /// Client must explicitely enable multi-mode. + multiMessageModeEnabled = false; + extMessageModeEnabled = true; + multiMsg = null; + multiMsgIdx = 0; + module = ""; + extBlockXmlParser = null; + } + + /** + Multi-message mode allows the client to attempt to receive several + messages from the server in a single request. Approximately 80K worth + of message data can be retrieved in a single request. + Even if enabled, it will only be used if the server supports it. + @param tf true if you want to use multi-mode + */ + public void enableMultiMessageMode(boolean tf) + { + multiMessageModeEnabled = tf; + } + + /** + Extended-message mode allows the client to attempt to receive several + messages from the server in a single request with extended status info + on each message. + Even if enabled, it will only be used if the server supports it. + @param tf true if you want to use multi-mode + */ + public void enableExtMessageMode(boolean tf) + { + extMessageModeEnabled = tf; + } + + /** + Connects to the specified host and port. + @throws IOException on socket error. + @throws UnknownHostException if can't resolve specified host name. + */ + public void connect() throws IOException, UnknownHostException + { + Logger.instance().debug2(module + + "Connecting to '" + host + "', port " + port); + super.connect(); + socket.setTcpNoDelay(true); + socket.setSoTimeout(60000); + linput = new LddsInputStream(input); + } + + /** + Disconnects from the server. + Close input & output streams and release all socket resources. + + This function should be called when any of the other methods throws + an exception. You can then call connect() again to reconnect to the + server. + */ + public void disconnect() + { + try + { + if (linput != null) + { + Logger.instance().debug2(module + + "Disconnecting from '" + host + "', port " + port); + linput.close(); + } + else + Logger.instance().debug2(module + + "Already disconnected from '" + host + "', port " + port); + super.disconnect(); + } + catch(Exception e) {} + finally + { + linput = null; + } + } + + /** + * @return true if this is currently connected to a server. + */ + public boolean isConnected() + { + return linput != null; + } + + /** + * @return true if successfully authenticated to the server. + */ + public boolean isAuthenticated() + { + return sessionKey != null; + } + + /** + Sends a Hello message with the specified user name. + Then awaits the response from the server. If an exception is not thrown, + then the login was successful. + + @param name the user name to send to the server + + @throws ServerError if the server rejected this request. In the case + of the hello message this means that the username is not known. + @throws ProtocolError if the server response could not be parsed + or it was of an unexpected type. + @throws IOException indicates that the socket is no longer usable. + */ + public void sendHello(String name) + throws ServerError, ProtocolError, IOException + { + // Send hello + if (debug != null) + { + debug.println("sendHello("+name+")"); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") sendHello(" + + name + ")"); + + LddsMessage msg = new LddsMessage(LddsMessage.IdHello, + name + " " + DdsVersion.getVersion()); + sendData(msg.getBytes()); + + // Read the response message - It should be same type ID. + msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdHello) + { + throw new ProtocolError("Unexpected response '" + + msg.MsgId + "' - expected '" + LddsMessage.IdHello + + "' (hello)"); + } + + String resp = ByteUtil.getCString(msg.MsgData, 0); + if (debug != null) + { + debug.println("Hello response '" + resp + "'"); + } + + // '?' means that server refused the login. + if (resp.length() > 0 && resp.charAt(0) == '?') + { + throw new ServerError(resp); + } + else if (resp.length() >= 9 && resp.substring(0,9).equals("HELLO ???")) + { + throw new ServerError(resp); + } + + // Try to parse the protocol version out of the response. + serverProtoVersion = DdsVersion.version_1; // Default assumption + StringTokenizer st = new StringTokenizer(resp); + if (st.countTokens() >= 2) + { + st.nextToken(); // skip name echo + String s = st.nextToken(); + try + { + serverProtoVersion = Integer.parseInt(s); + } + catch(NumberFormatException ex) + { + Logger.instance().warning(module + + "Invalid protocol version '" + s + + "' returned by server. Assuming protoVersion=3"); + serverProtoVersion = DdsVersion.version_1; + } + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") Hello response '" + + resp+ "', protocolVersion=" + serverProtoVersion); + userName = name; + } + + /** + Sends an Authenticated Hello message with the specified user name and + password. + Then awaits the response from the server. If an exception is not thrown, + then the login was successful. + + @param name the user name to send to the server + @param passwd the password to send to the server + + @throws ServerError if the server rejected this request. In the case + of the this message this means that the authentication failed. + @throws ProtocolError if the server response could not be parsed + or it was of an unexpected type. + @throws IOException indicates that the socket is no longer usable. + */ + public void sendAuthHello(String name, String passwd) + throws ServerError, ProtocolError, IOException + { + // Send hello + if (debug != null) + { + debug.println("sendAuthHello("+name+")"); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") sendAuthHello(" + + name + ")"); + + if (name == null || TextUtil.isAllWhitespace(name)) + { + throw new ServerError( + "Client-side reject: username cannot be blank", 0, 0); + } + + if (passwd == null || TextUtil.isAllWhitespace(passwd)) + { + throw new ServerError( + "Client-side reject: password cannot be blank", 0, 0); + } + + try + { + PasswordFileEntry pfe = new PasswordFileEntry(name, passwd); + sendAuthHello(pfe, strongOnly ? AuthenticatorString.ALGO_SHA256 : AuthenticatorString.ALGO_SHA); + } + catch(AuthException ex) + { + throw new ProtocolError("Invalid username or password: " + ex); + } + userName = name; + + } + + /** + * Sends an authenticated hello, using a prepared password file entry. + * @param pfe the password file entry. + */ + public void sendAuthHello(PasswordFileEntry pfe, String algo) + throws ServerError, ProtocolError, IOException + { + Date now = new Date(); + int timet = (int)(now.getTime() / 1000); + AuthenticatorString auth; + try + { + auth = new AuthenticatorString(timet, pfe, algo); + + // Construct a 1-time session key for admin functions. + sessionKey = AuthenticatorString.makeAuthenticator( + auth.getString().getBytes(), pfe.getShaPassword(), timet, algo); + } + catch(Exception ex) + { + sessionKey = null; + throw new ServerError( + "Client-side reject: cannot build authenticator: " + ex); + } + String tstr = goesDateFormat.format(now); + + String body = pfe.getUsername() + " " + tstr + " " + auth.getString() + + " " + DdsVersion.getVersion(); + + LddsMessage msg = new LddsMessage(LddsMessage.IdAuthHello, body); + sendData(msg.getBytes()); + + // Read the response message - It should be same type ID. + msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdAuthHello) + { + sessionKey = null; + throw new ProtocolError("Unexpected response '" + + msg.MsgId + "' - expected '" + LddsMessage.IdAuthHello + + "' (auth-hello)"); + } + + String resp = ByteUtil.getCString(msg.MsgData, 0); + Logger.instance().debug1("AuthHello response '" + resp + "'"); + + // '?' means that server refused the login. + if (resp.length() > 0 && resp.charAt(0) == '?') + { + sessionKey = null; + ServerError serverError = new ServerError(resp); + if (serverError.Derrno == LrgsErrorCode.DSTRONGREQUIRED + && algo == AuthenticatorString.ALGO_SHA) + { + // We tried with SHA, but server requires SHA-256. Try again. + sendAuthHello(pfe, AuthenticatorString.ALGO_SHA256); + return; + } + throw serverError; + } + StringTokenizer st = new StringTokenizer(resp); + if (st.countTokens() < 3) + { + sessionKey = null; + throw new ProtocolError("Invalid response '" + resp + + "' to AuthHello request"); + } + st.nextToken(); // skip name echo + st.nextToken(); // skip time echo + serverProtoVersionStr = st.nextToken(); + + try + { + int i=0; + while(i < serverProtoVersionStr.length() + && Character.isDigit(serverProtoVersionStr.charAt(i))) + { + i++; + } + serverProtoVersion = Integer.parseInt(serverProtoVersionStr.substring(0, i)); + } + catch(NumberFormatException ex) + { + Logger.instance().warning(module + + "Invalid protocol version '" + serverProtoVersionStr + + "' returned by server. Assuming protoVersion=3"); + serverProtoVersion = DdsVersion.version_3; + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") AuthHello response '" + + resp+ "', protocolVersion=" + serverProtoVersion); + + userName = pfe.getUsername(); + + } + + /** + Sends a goodbye message to server. Then waits for response. + + @throws IOException if the socket is no longer usable. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + */ + public void sendGoodbye() + throws IOException, ProtocolError + { + if (debug != null) + { + debug.println("sendGoodbye()"); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") sendGoodbye()"); + + LddsMessage msg = new LddsMessage(LddsMessage.IdGoodbye, null); + sendData(msg.getBytes()); + + // Read the response message - It should be same type ID. + msg = getAbortResponse(); + if (msg == null) + { + throw new ProtocolError("No response received for GOODBYE"); + } + else if (msg.MsgId != LddsMessage.IdGoodbye) + { + throw new ProtocolError( + "Unexpected response '" + msg.MsgId + "'" + + " - Expected '" + LddsMessage.IdGoodbye + "' (Goodbye)"); + } + + if (debug != null) + { + debug.println("Goodbye action complete"); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") Goodbye response OK"); + } + + + /** + Retrieves a search criteria file from the server. The file is always + called 'searchcrit' on the server and is always stored in the user's + home directory. The filename passed to this function is the local + file that will be created to hold the retrieved searchcrit. +

+ If the 'localfile' argument is left blank, a file called 'searchcrit' + will be created in the current directory. + + @param localfile the name of the local file to write SC data to. + + @throws IOException if the socket is no longer usable. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + @throws ServerError if the server returned an error response for + the request. + */ + public void getSearchCrit(String localfile) + throws IOException, ProtocolError, ServerError + { + if (localfile == null) + { + localfile = "searchcrit"; + } + + if (debug != null) + { + debug.println("getSearchCrit("+localfile+")"); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") getSearchCrit(" + + localfile + ")"); + + // Send request + LddsMessage msg = new LddsMessage(LddsMessage.IdCriteria, "?"); + sendData(msg.getBytes()); + + // Read the response message - It should be same type ID. + msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdCriteria) + { + throw new ProtocolError( + "Unexpected response to getSearchCrit '" + msg.MsgId + "'"); + } + + // Validate response + if ((char)msg.MsgData[0] == '?') + { + throw new ServerError(new String(msg.MsgData)); + } + + if (msg.MsgData.length < 50) + { + throw new ProtocolError("No searchcrit data returned"); + } + + // Save data. + if (debug != null) + { + debug.println("Saving " + (msg.MsgData.length - 50) + + " bytes to " + localfile); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") Saving " + + (msg.MsgData.length - 50) + " bytes to " + localfile); + + File file = new File(localfile); + FileOutputStream fos = new FileOutputStream(file); + fos.write(ArrayUtil.getField(msg.MsgData, 50, msg.MsgData.length-50)); + } + + /** + Sends a search criteria file to the server. The file is always + called 'searchcrit' on the server and is always stored in the user's + sandbox directory. The filename passed to this function is the local + file that will be read and transferred to the server. +

+ If the 'localfile' argument is left blank, a file called 'searchcrit' + will be read from the current directory. + + @param localfile the name of the local sc file to send. + + @throws IOException if either the socket is no longer usable, or + that the specified localfile could not be read. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + @throws ServerError if the server returned an error response for + the request. + */ + public void sendSearchCrit(String localfile) + throws IOException, ProtocolError, ServerError + { + if (localfile == null) + { + localfile = "searchcrit"; + } + + if (debug != null) + { + debug.println("sendSearchCrit("+localfile+")"); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") sendSearchCrit(" + + localfile + ")"); + + // Read contents of specified searchcrit file into memory. + File f = new File(localfile); + try + { + SearchCriteria sc = new SearchCriteria(f); + sendSearchCrit(sc); + } + catch(SearchSyntaxException ex) + { + throw new IOException("Bad SearchCriteria format: " + ex); + } + } + + /** + Sends search criteria from an existing SearchCriteria object rather + than a file. + +

+ New feature in LRGS 6: if the LRGS_SINCE field contains a string of + the form filetime(filename), then this method attempts to find the + local file, get its last-modify-time, and send that to the server. + If the file does not exist locally, it is equivalent to no SINCE + time being sent. + + @param searchcrit the SearchCriteria object to send to the server + @throws IOException if either the socket is no longer usable. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + @throws ServerError if the server returned an error response for + the request. + */ + public void sendSearchCrit(SearchCriteria searchcrit) + throws IOException, ProtocolError, ServerError + { + if (debug != null) + { + debug.println("sendSearchCrit(OBJECT)"); + } + + // Make a copy, preprocess, and send the copy. + SearchCriteria toSend = new SearchCriteria(searchcrit); + + // If single-mode then set in search-crit. + // Thus for a V11 server, we will still get expanded-mode data. + if (!multiMessageModeEnabled) + { + toSend.single = true; + } + + // Expand filetime for since, if used. + String st = toSend.getLrgsSince(); + if (st != null) + { + st = st.trim(); + if (TextUtil.startsWithIgnoreCase(st,"filetime(")) + { + st = st.substring(9); + int idx = st.indexOf(")"); + if (idx != -1) + { + st = st.substring(0, idx); + } + String fn = EnvExpander.expand(st); + File f = new File(fn); + long t; + if (!f.exists() || (t = f.lastModified()) <= 0) + { + toSend.setLrgsSince(null); + } + else + { + toSend.setLrgsSince( + IDateFormat.toString(new Date(t-60000L), false)); + } + } + } + + // MJM - The following added in Nov, 2007. Try to convert the + // DCP name to an address before sending to the server. This goes + // with the strategy of trying to void persistent client context + // on the server. + // Try to find a matching site name in the DECODES database. + if (toSend.DcpNames != null && toSend.DcpNames.size() > 0 + && Database.getDb() != null + && Database.getDb().platformList != null) + { + PlatformList platList = Database.getDb().platformList; + for (Iterator nmIt = toSend.DcpNames.iterator(); nmIt.hasNext();) + { + String nm = nmIt.next(); + Platform plat = platList.getByFileName(nm); + if (plat == null) + { + plat = platList.getBySiteNameValue(nm); + } + if (plat != null) + { + String dcpaddr = plat.getDcpAddress(); + if (dcpaddr != null) + { + toSend.addDcpAddress(new DcpAddress(dcpaddr)); + nmIt.remove(); + } + } + } + } + + + implicitAllUsed = false; + // MJM 2008 09/25 Implement the implicit and network + // lists. If these are used, build a dynamic list from the DECODES + // platform list containing all non-expired GOES IDs. + for(int i = 0; i") + || nlname.equalsIgnoreCase("")) + { + implicitAllUsed = true; + boolean productionOnly = nlname.equalsIgnoreCase(""); + decodes.db.Database db = decodes.db.Database.getDb(); + if (db == null) + { + toSend.NetlistFiles.remove(i--); + continue; + } + NetworkList nl = new NetworkList(); + for(Platform plat : db.platformList.getPlatformVector()) + { + if (plat.expiration != null) + continue; + if (productionOnly && !plat.isProduction) + continue; + for(TransportMedium tm : plat.transportMedia) + if (tm.isGoes() + || tm.getMediumType().equalsIgnoreCase(Constants.medium_IRIDIUM)) + { + DcpAddress addr = new DcpAddress(tm.getMediumId()); + if (!nl.containsDcpAddr(addr)) + nl.add(new NetworkListItem(addr, + plat.getDisplayName(), + plat.getDescription())); + } + } + String listname = productionOnly ? + "decodes_production.nl" : "decodes_all.nl"; + sendNetList(nl, listname); + toSend.NetlistFiles.set(i, listname); + } + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") sendSearchCrit(OBJECT)"); + + // If there are too many explicit DCP addresses, convert them to + // temporary network lists and send them first. + int listnum = 1; + while(toSend.ExplicitDcpAddrs.size() > 500) + { + NetworkList tmpNl = new NetworkList(); + for(int idx = 0; idx < 500; idx++) + { + tmpNl.add(new NetworkListItem(toSend.ExplicitDcpAddrs.get(idx),"","")); + } + String nlName = "searchcrit_" + (listnum++) + ".nl"; + sendNetList(tmpNl, nlName); + toSend.addNetworkList(nlName); + ArrayList tl = new ArrayList(toSend.ExplicitDcpAddrs.size()-500); + for(int idx = 500; idx < toSend.ExplicitDcpAddrs.size(); idx++) + { + tl.add(toSend.ExplicitDcpAddrs.get(idx)); + } + toSend.ExplicitDcpAddrs = tl; + } + + // Put searchcrit into a byte array. + byte data[] = toSend.toString(serverProtoVersion).getBytes(); + searchCritLocalFilter = toSend.getSearchCritLocalFilter(); + sendSearchCrit("OBJECT", data); + } + + /** + Sends search criteria from an in-memory byte array. + @param filename the name of the searchcrit to pass to the server + @param data the search criteria data + @throws IOException if either the socket is no longer usable. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + @throws ServerError if the server returned an error response for + the request. + */ + private void sendSearchCrit(String filename, byte data[]) + throws IOException, ProtocolError, ServerError + { + // Construct an empty criteria message big enought for this file. + LddsMessage msg = new LddsMessage(LddsMessage.IdCriteria, ""); + msg.MsgLength = data.length + 50; + msg.MsgData = new byte[msg.MsgLength]; + + // Create the 'header' portion containing the searchcrit filename. + // (First 40 bytes is filename) + int i; + for(i = 0; i<40 && i 0 && (char)msg.MsgData[0] == '?') + { + String s = new String(msg.MsgData); + throw new ServerError(s); + } + + if (debug != null) + { + debug.println("Successfully sent searchcrit."); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "Successfully sent searchcrit."); + + // MJM 20080619 - Just sent new crit, clear any buffered messages. + flushBufferedMessages(); + } + + + /** + * Requests the next DCP message from the server. + * If a search criteria file has previously been transfered + * (either to or from the server), then the server will only pass messages + * that meet the specified criteria. + *

+ * The timeout argument specifies the number of seconds to wait for a + * response from the server. + *

+ * Returns a DcpMsg or null if no response was received from the server + * within the specified # of seconds. + *

+ * @param timeout number of seconds to wait + * @throws IOException if socket is no longer usable. + * @throws ProtocolError if an unexpected response was received. + * (i.e. the wrong message type). + * @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if + * no message arrived at the server within the specified timeout + * period. This typically indicates that you are already caught-up + * to the present time. + * @throws ServerError with other Derrno codes to indicate other errors + * on the server which are not recoverable. When this happens, call + * disconnect() and then start the session over. + */ + public DcpMsg getDcpMsg(int timeout) + throws IOException, ProtocolError, ServerError + { + if (!this.multiMessageModeEnabled) //Single mode + { + return getDcpMsgSingle(timeout); + } + else if (this.multiMessageModeEnabled && serverProtoVersion >= DdsVersion.version_11) + { + //Proto V11, single mode is sent in searchcrit. + return getDcpMsgExt(timeout); + } + else if (this.extMessageModeEnabled && serverProtoVersion >= DdsVersion.version_8) + { + return getDcpMsgExt(timeout); + } + else if (this.multiMessageModeEnabled && serverProtoVersion >= DdsVersion.version_5) + { + return getDcpMsgMulti(timeout); + } + else + { + return getDcpMsgSingle(timeout); + } + } + + /** + Gets the next message from the server (single-mode). + Requests the next DCP message from the server. + If a search criteria file has previously been transfered + (either to or from the server), then the server will only pass messages + that meet the specified criteria. +

+ The timeout argument specifies the number of seconds to wait for a + response from the server. +

+ @param timeout number of seconds to wait + + @return a DcpMsg or null if no response was received from the server + within the specified # of seconds. + + @throws IOException if socket is no longer usable. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if + no message arrived at the server within the specified timeout + period. This typically indicates that you are already caught-up + to the present time. + @throws ServerError with other Derrno codes to indicate other errors + on the server which are not recoverable. When this happens, call + disconnect() and then start the session over. + */ + public DcpMsg getDcpMsgSingle(int timeout) + throws IOException, ProtocolError, ServerError + { + boolean requestAgain = true; + DcpMsg ret = null; + while(requestAgain) + { + requestDcpMsg(); + ret = receiveDcpMsg(timeout); + if (ret == null) + { + ret = abortDcpMsgRequest(); + } + + // If we have a local filter (i.e. we are talking to a legacy + // server and must do some of the filtering locally)... + requestAgain = ret != null + && searchCritLocalFilter != null + && !searchCritLocalFilter.passesCrit(ret); + } + + return ret; + } + + /** + Most clients can call the synchronous getDcpMsg() function. If you + need the ability to abort a request, call the requestDcpMsg method + followed by the receiveDcpMsg method. + + Request the next DCP message from the server. If your client process + needs the ability to abort a request in progress, you will have to + call requestDcpMsg followed by repeated calls to receiveDcpMsg. + + @throws IOException if the socket is no longer usable. + */ + public void requestDcpMsg() throws IOException + { + if (debug != null) + { + debug.println("Requesting DCP Message..."); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "Requesting DCP Message..."); + + // Request Dcp Message + LddsMessage msg = new LddsMessage(LddsMessage.IdDcp, ""); + sendData(msg.getBytes()); + } + + /** + * Receives a DCP Message after calling requestDcpMsg. + * If a message is received within timeout seconds, it will be returned. + * Otherwise null will be returned. + *

+ * Note: One message is returned by the server for each request. Once + * a message has been received you need to call requestDcpMsg again + * before calling this method. + *

+ * @throws IOException if the socket is no longer usable. + * @throws ProtocolError if an unexpected response was received. + * (i.e. the wrong message type). + * @throws ServerError with a Derrno equal to (DUNTIL) if the specified + * until time was reached. + * @throws ServerError with other codes for other errors on the server + * (probably not recoverable). + */ + public DcpMsg receiveDcpMsg(int timeout) + throws IOException, ProtocolError, ServerError + { + // Check for asynchronous disconnection. + if (linput == null) + { + return null; + } + + socket.setSoTimeout((timeout+1)*1000); + + // Get response. + LddsMessage msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdDcp) + { + throw new + ProtocolError("Unexpected responses '" + msg.MsgId + "'"); + } + if (msg.MsgData[0] == (byte)'?') + { + throw new ServerError(new String(msg.MsgData)); + } + + return lddsMsg2DcpMsg(msg); + } + + private DcpMsg lddsMsg2DcpMsg(LddsMessage msg) + throws ProtocolError + { + if (msg.MsgLength < 40 + DcpMsg.DCP_MSG_MIN_LENGTH) + { + if (debug != null) + { + debug.println("Too-Short DCP message response: id='" + + msg.MsgId + "' length=" + msg.MsgLength); + if (msg.MsgLength > 40) + { + String d = new String(ArrayUtil.getField(msg.MsgData, + 40, msg.MsgLength - 40)); + debug.println("data: " + d); + } + } + + Logger.instance().warning(module + + "DDS Connection (" + host + ":" + port + ") " + + "Too-Short DCP message response: id='" + + msg.MsgId + "' length=" + msg.MsgLength + " -- skipped."); + + if (msg.MsgLength > 40) + { + String d = new String( + ArrayUtil.getField(msg.MsgData, 40, msg.MsgLength - 40)); + Logger.instance().warning(module + + "Complete response '" + d + "'"); + } + + throw new ProtocolError("Too-Short DCP message response received"); + } +// DcpMsg ret = +// new DcpMsg(ArrayUtil.getField(msg.MsgData, 40, msg.MsgLength-40), +// msg.MsgLength - 40); + DcpMsg ret = new DcpMsg(msg.MsgData, msg.MsgLength-40, 40); + ret.flagbits = DcpMsgFlag.MSG_PRESENT | DcpMsgFlag.SRC_DDS + | DcpMsgFlag.MSG_NO_SEQNUM; + + // Get sequence filename from first 40 bytes of message. + ret.setSeqFileName(ByteUtil.getCString(msg.MsgData, 0)); + if (debug != null) + { + debug.println("Response received: fn = " + + ret.getSeqFileName() + ", length = " + (msg.MsgLength - 40)); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "Response received: fn = " + + ret.getSeqFileName() + ", length = " + (msg.MsgLength - 40)); + + return ret; + } + + /** + In order to be able to abort DCP message requests. You will need to + first call requestDcpMsg(). Then in a loop, repeatedly call + receiveDcpMsg with a brief timeout. When you want to stop, call + abortDcpMsgRequest(). This tells the server to abort the request. + + A race condition exists. The server might be just sending the + Dcp message response when I send the abort. If this happens, this + method will return the DCP message. Otherwise, null is returned. + + Failure to abort an outstanding DCP Message request will render the + socket unusable for other operations. + + @throws IOException if the socket is no longer usable. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + */ + public DcpMsg abortDcpMsgRequest() + throws IOException, ProtocolError + { + if (debug != null) + debug.println("abortDcpMsgRequest()"); + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "abortDcpMsgRequest()"); + + if (linput == null) + return null; + + LddsMessage msg = new LddsMessage(LddsMessage.IdStop, null); + sendData(msg.getBytes()); + + msg = getAbortResponse(); + + // There is a race condition here. The server may have just + // sent the message out when I sent it an abort. If the message I + // just read is a DCP message return it to the client. + DcpMsg ret = null; + if (msg != null && msg.MsgId == LddsMessage.IdDcp) + { + ret = lddsMsg2DcpMsg(msg); + + // Now read the response to the Abort request. + msg = getAbortResponse(); + } + + if (msg == null) + { + throw new ProtocolError( + "No response to abort request received"); + } + else if (msg.MsgId != LddsMessage.IdStop) + { + throw new ProtocolError( + "Unexpected response '" + msg.MsgId + "'" + + " - Expected '" + LddsMessage.IdStop + "' (Stop)"); + } + + return ret; + } + + private LddsMessage getAbortResponse() + throws IOException, ProtocolError + { + // Wait up to 10 seconds for the response to the abort. + // If none received, we'll just abort anyway. + socket.setSoTimeout(10000); + + return linput.getMessage(); + } + + /** + The getNetList method retrieves a network list file from the server. + The first argument (serverfile) specifies the name of the network + list file on the server. The second argument (localfile) specifies + the name of the file on the local system that will be created. + + @param serverfile name of network list on the server + @param localfile name of network list on the local computer + + @throws IOException if a network socket error or local file error. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + @throws ServerError if the server responded to the request with an + error message. This most likely means that that the requested + network list file does not exist on the server. + + */ + public void getNetList(String serverfile, File localfile) + throws IOException, ProtocolError, ServerError + { + if (debug != null) + { + debug.println("getNetList("+serverfile+ ", " + + localfile.getName() + ")"); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "getNetList("+serverfile+ ", " + localfile.getName() + ")"); + + // Send request + LddsMessage msg = new LddsMessage(LddsMessage.IdGetNetlist, + serverfile); + sendData(msg.getBytes()); + + // Read the response message - It should be same type ID. + msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdGetNetlist) + { + throw new ProtocolError("Unexpected responses '" + msg.MsgId + "'"); + } + + // Validate response + if ((char)msg.MsgData[0] == '?') + { + throw new ServerError(new String(msg.MsgData)); + } + if (msg.MsgLength < 64) + { + throw new ServerError("?0,0,No file data returned"); + } + + // Save data. + if (debug != null) + { + debug.println("Saving " + (msg.MsgLength - 64) + + " bytes to " + localfile.getName()); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "Saving " + (msg.MsgLength - 64) + + " bytes to " + localfile.getName()); + + FileOutputStream fos = new FileOutputStream(localfile); + fos.write( ArrayUtil.getField(msg.MsgData, 64, msg.MsgData.length-64)); + fos.close(); + } + + /** + sends a network list file to the server. + + @param serverfile name of network list on the server + @param localfile name of network list on the local computer + + @throws IOException on network socket error or local file error. + @throws ProtocolError if an unexpected response was received. + (i.e. the wrong message type). + @throws ServerError if the server responded to the request with an + error message. This most likely means that that the named + file could not be created on the server. + */ + public void sendNetList(File localfile, String serverfile) + throws IOException, ProtocolError, ServerError + { + if (debug != null) + { + debug.println("sendNetList("+localfile.getName() + +", " + serverfile + ")"); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "sendNetList("+localfile.getName() +", " + serverfile + ")"); + + // Read contents of specified searchcrit file into memory. + FileInputStream fis = new FileInputStream(localfile); + byte data[] = new byte[(int)localfile.length()]; + fis.read(data); + fis.close(); + + // Construct an empty criteria message big enought for this file. + LddsMessage msg = new LddsMessage(LddsMessage.IdPutNetlist, ""); + msg.MsgLength = data.length + 64; + msg.MsgData = new byte[msg.MsgLength]; + + // Create the 'header' portion, which contains 64 char filename + int i; + for(i = 0; i<64 && i + * The timeout argument specifies the number of seconds to wait for a + * response from the server. + *

+ * Returns an array DcpMsg objects, or null if no response was received + * from the server within the specified # of seconds. + *

+ * @param timeout number of seconds to wait + * @throws IOException if socket is no longer usable. + * @throws ProtocolError if an unexpected response was received. + * (i.e. the wrong message type). + * @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if + * the server indicates that you are already caught-up to the present + * time. When this happens, pause and try again later. + * @throws ServerError with other Derrno codes to indicate other errors + * on the server which are not recoverable. When this happens, call + * disconnect() and then start the session over. + */ + public DcpMsg[] getDcpMsgBlock(int timeout) + throws IOException, ProtocolError, ServerError + { + requestDcpMsgBlock(); + DcpMsg ret[] = receiveDcpMsgBlock(timeout); + if (ret == null) + { + ret = abortDcpMsgBlockRequest(); + } + return ret; + } + + public void requestDcpMsgBlock() throws IOException + { + if (debug != null) + { + debug.println("Requesting DCP Message Block..."); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "Requesting DCP Message Block..."); + + // Request Dcp Message + LddsMessage msg = new LddsMessage(LddsMessage.IdDcpBlock, ""); + sendData(msg.getBytes()); + } + + /** + * Receives a DCP Message Block after calling requestDcpMsg. + * The block is parsed into an array of DcpMsg objects and returned. + * Returns null if no response is received from server in timeout seconds. + *

+ * @throws IOException if the socket is no longer usable. + * @throws ProtocolError if an unexpected response was received. + * (i.e. the wrong message type). + * @throws ServerError with a Derrno equal to (DUNTIL) if the specified + * until time was reached. + * @throws ServerError with other codes for other errors on the server + * (probably not recoverable). + */ + public DcpMsg[] receiveDcpMsgBlock(int timeout) + throws IOException, ProtocolError, ServerError + { + // Check for asynchronous disconnection. + if (linput == null) + { + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "receiveDcpMsgBlock asynchronous disconect, aborting."); + return null; + } + + socket.setSoTimeout((timeout+1) * 1000); + + // Get response. + LddsMessage msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdDcpBlock) + { + throw new + ProtocolError("Unexpected response '" + msg.MsgId + + "', expected type '" + LddsMessage.IdDcpBlock + "'"); + } + + if (msg.MsgData[0] == (byte)'?') + { + String err = new String(msg.MsgData); + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") ServerError: " + + err); + throw new ServerError(err); + } + + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "received block response, length=" + msg.MsgLength); + + return lddsMsg2DcpMsgBlock(msg); + } + + private DcpMsg[] lddsMsg2DcpMsgBlock(LddsMessage msg) + throws ProtocolError + { + Logger.instance().debug3(module + + "Parsing block response. Total length = " + msg.MsgLength); + + // Got response, parse it into an array of DCP Messages. + ArrayList v = new ArrayList(); + boolean garbled = false; + int msgnum = 0; + for(int msgStart=0; msgStart= multiMsg.length) + { + // get next block of data + int numFiltered = 0; + do + { + multiMsgIdx = 0; + multiMsg = getDcpMsgBlock(timeout); + if (multiMsg == null) + { + throw new ProtocolError( + "Timeout waiting for block response from server."); + } + // If we have a local filter (i.e. we are talking to a legacy + // server and must do some of the filtering locally)... + if (searchCritLocalFilter != null) + { + numFiltered = 0; + for(int idx = 0; idx < multiMsg.length; idx++) + { + if (!searchCritLocalFilter.passesCrit(multiMsg[idx])) + { + multiMsg[idx] = null; + numFiltered++; + } + } + if (numFiltered > 0) + { + DcpMsg fret[] = new DcpMsg[multiMsg.length - numFiltered]; + int fidx = 0; + for(int idx = 0; idx < multiMsg.length; idx++) + { + if (multiMsg[idx] != null) + { + fret[fidx++] = multiMsg[idx]; + } + } + multiMsg = fret; + } + } + } while(multiMsg != null && multiMsg.length == 0 && + searchCritLocalFilter != null && numFiltered > 0); + } + if (multiMsg != null && multiMsgIdx < multiMsg.length) + { + return multiMsg[multiMsgIdx++]; + } + else + { + return null; + } + } + + /** + * @return the number of messages already received and buffered. + */ + public int getNumberBuffered() + { + if (multiMsg != null) + { + return multiMsg.length - multiMsgIdx; + } + else + { + return 0; + } + } + + /** + * Deletes any buffered messages, forcing next retrieve to send request + * to server. + */ + public void flushBufferedMessages() + { + multiMsgIdx = 0; + multiMsg = null; + } + + /** + Retrieves the status from the server. + @return byte array containing an XML block representing the server's + current status. + */ + public byte[] getStatus() + throws IOException, ProtocolError, ServerError + { + if (debug != null) + { + debug.println("getStatus"); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") getStatus"); + + // Send request + LddsMessage msg = new LddsMessage(LddsMessage.IdStatus, "?"); + sendData(msg.getBytes()); + + // Read the response message - It should be same type ID. + msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdStatus) + { + throw new ProtocolError( + "Unexpected response to getStatus '" + msg.MsgId + "'"); + } + + // Validate response + if ((char)msg.MsgData[0] == '?') + { + throw new ServerError(new String(msg.MsgData)); + } + + // Some servers throw a null byte at the end. If so, convert to LF. + if (msg.MsgData[msg.MsgData.length-1] == 0) + { + msg.MsgData[msg.MsgData.length-1] = (byte)'\n'; + } + return msg.MsgData; + } + + /** + Retrieve the next block of events from the server. + return an array of Strings, each represeting a single formated text + event. + @return array of event strings + */ + public String[] getEvents() + throws IOException, ProtocolError, ServerError + { + if (serverProtoVersion < DdsVersion.version_6) + { + return new String[0]; + } + + if (debug != null) + { + debug.println("getEvent"); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") getEvents"); + + // Send request + LddsMessage msg = new LddsMessage(LddsMessage.IdEvents, "?"); + sendData(msg.getBytes()); + + // Read the response message - It should be same type ID. + msg = linput.getMessage(); + if (msg.MsgId != LddsMessage.IdEvents) + { + throw new ProtocolError( + "Unexpected response to getEvents '" + msg.MsgId + "'"); + } + + // Validate response + if (msg.MsgData.length == 0) + { + return new String[0]; + } + + if ((char)msg.MsgData[0] == '?') + { + throw new ServerError(new String(msg.MsgData)); + } + + // Some servers throw a null byte at the end. If so, convert to space. + if (msg.MsgData[msg.MsgData.length-1] == 0) + { + msg.MsgData[msg.MsgData.length-1] = (byte)' '; + } + + int numEvents = 0; + for(int i=0; i < msg.MsgData.length; i++) + { + if (msg.MsgData[i] == (byte)'\n') + { + numEvents++; + } + } + if (numEvents == 0) + { + return null; + } + + String ret[] = new String[numEvents]; + int num = 0; + int sidx = 0; + for(int i=0; i 0 && (char)msg.MsgData[0] == '?') + { + throw new ServerError(new String(msg.MsgData)); + } + if (msg.MsgLength < 64) + { + throw new ServerError("?0,0,No file data returned"); + } + + return ArrayUtil.getField(msg.MsgData, 64, msg.MsgLength - 64); + } + + /** + * Installs a configuration on the server. + * @throws AuthException if you are not authenticated, or on any + * server-side error. + */ + public void installConfig(String cfgType, byte[] data) + throws AuthException + { + if (debug != null) + { + debug.println("installConfig(" + cfgType + ")"); + } + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "installConfig(" + cfgType + ")"); + + // Construct an empty criteria message big enought for this file. + LddsMessage msg = new LddsMessage(LddsMessage.IdInstConfig, ""); + msg.MsgLength = 64 + (data != null ? data.length : 0); + msg.MsgData = new byte[msg.MsgLength]; + + // Create the 'header' portion, which contains 64 char cfg type + int i; + for(i = 0; i<64 && i + * The timeout argument specifies the number of seconds to wait for a + * response from the server. + * + * @return uncompressed byte-array response to the Extended Block Request. + * from the server within the specified # of seconds. + * @param timeout number of seconds to wait + + * @throws IOException if socket is no longer usable. + * @throws ProtocolError if an unexpected response was received. + * (i.e. the wrong message type). + * @throws ServerError with Derrno equal to 11 (DMSGTIMEOUT) if + * the server indicates that you are already caught-up to the present + * time. When this happens, pause and try again later. + * @throws ServerError with other Derrno codes to indicate other errors + * on the server which are not recoverable. When this happens, call + * disconnect() and then start the session over. + */ + public byte[] getMsgBlockExtXml(int timeout) + throws IOException, ProtocolError, ServerError + { + Logger.instance().debug2(module + + "DDS Connection (" + host + ":" + port + ") " + + "Requesting DCP Message Block Ext (timeout=" + + timeout + ")..."); + + LddsMessage req = new LddsMessage(LddsMessage.IdDcpBlockExt, ""); + + LddsMessage resp = serverExec(req); + if (resp.MsgId != LddsMessage.IdDcpBlockExt) + { + throw new ProtocolError("Unexpected response '" + resp.MsgId + + "', expected type '" + LddsMessage.IdDcpBlockExt + "'"); + } + + // Message contains compressed byte-array of XML. Uncompress it. + try + { + ByteArrayInputStream bais = new ByteArrayInputStream(resp.MsgData); + GZIPInputStream gzis = new GZIPInputStream(bais); + ByteArrayOutputStream baos = + new ByteArrayOutputStream(resp.MsgData.length); + byte buf[] = new byte[4096]; + int len; + while ((len = gzis.read(buf)) > 0) + { + baos.write(buf, 0, len); + } + gzis.close(); + bais.close(); + baos.close(); + byte ret[] = baos.toByteArray(); + return ret; + } + catch(IOException ex) + { + throw new ProtocolError("Error unpacking compressed block: " + ex); + } + } + + /** + * Gets the next extended mode block and converts the XML into an array + * of DcpMsg objects. + */ + public DcpMsg[] getMsgBlockExt(int timeout) + throws IOException, ProtocolError, ServerError + { + DcpMsg ret[] = null; + int numFiltered = 0; + do + { + byte[] xmldata = getMsgBlockExtXml(timeout); + if (extBlockXmlParser == null) + extBlockXmlParser = new ExtBlockXmlParser(DcpMsgFlag.SRC_DDS); + ret = extBlockXmlParser.parseMsgBlock(xmldata); + // If we have a local filter (i.e. we are talking to a legacy + // server and must do some of the filtering locally)... + if (searchCritLocalFilter != null && ret != null) + { + numFiltered = 0; + for(int idx = 0; idx < ret.length; idx++) + if (!searchCritLocalFilter.passesCrit(ret[idx])) + { + ret[idx] = null; + numFiltered++; + } + if (numFiltered > 0) + { + DcpMsg fret[] = new DcpMsg[ret.length - numFiltered]; + int fidx = 0; + for(int idx = 0; idx < ret.length; idx++) + if (ret[idx] != null) + fret[fidx++] = ret[idx]; + ret = fret; + } + } + } while(ret != null && ret.length == 0 && + searchCritLocalFilter != null && numFiltered > 0); + return ret; + } + + /** + Get the next DCP message using extended-mode. + + @param timeout number of seconds to wait + @return DcpMsg object + */ + private DcpMsg getDcpMsgExt(int timeout) + throws IOException, ProtocolError, ServerError + { + if (multiMsg == null || multiMsgIdx >= multiMsg.length) + { + // get next block of data + multiMsgIdx = 0; + multiMsg = null; + multiMsg = getMsgBlockExt(timeout); + if (multiMsg == null) + { + throw new ProtocolError( + "Timeout waiting for ext block response from server."); + } + } + if (multiMsg != null && multiMsgIdx < multiMsg.length) + { + return multiMsg[multiMsgIdx++]; + } + else + { + return null; + } + } + + /** + * Returns the array of outages, optionally within a time range. + * If both start and end are null, all outages are returned. + * Else if only end is null, all outages since the start time are returned. + */ + public ArrayList getOutages(Date start, Date end) + throws IOException, ProtocolError, ServerError + { + String txt = ""; + if (start != null) + { + txt = outageDateFormat.format(start); + if (end != null) + txt = txt + " " + outageDateFormat.format(end); + } + LddsMessage msg = new LddsMessage(LddsMessage.IdGetOutages, txt); + LddsMessage resp = serverExec(msg); + // Response contains GZipped array of XML Outages. First unzip it. + + byte respData[] = null; + try + { + ByteArrayInputStream bais = new ByteArrayInputStream(resp.MsgData); + GZIPInputStream gzis = new GZIPInputStream(bais); + ByteArrayOutputStream baos = + new ByteArrayOutputStream(resp.MsgData.length); + byte buf[] = new byte[4096]; + int len; + while ((len = gzis.read(buf)) > 0) + baos.write(buf, 0, len); + gzis.close(); + bais.close(); + baos.close(); + respData = baos.toByteArray(); + } + catch(IOException ex) + { + throw new ProtocolError("Error unpacking compressed outages: "+ex); + } + + try { return getOutageXmlParser().parse(respData); } + catch(IOException ex) + { + Logger.instance().warning("Unparsable outages: " + ex); + return new ArrayList(); + } + } + + /** + @return the protocol version supported by the server to which you + are connected. + */ + public int getServerProtoVersion() + { + return serverProtoVersion; + } + + /** + * Sends a no-op command, which can be useful for keeping a connection + * alive in the absense of other requests. + */ + public void sendNoop() + throws IOException, ProtocolError, ServerError + { + LddsMessage msg = new LddsMessage(LddsMessage.IdStop, getName()); + sendData(msg.getBytes()); + msg = getAbortResponse(); + if (msg.MsgId != LddsMessage.IdStop) + { + throw new ProtocolError("Unexpected response to noop."); + } + } + + + /** + * Sets the module name, which will be prepended on log messages. + * @param mod the module name + */ + public void setModule(String mod) + { + module = mod; + if (!module.endsWith(" ")) + { + module = module + " "; + } + } + + /** + * Sends a raw LddsMessage and gets the response returned by server. + * It's up to the caller to validate the contents of the response. + * @param msg the message to send + * @return the message response from the server. + */ + public LddsMessage serverExec(LddsMessage msg) + throws IOException, ProtocolError, ServerError + { + Logger.instance().debug3("serverExec: sending LddsMessage type=" + + msg.MsgId + ", length=" + msg.MsgLength); + sendData(msg.getBytes()); + LddsMessage ret = linput.getMessage(); + Logger.instance().debug3("serverExec: response LddsMessage type=" + + ret.MsgId + ", length=" + ret.MsgLength); + + if ((char)ret.MsgData[0] == '?') + { + throw new ServerError(new String(ret.MsgData)); + } + return ret; + } + + /** + * @return the session key, or null if this is an unauthenticated + * connection. + */ + public byte[] getSessionKey() + { + return sessionKey; + } + + /** + * Gets a list of valid DDS users from the server. + * @throws AuthException if server rejects the request or on any other + * error. + * @return a list of valid DDS users from the server. + */ + public ArrayList getUsers() + throws AuthException + { + try + { + LddsMessage req = new LddsMessage(LddsMessage.IdUser,"list"); + LddsMessage resp = serverExec(req); + String listResp = new String(resp.MsgData); + StringTokenizer st = new StringTokenizer(listResp, "\r\n"); + ArrayList userList = new ArrayList(); + while(st.hasMoreTokens()) + { + String line = st.nextToken(); + try + { + userList.add(new DdsUser(line)); + } + catch(BadConfigException ex) + { + Logger.instance().warning(module + " Ignoring user spec '" + + line + "': " + ex); + } + } + return userList; + } + catch(Exception ex) + { + String m = "Cannot list users: " + ex; + Logger.instance().warning(m); + System.err.println(m); + ex.printStackTrace(); + throw new AuthException(m); + } + } + + /** + * Sends a request to add or edit a user on the DDS server. + * @param ddsUser the user data + * @param pw the password, or null to leave password unchanged on server. + * @throws AuthException if you are not authenticated, or on any + * server-side error. + */ + public void modUser(DdsUser ddsUser, String pw) + throws AuthException + { + byte[] sk = getSessionKey(); + if (sk == null) + { + throw new AuthException( + "Modify user requires authenticated connection."); + } + String sks = ByteUtil.toHexString(sk); + + String cmd = "set " + ddsUser.userName + " "; + + // If not setting pw, or if v13, put placeholder in pw field. + if (pw == null || pw.length() == 0 + || serverProtoVersion >= DdsVersion.version_13) + { + cmd += "-"; + } + else + { + PasswordFileEntry pfe = new PasswordFileEntry(ddsUser.userName); + pfe.setPassword(pw); + pw = ByteUtil.toHexString(pfe.getShaPassword()); + DesEncrypter de = new DesEncrypter(sks); + pw = de.encrypt(pw); + cmd += pw; + } + + // Syntax: set username DES(pw) perms props + // No field may have embedded blanks. + cmd = cmd + " " + ddsUser.permsString() + " " + ddsUser.propsString(); + try + { + LddsMessage msg = new LddsMessage(LddsMessage.IdUser, cmd); + LddsMessage resp = serverExec(msg); + } + catch(Exception ex) + { + throw new AuthException("Cannot set user info: " + ex.getLocalizedMessage(),ex); + } + + if (pw != null && pw.length() > 0 && serverProtoVersion >= DdsVersion.version_13) + { + cmd = "pw " + ddsUser.userName + " "; + DesEncrypter de = new DesEncrypter(sks); + cmd += de.encrypt(pw); + try + { + LddsMessage msg = new LddsMessage(LddsMessage.IdUser, cmd); + LddsMessage resp = serverExec(msg); + } + catch(Exception ex) + { + throw new AuthException("Cannot set user password: " + ex.getLocalizedMessage(),ex); + } + } + } + + /** + * Removes a user on the server. + * @param userName the user name to remove. + * @throws AuthException on any server-side error. + */ + public void rmUser(String userName) + throws AuthException + { + String cmd = "rm " + userName; + try + { + LddsMessage msg = new LddsMessage(LddsMessage.IdUser, cmd); + LddsMessage resp = serverExec(msg); + } + catch(Exception ex) + { + throw new AuthException("Cannot remove DDS user: " + ex); + } + } + + public OutageXmlParser getOutageXmlParser() + { + if (outageXmlParser == null) + { + outageXmlParser = new OutageXmlParser(); + } + return outageXmlParser; + } + + + /** find the LddsConnections file and return path */ + public static String getLddsConnectionsFile() + { + String dirs[] = { "DCSTOOL_USERDIR", "DCSTOOL_HOME", "user.home" }; + for(String p : dirs) + { + String dir = System.getProperty(p); + if (dir != null && dir.length() > 0) + { + return dir + "/LddsConnections"; + } + } + return "LddsConnections"; + } + + public String getUserName() + { + return userName; + } + + public void setStrongOnly(boolean strongOnly) + { + this.strongOnly = strongOnly; + } } diff --git a/src/main/java/lrgs/ldds/LddsCommand.java b/src/main/java/lrgs/ldds/LddsCommand.java index f715c5b7d..a2d88e27e 100644 --- a/src/main/java/lrgs/ldds/LddsCommand.java +++ b/src/main/java/lrgs/ldds/LddsCommand.java @@ -3,11 +3,8 @@ */ package lrgs.ldds; -import java.io.OutputStream; import java.io.IOException; -import ilex.util.ArrayUtil; - import lrgs.common.*; /** @@ -34,4 +31,3 @@ public abstract int execute(LddsThread ldds) */ public abstract char getCommandCode(); } - diff --git a/src/main/java/lrgs/ldds/LddsInputStream.java b/src/main/java/lrgs/ldds/LddsInputStream.java index 992a3d5b0..b3798dc6b 100644 --- a/src/main/java/lrgs/ldds/LddsInputStream.java +++ b/src/main/java/lrgs/ldds/LddsInputStream.java @@ -5,7 +5,6 @@ import java.io.InputStream; import java.io.IOException; -import ilex.util.Logger; /** This stream reads bytes from the socket and builds LddsMessage objects. @@ -13,10 +12,7 @@ public class LddsInputStream { private InputStream istrm = null; - - private static final int ReadLimit = LddsMessage.ValidHdrLength - + LddsMessage.ValidMaxDataLength; - + static final byte[] validSync = { (byte)'F', (byte)'A', (byte)'F', (byte)'0' }; @@ -46,10 +42,10 @@ public LddsMessage getMessage() while( done < ret.MsgLength ) { int n = istrm.read(ret.MsgData, done, ret.MsgLength-done); - if (n <= 0) + { throw new IOException("Socket closed."); - + } done += n; } @@ -67,19 +63,25 @@ private LddsMessage readHeader() // Read the 4-byte sync header & error out if it doesn't match. int n = istrm.read(hdr, 0, 4); if (n < 0) + { throw new IOException("Socket closed"); + } if (n != 4 || hdr[0] != validSync[0] || hdr[1] != validSync[1] || hdr[2] != validSync[2] || hdr[3] != validSync[3]) + { throw new ProtocolError("Could not read valid sync pattern (" + n + " bytes read)"); + } // Now have sync, block for rest of header. n = istrm.read(hdr, 4, LddsMessage.ValidHdrLength - 4); if (n == -1) + { throw new IOException("Socket closed"); + } return new LddsMessage(hdr); } @@ -92,27 +94,6 @@ public boolean isMsgAvailable() throws IOException { return istrm.available() >= LddsMessage.ValidHdrLength; - -// try -// { -// if (istrm.available() < LddsMessage.ValidHdrLength) -// return (char)0; -// -// istrm.mark(ReadLimit); // Mark current position in input stream. -// LddsMessage msg = readHeader(); -// -// int avail = istrm.available(); -// -// // See if complete body is available. -// char ret = (avail >= msg.MsgLength ? msg.MsgId : (char)0); -// -// istrm.reset(); // Move back to marked position. -// return ret; -// } -// catch (IOException ioe) -// { -// return (char)0; -// } } public void close() @@ -120,5 +101,4 @@ public void close() try { istrm.close(); } catch(IOException ex) { } } - } diff --git a/src/main/java/lrgs/ldds/LddsLoggerThread.java b/src/main/java/lrgs/ldds/LddsLoggerThread.java index db963a230..151ff337d 100644 --- a/src/main/java/lrgs/ldds/LddsLoggerThread.java +++ b/src/main/java/lrgs/ldds/LddsLoggerThread.java @@ -7,7 +7,6 @@ import java.util.Iterator; import java.util.TimeZone; import java.util.LinkedList; -import java.util.List; import java.text.SimpleDateFormat; import java.io.IOException; @@ -25,265 +24,264 @@ special log file. */ public class LddsLoggerThread extends Thread - implements StatLogger + implements StatLogger { - BasicServer theServer; - SequenceFileLogger statLogger; - SimpleDateFormat dateFormat; - private boolean shutdownFlag; - private LrgsDatabaseThread ldt; - DdsPeriodStats currentHour; - private long lastLogStatMsec = 0L; - private long connectMsecs = 0L; /* connections * msec */ - private long hourStartMsec = 0L; - private int prevNumClients = 0; - - /** - Constructor. - @param svr the server object - @param logname the file in which to periodically write client stats. - */ - public LddsLoggerThread(BasicServer svr, String logname) - { - theServer = svr; - shutdownFlag = false; - dateFormat = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss"); - dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); - String logFileName = EnvExpander.expand(logname); - try - { - statLogger = new SequenceFileLogger("DDS", logFileName); - statLogger.setMaxLength(5000000); - statLogger.setUsePriority(false); - } - catch(IOException ex) - { - Logger.instance().log(Logger.E_FAILURE, - "Cannot open '" + logFileName - + "' DDS stats will not be logged! : " + ex); - statLogger = null; - } - ldt = LrgsDatabaseThread.instance(); - currentHour = null; - } - - /** Called when server is exiting. */ - public void shutdown() - { - shutdownFlag = true; - } - - /** - Thread run method: sleep for a minute, then poll each client thread - and write its status to the file. - */ - public void run() - { - initCurrentHour(); - long lastMin = System.currentTimeMillis() / 60000L; - long lastHour = lastMin / 60; - Logger.instance().info("LddsLoggerThread starting. h=" - + lastHour+", m=" + lastMin); - while(!shutdownFlag && statLogger != null) - { - long thisMin = System.currentTimeMillis() / 60000L; - long thisHour = thisMin / 60; - if (thisMin > lastMin) - { - lastMin = thisMin; - logStats(); - if (thisHour != lastHour) - { - startNewHour(); - lastHour = thisHour; - } - } - try { sleep(1000L); } - catch(InterruptedException ex) {} - } - if (currentHour != null) - ldt.enqueue(currentHour); - - try { sleep(1000L); } - catch(InterruptedException ex) {} - if (statLogger != null) - statLogger.close(); - statLogger = null; - Logger.instance().info("LddsLoggerThread exiting."); - } - - private void logStats() - { -//Logger.instance().info("LddsLoggerThread.logStats() numClients = " + theServer.getAllSvrThreads().size() -//+ ", isNull(statLogger)=" + (statLogger==null)); - if (statLogger == null) - return; - // Collect & log info from each thread. - int numClients = 0; - LinkedList svrThreads = theServer.getAllSvrThreads(); - for(Iterator it = svrThreads.iterator(); it.hasNext(); ) - { - Object ob = it.next(); - if (ob instanceof LddsThread) - { - numClients++; - LddsThread lt = (LddsThread)ob; - logStat(lt); - } - } - ldt.enqueue(currentHour); - logStat(null); - } - - /** - * Log a change in status. Called when any client connects - * or disconnects, or once per minute from the thread above. - */ - public synchronized void logStat(LddsThread lt) - { - if (statLogger == null) - return; - if (lt != null) - { - lt.myStats.setLastActivity(lt.getLastActivity()); - statLogger.log(Logger.E_INFORMATION, - lt.myStats.getConnectionId() - + " " + lt.getClientName() - + " " + lt.retrieveNumServed() - + " " + dateFormat.format(lt.getLastActivity()) - + " " + (lt.user != null ? lt.user.getClientDdsVersion() : "")); - ldt.enqueue(lt.myStats); - } - - long now = System.currentTimeMillis(); - LinkedList llst = theServer.getAllSvrThreads(); - for(Iterator it = llst.iterator(); it.hasNext(); ) - { - LddsThread lddsThread = (LddsThread)it.next(); - currentHour.addMsgsDelivered(lddsThread.myStats.getMsgTally()); - } - int numClients = theServer.getNumSvrThreads(); - - if (currentHour != null) - doInitCurrentHour(); - int min = currentHour.getMinClients(); - int max = currentHour.getMaxClients(); - - if (numClients < min) - { - min = numClients; - currentHour.setMinClients(min); - } - if (numClients > max) - { - max = numClients; - currentHour.setMaxClients(max); - } - - long elapsedMsec = now - lastLogStatMsec; - long added = elapsedMsec * prevNumClients; - connectMsecs += added; - long msecThisHour = now - hourStartMsec; - if (msecThisHour > 0) - { - double ave = (double)connectMsecs / (double)msecThisHour; - currentHour.setAveClients(ave); -// Logger.instance().info( -// "logStat: prevNum=" + prevNumClients -// + ", last call=" + (new Date(lastLogStatMsec)) -// + ", elapsedMsec=" + elapsedMsec -// + ", added=" + added -// + ", connectMsecs=" + connectMsecs -// + ", ave=" + ave -// + ", newNumClients=" + numClients); - } - ldt.enqueue(currentHour); - prevNumClients = numClients; - lastLogStatMsec = now; - } - - public synchronized void rotateLogs() - { - statLogger.rotateLogs(); - } - - /** - * Called once only on startup. - * Retrieve current hour from DB if it exists. - * Initialize averaging variables. - */ - private synchronized void initCurrentHour() - { - doInitCurrentHour(); - } - - private void doInitCurrentHour() - { - long now = System.currentTimeMillis(); - hourStartMsec = (now / 3600000L) * 3600000L; - Date perStart = new Date(hourStartMsec); - currentHour = ldt.getPeriodStats(perStart); - - double ave = currentHour.getAveClients(); - - // Initialize tallies for computing the average. - prevNumClients = 0; - long elapsedMsec = now - hourStartMsec; - connectMsecs = (long)(elapsedMsec * ave); - lastLogStatMsec = now; - } - - - - - private synchronized void startNewHour() - { - if (currentHour != null) - ldt.enqueue(currentHour); - - currentHour = new DdsPeriodStats(); - long now = System.currentTimeMillis(); - hourStartMsec = (now / 3600000L) * 3600000L; - currentHour.setStartTime(new Date(hourStartMsec)); - - int numClients = theServer.getNumSvrThreads(); - currentHour.setMinClients( numClients ); - currentHour.setMaxClients( numClients ); - currentHour.setAveClients( (double)numClients ); - - // Initialize tallies for computing the average. - prevNumClients = theServer.getNumSvrThreads(); - long elapsedMsec = now - hourStartMsec; - connectMsecs = (elapsedMsec * numClients); -// Logger.instance().info("startNewHour: elapsedMsec=" + elapsedMsec -// + ", numClients=" + numClients -// + ", connectMsecs=" + connectMsecs); - lastLogStatMsec = now; - - // Purge dds stats records more than 60 days old. - Date cutoff = new Date(hourStartMsec - 60 * 24 * 3600000L); - ldt.deleteDdsStatsBefore(cutoff); - } - - - - public synchronized void incrNumAuth() - { - currentHour.incrNumAuth(); - } - public synchronized void incrNumUnAuth() - { - currentHour.incrNumUnAuth(); - } - public synchronized void incrBadPasswords() - { - currentHour.incrBadPasswords(); - } - public synchronized void incrBadUsernames() - { -// Logger.instance().info("incrBadUsernames"); - currentHour.incrBadUsernames(); - } + BasicServer theServer; + SequenceFileLogger statLogger; + SimpleDateFormat dateFormat; + private boolean shutdownFlag; + private LrgsDatabaseThread ldt; + DdsPeriodStats currentHour; + private long lastLogStatMsec = 0L; + private long connectMsecs = 0L; /* connections * msec */ + private long hourStartMsec = 0L; + private int prevNumClients = 0; + + /** + Constructor. + @param svr the server object + @param logname the file in which to periodically write client stats. + */ + public LddsLoggerThread(BasicServer svr, String logname) + { + theServer = svr; + shutdownFlag = false; + dateFormat = new SimpleDateFormat("yyyy/MM/dd-HH:mm:ss"); + dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + String logFileName = EnvExpander.expand(logname); + try + { + statLogger = new SequenceFileLogger("DDS", logFileName); + statLogger.setMaxLength(5000000); + statLogger.setUsePriority(false); + } + catch(IOException ex) + { + Logger.instance().log(Logger.E_FAILURE, + "Cannot open '" + logFileName + + "' DDS stats will not be logged! : " + ex); + statLogger = null; + } + ldt = LrgsDatabaseThread.instance(); + currentHour = null; + } + + /** Called when server is exiting. */ + public void shutdown() + { + shutdownFlag = true; + } + + /** + Thread run method: sleep for a minute, then poll each client thread + and write its status to the file. + */ + public void run() + { + initCurrentHour(); + long lastMin = System.currentTimeMillis() / 60000L; + long lastHour = lastMin / 60; + Logger.instance().info("LddsLoggerThread starting. h=" + + lastHour+", m=" + lastMin); + while(!shutdownFlag && statLogger != null) + { + long thisMin = System.currentTimeMillis() / 60000L; + long thisHour = thisMin / 60; + if (thisMin > lastMin) + { + lastMin = thisMin; + logStats(); + if (thisHour != lastHour) + { + startNewHour(); + lastHour = thisHour; + } + } + try { sleep(1000L); } + catch(InterruptedException ex) {} + } + if (currentHour != null) + { + ldt.enqueue(currentHour); + } + + try { sleep(1000L); } + catch(InterruptedException ex) {} + if (statLogger != null) + { + statLogger.close(); + } + statLogger = null; + Logger.instance().info("LddsLoggerThread exiting."); + } + + private void logStats() + { + if (statLogger == null) + { + return; + } + // Collect & log info from each thread. + + LinkedList svrThreads = theServer.getAllSvrThreads(); + for(Iterator it = svrThreads.iterator(); it.hasNext(); ) + { + Object ob = it.next(); + if (ob instanceof LddsThread) + { + LddsThread lt = (LddsThread)ob; + logStat(lt); + } + } + ldt.enqueue(currentHour); + logStat(null); + } + + /** + * Log a change in status. Called when any client connects + * or disconnects, or once per minute from the thread above. + */ + public synchronized void logStat(LddsThread lt) + { + if (statLogger == null) + { + return; + } + if (lt != null) + { + lt.myStats.setLastActivity(lt.getLastActivity()); + statLogger.log(Logger.E_INFORMATION, + lt.myStats.getConnectionId() + + " " + lt.getClientName() + + " " + lt.retrieveNumServed() + + " " + dateFormat.format(lt.getLastActivity()) + + " " + (lt.user != null ? lt.user.getClientDdsVersion() : "")); + ldt.enqueue(lt.myStats); + } + + long now = System.currentTimeMillis(); + LinkedList llst = theServer.getAllSvrThreads(); + for(Iterator it = llst.iterator(); it.hasNext(); ) + { + LddsThread lddsThread = (LddsThread)it.next(); + currentHour.addMsgsDelivered(lddsThread.myStats.getMsgTally()); + } + int numClients = theServer.getNumSvrThreads(); + + if (currentHour != null) + { + doInitCurrentHour(); + } + int min = currentHour.getMinClients(); + int max = currentHour.getMaxClients(); + + if (numClients < min) + { + min = numClients; + currentHour.setMinClients(min); + } + if (numClients > max) + { + max = numClients; + currentHour.setMaxClients(max); + } + + long elapsedMsec = now - lastLogStatMsec; + long added = elapsedMsec * prevNumClients; + connectMsecs += added; + long msecThisHour = now - hourStartMsec; + if (msecThisHour > 0) + { + double ave = (double)connectMsecs / (double)msecThisHour; + currentHour.setAveClients(ave); + } + ldt.enqueue(currentHour); + prevNumClients = numClients; + lastLogStatMsec = now; + } + + public synchronized void rotateLogs() + { + statLogger.rotateLogs(); + } + + /** + * Called once only on startup. + * Retrieve current hour from DB if it exists. + * Initialize averaging variables. + */ + private synchronized void initCurrentHour() + { + doInitCurrentHour(); + } + + private void doInitCurrentHour() + { + long now = System.currentTimeMillis(); + hourStartMsec = (now / 3600000L) * 3600000L; + Date perStart = new Date(hourStartMsec); + currentHour = ldt.getPeriodStats(perStart); + + double ave = currentHour.getAveClients(); + + // Initialize tallies for computing the average. + prevNumClients = 0; + long elapsedMsec = now - hourStartMsec; + connectMsecs = (long)(elapsedMsec * ave); + lastLogStatMsec = now; + } + + + + + private synchronized void startNewHour() + { + if (currentHour != null) + { + ldt.enqueue(currentHour); + } + + currentHour = new DdsPeriodStats(); + long now = System.currentTimeMillis(); + hourStartMsec = (now / 3600000L) * 3600000L; + currentHour.setStartTime(new Date(hourStartMsec)); + + int numClients = theServer.getNumSvrThreads(); + currentHour.setMinClients( numClients ); + currentHour.setMaxClients( numClients ); + currentHour.setAveClients( (double)numClients ); + + // Initialize tallies for computing the average. + prevNumClients = theServer.getNumSvrThreads(); + long elapsedMsec = now - hourStartMsec; + connectMsecs = (elapsedMsec * numClients); + + lastLogStatMsec = now; + + // Purge dds stats records more than 60 days old. + Date cutoff = new Date(hourStartMsec - 60 * 24 * 3600000L); + ldt.deleteDdsStatsBefore(cutoff); + } + + + + public synchronized void incrNumAuth() + { + currentHour.incrNumAuth(); + } + + public synchronized void incrNumUnAuth() + { + currentHour.incrNumUnAuth(); + } + + public synchronized void incrBadPasswords() + { + currentHour.incrBadPasswords(); + } + + public synchronized void incrBadUsernames() + { + currentHour.incrBadUsernames(); + } } - - diff --git a/src/main/java/lrgs/ldds/LddsMessage.java b/src/main/java/lrgs/ldds/LddsMessage.java index 59fed1267..0d563bc9c 100644 --- a/src/main/java/lrgs/ldds/LddsMessage.java +++ b/src/main/java/lrgs/ldds/LddsMessage.java @@ -4,7 +4,6 @@ package lrgs.ldds; import ilex.util.ArrayUtil; -import ilex.util.Logger; /** This class represents a complete DDS protocol message. It is used on both @@ -12,123 +11,122 @@ */ public class LddsMessage { - public static final int ValidHdrLength = 10; - public static final String ValidSync = "FAF0"; - public static final int ValidMaxDataLength = 99000; - - public static final String ValidIds = "abcdefghijklmnopqrstu"; - public static final char IdHello = 'a'; - public static final char IdGoodbye = 'b'; - public static final char IdStatus = 'c'; - public static final char IdStart = 'd'; - public static final char IdStop = 'e'; - public static final char IdDcp = 'f'; - public static final char IdCriteria = 'g'; - public static final char IdGetOutages = 'h'; - public static final char IdIdle = 'i'; - public static final char IdPutNetlist = 'j'; - public static final char IdGetNetlist = 'k'; - public static final char IdAssertOutages = 'l'; - public static final char IdAuthHello = 'm'; - public static final char IdDcpBlock = 'n'; - public static final char IdEvents = 'o'; - public static final char IdRetConfig = 'p'; - public static final char IdInstConfig = 'q'; - public static final char IdDcpBlockExt = 'r'; - public static final char IdUnused_6 = 's'; - public static final char IdUnused_7 = 't'; - public static final char IdUser = 'u'; - - // Instance data: - public char MsgId; // Identifies type of message - public int MsgLength; // Length of data field following header - public byte MsgData[]; // Data following header as a string - - /** - This constructor is used on the receiving end after ValidHdrLength bytes - have been read from the socket. It will throw ProtocolError - if the header is invalid. It builds a message containing only the - header field. - @param hdr the DDS message header. - */ - public LddsMessage(byte hdr[]) throws ProtocolError - { - if (hdr.length < ValidHdrLength) - throw new ProtocolError( - "Invalid LDDS message header - length=" + hdr.length); - String sync = new String(ArrayUtil.getField(hdr, 0, 4)); - - if (sync.compareTo(ValidSync) != 0) - throw new ProtocolError( - "Invalid LDDS message header - bad sync '" + sync + "'"); - - MsgId = (char)hdr[4]; - if (ValidIds.indexOf((int)MsgId) < 0) - throw new ProtocolError( - "Invalid LDDS message header - ID = '" + MsgId + "'"); - - // DRS server may have leading spaces in the length field. - byte lenbytes[] = ArrayUtil.getField(hdr, 5, 5); - for(int i = 0; i < 5; i++) - if (lenbytes[i] == (byte)' ') - lenbytes[i] = (byte)'0'; - - String lenstr = new String(lenbytes); - try { MsgLength = Integer.parseInt(lenstr); } - catch (NumberFormatException nfe) - { - throw new ProtocolError( - "Invalid LDDS message header - bad length field = '" + - lenstr+ "'"); - } - } - - /** - Use this constructor on the sending end. Construct the object and then - call getBytes() to get the data to send over the socket. - - Throws ProtocolError if ID is invalid or if length is - negative or greater than maximum allowable length. - - @param MsgId the ID to place in the header - @param StrData the message data as a string - */ - public LddsMessage(char MsgId, String StrData) - { - this.MsgId = MsgId; - - MsgLength = StrData != null ? StrData.length() : 0; + public static final int ValidHdrLength = 10; + public static final String ValidSync = "FAF0"; + public static final int ValidMaxDataLength = 99000; + + public static final String ValidIds = "abcdefghijklmnopqrstu"; + public static final char IdHello = 'a'; + public static final char IdGoodbye = 'b'; + public static final char IdStatus = 'c'; + public static final char IdStart = 'd'; + public static final char IdStop = 'e'; + public static final char IdDcp = 'f'; + public static final char IdCriteria = 'g'; + public static final char IdGetOutages = 'h'; + public static final char IdIdle = 'i'; + public static final char IdPutNetlist = 'j'; + public static final char IdGetNetlist = 'k'; + public static final char IdAssertOutages = 'l'; + public static final char IdAuthHello = 'm'; + public static final char IdDcpBlock = 'n'; + public static final char IdEvents = 'o'; + public static final char IdRetConfig = 'p'; + public static final char IdInstConfig = 'q'; + public static final char IdDcpBlockExt = 'r'; + public static final char IdUnused_6 = 's'; + public static final char IdUnused_7 = 't'; + public static final char IdUser = 'u'; + + // Instance data: + public char MsgId; // Identifies type of message + public int MsgLength; // Length of data field following header + public byte MsgData[]; // Data following header as a string + + /** + This constructor is used on the receiving end after ValidHdrLength bytes + have been read from the socket. It will throw ProtocolError + if the header is invalid. It builds a message containing only the + header field. + @param hdr the DDS message header. + */ + public LddsMessage(byte hdr[]) throws ProtocolError + { + if (hdr.length < ValidHdrLength) + throw new ProtocolError( + "Invalid LDDS message header - length=" + hdr.length); + String sync = new String(ArrayUtil.getField(hdr, 0, 4)); + + if (sync.compareTo(ValidSync) != 0) + throw new ProtocolError( + "Invalid LDDS message header - bad sync '" + sync + "'"); + + MsgId = (char)hdr[4]; + if (ValidIds.indexOf((int)MsgId) < 0) + throw new ProtocolError( + "Invalid LDDS message header - ID = '" + MsgId + "'"); + + // DRS server may have leading spaces in the length field. + byte lenbytes[] = ArrayUtil.getField(hdr, 5, 5); + for(int i = 0; i < 5; i++) + if (lenbytes[i] == (byte)' ') + lenbytes[i] = (byte)'0'; + + String lenstr = new String(lenbytes); + try { MsgLength = Integer.parseInt(lenstr); } + catch (NumberFormatException nfe) + { + throw new ProtocolError( + "Invalid LDDS message header - bad length field = '" + + lenstr+ "'"); + } + } + + /** + Use this constructor on the sending end. Construct the object and then + call getBytes() to get the data to send over the socket. + + Throws ProtocolError if ID is invalid or if length is + negative or greater than maximum allowable length. + + @param MsgId the ID to place in the header + @param StrData the message data as a string + */ + public LddsMessage(char MsgId, String StrData) + { + this.MsgId = MsgId; + + MsgLength = StrData != null ? StrData.length() : 0; // Experimentally DON'T add the null byte at the end. -// MsgLength = StrData != null ? StrData.length()+1 : 0; - - // Using resize will add a null byte at the end. Legacy requires this. - MsgData = MsgLength > 0 ? - ArrayUtil.resize(StrData.getBytes(), MsgLength) : null; - } - - /** - @return byte array representation of this header for sending over - a socket. - */ - public byte[] getBytes() - { - byte ret[] = new byte[ValidHdrLength + MsgLength]; - for(int i = 0; i < 4; i++) - ret[i] = (byte)ValidSync.charAt(i); - ret[4] = (byte)MsgId; - - // Note: 48 == ASCII '0' - ret[5] = (byte)(48 + MsgLength / 10000); - ret[6] = (byte)(48 + (MsgLength%10000) / 1000); - ret[7] = (byte)(48 + (MsgLength% 1000) / 100); - ret[8] = (byte)(48 + (MsgLength% 100) / 10); - ret[9] = (byte)(48 + (MsgLength% 10) ); - - if (MsgLength > 0 && MsgData != null) - for(int i = 0; i < MsgLength; i++) - ret[10+i] = MsgData[i]; - return ret; - } +// MsgLength = StrData != null ? StrData.length()+1 : 0; + + // Using resize will add a null byte at the end. Legacy requires this. + MsgData = MsgLength > 0 ? + ArrayUtil.resize(StrData.getBytes(), MsgLength) : null; + } + + /** + @return byte array representation of this header for sending over + a socket. + */ + public byte[] getBytes() + { + byte ret[] = new byte[ValidHdrLength + MsgLength]; + for(int i = 0; i < 4; i++) + ret[i] = (byte)ValidSync.charAt(i); + ret[4] = (byte)MsgId; + + // Note: 48 == ASCII '0' + ret[5] = (byte)(48 + MsgLength / 10000); + ret[6] = (byte)(48 + (MsgLength%10000) / 1000); + ret[7] = (byte)(48 + (MsgLength% 1000) / 100); + ret[8] = (byte)(48 + (MsgLength% 100) / 10); + ret[9] = (byte)(48 + (MsgLength% 10) ); + + if (MsgLength > 0 && MsgData != null) + for(int i = 0; i < MsgLength; i++) + ret[10+i] = MsgData[i]; + return ret; + } } - diff --git a/src/main/java/lrgs/ldds/LddsThread.java b/src/main/java/lrgs/ldds/LddsThread.java index 14520ad2e..67c752c3c 100644 --- a/src/main/java/lrgs/ldds/LddsThread.java +++ b/src/main/java/lrgs/ldds/LddsThread.java @@ -6,7 +6,7 @@ * source code for your own purposes, except that no part of this source * code may be claimed to be proprietary. * -* Except for specific contractual terms between ILEX and the federal +* Except for specific contractual terms between ILEX and the federal * government, this source code is provided completely without warranty. * For more information contact: info@ilexeng.com */ @@ -32,7 +32,7 @@ /** Each connected client will have an LddsThread object. This is an abstract base class that is missing the methods that create -the interfaces to the archive, retriever, and dcp-name-mapper. +the interfaces to the archive, retriever, and dcp-name-mapper.

For the legacy Linux LRGS, these interfaces use JNI to communicate with C modules via shared memory and semaphores. For the Java-Only-Archive, @@ -40,514 +40,521 @@ */ public abstract class LddsThread extends BasicSvrThread { - /** The input stream for building protocol messages. */ - protected LddsInputStream ins; + /** The input stream for building protocol messages. */ + protected LddsInputStream ins; - /** The socket output stream. */ - private OutputStream outs; + /** The socket output stream. */ + private OutputStream outs; - /** Unique number of this connection within this server-run. */ - protected int uniqueID; - - /** Used to map names to dcp addresses. */ - protected DcpNameMapper nameMapper; - - /** The client user: */ - public LddsUser user; - - /** Search criteria being used on this connection. */ - public SearchCriteria crit; - - /** Native interface to retrieve messages. */ - protected DcpMsgSource msgacc; - - /** Interface used to retrieve messages from the local system. */ - protected DcpMsgRetriever msgretriever; - - /** For building get-block responses */ - private byte blockBuffer[]; - - /** The number of messages served since last call to retrieveNumServed */ - private int numServed; - - /** The last time a request was received on this connection. */ - private Date lastActivity; - - /** The Queue Logger used for serving out log messages. */ - protected QueueLogger qlog; - - /** My log index. */ - public int logIndex; - - /** Object to provide LRGS status. */ - private LrgsStatusProvider statusProvider; - - /** Last sequence number retrieved, for status reporting. */ - public int lastSeqNum; - - /** Unix time_t of last message retrieved. */ - public int lastMsgTime; - - /** Factory used to convert incoming client messages into commands. */ - protected static CmdFactory cmdFactory = null; - - /** Store various statistics about this connection. */ - public DdsConnectionStats myStats; - - public StatLogger statLogger; - - ArrayList seqNumMsgBuf = null; - int seqNumMsgBufIdx = 0; - - private OutageXmlParser outageXmlParser = null; - - private String hostname = "(unknown host)"; - - boolean secondAuthAttempt = false; - - /** - Constructor. - @param parent the server object - @param socket the socket to the client - @param id unique integer ID for this client. - */ - public LddsThread(BasicServer parent, Socket socket, int id) - throws IOException - { - super(parent, socket); - - ins = new LddsInputStream(socket.getInputStream()); - outs = socket.getOutputStream(); - uniqueID = id; - - user = null; // Will be created when client sends 'Hello' - crit = null; // Will be created on get/put criteria messages - msgacc = null; // Will be created on HELLO message - blockBuffer = new byte[99999]; - qlog = null; - - lastActivity = new Date(); - Logger.instance().debug1(DdsServer.module + - " New client: " + getClientName() + " id=" + id); - - setName("ddsclient-" + id); - - statusProvider = null; - lastSeqNum = 0; - lastMsgTime = 0; - hostname = socket.getInetAddress().toString(); - Logger.instance().debug1(DdsServer.module + - " set hostname initially to '" + hostname + "'"); - - myStats = new DdsConnectionStats(); - myStats.setConnectionId(id); - myStats.setStartTime(new Date()); - myStats.setFromIpAddr(hostname); - myStats.setSuccessCode(DdsConnectionStats.SC_CONNECTED); - myStats.setLastActivity(myStats.getStartTime()); - - int pri = this.getPriority(); - this.setPriority(pri - 1); -Logger.instance().debug1(DdsServer.module -+ " enqueing LddsThread to GetHostnameThread priority=" + getPriority()); - GetHostnameThread.instance().enqueue(this); -Logger.instance().debug1(DdsServer.module -+ " enqueue done."); - } - - /** - * Sets the command factory, used to convert client messages into commands. - * @param factory the factory\ - */ - public static void setCmdFactory(CmdFactory factory) - { - cmdFactory = factory; - } - - /** - Sets the Queue Logger allowing clients to retrieve log messages. - @param qlog the logger - */ - public void setQueueLogger(QueueLogger qlog) - { - this.qlog = qlog; - logIndex = qlog.getNextIdx(); - } - - /** - Called when the hello message is received. - @param user the LddsUser object containing name and context - */ - public void attachLrgs(LddsUser user) - throws ArchiveUnavailableException, DdsInternalException - { - if (msgacc != null) - { - msgacc.detachSource(); - msgacc = null; - } - this.user = user; - if (user.isAuthenticated) - { - myStats.setSuccessCode(DdsConnectionStats.SC_AUTHENTICATED); - statLogger.incrNumAuth(); - } - else - { - myStats.setSuccessCode(DdsConnectionStats.SC_UNAUTHENTICATED); - statLogger.incrNumUnAuth(); - } - myStats.setUserName(user.name); - myStats.setProtocolVersion(user.getClientDdsVersionNum()); - - // The name mapper maps DCP names in a search crit to addresses - if (nameMapper == null) - nameMapper = makeDcpNameMapper(); - - // the DcpMsgSource provides the actual interface to the archive. - msgacc = makeDcpMsgSource(); -// msgacc.setClientName(hostname+"-"+uniqueID); - msgacc.setClientName(hostname); - msgacc.attachSource(); - msgacc.setProcInfo("DDS-CLI", user.name); - - // Set up the msgacc interface to save the last index after - // each read. This is necessary so that the search criteria - // "LRGS_SINCE: last" will work. - msgacc.setSaveLast(user.directory.getPath() - +File.separator+"lrgslastindex", - DcpMsgSource.SaveLastOnGetIndex); - - // The message retriever handles search criteria evaluation. - msgretriever = makeDcpMsgRetriever(); - msgretriever.setDcpMsgSource(msgacc); - msgretriever.setUsername(user.name); - - msgretriever.setUserSandbox(user.directory); - msgretriever.setDcpNameMapper(nameMapper); - ((MessageArchiveRetriever)msgretriever).setProtocolVersion( - user.getClientDdsVersion()); - try { msgretriever.init(); } - catch(Exception ex) - { - ex.printStackTrace(); - throw new DdsInternalException("msgretriever.init(): " + ex); - } - - msgacc.setStatus("Running"); - Logger.instance().debug1(DdsServer.module + - " Accepted connection #" + getUniqueID() + " from " - + getClientName() + ""); - lastActivity = new Date(); - statLogger.logStat(this); - } - - /** - Template method to create the DcpMsgSource object. - */ - protected abstract DcpMsgSource makeDcpMsgSource() - throws ArchiveUnavailableException; - - /** - Template method to create the DcpMsgRetriever object. - */ - protected abstract DcpMsgRetriever makeDcpMsgRetriever() - throws DdsInternalException; - - /** - Template method to create the name mapper. - This version in the base class uses the native shared memory interface. - */ - protected abstract DcpNameMapper makeDcpNameMapper(); - - /** - Disconnects from this client. - */ - public void disconnect() - { - Logger.instance().debug1(DdsServer.module + " Connection #" - + getUniqueID() + " " + getClientName() + " disconnecting"); - myStats.setEndTime(new Date()); - if (myStats.getSuccessCode() == DdsConnectionStats.SC_CONNECTED) - myStats.setSuccessCode(DdsConnectionStats.SC_HANGUP); - - try - { - outs.close(); - ins.close(); - } - catch(IOException ioe) {} - - // This will cause thread to terminate & rm this from the list. - super.disconnect(); - - // Log the stats now that we are no longer in the list. - statLogger.logStat(this); - - if (msgacc != null) - { - msgacc.detachSource(); - msgacc = null; - } - user = null; - crit = null; - msgretriever = null; - Logger.instance().debug1(DdsServer.module + " Connection #" - + getUniqueID() + " disconnection complete."); - } - - /** - Called continually from BasicSvrThread: - - Block waiting for complete request from client - - Execute request when one is received. - */ - protected void serviceClient() - { - LddsCommand cmd; - LddsMessage msg = null; - long serviceStart = System.currentTimeMillis(); - try - { - msg = ins.getMessage(); - if (cmdFactory == null) - cmdFactory = new CmdFactory(); - cmd = cmdFactory.makeCommand(msg); - } - catch(IOException ex) - { - Logger.instance().debug1(DdsServer.module - + " IO Error on connection to " - + getClientName() + " (Disconnecting): " + ex.toString()); - disconnect(); - return; - } - catch(ProtocolError ex) - { - Logger.instance().info(DdsServer.module - + " Protocol error on connection to " + getClientName() - + "(" + ex.getMessage() - + ") -- Hanging up. " - + "Ask this user if they are using DDS-compliant software."); - disconnect(); - return; - } - catch(Exception ex) - { - String emsg = "Unexpected Error on connection to " + getClientName() - + " (Disconnecting): " + ex; - System.err.println(emsg); - ex.printStackTrace(System.err); - warning(emsg); - disconnect(); - - return; - } - - lastActivity = new Date(); - - if (cmd != null) - { - try - { - int n = cmd.execute(this); - if (n > 0) - myStats.addMsgsReceived(n); - numServed += n; - } - catch(ArchiveException aex) - { - String rs = "?" + aex.getErrorCode() + ",0," + aex.getMessage(); - if (!(aex instanceof UntilReachedException)) - Logger.instance().debug3(DdsServer.module - + " ArchiveException on " - + getClientName() + " Response='" + rs + "' : " + aex); - LddsMessage resp = new LddsMessage(cmd.getCommandCode(), rs); - try { send(resp); } - catch(IOException ioex) - { - Logger.instance().debug1(DdsServer.module - + "Cannot return response to " - + getClientName() + ": " + ioex); - aex.setHangup(true); - } - if (aex.getHangup()) - disconnect(); - } - catch(IOException ex) - { - long elapsed = System.currentTimeMillis() - serviceStart; - String emsg = DdsServer.module - + " Client hangup on connection with user '" - + getClientName() + "', elapsed msec=" + elapsed - + ": " + ex.toString(); - if (emsg.contains("Connection reset by peer") - || emsg.contains("Broken pipe")) - Logger.instance().debug1(emsg); - else - Logger.instance().warning(emsg); - disconnect(); - } - catch(Exception ex) - { - long elapsed = System.currentTimeMillis() - serviceStart; - String emsg = DdsServer.module + - " " + (new Date()).toString() - + " Unexpected Exception on connection with user '" - + getClientName() + "', elapsed msec=" + elapsed - + ": " + ex.toString(); - System.err.println(emsg); - ex.printStackTrace(System.err); - Logger.instance().warning(emsg); - disconnect(); - } - } - else // (cmd == null) - { - String resptext = "?" + LrgsErrorCode.DBADKEYWORD + - ",0,Unrecognized request ID '" + msg.MsgId + "'"; - Logger.instance().warning(DdsServer.module + - " client " + getClientName() + " unrecognized request ID " - + msg.MsgId + " resp='" + resptext + "' -- will hangup."); - LddsMessage resp = new LddsMessage(LddsMessage.IdHello, resptext); - try { send(resp); } - catch(IOException ex) - { - Logger.instance().warning(DdsServer.module + " " - + getClientName() + ": " + ex); - } - disconnect(); - } - } - - /** - Send a message to the client. - @param msg the message to send - */ - public void send(LddsMessage msg) - throws IOException - { - byte msgbytes[] = msg.getBytes(); - try - { - outs.write(msgbytes); - outs.flush(); - } - catch(Exception ex) - { - throw new IOException("Error sending data: " + ex); - } - } - - /** @return the name of the remote user. */ - public String getUserName() - { - return user != null ? user.name : "(unknown)"; - } - - /** @return the DDS Version number of the client connected to this server. */ - public int getClientDdsVersion() - { - return user != null ? user.getClientDdsVersionNum() : DdsVersion.DdsVersionNum; - } - - public void setHostName(String hostname) - { - this.hostname = hostname; - if (myStats != null) - myStats.setFromIpAddr(hostname); - } - - /** @return the hostname for remote user. */ - public String getHostName() - { - return hostname; - } - - /** @return a string of the form username@hostname */ - public String getClientName() - { - StringBuilder ret = - new StringBuilder(user != null ? user.name : "(unknown)"); - ret.append("@" + hostname); - ret.append("(id=" + uniqueID + ")"); - return ret.toString(); - } - - /** @return internal block buffer */ - public byte[] getBlockBuffer() { return blockBuffer; } - - /** @return number of DCP messages served to this client connection */ - public synchronized int retrieveNumServed() - { - int ret = numServed; - numServed = 0; - return ret; - } - - /** return time of last activity on this connection */ - public Date getLastActivity() - { - return lastActivity; - } - - /** return unique ID assigned to this connection */ - public int getUniqueID() - { - return uniqueID; - } - - /** @return the status provider */ - public LrgsStatusProvider getStatusProvider() - { - return statusProvider; - } - - /** - * Sets the status provider. - * @param sp the status provider. - */ - public void setStatusProvider(LrgsStatusProvider sp) - { - statusProvider = sp; - } - - /** - * @return true if authentication is required by this server. - */ - public abstract boolean isAuthRequired(); - - /** - * @return true if same user is allowed multiple connections. - */ - public abstract boolean isSameUserMultAttachOK(); - -// /** -// * @return the root directory for user sandbox directories. -// */ -// public abstract String getDdsUserRootDir(); - - /** - * Convenience method to issue a warning log message on behalf of this - * client connection. - */ - public void warning(String msg) - { - Logger.instance().warning("DDS Client " + getClientName() - + " " + msg); - } - - public OutageXmlParser getOutageXmlParser() - { - if (outageXmlParser == null) - outageXmlParser = new OutageXmlParser(); - return outageXmlParser; - } - - public boolean isLocal() - { - if (this.user == null) - return false; - return user.isLocal(); - } + /** Unique number of this connection within this server-run. */ + protected int uniqueID; + + /** Used to map names to dcp addresses. */ + protected DcpNameMapper nameMapper; + + /** The client user: */ + public LddsUser user; + + /** Search criteria being used on this connection. */ + public SearchCriteria crit; + + /** Native interface to retrieve messages. */ + protected DcpMsgSource msgacc; + + /** Interface used to retrieve messages from the local system. */ + protected DcpMsgRetriever msgretriever; + + /** For building get-block responses */ + private byte blockBuffer[]; + + /** The number of messages served since last call to retrieveNumServed */ + private int numServed; + + /** The last time a request was received on this connection. */ + private Date lastActivity; + + /** The Queue Logger used for serving out log messages. */ + protected QueueLogger qlog; + + /** My log index. */ + public int logIndex; + + /** Object to provide LRGS status. */ + private LrgsStatusProvider statusProvider; + + /** Last sequence number retrieved, for status reporting. */ + public int lastSeqNum; + + /** Unix time_t of last message retrieved. */ + public int lastMsgTime; + + /** Factory used to convert incoming client messages into commands. */ + protected static CmdFactory cmdFactory = null; + + /** Store various statistics about this connection. */ + public DdsConnectionStats myStats; + + public StatLogger statLogger; + + ArrayList seqNumMsgBuf = null; + int seqNumMsgBufIdx = 0; + + private OutageXmlParser outageXmlParser = null; + + private String hostname = "(unknown host)"; + + boolean secondAuthAttempt = false; + + /** + Constructor. + @param parent the server object + @param socket the socket to the client + @param id unique integer ID for this client. + */ + public LddsThread(BasicServer parent, Socket socket, int id) + throws IOException + { + super(parent, socket); + + ins = new LddsInputStream(socket.getInputStream()); + outs = socket.getOutputStream(); + uniqueID = id; + + user = null; // Will be created when client sends 'Hello' + crit = null; // Will be created on get/put criteria messages + msgacc = null; // Will be created on HELLO message + blockBuffer = new byte[99999]; + qlog = null; + + lastActivity = new Date(); + Logger.instance().debug1(DdsServer.module + + " New client: " + getClientName() + " id=" + id); + + setName("ddsclient-" + id); + + statusProvider = null; + lastSeqNum = 0; + lastMsgTime = 0; + hostname = socket.getInetAddress().toString(); + Logger.instance().debug1(DdsServer.module + + " set hostname initially to '" + hostname + "'"); + + myStats = new DdsConnectionStats(); + myStats.setConnectionId(id); + myStats.setStartTime(new Date()); + myStats.setFromIpAddr(hostname); + myStats.setSuccessCode(DdsConnectionStats.SC_CONNECTED); + myStats.setLastActivity(myStats.getStartTime()); + + int pri = this.getPriority(); + this.setPriority(pri - 1); + Logger.instance().debug1(DdsServer.module + + " enqueing LddsThread to GetHostnameThread priority=" + getPriority()); + GetHostnameThread.instance().enqueue(this); + Logger.instance().debug1(DdsServer.module + + " enqueue done."); + } + + /** + * Sets the command factory, used to convert client messages into commands. + * @param factory the factory\ + */ + public static void setCmdFactory(CmdFactory factory) + { + cmdFactory = factory; + } + + /** + Sets the Queue Logger allowing clients to retrieve log messages. + @param qlog the logger + */ + public void setQueueLogger(QueueLogger qlog) + { + this.qlog = qlog; + logIndex = qlog.getNextIdx(); + } + + /** + Called when the hello message is received. + @param user the LddsUser object containing name and context + */ + public void attachLrgs(LddsUser user) + throws ArchiveUnavailableException, DdsInternalException + { + if (msgacc != null) + { + msgacc.detachSource(); + msgacc = null; + } + this.user = user; + if (user.isAuthenticated) + { + myStats.setSuccessCode(DdsConnectionStats.SC_AUTHENTICATED); + statLogger.incrNumAuth(); + } + else + { + myStats.setSuccessCode(DdsConnectionStats.SC_UNAUTHENTICATED); + statLogger.incrNumUnAuth(); + } + myStats.setUserName(user.name); + myStats.setProtocolVersion(user.getClientDdsVersionNum()); + + // The name mapper maps DCP names in a search crit to addresses + if (nameMapper == null) + { + nameMapper = makeDcpNameMapper(); + } + + // the DcpMsgSource provides the actual interface to the archive. + msgacc = makeDcpMsgSource(); + msgacc.setClientName(hostname); + msgacc.attachSource(); + msgacc.setProcInfo("DDS-CLI", user.name); + + // Set up the msgacc interface to save the last index after + // each read. This is necessary so that the search criteria + // "LRGS_SINCE: last" will work. + msgacc.setSaveLast(user.directory.getPath() + +File.separator+"lrgslastindex", + DcpMsgSource.SaveLastOnGetIndex); + + // The message retriever handles search criteria evaluation. + msgretriever = makeDcpMsgRetriever(); + msgretriever.setDcpMsgSource(msgacc); + msgretriever.setUsername(user.name); + + msgretriever.setUserSandbox(user.directory); + msgretriever.setDcpNameMapper(nameMapper); + ((MessageArchiveRetriever)msgretriever).setProtocolVersion( + user.getClientDdsVersion()); + try + { + msgretriever.init(); + } + catch(Exception ex) + { + ex.printStackTrace(); + throw new DdsInternalException("msgretriever.init(): " + ex); + } + + msgacc.setStatus("Running"); + Logger.instance().debug1(DdsServer.module + + " Accepted connection #" + getUniqueID() + " from " + + getClientName() + ""); + lastActivity = new Date(); + statLogger.logStat(this); + } + + /** + Template method to create the DcpMsgSource object. + */ + protected abstract DcpMsgSource makeDcpMsgSource() + throws ArchiveUnavailableException; + + /** + Template method to create the DcpMsgRetriever object. + */ + protected abstract DcpMsgRetriever makeDcpMsgRetriever() + throws DdsInternalException; + + /** + Template method to create the name mapper. + This version in the base class uses the native shared memory interface. + */ + protected abstract DcpNameMapper makeDcpNameMapper(); + + /** + Disconnects from this client. + */ + public void disconnect() + { + Logger.instance().debug1(DdsServer.module + " Connection #" + + getUniqueID() + " " + getClientName() + " disconnecting"); + myStats.setEndTime(new Date()); + if (myStats.getSuccessCode() == DdsConnectionStats.SC_CONNECTED) + { + myStats.setSuccessCode(DdsConnectionStats.SC_HANGUP); + } + + try + { + outs.close(); + ins.close(); + } + catch(IOException ioe) {} + + // This will cause thread to terminate & rm this from the list. + super.disconnect(); + + // Log the stats now that we are no longer in the list. + statLogger.logStat(this); + + if (msgacc != null) + { + msgacc.detachSource(); + msgacc = null; + } + user = null; + crit = null; + msgretriever = null; + Logger.instance().debug1(DdsServer.module + " Connection #" + + getUniqueID() + " disconnection complete."); + } + + /** + Called continually from BasicSvrThread: + - Block waiting for complete request from client + - Execute request when one is received. + */ + protected void serviceClient() + { + LddsCommand cmd; + LddsMessage msg = null; + long serviceStart = System.currentTimeMillis(); + try + { + msg = ins.getMessage(); + if (cmdFactory == null) + cmdFactory = new CmdFactory(); + cmd = cmdFactory.makeCommand(msg); + } + catch(IOException ex) + { + Logger.instance().debug1(DdsServer.module + + " IO Error on connection to " + + getClientName() + " (Disconnecting): " + ex.toString()); + disconnect(); + return; + } + catch(ProtocolError ex) + { + Logger.instance().info(DdsServer.module + + " Protocol error on connection to " + getClientName() + + "(" + ex.getMessage() + + ") -- Hanging up. " + + "Ask this user if they are using DDS-compliant software."); + disconnect(); + return; + } + catch(Exception ex) + { + String emsg = "Unexpected Error on connection to " + getClientName() + + " (Disconnecting): " + ex; + System.err.println(emsg); + ex.printStackTrace(System.err); + warning(emsg); + disconnect(); + + return; + } + + lastActivity = new Date(); + + if (cmd != null) + { + try + { + int n = cmd.execute(this); + if (n > 0) + myStats.addMsgsReceived(n); + numServed += n; + } + catch(ArchiveException aex) + { + String rs = "?" + aex.getErrorCode() + ",0," + aex.getMessage(); + if (!(aex instanceof UntilReachedException)) + Logger.instance().debug3(DdsServer.module + + " ArchiveException on " + + getClientName() + " Response='" + rs + "' : " + aex); + LddsMessage resp = new LddsMessage(cmd.getCommandCode(), rs); + try { send(resp); } + catch(IOException ioex) + { + Logger.instance().debug1(DdsServer.module + + "Cannot return response to " + + getClientName() + ": " + ioex); + aex.setHangup(true); + } + if (aex.getHangup()) + disconnect(); + } + catch(IOException ex) + { + long elapsed = System.currentTimeMillis() - serviceStart; + String emsg = DdsServer.module + + " Client hangup on connection with user '" + + getClientName() + "', elapsed msec=" + elapsed + + ": " + ex.toString(); + if (emsg.contains("Connection reset by peer") + || emsg.contains("Broken pipe")) + Logger.instance().debug1(emsg); + else + Logger.instance().warning(emsg); + disconnect(); + } + catch(Exception ex) + { + long elapsed = System.currentTimeMillis() - serviceStart; + String emsg = DdsServer.module + + " " + (new Date()).toString() + + " Unexpected Exception on connection with user '" + + getClientName() + "', elapsed msec=" + elapsed + + ": " + ex.toString(); + System.err.println(emsg); + ex.printStackTrace(System.err); + Logger.instance().warning(emsg); + disconnect(); + } + } + else // (cmd == null) + { + String resptext = "?" + LrgsErrorCode.DBADKEYWORD + + ",0,Unrecognized request ID '" + msg.MsgId + "'"; + Logger.instance().warning(DdsServer.module + + " client " + getClientName() + " unrecognized request ID " + + msg.MsgId + " resp='" + resptext + "' -- will hangup."); + LddsMessage resp = new LddsMessage(LddsMessage.IdHello, resptext); + try { send(resp); } + catch(IOException ex) + { + Logger.instance().warning(DdsServer.module + " " + + getClientName() + ": " + ex); + } + disconnect(); + } + } + + /** + Send a message to the client. + @param msg the message to send + */ + public void send(LddsMessage msg) + throws IOException + { + byte msgbytes[] = msg.getBytes(); + try + { + outs.write(msgbytes); + outs.flush(); + } + catch(Exception ex) + { + throw new IOException("Error sending data: " + ex); + } + } + + /** @return the name of the remote user. */ + public String getUserName() + { + return user != null ? user.name : "(unknown)"; + } + + /** @return the DDS Version number of the client connected to this server. */ + public int getClientDdsVersion() + { + return user != null ? user.getClientDdsVersionNum() : DdsVersion.DdsVersionNum; + } + + public void setHostName(String hostname) + { + this.hostname = hostname; + if (myStats != null) + { + myStats.setFromIpAddr(hostname); + } + } + + /** @return the hostname for remote user. */ + public String getHostName() + { + return hostname; + } + + /** @return a string of the form username@hostname */ + public String getClientName() + { + StringBuilder ret = + new StringBuilder(user != null ? user.name : "(unknown)"); + ret.append("@" + hostname); + ret.append("(id=" + uniqueID + ")"); + return ret.toString(); + } + + /** @return internal block buffer */ + public byte[] getBlockBuffer() { return blockBuffer; } + + /** @return number of DCP messages served to this client connection */ + public synchronized int retrieveNumServed() + { + int ret = numServed; + numServed = 0; + return ret; + } + + /** return time of last activity on this connection */ + public Date getLastActivity() + { + return lastActivity; + } + + /** return unique ID assigned to this connection */ + public int getUniqueID() + { + return uniqueID; + } + + /** @return the status provider */ + public LrgsStatusProvider getStatusProvider() + { + return statusProvider; + } + + /** + * Sets the status provider. + * @param sp the status provider. + */ + public void setStatusProvider(LrgsStatusProvider sp) + { + statusProvider = sp; + } + + /** + * @return true if authentication is required by this server. + */ + public abstract boolean isAuthRequired(); + + /** + * @return true if same user is allowed multiple connections. + */ + public abstract boolean isSameUserMultAttachOK(); + + /** + * Convenience method to issue a warning log message on behalf of this + * client connection. + */ + public void warning(String msg) + { + Logger.instance().warning("DDS Client " + getClientName() + + " " + msg); + } + + public OutageXmlParser getOutageXmlParser() + { + if (outageXmlParser == null) + { + outageXmlParser = new OutageXmlParser(); + } + return outageXmlParser; + } + + public boolean isLocal() + { + if (this.user == null) + { + return false; + } + return user.isLocal(); + } } diff --git a/src/main/java/lrgs/ldds/ProtocolError.java b/src/main/java/lrgs/ldds/ProtocolError.java index 7226054e7..724b22a38 100644 --- a/src/main/java/lrgs/ldds/ProtocolError.java +++ b/src/main/java/lrgs/ldds/ProtocolError.java @@ -24,26 +24,25 @@ /** ProtocolError is used by the various LRGS Servers and the corresponding - client interfaces. + client interfaces. It either means that the message received could not be parsed (bad - format) or that it was not the expected message type. + format) or that it was not the expected message type. */ public class ProtocolError extends Exception { - /** - Constructor. - @param msg the message - */ - public ProtocolError(String msg) - { - super(msg); - } + /** + Constructor. + @param msg the message + */ + public ProtocolError(String msg) + { + super(msg); + } - /** @return string representation of this exception. */ - public String toString() - { - return "Protocol Error: " + super.toString(); - } + /** @return string representation of this exception. */ + public String toString() + { + return "Protocol Error: " + super.toString(); + } } - diff --git a/src/main/java/lrgs/lrgsmain/JavaLrgsStatusProvider.java b/src/main/java/lrgs/lrgsmain/JavaLrgsStatusProvider.java index d718ddaf4..e677735b7 100644 --- a/src/main/java/lrgs/lrgsmain/JavaLrgsStatusProvider.java +++ b/src/main/java/lrgs/lrgsmain/JavaLrgsStatusProvider.java @@ -6,7 +6,6 @@ import java.net.InetAddress; import java.util.Date; import java.util.Iterator; -import java.util.Vector; import java.util.LinkedList; import ilex.util.Logger; @@ -19,7 +18,6 @@ import lrgs.archive.QualLogEntry; import lrgs.archive.MergeFilter; import lrgs.common.LrgsStatusProvider; -import lrgs.ddsserver.DdsServer; import lrgs.ddsserver.JLddsThread; import lrgs.gui.LrgsApp; import lrgs.ldds.LddsParams; @@ -31,579 +29,604 @@ by accessing java-only methods in the archive and downlinks. */ public class JavaLrgsStatusProvider - implements LrgsStatusProvider + implements LrgsStatusProvider { - /** Reference back to parent. */ - private LrgsMain lrgsMain; - - /** The status snapshot that everyone will work from. */ - private LrgsStatusSnapshotExt lsse; - - /** The last time a message was received. */ - private int lastMsgRcv; - - /** Used to maintain the quality log. */ - QualLogFile qualLogFile; - - /** Current minute's quality log entry. */ - QualLogEntry minuteQuality; - - /** Slot number for the DdsRecv main interface (set from LrgsMain) */ - public int ddsRecvMainSlotNum; - - /** Slot number for the DdsRecv main interface (set from LrgsMain) */ - public int ddsRecvSecMainSlotNum; - - /** Slot number for the DrgsRecv main interface (set from LrgsMain) */ - public int drgsRecvMainSlotNum; - - public int networkDcpMainSlotNum; - - /** Slot number for the NoaaportRecv main interface (set from LrgsMain) */ - public int noaaportRecvMainSlotNum; - - public Date lrgsStartupTime; - - /** Last hour we put dd info into. */ - private int lastDomsatDroppedHour = -1; - - /** The DQM Interface if one is active. */ - private DqmInterface dqmInterface; - - /** Last Domsat Sequence Number Seen */ - public int lastDomsatSequenceNum; - - public long qualLogLastModified = 0L; - - /** - * Construct the provider and an internal status snapshot structure, - * along with all the subordinate structures. - * @param lrgsMain the parent. - */ - public JavaLrgsStatusProvider(LrgsMain lrgsMain) - { - this.lrgsMain = lrgsMain; - ddsRecvMainSlotNum = -1; - drgsRecvMainSlotNum = -1; - noaaportRecvMainSlotNum = -1; - networkDcpMainSlotNum = -1; - ddsRecvSecMainSlotNum=-1; // added for secondary group - - lsse = new LrgsStatusSnapshotExt(); - - lsse.fullVersion = LrgsApp.AppVersion + " (" + LrgsApp.releasedOn + ")"; - - LrgsConfig cfg = LrgsConfig.instance(); - lsse.setMaxDownlinks(cfg.maxDownlinks); - lsse.setMaxClients(cfg.ddsMaxClients); - lsse.isUsable = false; - lsse.currentNumClients = 0; - - lsse.lss.lrgsTime = (int)(System.currentTimeMillis() / 1000L); - lsse.lss.currentHour = (short)((lsse.lss.lrgsTime / 3600) % 24); - lsse.lss.primaryMissingCount = 0; - lsse.lss.totalRecoveredCount = 0; - lsse.lss.totalGoodCount = 0; + /** Reference back to parent. */ + private LrgsMain lrgsMain; + + /** The status snapshot that everyone will work from. */ + private LrgsStatusSnapshotExt lsse; + + /** The last time a message was received. */ + private int lastMsgRcv; + + /** Used to maintain the quality log. */ + QualLogFile qualLogFile; + + /** Current minute's quality log entry. */ + QualLogEntry minuteQuality; + + /** Slot number for the DdsRecv main interface (set from LrgsMain) */ + public int ddsRecvMainSlotNum; + + /** Slot number for the DdsRecv main interface (set from LrgsMain) */ + public int ddsRecvSecMainSlotNum; + + /** Slot number for the DrgsRecv main interface (set from LrgsMain) */ + public int drgsRecvMainSlotNum; + + public int networkDcpMainSlotNum; + + /** Slot number for the NoaaportRecv main interface (set from LrgsMain) */ + public int noaaportRecvMainSlotNum; + + public Date lrgsStartupTime; + + /** Last hour we put dd info into. */ + private int lastDomsatDroppedHour = -1; + + /** The DQM Interface if one is active. */ + private DqmInterface dqmInterface; + + /** Last Domsat Sequence Number Seen */ + public int lastDomsatSequenceNum; + + public long qualLogLastModified = 0L; + + /** + * Construct the provider and an internal status snapshot structure, + * along with all the subordinate structures. + * @param lrgsMain the parent. + */ + public JavaLrgsStatusProvider(LrgsMain lrgsMain) + { + this.lrgsMain = lrgsMain; + ddsRecvMainSlotNum = -1; + drgsRecvMainSlotNum = -1; + noaaportRecvMainSlotNum = -1; + networkDcpMainSlotNum = -1; + ddsRecvSecMainSlotNum=-1; // added for secondary group + + lsse = new LrgsStatusSnapshotExt(); + + lsse.fullVersion = LrgsApp.AppVersion + " (" + LrgsApp.releasedOn + ")"; + + LrgsConfig cfg = LrgsConfig.instance(); + lsse.setMaxDownlinks(cfg.maxDownlinks); + lsse.setMaxClients(cfg.ddsMaxClients); + lsse.isUsable = false; + lsse.currentNumClients = 0; + + lsse.lss.lrgsTime = (int)(System.currentTimeMillis() / 1000L); + lsse.lss.currentHour = (short)((lsse.lss.lrgsTime / 3600) % 24); + lsse.lss.primaryMissingCount = 0; + lsse.lss.totalRecoveredCount = 0; + lsse.lss.totalGoodCount = 0; lsse.lss.downLinks = new DownLink[lsse.maxDownlinks]; - for(int i=0; i cfg.timeoutSeconds - && !cfg.getNoTimeout()) - { - if (lsse.isUsable) - { - lsse.isUsable = false; - Logger.instance().failure( - LrgsMain.module + ":" + LrgsMain.EVT_TIMEOUT - + " LRGS Timeout: No data in " - + cfg.timeoutSeconds + " seconds."); - } - lsse.systemStatus = "Timeout"; - } - else if (!lsse.isUsable) - { - Logger.instance().info( - LrgsMain.module + ":" + (-LrgsMain.EVT_TIMEOUT) - + " LRGS Recovery: Receiving Data Again!"); - lsse.isUsable = true; - lsse.systemStatus = "Running"; - } - - syncDownlinks(); - - lsse.currentNumClients = getAllClients(lsse.lss.attProcs); - - int hour = (lsse.lss.lrgsTime / 3600) % 24; - if (hour != lsse.lss.currentHour) - { - // Starting a new hour, zero out the status structs. -// System.out.println("setiing zero"); - lsse.lss.currentHour = (short)hour; - lsse.domsatDropped[hour] = 0; - QualityMeasurement qm = lsse.lss.qualMeas[hour]; - qm.containsData = true; - qm.numGood = 0; - qm.numDropped = 0; - qm.numRecovered = 0; - - for(int i=0; i= 0) - lsse.lss.arcStats.dirNext = idxNum+1; - DownLink dl = lsse.lss.downLinks[dl_slot]; - dl.lastMsgRecvTime = arcTime; - - int goodInc = (failcode == 'G') ? 1 : 0; - int badInc = (failcode == '?') ? 1 : 0; - - if (seqNum != -1) - { - lsse.lss.arcStats.lastSeqNum = seqNum; - dl.lastSeqNum = seqNum; - } - - // Update this slot's quality measurement for this hour. - int hour = (arcTime / 3600) % 24; - QualityMeasurement qm = lsse.downlinkQMs[dl_slot].dl_qual[hour]; - qm.containsData = true; - qm.numGood += goodInc; - qm.numDropped += badInc; - - // Update the 'archived' quality measurements for this hour. - QualityMeasurement arcQM = lsse.lss.qualMeas[hour]; - arcQM.containsData = true; - - if (mergeResult == MergeFilter.SAVE_DCPMSG) - { - arcQM.numGood += goodInc; - arcQM.numDropped += badInc; - minuteQuality.archivedGood += goodInc; - minuteQuality.archivedErr += badInc; - } - else if (mergeResult == MergeFilter.OVERWRITE_PREV_BAD) - { - // It could be a bad overwriting a bad, so use the incs: - arcQM.numGood += goodInc; - arcQM.numDropped += badInc; - arcQM.numDropped--; - minuteQuality.archivedGood++; - minuteQuality.archivedErr--; - } - // Else no changes to archived stats: Either discarded or overwrote-good - - /* - DDS and DRGS are composit downlinks that may have several connections. - After tracking the individual slot quality, we also aggregate - statistics in the parent slot. - */ - if (dl.type == LrgsInputInterface.DL_DDSCON && dl.group.equalsIgnoreCase(LrgsInputInterface.PRIMARY)) - { - dl = lsse.lss.downLinks[ddsRecvMainSlotNum]; - dl.lastMsgRecvTime = arcTime; - QualityMeasurement mainQM = - lsse.downlinkQMs[ddsRecvMainSlotNum].dl_qual[hour]; - mainQM.containsData = true; - mainQM.numGood += goodInc; - mainQM.numDropped += badInc; - minuteQuality.ddsGood += goodInc; - minuteQuality.ddsErr += badInc; - } - else if (dl.type == LrgsInputInterface.DL_DDSCON && dl.group.equalsIgnoreCase(LrgsInputInterface.SECONDARY)) - { - dl = lsse.lss.downLinks[ddsRecvSecMainSlotNum]; - dl.lastMsgRecvTime = arcTime; - QualityMeasurement mainQM = - lsse.downlinkQMs[ddsRecvSecMainSlotNum].dl_qual[hour]; - mainQM.containsData = true; - mainQM.numGood += goodInc; - mainQM.numDropped += badInc; - minuteQuality.ddsGood += goodInc; - minuteQuality.ddsErr += badInc; - } - else if (dl.type == LrgsInputInterface.DL_DRGSCON) - { - dl = lsse.lss.downLinks[drgsRecvMainSlotNum]; - dl.lastMsgRecvTime = arcTime; - QualityMeasurement mainQM = - lsse.downlinkQMs[drgsRecvMainSlotNum].dl_qual[hour]; - mainQM.containsData = true; - mainQM.numGood += goodInc; - mainQM.numDropped += badInc; - minuteQuality.drgsGood += goodInc; - minuteQuality.drgsErr += badInc; - } - else if (dl.type == LrgsInputInterface.DL_NETDCPCONT - || dl.type == LrgsInputInterface.DL_NETDCPPOLL) - { - dl = lsse.lss.downLinks[networkDcpMainSlotNum]; - dl.lastMsgRecvTime = arcTime; - QualityMeasurement mainQM = - lsse.downlinkQMs[networkDcpMainSlotNum].dl_qual[hour]; - mainQM.containsData = true; - mainQM.numGood += goodInc; - mainQM.numDropped += badInc; - minuteQuality.drgsGood += goodInc; - minuteQuality.drgsErr += badInc; - } - else if (dl.type == LrgsInputInterface.DL_DOMSAT) - { - minuteQuality.domsatGood += goodInc; - minuteQuality.domsatErr += badInc; - lastDomsatSequenceNum = seqNum; - } - else if (dl.type == LrgsInputInterface.DL_NOAAPORTCON) - { - dl = lsse.lss.downLinks[noaaportRecvMainSlotNum]; - dl.lastMsgRecvTime = arcTime; - QualityMeasurement npQM = - lsse.downlinkQMs[noaaportRecvMainSlotNum].dl_qual[hour]; - npQM.containsData = true; - npQM.numGood += goodInc; - npQM.numDropped += badInc; - minuteQuality.noaaportGood += goodInc; - minuteQuality.noaaportErr += badInc; - } - else if (dl.type == LrgsInputInterface.DL_LRIT) - { - minuteQuality.lritGood += goodInc; - minuteQuality.lritErr += badInc; - } - else if (dl.type == LrgsInputInterface.DL_GR3110) - { - minuteQuality.gr3110Count += goodInc; - } - else if (dl.type == LrgsInputInterface.DL_IRIDIUM) - minuteQuality.iridiumCount += goodInc; - else if (dl.type == LrgsInputInterface.DL_EDL) - minuteQuality.edlCount += goodInc; - } - - /** - * Called when a domsat dropout is detected. - * @param numDropped the number of messages dropped. - * @param arcTime the current time_t - * @param gapStart the sequence number of the start of the gap. - * @param elapsedSec the elapsed number of seconds in the gap. - */ - public synchronized void domsatDropped(int numDropped, int arcTime, - int gapStart, int elapsedSec) - { - int hour = (arcTime / 3600) % 24; - if (hour != lastDomsatDroppedHour) - { - // Starting new hour? Zero it out first. - lsse.domsatDropped[hour] = 0; - lastDomsatDroppedHour = hour; - } - lsse.domsatDropped[hour] += numDropped; - - minuteQuality.domsatDropped += numDropped; - - /* - * This is a hook for DAPS, which monitors quality on the DOMSAT - * uplink. Most LRGS systems will not have a dqmInterface. - */ - if (dqmInterface != null) - dqmInterface.domsatDropped(gapStart, numDropped, elapsedSec); - } - - - public void setSystemStatus(String status) - { - lsse.systemStatus = status; - } - - /** - * Called when we get a new client connection. - * @return AttachedProcess with which to track the client's status, - * or null if all client slots are used. - */ - public AttachedProcess getFreeClientSlot() - { - for(int i=0; i< lsse.lss.attProcs.length; i++) - { - AttachedProcess ap = lsse.lss.attProcs[i]; - if (ap.pid == -1) - return ap; - } - return null; - } - - /** - * @return ms time for the last time message was received over the - * DDS link. - */ - public long getLastDdsReceiveTime() - { - if (ddsRecvMainSlotNum == -1) - { - Logger.instance().debug1("StatusProvider.getLastDdsReceiveTime no " + - "ddsRecvMainSlotNum, returning now - 1 hour"); - return System.currentTimeMillis() - 3600000L; - } - else - { - DownLink dl = lsse.lss.downLinks[ddsRecvMainSlotNum]; - Logger.instance().debug1("StatusProvider.getLastDdsReceiveTime " - + "returning " + new Date(dl.lastMsgRecvTime * 1000L)); - return dl.lastMsgRecvTime * 1000L; - } - } - - /** - * @return ms time for the last time message was received over the - * DDS Secondary(Backup) link. - */ - public long getLastSecDdsReceiveTime() - { - if (ddsRecvSecMainSlotNum == -1) - return System.currentTimeMillis() - 3600000L; - else - { - DownLink dl = lsse.lss.downLinks[ddsRecvSecMainSlotNum]; - return dl.lastMsgRecvTime * 1000L; - } - } - - - /** - * @return ms time for the last time message was received over any link. - */ - public long getLastReceiveTime() - { - long latest = 0L; - String latestName = "(unknown)"; - for(int slot = 0; slot latest) - { - latest = t; - latestName = lsse.lss.downLinks[slot].name; - } - } - Logger.instance().info("At LRGS Startup, last msg was received at " - + new Date(latest) + " on downlink " + latestName); - return latest; - } - - public boolean isUsable() - { - return lsse.isUsable; - } - - public void setIsUsable(boolean tf) { lsse.isUsable = tf; } + for(int i=0; i<24; i++) + { + lsse.lss.qualMeas[i] = new QualityMeasurement(false, 0, 0, 0); + } + + int maxcli = lsse.maxClients == 0 ? 250 : lsse.maxClients; + lsse.lss.attProcs = new AttachedProcess[maxcli]; + for(int i=0; i cfg.timeoutSeconds + && !cfg.getNoTimeout()) + { + if (lsse.isUsable) + { + lsse.isUsable = false; + Logger.instance().failure( + LrgsMain.module + ":" + LrgsMain.EVT_TIMEOUT + + " LRGS Timeout: No data in " + + cfg.timeoutSeconds + " seconds."); + } + lsse.systemStatus = "Timeout"; + } + else if (!lsse.isUsable) + { + Logger.instance().info( + LrgsMain.module + ":" + (-LrgsMain.EVT_TIMEOUT) + + " LRGS Recovery: Receiving Data Again!"); + lsse.isUsable = true; + lsse.systemStatus = "Running"; + } + + syncDownlinks(); + + lsse.currentNumClients = getAllClients(lsse.lss.attProcs); + + int hour = (lsse.lss.lrgsTime / 3600) % 24; + if (hour != lsse.lss.currentHour) + { + // Starting a new hour, zero out the status structs. + lsse.lss.currentHour = (short)hour; + lsse.domsatDropped[hour] = 0; + QualityMeasurement qm = lsse.lss.qualMeas[hour]; + qm.containsData = true; + qm.numGood = 0; + qm.numDropped = 0; + qm.numRecovered = 0; + + for(int i=0; i= 0) + { + lsse.lss.arcStats.dirNext = idxNum+1; + } + DownLink dl = lsse.lss.downLinks[dl_slot]; + dl.lastMsgRecvTime = arcTime; + + int goodInc = (failcode == 'G') ? 1 : 0; + int badInc = (failcode == '?') ? 1 : 0; + + if (seqNum != -1) + { + lsse.lss.arcStats.lastSeqNum = seqNum; + dl.lastSeqNum = seqNum; + } + + // Update this slot's quality measurement for this hour. + int hour = (arcTime / 3600) % 24; + QualityMeasurement qm = lsse.downlinkQMs[dl_slot].dl_qual[hour]; + qm.containsData = true; + qm.numGood += goodInc; + qm.numDropped += badInc; + + // Update the 'archived' quality measurements for this hour. + QualityMeasurement arcQM = lsse.lss.qualMeas[hour]; + arcQM.containsData = true; + + if (mergeResult == MergeFilter.SAVE_DCPMSG) + { + arcQM.numGood += goodInc; + arcQM.numDropped += badInc; + minuteQuality.archivedGood += goodInc; + minuteQuality.archivedErr += badInc; + } + else if (mergeResult == MergeFilter.OVERWRITE_PREV_BAD) + { + // It could be a bad overwriting a bad, so use the incs: + arcQM.numGood += goodInc; + arcQM.numDropped += badInc; + arcQM.numDropped--; + minuteQuality.archivedGood++; + minuteQuality.archivedErr--; + } + // Else no changes to archived stats: Either discarded or overwrote-good + + /* + DDS and DRGS are composit downlinks that may have several connections. + After tracking the individual slot quality, we also aggregate + statistics in the parent slot. + */ + if (dl.type == LrgsInputInterface.DL_DDSCON && dl.group.equalsIgnoreCase(LrgsInputInterface.PRIMARY)) + { + dl = lsse.lss.downLinks[ddsRecvMainSlotNum]; + dl.lastMsgRecvTime = arcTime; + QualityMeasurement mainQM = + lsse.downlinkQMs[ddsRecvMainSlotNum].dl_qual[hour]; + mainQM.containsData = true; + mainQM.numGood += goodInc; + mainQM.numDropped += badInc; + minuteQuality.ddsGood += goodInc; + minuteQuality.ddsErr += badInc; + } + else if (dl.type == LrgsInputInterface.DL_DDSCON && dl.group.equalsIgnoreCase(LrgsInputInterface.SECONDARY)) + { + dl = lsse.lss.downLinks[ddsRecvSecMainSlotNum]; + dl.lastMsgRecvTime = arcTime; + QualityMeasurement mainQM = + lsse.downlinkQMs[ddsRecvSecMainSlotNum].dl_qual[hour]; + mainQM.containsData = true; + mainQM.numGood += goodInc; + mainQM.numDropped += badInc; + minuteQuality.ddsGood += goodInc; + minuteQuality.ddsErr += badInc; + } + else if (dl.type == LrgsInputInterface.DL_DRGSCON) + { + dl = lsse.lss.downLinks[drgsRecvMainSlotNum]; + dl.lastMsgRecvTime = arcTime; + QualityMeasurement mainQM = + lsse.downlinkQMs[drgsRecvMainSlotNum].dl_qual[hour]; + mainQM.containsData = true; + mainQM.numGood += goodInc; + mainQM.numDropped += badInc; + minuteQuality.drgsGood += goodInc; + minuteQuality.drgsErr += badInc; + } + else if (dl.type == LrgsInputInterface.DL_NETDCPCONT + || dl.type == LrgsInputInterface.DL_NETDCPPOLL) + { + dl = lsse.lss.downLinks[networkDcpMainSlotNum]; + dl.lastMsgRecvTime = arcTime; + QualityMeasurement mainQM = + lsse.downlinkQMs[networkDcpMainSlotNum].dl_qual[hour]; + mainQM.containsData = true; + mainQM.numGood += goodInc; + mainQM.numDropped += badInc; + minuteQuality.drgsGood += goodInc; + minuteQuality.drgsErr += badInc; + } + else if (dl.type == LrgsInputInterface.DL_DOMSAT) + { + minuteQuality.domsatGood += goodInc; + minuteQuality.domsatErr += badInc; + lastDomsatSequenceNum = seqNum; + } + else if (dl.type == LrgsInputInterface.DL_NOAAPORTCON) + { + dl = lsse.lss.downLinks[noaaportRecvMainSlotNum]; + dl.lastMsgRecvTime = arcTime; + QualityMeasurement npQM = + lsse.downlinkQMs[noaaportRecvMainSlotNum].dl_qual[hour]; + npQM.containsData = true; + npQM.numGood += goodInc; + npQM.numDropped += badInc; + minuteQuality.noaaportGood += goodInc; + minuteQuality.noaaportErr += badInc; + } + else if (dl.type == LrgsInputInterface.DL_LRIT) + { + minuteQuality.lritGood += goodInc; + minuteQuality.lritErr += badInc; + } + else if (dl.type == LrgsInputInterface.DL_GR3110) + { + minuteQuality.gr3110Count += goodInc; + } + else if (dl.type == LrgsInputInterface.DL_IRIDIUM) + minuteQuality.iridiumCount += goodInc; + else if (dl.type == LrgsInputInterface.DL_EDL) + minuteQuality.edlCount += goodInc; + } + + /** + * Called when a domsat dropout is detected. + * @param numDropped the number of messages dropped. + * @param arcTime the current time_t + * @param gapStart the sequence number of the start of the gap. + * @param elapsedSec the elapsed number of seconds in the gap. + */ + public synchronized void domsatDropped(int numDropped, int arcTime, + int gapStart, int elapsedSec) + { + int hour = (arcTime / 3600) % 24; + if (hour != lastDomsatDroppedHour) + { + // Starting new hour? Zero it out first. + lsse.domsatDropped[hour] = 0; + lastDomsatDroppedHour = hour; + } + lsse.domsatDropped[hour] += numDropped; + + minuteQuality.domsatDropped += numDropped; + + /* + * This is a hook for DAPS, which monitors quality on the DOMSAT + * uplink. Most LRGS systems will not have a dqmInterface. + */ + if (dqmInterface != null) + dqmInterface.domsatDropped(gapStart, numDropped, elapsedSec); + } + + + public void setSystemStatus(String status) + { + lsse.systemStatus = status; + } + + /** + * Called when we get a new client connection. + * @return AttachedProcess with which to track the client's status, + * or null if all client slots are used. + */ + public AttachedProcess getFreeClientSlot() + { + for(int i=0; i< lsse.lss.attProcs.length; i++) + { + AttachedProcess ap = lsse.lss.attProcs[i]; + if (ap.pid == -1) + { + return ap; + } + } + return null; + } + + /** + * @return ms time for the last time message was received over the + * DDS link. + */ + public long getLastDdsReceiveTime() + { + if (ddsRecvMainSlotNum == -1) + { + Logger.instance().debug1("StatusProvider.getLastDdsReceiveTime no " + + "ddsRecvMainSlotNum, returning now - 1 hour"); + return System.currentTimeMillis() - 3600000L; + } + else + { + DownLink dl = lsse.lss.downLinks[ddsRecvMainSlotNum]; + Logger.instance().debug1("StatusProvider.getLastDdsReceiveTime " + + "returning " + new Date(dl.lastMsgRecvTime * 1000L)); + return dl.lastMsgRecvTime * 1000L; + } + } + + /** + * @return ms time for the last time message was received over the + * DDS Secondary(Backup) link. + */ + public long getLastSecDdsReceiveTime() + { + if (ddsRecvSecMainSlotNum == -1) + { + return System.currentTimeMillis() - 3600000L; + } + else + { + DownLink dl = lsse.lss.downLinks[ddsRecvSecMainSlotNum]; + return dl.lastMsgRecvTime * 1000L; + } + } + + + /** + * @return ms time for the last time message was received over any link. + */ + public long getLastReceiveTime() + { + long latest = 0L; + String latestName = "(unknown)"; + for(int slot = 0; slot latest) + { + latest = t; + latestName = lsse.lss.downLinks[slot].name; + } + } + } + Logger.instance().info("At LRGS Startup, last msg was received at " + + new Date(latest) + " on downlink " + latestName); + return latest; + } + + public boolean isUsable() + { + return lsse.isUsable; + } + + public void setIsUsable(boolean tf) { lsse.isUsable = tf; } } diff --git a/src/main/java/lrgs/lrgsmain/LrgsConfig.java b/src/main/java/lrgs/lrgsmain/LrgsConfig.java index 1c3211b5c..41b2e2d87 100644 --- a/src/main/java/lrgs/lrgsmain/LrgsConfig.java +++ b/src/main/java/lrgs/lrgsmain/LrgsConfig.java @@ -6,7 +6,7 @@ * source code for your own purposes, except that no part of this source * code may be claimed to be proprietary. * -* Except for specific contractual terms between ILEX and the federal +* Except for specific contractual terms between ILEX and the federal * government, this source code is provided completely without warranty. * For more information contact: info@ilexeng.com */ @@ -28,590 +28,609 @@ /** This class holds all of the configuration variables for the archive module. */ -public class LrgsConfig - implements PropertiesOwner +public class LrgsConfig implements PropertiesOwner { - /** True if noaaport interface is enabled. */ - public boolean noaaportEnabled; - - /** Port number to either listen on or connect to */ - public int noaaportPort; - - /** Either "unisys", "marta", or "PDI" */ - public String noaaportReceiverType = "marta"; - - /** Needed if receiver is "unisys" */ - public String noaaportHostname = ""; - - /** If supplied, capture noaaport data to this file with date/time extension */ - public String noaaportCaptureFile = ""; - - /** Private instance reference */ - private static LrgsConfig _instance = null; - - /** File object for config file. */ - private File cfgFile; - - /** Last time configuration was loaded from file. */ - private long lastLoadTime; - - // Configuration variables settable from properties are public - - /** Directory containing all archive files */ - public String archiveDir; - - /** Number of day files to save in archive */ - public int numDayFiles; - - /** True if LRIT Input Interface is to be enabled. */ - public boolean enableLritRecv; + /** True if noaaport interface is enabled. */ + public boolean noaaportEnabled; - /** for dams-nt LRIT connection, this is the host or IP address to connect to */ - public String lritHostName = null; - - /** For dams-nt LRIT connection, this is the port to connect to */ - public int lritPort = 17010; + /** Port number to either listen on or connect to */ + public int noaaportPort; - /** Hex string representing the DRGS Start Pattern */ - public String lritDamsNtStartPattern = "534D0D0A"; - - /** One of the HEADER_TYPE constants in LritFileMonitor */ - public char lritHeaderType; - - /** The 2-char msg source code to use for messages received from LRIT DAMS-NT */ - public String lritSrcCode = "LR"; + /** Either "unisys", "marta", or "PDI" */ + public String noaaportReceiverType = "marta"; - /** True if DDS Input Interface is to be enabled. */ - public boolean enableDdsRecv; + /** Needed if receiver is "unisys" */ + public String noaaportHostname = ""; - /** Name of DDS Receive Config File. */ - public String ddsRecvConfig; + /** If supplied, capture noaaport data to this file with date/time extension */ + public String noaaportCaptureFile = ""; - /** True if DRGS Input Interface is to be enabled. */ - public boolean enableDrgsRecv; + /** Private instance reference */ + private static LrgsConfig _instance = null; - /** Name of DRGS Receive Config File. */ - public String drgsRecvConfig; + /** File object for config file. */ + private File cfgFile; - /** Port number for DDS Server to listen on. */ - public int ddsListenPort; - - /** If multi-NIC server and DDS only listens on one NIC, set bind addr. */ - public String ddsBindAddr; - - /** Maximum number of DDS clients to accept at any one time (0=no limit). */ - public int ddsMaxClients; - - /** True if DDS requires password authentication for message retreival. */ - public boolean ddsRequireAuth; - - /** True to enable administrative functions via DDS. */ - public boolean ddsAllowAdmin; - - /** DDS Usage Log Filename. */ - public String ddsUsageLog; - - /** DDS Network List Directory for mapping global names. */ - public String ddsNetlistDir; - - /** DDS Directory containing user sandbox directories. */ - public String ddsUserRootDir; - - /** DDS Directory containing user sandbox directories. */ - public String ddsUserRootDirLocal; - - /** Maximum number of downlink interfaces. */ - public int maxDownlinks; - - /** Assert Timeout if this many seconds goes by with no messages. */ - public int timeoutSeconds; - - /** File in which to place periodic HTML status snapshot. */ - public String htmlStatusFile; - - /** Number of seconds between HTML status snapshots. */ - public int htmlStatusSeconds; - - /** Merge preference 1: Highest priority. */ - public String mergePref1; - - /** Merge preference 2. */ - public String mergePref2; - - /** Merge preference 3. */ - public String mergePref3; - - /** Merge preference 4: Lowest priority. */ - public String mergePref4; - - /** True if DOMSAT Input Interface is to be even loaded. */ - public boolean loadDomsat; - - /** True if DOMSAT Input Interface is to be enabled. */ - public boolean enableDomsatRecv; - - /** Number of seconds after which DOMSAT declares a timeout. */ - public int domsatTimeout; - - /** Interface class to use for DOMSAT hardware. */ - public String domsatClass; - - /** NESDIS-ONLY: Enables output of DQM messages to COM1 serial port. */ - public boolean enableDapsDqm; - - /** NESDIS-ONLY: serial port for sending messages to DAPS. */ - public String dqmSerialPort; - - /** For bad DRGS's, option to ignore No-EOT-Termination condition. */ - public boolean ignoreDrgsNoEotTermination; - - /** Maximum size of a single lrgslog file */ - public int maxLogSize; - - /** Number of old log files to keep */ - public int numOldLogs; - - /** URL for accessing the LRGS database. */ - public String dbUrl; - - /** SimpleDateString format for writing to database. */ - public String sqlWriteDateFormat; - - /** SimpleDateString format for reading database. */ - public String sqlReadDateFormat; - - /** TimeZone for dates read from or written to the database */ - public String sqlTimeZone; - - /** Full package/class name for JDBC Driver */ - public String JdbcDriverClass; - - /** Name of class for key generation. */ - public String keyGeneratorClass; - - /** True if ddsrecv is to to recover discrete outages, else rt stream */ - public boolean recoverOutages; - - /** True if the network DCPs interface is enabled. */ - public boolean networkDcpEnable = false; - - /** URL for downloading PDT - defaults to NESDIS DCS location */ - public String pdtUrl = "https://dcs1.noaa.gov/pdts_compressed.txt"; - - /** True if this LRGS should do PDT validation for interfaces that don't - * already provide it. - */ - public boolean doPdtValidation = false; - - /** URL for downloading channel table from NOAA */ - public String channelMapUrl = - "https://dcs1.noaa.gov/chans_by_baud.txt"; - - /** Tells merge filter to prefer good messages from designated input */ - public boolean archivePreferredGood = false; - - /** If true, then only locally-assigned DDS accounts can do admin. */ - public boolean localAdminOnly = false; - - /** True to enable Iridium interface */ - public boolean iridiumEnabled = false; - - /** Port number for incoming Iridium SBD messages */ - public int iridiumPort = 10800; - - /** If specified, iridium raw-data will be captured here. */ - public String iridiumCaptureFile = null; - - /** Domsat Protocol Converter Host Name */ - public String dpcHost = null; - - /** Domsat Protocol Converter Port Number */ - public int dpcPort = 9000; - - /** Accept Abnormal Response Messages from DOMSAT (default=true) */ - public boolean acceptDomsatARMs = true; - - /** Store XMIT Records (i.e. the DCP Monitor Function) */ - public boolean storeXmitRecords = false; - - /** Meteosat LRIT can be VCS (default) or IBL*/ - public boolean iblLrit = false; - - /** Number of seconds after which to assert an LRIT timeout. */ - public int lritTimeout = 120; - - /** Enables ingest of EDL files via hot directory */ - public boolean edlIngestEnable = false; - - /** Specifies directory for incoming EDL files to be ingested into LRGS archive */ - public String edlIngestDirectory = "$LRGSHOME/edl-incoming"; - - /** If true, then subdirectories of edlIngestDirectory are recursively searched */ - public boolean edlIngestRecursive = false; - - /** If set, then only files with a specific suffix will be processed */ - public String edlFilenameSuffix = null; - - /** If set, then edl files will be moved here after processing */ - public String edlDoneDirectory = null; - - /** Max age of an LRIT message in seconds. Messages older than this are discarded. */ - public int lritMaxMsgAgeSec = 7200; - - /** Set to positive integer to enable minimum hourly checking on LRIT */ - public int lritMinHourly = 0; - - /** Set to positive integer to enable minimum hourly checking on DDS Recv */ - public int ddsMinHourly = 0; - - /** Set to positive integer to enable minimum hourly checking on EDL */ - public int edlMinHourly = 0; - - /** Set to positive integer to enable minimum hourly checking on DRGS */ - public int drgsMinHourly = 0; - - public boolean hritFileEnabled = false; - public String hritInputDir = null; - public String hritFilePrefix = null; - public String hritFileSuffix = null; - public String hritSourceCode = "HR"; - public String hritDoneDir = null; - public int hritTimeoutSec = 120; - public int hritFileMaxAgeSec = 7200; - - public static final boolean def_noaaportEnabled = false; - public static final int def_noaaportPort = 18000; - public static final String def_archiveDir = "."; - public static final int def_numDayFiles = 31; - public static final boolean def_enableLritRecv = false; - public static final char def_lritHeaderType = '6'; - public static final boolean def_enableDdsRecv = false; - public static final boolean def_enableDrgsRecv = false; - public static final int def_ddsListenPort = 16003; - public static final String def_ddsBindAddr = null; - public static final int def_ddsMaxClients = 150; - public static final boolean def_ddsRequireAuth = false; - public static final boolean def_ddsAllowAdmin = false; - public static final String def_ddsUsageLog = "$LRGSHOME/dds-log"; - public static final String def_ddsNetlistDir = "$LRGSHOME/netlist"; - public static final String def_ddsUserRootDir = "$LRGSHOME/users"; - public static final String def_ddsUserRootDirLocal = "$LRGSHOME/users.local"; - public static final int def_maxDownlinks = 32; - public static final int def_timeoutSeconds = 90; - public static final String def_ddsRecvConfig = "$LRGSHOME/ddsrecv.conf"; - public static final String def_drgsRecvConfig = "$LRGSHOME/drgsrecv.conf"; - public static final String def_htmlStatusFile = "$LRGSHOME/lrgsstatus.html"; - public static final int def_htmlStatusSeconds = 10; - public static final String def_mergePref1 = null; - public static final String def_mergePref2 = null; - public static final String def_mergePref3 = null; - public static final String def_mergePref4 = null; - public static final boolean def_enableDomsatRecv = false; - public static final int def_domsatTimeout = 60; - public static final boolean def_loadDomsat = false; - public static final boolean def_enableDapsDqm = false; - public static final String def_dqmSerialPort = "COM1"; - public static final String def_domsatClass = "lrgs.domsatrecv.DomsatSangoma"; - public static final boolean def_ignoreDrgsNoEotTermination = false; - public static final int def_maxLogSize = 20000000; // 20 meg. - public static final String def_dbUrl = null; - public static final String def_sqlWriteDateFormat = "''yyyy-MM-dd HH:mm:ss''"; - public static final String def_sqlReadDateFormat = "yyyy-MM-dd HH:mm:ss"; - public static final String def_sqlTimeZone = "UTC"; - public static final String def_keyGeneratorClass = "decodes.sql.SequenceKeyGenerator"; - public static final String def_JdbcDriverClass = "org.postgresql.Driver"; - public static final boolean def_recoverOutages = false; - public static final boolean def_localAdminOnly = false; - public static final String def_dpcHost = ""; - public static final int def_dpcPort = 9000; - public static final boolean def_enableDcpInterface = false; - public static final boolean def_storeXmitRecords = false; - public static final String def_dcpInterfaceXmlConfig = null; - - /** - * This contains the miscellaneous properties not represented on a custom - * GUI panel in rtstat. - */ - private PropertySpec miscPropSpecs[] = - { - new PropertySpec("loadDecodes", PropertySpec.BOOLEAN, - "Set to true to have DECODES database loaded at LRGS startup. Used in some" - + " circumstances to resolve network lists for DDS Receive"), - new PropertySpec("damsNtTimeout", PropertySpec.INT, - "If no data is received on a DAMS-NT socket in this many seconds, then issue a timeout" - + " warning and reconnect."), - new PropertySpec("passwordCheckerClass", PropertySpec.STRING, - "Name of class that does password checking. If not set, then all passwords accepted."), - new PropertySpec("localIpMask", PropertySpec.STRING, - "(e.g. 192.168.0.0/24) Local IP addresses will not be displayed on rtstat page"), - new PropertySpec("hideHostNames", PropertySpec.BOOLEAN, - "(default=false) Set to true to hide host names on the rtstat display."), - new PropertySpec("restrictEventsToAdmin", PropertySpec.BOOLEAN, - "(default=false) Set to true to disallow events to non-adminstrators " - + "on the rtstat display."), - - new PropertySpec("writeDacqEvents", PropertySpec.BOOLEAN, - "(default=false) if loadDecodes is also true, this means to create DACQ_EVENT " - + "entries in the database for INFO and higher-priority events."), - -// new PropertySpec("storeXmitRecords", PropertySpec.BOOLEAN, -// "Set to true to store XMIT Records (i.e. the DCP Monitor Function) (NOT IMPLEMENTED)") - }; - - /** - * This needs to be public so that PropertiesUtil.loadFromProps will add - * properties with names that don't match public attributes to it. - */ - public Properties otherProps = new Properties(); - - private PasswordChecker passwordChecker = null; - - /** If true, then Authenticated DDS connections must be done with SHA-256. */ - public boolean reqStrongEncryption = false; - - public static LrgsConfig instance() - { - if (_instance == null) - _instance = new LrgsConfig(); - return _instance; - } - - public LrgsConfig() - { - lastLoadTime = 0L; - archiveDir = def_archiveDir; - numDayFiles = def_numDayFiles; - enableLritRecv = def_enableLritRecv; - lritHeaderType = def_lritHeaderType; - enableDdsRecv = def_enableDdsRecv; - enableDrgsRecv = def_enableDrgsRecv; - ddsListenPort = def_ddsListenPort; - ddsBindAddr = def_ddsBindAddr; - ddsMaxClients = def_ddsMaxClients; - ddsRequireAuth = def_ddsRequireAuth; - ddsAllowAdmin = def_ddsAllowAdmin; - ddsUsageLog = def_ddsUsageLog; - ddsNetlistDir = def_ddsNetlistDir; - ddsUserRootDir = def_ddsUserRootDir; - ddsUserRootDirLocal = def_ddsUserRootDirLocal; - maxDownlinks = def_maxDownlinks; - timeoutSeconds = def_timeoutSeconds; - ddsRecvConfig = def_ddsRecvConfig; - drgsRecvConfig = def_drgsRecvConfig; - htmlStatusFile = def_htmlStatusFile; - htmlStatusSeconds = def_htmlStatusSeconds; - mergePref1 = def_mergePref1; - mergePref2 = def_mergePref2; - mergePref3 = def_mergePref3; - mergePref4 = def_mergePref4; - enableDomsatRecv = def_enableDomsatRecv; - domsatTimeout = def_domsatTimeout; - loadDomsat = def_loadDomsat; - enableDapsDqm = def_enableDapsDqm; - dqmSerialPort = def_dqmSerialPort; - domsatClass = def_domsatClass; - ignoreDrgsNoEotTermination = def_ignoreDrgsNoEotTermination; - maxLogSize = def_maxLogSize; - dbUrl = def_dbUrl; - sqlWriteDateFormat = def_sqlWriteDateFormat; - sqlReadDateFormat = def_sqlReadDateFormat; - sqlTimeZone = def_sqlTimeZone; - keyGeneratorClass = def_keyGeneratorClass; - JdbcDriverClass = def_JdbcDriverClass; - recoverOutages = def_recoverOutages; - localAdminOnly = def_localAdminOnly; - reqStrongEncryption = false; - } - - public void setConfigFileName(String cfgName) - { - this.cfgFile = new File(cfgName); - } - - /** Loads configuration from specified config file. */ - public void loadConfig() - throws IOException - { - Logger.instance().warning( - LrgsMain.module + ":" + LrgsMain.EVT_CONFIG_CHANGE - + " Loading configuration file '" + cfgFile.getPath() + "'"); - lastLoadTime = System.currentTimeMillis(); - Properties props = new Properties(); - FileInputStream is = new FileInputStream(cfgFile); - props.load(is); - is.close(); - - PropertiesUtil.loadFromProps(this, props); - - this.enableDomsatRecv = false; - this.loadDomsat = false; - } - - /** @return msec time of last configuration load. */ - public long getLastLoadTime() { return lastLoadTime; } - - /** - * Checks to see if config file has changed, and if so, reloads it. - */ - public void checkConfig() - { - if (cfgFile.lastModified() > lastLoadTime) - { - try { loadConfig(); } - catch(IOException ex) - { - Logger.instance().failure("Cannot load config file '" - + cfgFile.getPath() + "': " + ex); - } - } - } - - /** @return the configuration File object. */ - public File getCfgFile() { return cfgFile; } - - /** - * Retrieves a 'miscellaneous' property. - * @param name property name - * @return property value or null if undefined. - */ - public String getMiscProp(String name) - { - return PropertiesUtil.getIgnoreCase(otherProps, name); - } - - public void setMiscProp(String name, String value) - { - otherProps.setProperty(name, value); - } - - /** - * Retrieves a 'miscellaneous' boolean property. - * If not defined, returns the specified default value. - * @param name property name - * @defaultV the default value - * @return property value as a boolean or 'defaultV' if undefined. - */ - public boolean getMiscBooleanProperty(String name, boolean defaultV) - { - String pv = getMiscProp(name); - if (pv == null) - return defaultV; - return TextUtil.str2boolean(pv); - } - - public int getMiscIntProperty(String name, int defaultV) - { - String pv = getMiscProp(name); - if (pv == null) - return defaultV; - try { return Integer.parseInt(pv); } - catch(Exception ex) - { - Logger.instance().warning("Bad format for config value '" + name - + "': expected integer"); - return defaultV; - } - } - - /** - * @return true if GR3110 interface is enabled. - */ - public boolean getEnableGR3110Recv() - { - return getMiscBooleanProperty("gr3110.enable", false); - } - - public int getGR3110Timeout() - { - return getMiscIntProperty("gr3110.timeout", 3600); - } - - public String getGR3110SerialPort() - { - return getMiscProp("gr3110.serialPort"); - } - - public String getGR3110CaptureFile() - { - return getMiscProp("gr3110.captureFile"); - } - - public String getGR3110SrcCode() - { - return getMiscProp("gr3110.srcCode"); - } - - public String getGR3110SatelliteCode() - { - return getMiscProp("gr3110.satelliteCode"); - } - - public boolean getGR3110ParityStrip() - { - return getMiscBooleanProperty("gr3110.parityStrip", true); - } - - /** - * The 'noTimeout' property says to never go 'unusable' because of a - * timeout. It is for and LRGS that should continue to function even - * when it is offline. - */ - public boolean getNoTimeout() - { - return getMiscBooleanProperty("noTimeout", false); - } - - public boolean getLoadDecodes() - { - return getMiscBooleanProperty("loadDecodes", false); - } - - public int getDamsNtTimeout() - { - return this.getMiscIntProperty("damsNtTimeout", 20); - } - - public String getSangomaIfName() - { - return getMiscProp("SangomaIfName"); - } - - /** @return URL for downloading PDT - defaults to NESDIS DCS location */ - public String getPdtUrl() { return pdtUrl; } - - /** True if this LRGS should do PDT validation for interfaces that don't - * already provide it. - */ - public boolean getDoPdtValidation() { return doPdtValidation; } - - /** @return URL for downloading channel map - default = nesdis ftp site */ - public String getChannelMapUrl() { return channelMapUrl; } - - public Properties getOtherProps() - { - return otherProps; - } - - - @Override - public PropertySpec[] getSupportedProps() - { - return miscPropSpecs; - } - - @Override - public boolean additionalPropsAllowed() - { - return true; - } - - public PasswordChecker getPasswordChecker() - { - return passwordChecker; - } - - public void setPasswordChecker(PasswordChecker passwordChecker) - { - this.passwordChecker = passwordChecker; - } + /** Last time configuration was loaded from file. */ + private long lastLoadTime; + + // Configuration variables settable from properties are public + + /** Directory containing all archive files */ + public String archiveDir; + + /** Number of day files to save in archive */ + public int numDayFiles; + + /** True if LRIT Input Interface is to be enabled. */ + public boolean enableLritRecv; + + /** for dams-nt LRIT connection, this is the host or IP address to connect to */ + public String lritHostName = null; + + /** For dams-nt LRIT connection, this is the port to connect to */ + public int lritPort = 17010; + + /** Hex string representing the DRGS Start Pattern */ + public String lritDamsNtStartPattern = "534D0D0A"; + + /** One of the HEADER_TYPE constants in LritFileMonitor */ + public char lritHeaderType; + + /** The 2-char msg source code to use for messages received from LRIT DAMS-NT */ + public String lritSrcCode = "LR"; + + /** True if DDS Input Interface is to be enabled. */ + public boolean enableDdsRecv; + + /** Name of DDS Receive Config File. */ + public String ddsRecvConfig; + + /** True if DRGS Input Interface is to be enabled. */ + public boolean enableDrgsRecv; + + /** Name of DRGS Receive Config File. */ + public String drgsRecvConfig; + + /** Port number for DDS Server to listen on. */ + public int ddsListenPort; + + /** If multi-NIC server and DDS only listens on one NIC, set bind addr. */ + public String ddsBindAddr; + + /** Maximum number of DDS clients to accept at any one time (0=no limit). */ + public int ddsMaxClients; + + /** True if DDS requires password authentication for message retreival. */ + public boolean ddsRequireAuth; + + /** True to enable administrative functions via DDS. */ + public boolean ddsAllowAdmin; + + /** DDS Usage Log Filename. */ + public String ddsUsageLog; + + /** DDS Network List Directory for mapping global names. */ + public String ddsNetlistDir; + + /** DDS Directory containing user sandbox directories. */ + public String ddsUserRootDir; + + /** DDS Directory containing user sandbox directories. */ + public String ddsUserRootDirLocal; + + /** Maximum number of downlink interfaces. */ + public int maxDownlinks; + + /** Assert Timeout if this many seconds goes by with no messages. */ + public int timeoutSeconds; + + /** File in which to place periodic HTML status snapshot. */ + public String htmlStatusFile; + + /** Number of seconds between HTML status snapshots. */ + public int htmlStatusSeconds; + + /** Merge preference 1: Highest priority. */ + public String mergePref1; + + /** Merge preference 2. */ + public String mergePref2; + + /** Merge preference 3. */ + public String mergePref3; + + /** Merge preference 4: Lowest priority. */ + public String mergePref4; + + /** True if DOMSAT Input Interface is to be even loaded. */ + public boolean loadDomsat; + + /** True if DOMSAT Input Interface is to be enabled. */ + public boolean enableDomsatRecv; + + /** Number of seconds after which DOMSAT declares a timeout. */ + public int domsatTimeout; + + /** Interface class to use for DOMSAT hardware. */ + public String domsatClass; + + /** NESDIS-ONLY: Enables output of DQM messages to COM1 serial port. */ + public boolean enableDapsDqm; + + /** NESDIS-ONLY: serial port for sending messages to DAPS. */ + public String dqmSerialPort; + + /** For bad DRGS's, option to ignore No-EOT-Termination condition. */ + public boolean ignoreDrgsNoEotTermination; + + /** Maximum size of a single lrgslog file */ + public int maxLogSize; + + /** Number of old log files to keep */ + public int numOldLogs; + + /** URL for accessing the LRGS database. */ + public String dbUrl; + + /** SimpleDateString format for writing to database. */ + public String sqlWriteDateFormat; + + /** SimpleDateString format for reading database. */ + public String sqlReadDateFormat; + + /** TimeZone for dates read from or written to the database */ + public String sqlTimeZone; + + /** Full package/class name for JDBC Driver */ + public String JdbcDriverClass; + + /** Name of class for key generation. */ + public String keyGeneratorClass; + + /** True if ddsrecv is to to recover discrete outages, else rt stream */ + public boolean recoverOutages; + + /** True if the network DCPs interface is enabled. */ + public boolean networkDcpEnable = false; + + /** URL for downloading PDT - defaults to NESDIS DCS location */ + public String pdtUrl = "https://dcs1.noaa.gov/pdts_compressed.txt"; + + /** True if this LRGS should do PDT validation for interfaces that don't + * already provide it. + */ + public boolean doPdtValidation = false; + + /** URL for downloading channel table from NOAA */ + public String channelMapUrl = + "https://dcs1.noaa.gov/chans_by_baud.txt"; + + /** Tells merge filter to prefer good messages from designated input */ + public boolean archivePreferredGood = false; + + /** If true, then only locally-assigned DDS accounts can do admin. */ + public boolean localAdminOnly = false; + + /** True to enable Iridium interface */ + public boolean iridiumEnabled = false; + + /** Port number for incoming Iridium SBD messages */ + public int iridiumPort = 10800; + + /** If specified, iridium raw-data will be captured here. */ + public String iridiumCaptureFile = null; + + /** Domsat Protocol Converter Host Name */ + public String dpcHost = null; + + /** Domsat Protocol Converter Port Number */ + public int dpcPort = 9000; + + /** Accept Abnormal Response Messages from DOMSAT (default=true) */ + public boolean acceptDomsatARMs = true; + + /** Store XMIT Records (i.e. the DCP Monitor Function) */ + public boolean storeXmitRecords = false; + + /** Meteosat LRIT can be VCS (default) or IBL*/ + public boolean iblLrit = false; + + /** Number of seconds after which to assert an LRIT timeout. */ + public int lritTimeout = 120; + + /** Enables ingest of EDL files via hot directory */ + public boolean edlIngestEnable = false; + + /** Specifies directory for incoming EDL files to be ingested into LRGS archive */ + public String edlIngestDirectory = "$LRGSHOME/edl-incoming"; + + /** If true, then subdirectories of edlIngestDirectory are recursively searched */ + public boolean edlIngestRecursive = false; + + /** If set, then only files with a specific suffix will be processed */ + public String edlFilenameSuffix = null; + + /** If set, then edl files will be moved here after processing */ + public String edlDoneDirectory = null; + + /** Max age of an LRIT message in seconds. Messages older than this are discarded. */ + public int lritMaxMsgAgeSec = 7200; + + /** Set to positive integer to enable minimum hourly checking on LRIT */ + public int lritMinHourly = 0; + + /** Set to positive integer to enable minimum hourly checking on DDS Recv */ + public int ddsMinHourly = 0; + + /** Set to positive integer to enable minimum hourly checking on EDL */ + public int edlMinHourly = 0; + + /** Set to positive integer to enable minimum hourly checking on DRGS */ + public int drgsMinHourly = 0; + + public boolean hritFileEnabled = false; + public String hritInputDir = null; + public String hritFilePrefix = null; + public String hritFileSuffix = null; + public String hritSourceCode = "HR"; + public String hritDoneDir = null; + public int hritTimeoutSec = 120; + public int hritFileMaxAgeSec = 7200; + + public static final boolean def_noaaportEnabled = false; + public static final int def_noaaportPort = 18000; + public static final String def_archiveDir = "."; + public static final int def_numDayFiles = 31; + public static final boolean def_enableLritRecv = false; + public static final char def_lritHeaderType = '6'; + public static final boolean def_enableDdsRecv = false; + public static final boolean def_enableDrgsRecv = false; + public static final int def_ddsListenPort = 16003; + public static final String def_ddsBindAddr = null; + public static final int def_ddsMaxClients = 150; + public static final boolean def_ddsRequireAuth = false; + public static final boolean def_ddsAllowAdmin = false; + public static final String def_ddsUsageLog = "$LRGSHOME/dds-log"; + public static final String def_ddsNetlistDir = "$LRGSHOME/netlist"; + public static final String def_ddsUserRootDir = "$LRGSHOME/users"; + public static final String def_ddsUserRootDirLocal = "$LRGSHOME/users.local"; + public static final int def_maxDownlinks = 32; + public static final int def_timeoutSeconds = 90; + public static final String def_ddsRecvConfig = "$LRGSHOME/ddsrecv.conf"; + public static final String def_drgsRecvConfig = "$LRGSHOME/drgsrecv.conf"; + public static final String def_htmlStatusFile = "$LRGSHOME/lrgsstatus.html"; + public static final int def_htmlStatusSeconds = 10; + public static final String def_mergePref1 = null; + public static final String def_mergePref2 = null; + public static final String def_mergePref3 = null; + public static final String def_mergePref4 = null; + public static final boolean def_enableDomsatRecv = false; + public static final int def_domsatTimeout = 60; + public static final boolean def_loadDomsat = false; + public static final boolean def_enableDapsDqm = false; + public static final String def_dqmSerialPort = "COM1"; + public static final String def_domsatClass = "lrgs.domsatrecv.DomsatSangoma"; + public static final boolean def_ignoreDrgsNoEotTermination = false; + public static final int def_maxLogSize = 20000000; // 20 meg. + public static final String def_dbUrl = null; + public static final String def_sqlWriteDateFormat = "''yyyy-MM-dd HH:mm:ss''"; + public static final String def_sqlReadDateFormat = "yyyy-MM-dd HH:mm:ss"; + public static final String def_sqlTimeZone = "UTC"; + public static final String def_keyGeneratorClass = "decodes.sql.SequenceKeyGenerator"; + public static final String def_JdbcDriverClass = "org.postgresql.Driver"; + public static final boolean def_recoverOutages = false; + public static final boolean def_localAdminOnly = false; + public static final String def_dpcHost = ""; + public static final int def_dpcPort = 9000; + public static final boolean def_enableDcpInterface = false; + public static final boolean def_storeXmitRecords = false; + public static final String def_dcpInterfaceXmlConfig = null; + + /** + * This contains the miscellaneous properties not represented on a custom + * GUI panel in rtstat. + */ + private PropertySpec miscPropSpecs[] = + { + new PropertySpec("loadDecodes", PropertySpec.BOOLEAN, + "Set to true to have DECODES database loaded at LRGS startup. Used in some" + + " circumstances to resolve network lists for DDS Receive"), + new PropertySpec("damsNtTimeout", PropertySpec.INT, + "If no data is received on a DAMS-NT socket in this many seconds, then issue a timeout" + + " warning and reconnect."), + new PropertySpec("passwordCheckerClass", PropertySpec.STRING, + "Name of class that does password checking. If not set, then all passwords accepted."), + new PropertySpec("localIpMask", PropertySpec.STRING, + "(e.g. 192.168.0.0/24) Local IP addresses will not be displayed on rtstat page"), + new PropertySpec("hideHostNames", PropertySpec.BOOLEAN, + "(default=false) Set to true to hide host names on the rtstat display."), + new PropertySpec("restrictEventsToAdmin", PropertySpec.BOOLEAN, + "(default=false) Set to true to disallow events to non-adminstrators " + + "on the rtstat display."), + + new PropertySpec("writeDacqEvents", PropertySpec.BOOLEAN, + "(default=false) if loadDecodes is also true, this means to create DACQ_EVENT " + + "entries in the database for INFO and higher-priority events."), + + }; + + /** + * This needs to be public so that PropertiesUtil.loadFromProps will add + * properties with names that don't match public attributes to it. + */ + public Properties otherProps = new Properties(); + + private PasswordChecker passwordChecker = null; + + /** If true, then Authenticated DDS connections must be done with SHA-256. */ + public boolean reqStrongEncryption = false; + + public static LrgsConfig instance() + { + if (_instance == null) + _instance = new LrgsConfig(); + return _instance; + } + + public LrgsConfig() + { + lastLoadTime = 0L; + archiveDir = def_archiveDir; + numDayFiles = def_numDayFiles; + enableLritRecv = def_enableLritRecv; + lritHeaderType = def_lritHeaderType; + enableDdsRecv = def_enableDdsRecv; + enableDrgsRecv = def_enableDrgsRecv; + ddsListenPort = def_ddsListenPort; + ddsBindAddr = def_ddsBindAddr; + ddsMaxClients = def_ddsMaxClients; + ddsRequireAuth = def_ddsRequireAuth; + ddsAllowAdmin = def_ddsAllowAdmin; + ddsUsageLog = def_ddsUsageLog; + ddsNetlistDir = def_ddsNetlistDir; + ddsUserRootDir = def_ddsUserRootDir; + ddsUserRootDirLocal = def_ddsUserRootDirLocal; + maxDownlinks = def_maxDownlinks; + timeoutSeconds = def_timeoutSeconds; + ddsRecvConfig = def_ddsRecvConfig; + drgsRecvConfig = def_drgsRecvConfig; + htmlStatusFile = def_htmlStatusFile; + htmlStatusSeconds = def_htmlStatusSeconds; + mergePref1 = def_mergePref1; + mergePref2 = def_mergePref2; + mergePref3 = def_mergePref3; + mergePref4 = def_mergePref4; + enableDomsatRecv = def_enableDomsatRecv; + domsatTimeout = def_domsatTimeout; + loadDomsat = def_loadDomsat; + enableDapsDqm = def_enableDapsDqm; + dqmSerialPort = def_dqmSerialPort; + domsatClass = def_domsatClass; + ignoreDrgsNoEotTermination = def_ignoreDrgsNoEotTermination; + maxLogSize = def_maxLogSize; + dbUrl = def_dbUrl; + sqlWriteDateFormat = def_sqlWriteDateFormat; + sqlReadDateFormat = def_sqlReadDateFormat; + sqlTimeZone = def_sqlTimeZone; + keyGeneratorClass = def_keyGeneratorClass; + JdbcDriverClass = def_JdbcDriverClass; + recoverOutages = def_recoverOutages; + localAdminOnly = def_localAdminOnly; + reqStrongEncryption = false; + } + + public void setConfigFileName(String cfgName) + { + this.cfgFile = new File(cfgName); + } + + /** Loads configuration from specified config file. */ + public void loadConfig() + throws IOException + { + Logger.instance().warning( + LrgsMain.module + ":" + LrgsMain.EVT_CONFIG_CHANGE + + " Loading configuration file '" + cfgFile.getPath() + "'"); + lastLoadTime = System.currentTimeMillis(); + Properties props = new Properties(); + FileInputStream is = new FileInputStream(cfgFile); + props.load(is); + is.close(); + + PropertiesUtil.loadFromProps(this, props); + + this.enableDomsatRecv = false; + this.loadDomsat = false; + } + + /** @return msec time of last configuration load. */ + public long getLastLoadTime() + { + return lastLoadTime; + } + + /** + * Checks to see if config file has changed, and if so, reloads it. + */ + public void checkConfig() + { + if (cfgFile.lastModified() > lastLoadTime) + { + try { loadConfig(); } + catch(IOException ex) + { + Logger.instance().failure("Cannot load config file '" + + cfgFile.getPath() + "': " + ex); + } + } + } + + /** @return the configuration File object. */ + public File getCfgFile() + { + return cfgFile; + } + + /** + * Retrieves a 'miscellaneous' property. + * @param name property name + * @return property value or null if undefined. + */ + public String getMiscProp(String name) + { + return PropertiesUtil.getIgnoreCase(otherProps, name); + } + + public void setMiscProp(String name, String value) + { + otherProps.setProperty(name, value); + } + + /** + * Retrieves a 'miscellaneous' boolean property. + * If not defined, returns the specified default value. + * @param name property name + * @defaultV the default value + * @return property value as a boolean or 'defaultV' if undefined. + */ + public boolean getMiscBooleanProperty(String name, boolean defaultV) + { + String pv = getMiscProp(name); + if (pv == null) + { + return defaultV; + } + return TextUtil.str2boolean(pv); + } + + public int getMiscIntProperty(String name, int defaultV) + { + String pv = getMiscProp(name); + if (pv == null) + { + return defaultV; + } + try + { + return Integer.parseInt(pv); + } + catch(Exception ex) + { + Logger.instance().warning("Bad format for config value '" + name + + "': expected integer"); + return defaultV; + } + } + + /** + * @return true if GR3110 interface is enabled. + */ + public boolean getEnableGR3110Recv() + { + return getMiscBooleanProperty("gr3110.enable", false); + } + + public int getGR3110Timeout() + { + return getMiscIntProperty("gr3110.timeout", 3600); + } + + public String getGR3110SerialPort() + { + return getMiscProp("gr3110.serialPort"); + } + + public String getGR3110CaptureFile() + { + return getMiscProp("gr3110.captureFile"); + } + + public String getGR3110SrcCode() + { + return getMiscProp("gr3110.srcCode"); + } + + public String getGR3110SatelliteCode() + { + return getMiscProp("gr3110.satelliteCode"); + } + + public boolean getGR3110ParityStrip() + { + return getMiscBooleanProperty("gr3110.parityStrip", true); + } + + /** + * The 'noTimeout' property says to never go 'unusable' because of a + * timeout. It is for and LRGS that should continue to function even + * when it is offline. + */ + public boolean getNoTimeout() + { + return getMiscBooleanProperty("noTimeout", false); + } + + public boolean getLoadDecodes() + { + return getMiscBooleanProperty("loadDecodes", false); + } + + public int getDamsNtTimeout() + { + return this.getMiscIntProperty("damsNtTimeout", 20); + } + + public String getSangomaIfName() + { + return getMiscProp("SangomaIfName"); + } + + /** @return URL for downloading PDT - defaults to NESDIS DCS location */ + public String getPdtUrl() + { + return pdtUrl; + } + + /** True if this LRGS should do PDT validation for interfaces that don't + * already provide it. + */ + public boolean getDoPdtValidation() + { + return doPdtValidation; + } + + /** @return URL for downloading channel map - default = nesdis ftp site */ + public String getChannelMapUrl() + { + return channelMapUrl; + } + + public Properties getOtherProps() + { + return otherProps; + } + + + @Override + public PropertySpec[] getSupportedProps() + { + return miscPropSpecs; + } + + @Override + public boolean additionalPropsAllowed() + { + return true; + } + + public PasswordChecker getPasswordChecker() + { + return passwordChecker; + } + + public void setPasswordChecker(PasswordChecker passwordChecker) + { + this.passwordChecker = passwordChecker; + } } diff --git a/src/main/java/lrgs/lrgsmain/LrgsInputException.java b/src/main/java/lrgs/lrgsmain/LrgsInputException.java index ebab55807..64fa0b092 100644 --- a/src/main/java/lrgs/lrgsmain/LrgsInputException.java +++ b/src/main/java/lrgs/lrgsmain/LrgsInputException.java @@ -6,7 +6,7 @@ * source code for your own purposes, except that no part of this source * code may be claimed to be proprietary. * -* Except for specific contractual terms between ILEX and the federal +* Except for specific contractual terms between ILEX and the federal * government, this source code is provided completely without warranty. * For more information contact: info@ilexeng.com * @@ -22,13 +22,13 @@ public class LrgsInputException extends Exception { - public LrgsInputException(String msg) - { - super(msg); - } + public LrgsInputException(String msg) + { + super(msg); + } - public LrgsInputException(String msg, Throwable cause) - { - super(msg,cause); - } + public LrgsInputException(String msg, Throwable cause) + { + super(msg,cause); + } } diff --git a/src/main/java/lrgs/rtstat/DdsRecvConDialog.java b/src/main/java/lrgs/rtstat/DdsRecvConDialog.java index 0c81ca6e0..ef0c7fc18 100644 --- a/src/main/java/lrgs/rtstat/DdsRecvConDialog.java +++ b/src/main/java/lrgs/rtstat/DdsRecvConDialog.java @@ -235,8 +235,10 @@ private void guiInit() * * @return javax.swing.JTextField */ - private JTextField getDdsDialogNumberField() { - if (ddsDialogNumberField == null) { + private JTextField getDdsDialogNumberField() + { + if (ddsDialogNumberField == null) + { ddsDialogNumberField = new JTextField(); } return ddsDialogNumberField; @@ -247,8 +249,10 @@ private JTextField getDdsDialogNumberField() { * * @return javax.swing.JCheckBox */ - private JCheckBox getDdsDialogEnabledCheck() { - if (ddsDialogEnabledCheck == null) { + private JCheckBox getDdsDialogEnabledCheck() + { + if (ddsDialogEnabledCheck == null) + { ddsDialogEnabledCheck = new JCheckBox(); ddsDialogEnabledCheck.setText(labels.getString( "DdsRecvConDialog.enabled")); @@ -261,8 +265,10 @@ private JCheckBox getDdsDialogEnabledCheck() { * * @return javax.swing.JTextField */ - private JTextField getDdsDialogHostField() { - if (ddsDialogHostField == null) { + private JTextField getDdsDialogHostField() + { + if (ddsDialogHostField == null) + { ddsDialogHostField = new JTextField(); } return ddsDialogHostField; @@ -273,8 +279,10 @@ private JTextField getDdsDialogHostField() { * * @return javax.swing.JTextField */ - private JTextField getDdsDialogNameField() { - if (ddsDialogNameField == null) { + private JTextField getDdsDialogNameField() + { + if (ddsDialogNameField == null) + { ddsDialogNameField = new JTextField(); } return ddsDialogNameField; @@ -285,8 +293,10 @@ private JTextField getDdsDialogNameField() { * * @return javax.swing.JTextField */ - private JTextField getDdsDialogPortField() { - if (ddsDialogPortField == null) { + private JTextField getDdsDialogPortField() + { + if (ddsDialogPortField == null) + { ddsDialogPortField = new JTextField(); } return ddsDialogPortField; @@ -297,8 +307,10 @@ private JTextField getDdsDialogPortField() { * * @return javax.swing.JTextField */ - private JTextField getDdsDialogUserField() { - if (ddsDialogUserField == null) { + private JTextField getDdsDialogUserField() + { + if (ddsDialogUserField == null) + { ddsDialogUserField = new JTextField(); } return ddsDialogUserField; @@ -309,8 +321,10 @@ private JTextField getDdsDialogUserField() { * * @return javax.swing.JCheckBox */ - private JCheckBox getDdsDialogPasswordCheck() { - if (ddsDialogPasswordCheck == null) { + private JCheckBox getDdsDialogPasswordCheck() + { + if (ddsDialogPasswordCheck == null) + { ddsDialogPasswordCheck = new JCheckBox(); ddsDialogPasswordCheck.setText( labels.getString("DdsRecvConDialog.usePassword")); @@ -324,12 +338,13 @@ private JCheckBox getDdsDialogPasswordCheck() { * * @return javax.swing.JComboBox */ - private JComboBox getDdsGroupCombo() { - if (ddsGroupCombo == null) { + private JComboBox getDdsGroupCombo() + { + if (ddsGroupCombo == null) + { ddsGroupCombo = new JComboBox(); ddsGroupCombo.addItem("Primary"); - ddsGroupCombo.addItem("Secondary"); - + ddsGroupCombo.addItem("Secondary"); } return ddsGroupCombo; } @@ -338,8 +353,10 @@ private JComboBox getDdsGroupCombo() { * * @return javax.swing.JCheckBox */ - private JCheckBox getDdsDialogDomsatCheck() { - if (ddsDialogDomsatCheck == null) { + private JCheckBox getDdsDialogDomsatCheck() + { + if (ddsDialogDomsatCheck == null) + { ddsDialogDomsatCheck = new JCheckBox(); ddsDialogDomsatCheck.setText( labels.getString("DdsRecvConDialog.seqNumbers")); @@ -375,8 +392,10 @@ public void actionPerformed(ActionEvent e) * * @return javax.swing.JButton */ - private JButton getDdsDialogCancelButton() { - if (ddsDialogCancelButton == null) { + private JButton getDdsDialogCancelButton() + { + if (ddsDialogCancelButton == null) + { ddsDialogCancelButton = new JButton(); ddsDialogCancelButton.setText(genericLabels.getString("cancel")); ddsDialogCancelButton.setPreferredSize(new Dimension(82, 26)); @@ -400,7 +419,9 @@ private void okButtonPressed() { wasOk = copyBackToObject(); if (wasOk) + { setVisible(false); + } } private void cancelButtonPressed() diff --git a/src/main/java/lrgs/rtstat/LrgsConfigDialog.java b/src/main/java/lrgs/rtstat/LrgsConfigDialog.java index fa2a8f087..ec395983f 100644 --- a/src/main/java/lrgs/rtstat/LrgsConfigDialog.java +++ b/src/main/java/lrgs/rtstat/LrgsConfigDialog.java @@ -59,3208 +59,3011 @@ import decodes.gui.PropertiesEditPanel; import decodes.gui.SortingListTable; import decodes.gui.SortingListTableModel; -import decodes.util.ResourceFactory; public class LrgsConfigDialog extends GuiDialog { - private static ResourceBundle labels = - RtStat.getLabels(); - private static ResourceBundle genericLabels = - RtStat.getGenericLabels(); - private DefaultListModel netlistListModel = new DefaultListModel(); - private DefaultTableModel netlistTableModel = new DefaultTableModel(); - private DdsSortingListTableModel ddsTableModel; - private DrgsSortingListTableModel drgsTableModel; - private JPanel centralPane = null; - private JTabbedPane tabbedPane = null; - private JPanel buttonPanel = null; // @jve:decl-index=0:visual-constraint="774,380" - private JButton okButton = null; - private JButton cancelButton = null; - private JButton applyButton = null; - private JPanel archiveConfigTab = null; -// private JPanel domsatConfigTab = null; - private JPanel ddsServerConfigTab = null; - private JPanel ddsRecvConfigTab = null; - private JPanel drgsConfigTab = null; - private JPanel miscConfigTab = null; - private NoaaportConfigPanel noaaConfigTab = null; - private JPanel lrgsArchiveConfigPanel = null; - private JPanel dataSourcePrefPanel = null; - private JLabel archiveDirectoryLabel = null; - private JLabel archiveLengthLabel = null; - private JLabel archiveTimeoutLabel = null; - private JLabel localStatusFileLabel = null; - private JLabel statusPeriodLabel = null; - private JLabel sharedNetlistDirectoryLabel = null; - private JTextField archiveDirField = null; - private JTextField archiveLengthField = null; - private JTextField archiveTimeoutField = null; - private JTextField localStatusFileField = null; - private JTextField statusPeriodField = null; - private JTextField sharedNetlistDirectoryField = null; - private JTextField ddsTimeoutField = new JTextField(9); - private JLabel preference1Label = null; - private JLabel preference2Label = null; - private JLabel preference3Label = null; - private JLabel preference4Label = null; - private JComboBox mergePref1Combo = null; - private JComboBox mergePref2Combo = null; - private JComboBox mergePref3Combo = null; - private JComboBox mergePref4Combo = null; -// private JPanel domsatPanel = null; -// private JCheckBox initializeDOMSATcheck = null; -// private JLabel domsatHardwareLabel = null; -// private JCheckBox domsatLinkCheck = null; -// private JLabel domsatTimeoutLabel = null; -// private JComboBox domsatHardwareCombo = null; -// private JTextField domsatTimeoutField = null; -// private JTextField domsatDpcHost = new JTextField();; -// private JTextField domsatDpcPort = new JTextField();; - private JTextField ddsListenPortField = null; - private JTextField ddsBindAddrField = null; - private JTextField ddsMaxClientsField = null; - private JTextField ddsParentDirectoryField = null; - private JTextField ddsLogFileField = null; - private JCheckBox ddsRequireAuthCheck = null; - private JPanel recoverPanel = null; - private JLabel recoveryLabel = null; -// private JComboBox recoveryCombo = null; - private JCheckBox enableDDSReceiveCheck = null; - private JLabel emptyLabel1 = null; - private JLabel emptyLabel2 = null; - private JLabel emptyLabel5 = null; - private JLabel nicLabel = null; - private JPanel connectionsPanel = null; // @jve:decl-index=0:visual-constraint="884,87" - private JPanel connectionsButtonPanel = null; - private JButton ddsConAddButton = null; // @jve:decl-index=0:visual-constraint="862,324" - private JButton ddsConEditButton = null; - private JButton ddsConDeleteButton = null; - private JButton ddsConMoveUpButton = null; - private JButton ddsConMoveDownButton = null; - private JButton ddsConTestButton = null; - private JPanel networkListsPanel = null; // @jve:decl-index=0:visual-constraint="862,260" - private JPanel networkListsButtonPanel = null; - private JButton networkListsAddButton = null; - private JButton networkListsDeleteButton = null; - private JPanel jPanel = null; - private JPanel drgsConfigPanel = null; - private JPanel drgsButtonPanel = null; - private JButton drgsAddButton = null; // @jve:decl-index=0:visual-constraint="891,230" - private JButton drgsEditButton = null; - private JButton drgsDeleteButton = null; - private JButton drgsTestButton = null; - private JScrollPane networkListsScrollPane = null; - private JList networkList = null; - private JTable networkListTable = null; - private JPanel drgsTablePanel = null; - private JCheckBox enableDRGSCheck = null; - private JTable drgsConTable = null; - private JTable ddsConTable = null; - private JPanel SqlDatabasePanel = null; // @jve:decl-index=0:visual-constraint="663,689" - private JPanel containerPanel = null; // @jve:decl-index=0:visual-constraint="373,705" - private JLabel sqlUrlLabel = null; - private JLabel sqlReadLabel = null; - private JLabel sqlWriteLabel = null; - private JTextField sqlUrlField = null; - private JTextField sqlReadField = null; - private JTextField sqlWriteField = null; - private JLabel sqlTimeZoneLabel = null; - private TimeZoneSelector sqlTimeZoneCombo = null; - private JLabel sqlDriverLabel = null; - private JLabel sqlKeyLabel = null; - private JTextField sqlDriverField = null; - private JTextField sqlKeyField = null; - private JScrollPane connectionsScrollPane = null; - private JScrollPane ddsReceiveScrollPane = null; - private JCheckBox pdtValidationCheck = null; - private JTextField pdtUrlField = new JTextField(); - private JTextField cdtUrlField = new JTextField(); - private JCheckBox localAdminOnlyCheck = new JCheckBox(); - private JTextField localSandboxDir = new JTextField(); - private JCheckBox goesXmitCheck = new JCheckBox("Save GOES Xmit Records"); - private JCheckBox requireStrongAuthCheck = new JCheckBox(); - - private String mergePrefs[] = { "(unspecified)", "DRGS", "HRIT", "DDS-Receive" }; - - private LrgsConfig lrgsConfig; // @jve:decl-index=0: - public DdsRecvSettings ddsSettings; - private DrgsInputSettings drgsSettings; - private DdsClientIf ddsClientIf = null; - private boolean netlistsModified = false; - private PropertiesEditPanel miscPanel = null; - private JPanel networkDcpTab = null; - private DrgsInputSettings networkDcpSettings; - private NetworkDcpCfgPanel networkDcpCfgPanel; - private JCheckBox preferredGoodCheck = new JCheckBox(); -// private JCheckBox acceptDomsatARMsCheck = new JCheckBox(); - private IridiumCfgPanel iridiumCfgTab = null; - private LritCfgPanel lritCfgPanel = null; - private HritFileCfgPanel hritFileCfgPanel = null; - private EdlConfigPanel edlConfigPanel = null; - private JTextField ddsMinHourlyField = new JTextField(9); - private JTextField drgsMinHourlyField = new JTextField(9); - - public LrgsConfigDialog(JFrame parent, String title) - { - super(parent, title, true); - pdtValidationCheck - = new JCheckBox(labels.getString( - "LrgsConfigDialog.enableScheChanVal")); - centralPane = new JPanel(); - centralPane.setLayout(new BorderLayout()); - centralPane.add(getTabbedPane(), BorderLayout.CENTER); - centralPane.add(getButtonPanel(),BorderLayout.SOUTH); - centralPane.setPreferredSize(new Dimension(720, 700)); - getContentPane().add(centralPane); - pack(); - } - - /** - * Clears all the controls, as if creating a new LRGS Configuration. - */ - public void clear() - { - lrgsConfig=null; - ddsSettings=null; - drgsSettings=null; - - //Archive Tab - getArchiveDirField().setText(""); - getArchiveLengthField().setText(""); - getArchiveTimeoutField().setText(""); - getLocalStatusFileField().setText(""); - getStatusPeriodField().setText(""); - getSharedNetlistDirectoryField().setText(""); - preferredGoodCheck.setSelected(false); - mergePref1Combo.setSelectedIndex(0); - mergePref2Combo.setSelectedIndex(0); - mergePref3Combo.setSelectedIndex(0); - mergePref4Combo.setSelectedIndex(0); - getSqlUrlField().setText(""); - getSqlReadField().setText(""); - getSqlWriteField().setText(""); - getSqlTimeZoneCombo().setSelectedItem("UTC"); - sqlDriverField.setText(""); - sqlKeyField.setText(""); - ddsTimeoutField.setText(""); - ddsMinHourlyField.setText(""); - drgsMinHourlyField.setText(""); - pdtValidationCheck.setSelected(false); - pdtUrlField.setText(""); - cdtUrlField.setText(""); - goesXmitCheck.setSelected(false); - - //Domsat Tab -// getInitializeDOMSATcheck().setSelected(false); -// getDomsatHardwareCombo().setSelectedItem(0); -// getDomsatTimeoutField().setText(""); -// getDomsatLinkCheck().setSelected(false); -// domsatDpcHost.setText(LrgsConfig.def_dpcHost); -// domsatDpcPort.setText("" + LrgsConfig.def_dpcPort); -// chkDpcEnabled(); -// acceptDomsatARMsCheck.setSelected(true); - - //dds server tab - getDdsListenPortField().setText(""); - getDdsBindAddrField().setText(""); - getDdsMaxClientsField().setText(""); - getDdsParentDirectoryField().setText(""); - getDdsLogFileField().setText(""); - getDdsRequireAuthCheck().setSelected(false); - - //DDS Receive tab -// recoveryCombo.setSelectedIndex(0); - enableDDSReceiveCheck.setSelected(true); - //netlistListModel.clear(); - netlistTableModel.getDataVector().removeAllElements(); - ddsTableModel.clear(); - - //DRGS tab - enableDRGSCheck.setSelected(false); - drgsTableModel.clear(); - - tabbedPane.setSelectedIndex(0); - - // Network DCP Tab - this.networkDcpCfgPanel.clear(); - } - - public void setConfig(LrgsConfig tmpLrgsConfig, - DdsRecvSettings tmpDdsSettings, DrgsInputSettings tmpDrgsSettings, - DrgsInputSettings networkDcpSettings) - { - this.lrgsConfig=tmpLrgsConfig; - this.ddsSettings=tmpDdsSettings; - this.drgsSettings=tmpDrgsSettings; - this.networkDcpSettings = networkDcpSettings; - - //Archive Tab - getArchiveDirField().setText(lrgsConfig.archiveDir); - getArchiveLengthField().setText(String.valueOf(lrgsConfig.numDayFiles)); - getArchiveTimeoutField().setText(String.valueOf(lrgsConfig.timeoutSeconds)); - getLocalStatusFileField().setText(lrgsConfig.htmlStatusFile); - getStatusPeriodField().setText(String.valueOf(lrgsConfig.htmlStatusSeconds)); - getSharedNetlistDirectoryField().setText(lrgsConfig.ddsNetlistDir); - preferredGoodCheck.setSelected(lrgsConfig.archivePreferredGood); - pdtValidationCheck.setSelected(lrgsConfig.getDoPdtValidation()); - pdtUrlField.setText(lrgsConfig.getPdtUrl()); - cdtUrlField.setText(lrgsConfig.getChannelMapUrl()); - for(int i=1; i 0 ? ("" + lrgsConfig.ddsMinHourly) : ""); - - for(NetlistGroupAssoc nga : ddsSettings.getNetlistGroupAssociations()) - { - Object[] obj = { nga.getNetlistName(), nga.getGroupName() }; - netlistTableModel.addRow(obj); - } - - ddsTableModel.setContents(ddsSettings); - - // DRGS Tab - drgsTableModel.setContents(drgsSettings); - enableDRGSCheck.setSelected(lrgsConfig.enableDrgsRecv); - drgsMinHourlyField.setText( - lrgsConfig.drgsMinHourly > 0 ? ("" + lrgsConfig.drgsMinHourly) : ""); - - // Network DCP Tab - networkDcpCfgPanel.setContents(networkDcpSettings, - lrgsConfig.networkDcpEnable); - - miscPanel.setPropertiesOwner(lrgsConfig); - } - - /** - * Copy data from controls back to the LrgsConfig object. - * @return true if anything was changed. - */ - private boolean copyBackLrgsConfig() - throws ParseException - { - boolean changed = false; - - String fieldName = "Archive Directory"; - try - { - //Archive Tab - String sv = getStringFieldValue(getArchiveDirField(), - lrgsConfig.def_archiveDir); - if (!TextUtil.strEqual(sv, lrgsConfig.archiveDir)) - { - lrgsConfig.archiveDir = sv; - changed = true; - } - - fieldName = "Archive Length"; - int iv = getIntFieldValue(getArchiveLengthField(), - lrgsConfig.def_numDayFiles); - if (lrgsConfig.numDayFiles != iv) - { - lrgsConfig.numDayFiles = iv; - changed = true; - } - - fieldName = "Archive Timeout"; - iv = getIntFieldValue(getArchiveTimeoutField(), - lrgsConfig.def_timeoutSeconds); - if (lrgsConfig.timeoutSeconds != iv) - { - lrgsConfig.timeoutSeconds = iv; - changed = true; - } - - fieldName = "Local Status File"; - sv = getStringFieldValue(getLocalStatusFileField(), - lrgsConfig.def_htmlStatusFile); - if (!TextUtil.strEqual(lrgsConfig.htmlStatusFile, sv)) - { - lrgsConfig.htmlStatusFile = sv; - changed = true; - } - - fieldName = "Status Period"; - iv = getIntFieldValue(getStatusPeriodField(), - lrgsConfig.def_htmlStatusSeconds); - if (lrgsConfig.htmlStatusSeconds != iv) - { - lrgsConfig.htmlStatusSeconds = iv; - changed = true; - } - - fieldName = "Netlist Directory"; - sv = getStringFieldValue(getSharedNetlistDirectoryField(), - lrgsConfig.def_ddsNetlistDir); - if (!TextUtil.strEqual(lrgsConfig.ddsNetlistDir, sv)) - { - lrgsConfig.ddsNetlistDir = sv; - changed = true; - } - - - boolean bv = preferredGoodCheck.isSelected(); - if (bv != lrgsConfig.archivePreferredGood) - { - lrgsConfig.archivePreferredGood = bv; - changed = true; - } - - fieldName = "Merge Pref1"; - iv = getMergePref1Combo().getSelectedIndex(); - sv = iv == 0 ? null : mergePrefs[iv]; - if (!TextUtil.strEqual(lrgsConfig.mergePref1, sv)) - { - lrgsConfig.mergePref1 = sv; - changed = true; - } - - fieldName = "Merge Pref2"; - iv = getMergePref2Combo().getSelectedIndex(); - sv = iv == 0 ? null : mergePrefs[iv]; - if (!TextUtil.strEqual(lrgsConfig.mergePref2, sv)) - { - lrgsConfig.mergePref2 = sv; - changed = true; - } - - fieldName = "Merge Pref3"; - iv = getMergePref3Combo().getSelectedIndex(); - sv = iv == 0 ? null : mergePrefs[iv]; - if (!TextUtil.strEqual(lrgsConfig.mergePref3, sv)) - { - lrgsConfig.mergePref3 = sv; - changed = true; - } - - fieldName = "Merge Pref4"; - iv = getMergePref4Combo().getSelectedIndex(); - sv = iv == 0 ? null : mergePrefs[iv]; - if (!TextUtil.strEqual(lrgsConfig.mergePref4, sv)) - { - lrgsConfig.mergePref4 = sv; - changed = true; - } - - fieldName = "SQL URL"; - sv = getStringFieldValue(getSqlUrlField(), lrgsConfig.def_dbUrl); - if (!TextUtil.strEqual(lrgsConfig.dbUrl, sv)) - { - lrgsConfig.dbUrl = sv; - changed = true; - } - - fieldName = "SQL Read Date Fmt"; - sv = getStringFieldValue(getSqlReadField(), - lrgsConfig.def_sqlReadDateFormat); - if (!TextUtil.strEqual(lrgsConfig.sqlReadDateFormat, sv)) - { - lrgsConfig.sqlReadDateFormat = sv; - changed = true; - } - - fieldName = "SQL Write Date Fmt"; - sv = getStringFieldValue(getSqlWriteField(), - lrgsConfig.def_sqlWriteDateFormat); - if (!TextUtil.strEqual(lrgsConfig.sqlWriteDateFormat, sv)) - { - lrgsConfig.sqlWriteDateFormat = sv; - changed = true; - } - - fieldName = "SQL Driver"; - sv = getStringFieldValue(sqlDriverField, - lrgsConfig.def_JdbcDriverClass); - if (!TextUtil.strEqual(lrgsConfig.JdbcDriverClass, sv)) - { - lrgsConfig.JdbcDriverClass = sv; - changed = true; - } - - fieldName = "SQL Key Generator"; - sv = getStringFieldValue(sqlKeyField, - lrgsConfig.def_keyGeneratorClass); - if (!TextUtil.strEqual(lrgsConfig.keyGeneratorClass, sv)) - { - lrgsConfig.keyGeneratorClass = sv; - changed = true; - } - - fieldName = "SQL Time Zone"; - sv = (String)getSqlTimeZoneCombo().getSelectedItem(); - if (!TextUtil.strEqual(lrgsConfig.sqlTimeZone, sv)) - { - lrgsConfig.sqlReadDateFormat = sv; - changed = true; - } - - fieldName = "GOES Xmit Check"; - bv = goesXmitCheck.isSelected(); - if (bv != lrgsConfig.storeXmitRecords) - { - lrgsConfig.storeXmitRecords = bv; - changed = true; - } - - fieldName = "PDT Validation Check"; - bv = pdtValidationCheck.isSelected(); - if (bv != lrgsConfig.getDoPdtValidation()) - { - lrgsConfig.doPdtValidation = bv; - changed = true; - } - - fieldName = "PDT URL"; - sv = pdtUrlField.getText().trim(); - if (!sv.equals(lrgsConfig.getPdtUrl())) - { - lrgsConfig.pdtUrl = sv; - changed = true; - } - - fieldName = "CDT URL"; - sv = cdtUrlField.getText().trim(); - if (!sv.equals(lrgsConfig.getChannelMapUrl())) - { - lrgsConfig.channelMapUrl = sv; - changed = true; - } - -// // DOMSAT Tab -// fieldName = "DOMSAT Load"; -// bv = getInitializeDOMSATcheck().isSelected(); -// if (lrgsConfig.loadDomsat != bv) -// { -// lrgsConfig.loadDomsat = bv; -// changed = true; -// } + private static ResourceBundle labels = + RtStat.getLabels(); + private static ResourceBundle genericLabels = + RtStat.getGenericLabels(); + private DefaultListModel netlistListModel = new DefaultListModel(); + private DefaultTableModel netlistTableModel = new DefaultTableModel(); + private DdsSortingListTableModel ddsTableModel; + private DrgsSortingListTableModel drgsTableModel; + private JPanel centralPane = null; + private JTabbedPane tabbedPane = null; + private JPanel buttonPanel = null; // @jve:decl-index=0:visual-constraint="774,380" + private JButton okButton = null; + private JButton cancelButton = null; + private JButton applyButton = null; + private JPanel archiveConfigTab = null; + private JPanel ddsServerConfigTab = null; + private JPanel ddsRecvConfigTab = null; + private JPanel drgsConfigTab = null; + private JPanel miscConfigTab = null; + private NoaaportConfigPanel noaaConfigTab = null; + private JPanel lrgsArchiveConfigPanel = null; + private JPanel dataSourcePrefPanel = null; + private JLabel archiveDirectoryLabel = null; + private JLabel archiveLengthLabel = null; + private JLabel archiveTimeoutLabel = null; + private JLabel localStatusFileLabel = null; + private JLabel statusPeriodLabel = null; + private JLabel sharedNetlistDirectoryLabel = null; + private JTextField archiveDirField = null; + private JTextField archiveLengthField = null; + private JTextField archiveTimeoutField = null; + private JTextField localStatusFileField = null; + private JTextField statusPeriodField = null; + private JTextField sharedNetlistDirectoryField = null; + private JTextField ddsTimeoutField = new JTextField(9); + private JLabel preference1Label = null; + private JLabel preference2Label = null; + private JLabel preference3Label = null; + private JLabel preference4Label = null; + private JComboBox mergePref1Combo = null; + private JComboBox mergePref2Combo = null; + private JComboBox mergePref3Combo = null; + private JComboBox mergePref4Combo = null; + private JTextField ddsListenPortField = null; + private JTextField ddsBindAddrField = null; + private JTextField ddsMaxClientsField = null; + private JTextField ddsParentDirectoryField = null; + private JTextField ddsLogFileField = null; + private JCheckBox ddsRequireAuthCheck = null; + private JPanel recoverPanel = null; + private JLabel recoveryLabel = null; + private JCheckBox enableDDSReceiveCheck = null; + private JLabel emptyLabel1 = null; + private JLabel emptyLabel2 = null; + private JLabel emptyLabel5 = null; + private JLabel nicLabel = null; + private JPanel connectionsPanel = null; // @jve:decl-index=0:visual-constraint="884,87" + private JPanel connectionsButtonPanel = null; + private JButton ddsConAddButton = null; // @jve:decl-index=0:visual-constraint="862,324" + private JButton ddsConEditButton = null; + private JButton ddsConDeleteButton = null; + private JButton ddsConMoveUpButton = null; + private JButton ddsConMoveDownButton = null; + private JButton ddsConTestButton = null; + private JPanel networkListsPanel = null; // @jve:decl-index=0:visual-constraint="862,260" + private JPanel networkListsButtonPanel = null; + private JButton networkListsAddButton = null; + private JButton networkListsDeleteButton = null; + private JPanel jPanel = null; + private JPanel drgsConfigPanel = null; + private JPanel drgsButtonPanel = null; + private JButton drgsAddButton = null; // @jve:decl-index=0:visual-constraint="891,230" + private JButton drgsEditButton = null; + private JButton drgsDeleteButton = null; + private JButton drgsTestButton = null; + private JScrollPane networkListsScrollPane = null; + private JTable networkListTable = null; + private JPanel drgsTablePanel = null; + private JCheckBox enableDRGSCheck = null; + private JTable drgsConTable = null; + private JTable ddsConTable = null; + private JPanel SqlDatabasePanel = null; // @jve:decl-index=0:visual-constraint="663,689" + private JPanel containerPanel = null; // @jve:decl-index=0:visual-constraint="373,705" + private JLabel sqlUrlLabel = null; + private JLabel sqlReadLabel = null; + private JLabel sqlWriteLabel = null; + private JTextField sqlUrlField = null; + private JTextField sqlReadField = null; + private JTextField sqlWriteField = null; + private JLabel sqlTimeZoneLabel = null; + private TimeZoneSelector sqlTimeZoneCombo = null; + private JLabel sqlDriverLabel = null; + private JLabel sqlKeyLabel = null; + private JTextField sqlDriverField = null; + private JTextField sqlKeyField = null; + private JScrollPane connectionsScrollPane = null; + private JScrollPane ddsReceiveScrollPane = null; + private JCheckBox pdtValidationCheck = null; + private JTextField pdtUrlField = new JTextField(); + private JTextField cdtUrlField = new JTextField(); + private JCheckBox localAdminOnlyCheck = new JCheckBox(); + private JTextField localSandboxDir = new JTextField(); + private JCheckBox goesXmitCheck = new JCheckBox("Save GOES Xmit Records"); + private JCheckBox requireStrongAuthCheck = new JCheckBox(); + + private String mergePrefs[] = { "(unspecified)", "DRGS", "HRIT", "DDS-Receive" }; + + private LrgsConfig lrgsConfig; // @jve:decl-index=0: + public DdsRecvSettings ddsSettings; + private DrgsInputSettings drgsSettings; + private DdsClientIf ddsClientIf = null; + private boolean netlistsModified = false; + private PropertiesEditPanel miscPanel = null; + private JPanel networkDcpTab = null; + private DrgsInputSettings networkDcpSettings; + private NetworkDcpCfgPanel networkDcpCfgPanel; + private JCheckBox preferredGoodCheck = new JCheckBox(); + private IridiumCfgPanel iridiumCfgTab = null; + private LritCfgPanel lritCfgPanel = null; + private HritFileCfgPanel hritFileCfgPanel = null; + private EdlConfigPanel edlConfigPanel = null; + private JTextField ddsMinHourlyField = new JTextField(9); + private JTextField drgsMinHourlyField = new JTextField(9); + + public LrgsConfigDialog(JFrame parent, String title) + { + super(parent, title, true); + pdtValidationCheck + = new JCheckBox(labels.getString( + "LrgsConfigDialog.enableScheChanVal")); + centralPane = new JPanel(); + centralPane.setLayout(new BorderLayout()); + centralPane.add(getTabbedPane(), BorderLayout.CENTER); + centralPane.add(getButtonPanel(),BorderLayout.SOUTH); + centralPane.setPreferredSize(new Dimension(720, 700)); + getContentPane().add(centralPane); + pack(); + } + + /** + * Clears all the controls, as if creating a new LRGS Configuration. + */ + public void clear() + { + lrgsConfig=null; + ddsSettings=null; + drgsSettings=null; + + //Archive Tab + getArchiveDirField().setText(""); + getArchiveLengthField().setText(""); + getArchiveTimeoutField().setText(""); + getLocalStatusFileField().setText(""); + getStatusPeriodField().setText(""); + getSharedNetlistDirectoryField().setText(""); + preferredGoodCheck.setSelected(false); + mergePref1Combo.setSelectedIndex(0); + mergePref2Combo.setSelectedIndex(0); + mergePref3Combo.setSelectedIndex(0); + mergePref4Combo.setSelectedIndex(0); + getSqlUrlField().setText(""); + getSqlReadField().setText(""); + getSqlWriteField().setText(""); + getSqlTimeZoneCombo().setSelectedItem("UTC"); + sqlDriverField.setText(""); + sqlKeyField.setText(""); + ddsTimeoutField.setText(""); + ddsMinHourlyField.setText(""); + drgsMinHourlyField.setText(""); + pdtValidationCheck.setSelected(false); + pdtUrlField.setText(""); + cdtUrlField.setText(""); + goesXmitCheck.setSelected(false); + + //dds server tab + getDdsListenPortField().setText(""); + getDdsBindAddrField().setText(""); + getDdsMaxClientsField().setText(""); + getDdsParentDirectoryField().setText(""); + getDdsLogFileField().setText(""); + getDdsRequireAuthCheck().setSelected(false); + + //DDS Receive tab + enableDDSReceiveCheck.setSelected(true); + netlistTableModel.getDataVector().removeAllElements(); + ddsTableModel.clear(); + + //DRGS tab + enableDRGSCheck.setSelected(false); + drgsTableModel.clear(); + + tabbedPane.setSelectedIndex(0); + + // Network DCP Tab + this.networkDcpCfgPanel.clear(); + } + + public void setConfig(LrgsConfig tmpLrgsConfig, + DdsRecvSettings tmpDdsSettings, DrgsInputSettings tmpDrgsSettings, + DrgsInputSettings networkDcpSettings) + { + this.lrgsConfig=tmpLrgsConfig; + this.ddsSettings=tmpDdsSettings; + this.drgsSettings=tmpDrgsSettings; + this.networkDcpSettings = networkDcpSettings; + + //Archive Tab + getArchiveDirField().setText(lrgsConfig.archiveDir); + getArchiveLengthField().setText(String.valueOf(lrgsConfig.numDayFiles)); + getArchiveTimeoutField().setText(String.valueOf(lrgsConfig.timeoutSeconds)); + getLocalStatusFileField().setText(lrgsConfig.htmlStatusFile); + getStatusPeriodField().setText(String.valueOf(lrgsConfig.htmlStatusSeconds)); + getSharedNetlistDirectoryField().setText(lrgsConfig.ddsNetlistDir); + preferredGoodCheck.setSelected(lrgsConfig.archivePreferredGood); + pdtValidationCheck.setSelected(lrgsConfig.getDoPdtValidation()); + pdtUrlField.setText(lrgsConfig.getPdtUrl()); + cdtUrlField.setText(lrgsConfig.getChannelMapUrl()); + for(int i=1; i 0 ? ("" + lrgsConfig.ddsMinHourly) : ""); + + for(NetlistGroupAssoc nga : ddsSettings.getNetlistGroupAssociations()) + { + Object[] obj = { nga.getNetlistName(), nga.getGroupName() }; + netlistTableModel.addRow(obj); + } + + ddsTableModel.setContents(ddsSettings); + + // DRGS Tab + drgsTableModel.setContents(drgsSettings); + enableDRGSCheck.setSelected(lrgsConfig.enableDrgsRecv); + drgsMinHourlyField.setText( + lrgsConfig.drgsMinHourly > 0 ? ("" + lrgsConfig.drgsMinHourly) : ""); + + // Network DCP Tab + networkDcpCfgPanel.setContents(networkDcpSettings, + lrgsConfig.networkDcpEnable); + + miscPanel.setPropertiesOwner(lrgsConfig); + } + + /** + * Copy data from controls back to the LrgsConfig object. + * @return true if anything was changed. + */ + private boolean copyBackLrgsConfig() + throws ParseException + { + boolean changed = false; + + String fieldName = "Archive Directory"; + try + { + //Archive Tab + String sv = getStringFieldValue(getArchiveDirField(), + lrgsConfig.def_archiveDir); + if (!TextUtil.strEqual(sv, lrgsConfig.archiveDir)) + { + lrgsConfig.archiveDir = sv; + changed = true; + } + + fieldName = "Archive Length"; + int iv = getIntFieldValue(getArchiveLengthField(), + lrgsConfig.def_numDayFiles); + if (lrgsConfig.numDayFiles != iv) + { + lrgsConfig.numDayFiles = iv; + changed = true; + } + + fieldName = "Archive Timeout"; + iv = getIntFieldValue(getArchiveTimeoutField(), + lrgsConfig.def_timeoutSeconds); + if (lrgsConfig.timeoutSeconds != iv) + { + lrgsConfig.timeoutSeconds = iv; + changed = true; + } + + fieldName = "Local Status File"; + sv = getStringFieldValue(getLocalStatusFileField(), + lrgsConfig.def_htmlStatusFile); + if (!TextUtil.strEqual(lrgsConfig.htmlStatusFile, sv)) + { + lrgsConfig.htmlStatusFile = sv; + changed = true; + } + + fieldName = "Status Period"; + iv = getIntFieldValue(getStatusPeriodField(), + lrgsConfig.def_htmlStatusSeconds); + if (lrgsConfig.htmlStatusSeconds != iv) + { + lrgsConfig.htmlStatusSeconds = iv; + changed = true; + } + + fieldName = "Netlist Directory"; + sv = getStringFieldValue(getSharedNetlistDirectoryField(), + lrgsConfig.def_ddsNetlistDir); + if (!TextUtil.strEqual(lrgsConfig.ddsNetlistDir, sv)) + { + lrgsConfig.ddsNetlistDir = sv; + changed = true; + } + + + boolean bv = preferredGoodCheck.isSelected(); + if (bv != lrgsConfig.archivePreferredGood) + { + lrgsConfig.archivePreferredGood = bv; + changed = true; + } + + fieldName = "Merge Pref1"; + iv = getMergePref1Combo().getSelectedIndex(); + sv = iv == 0 ? null : mergePrefs[iv]; + if (!TextUtil.strEqual(lrgsConfig.mergePref1, sv)) + { + lrgsConfig.mergePref1 = sv; + changed = true; + } + + fieldName = "Merge Pref2"; + iv = getMergePref2Combo().getSelectedIndex(); + sv = iv == 0 ? null : mergePrefs[iv]; + if (!TextUtil.strEqual(lrgsConfig.mergePref2, sv)) + { + lrgsConfig.mergePref2 = sv; + changed = true; + } + + fieldName = "Merge Pref3"; + iv = getMergePref3Combo().getSelectedIndex(); + sv = iv == 0 ? null : mergePrefs[iv]; + if (!TextUtil.strEqual(lrgsConfig.mergePref3, sv)) + { + lrgsConfig.mergePref3 = sv; + changed = true; + } + + fieldName = "Merge Pref4"; + iv = getMergePref4Combo().getSelectedIndex(); + sv = iv == 0 ? null : mergePrefs[iv]; + if (!TextUtil.strEqual(lrgsConfig.mergePref4, sv)) + { + lrgsConfig.mergePref4 = sv; + changed = true; + } + + fieldName = "SQL URL"; + sv = getStringFieldValue(getSqlUrlField(), lrgsConfig.def_dbUrl); + if (!TextUtil.strEqual(lrgsConfig.dbUrl, sv)) + { + lrgsConfig.dbUrl = sv; + changed = true; + } + + fieldName = "SQL Read Date Fmt"; + sv = getStringFieldValue(getSqlReadField(), + lrgsConfig.def_sqlReadDateFormat); + if (!TextUtil.strEqual(lrgsConfig.sqlReadDateFormat, sv)) + { + lrgsConfig.sqlReadDateFormat = sv; + changed = true; + } + + fieldName = "SQL Write Date Fmt"; + sv = getStringFieldValue(getSqlWriteField(), + lrgsConfig.def_sqlWriteDateFormat); + if (!TextUtil.strEqual(lrgsConfig.sqlWriteDateFormat, sv)) + { + lrgsConfig.sqlWriteDateFormat = sv; + changed = true; + } + + fieldName = "SQL Driver"; + sv = getStringFieldValue(sqlDriverField, + lrgsConfig.def_JdbcDriverClass); + if (!TextUtil.strEqual(lrgsConfig.JdbcDriverClass, sv)) + { + lrgsConfig.JdbcDriverClass = sv; + changed = true; + } + + fieldName = "SQL Key Generator"; + sv = getStringFieldValue(sqlKeyField, + lrgsConfig.def_keyGeneratorClass); + if (!TextUtil.strEqual(lrgsConfig.keyGeneratorClass, sv)) + { + lrgsConfig.keyGeneratorClass = sv; + changed = true; + } + + fieldName = "SQL Time Zone"; + sv = (String)getSqlTimeZoneCombo().getSelectedItem(); + if (!TextUtil.strEqual(lrgsConfig.sqlTimeZone, sv)) + { + lrgsConfig.sqlReadDateFormat = sv; + changed = true; + } + + fieldName = "GOES Xmit Check"; + bv = goesXmitCheck.isSelected(); + if (bv != lrgsConfig.storeXmitRecords) + { + lrgsConfig.storeXmitRecords = bv; + changed = true; + } + + fieldName = "PDT Validation Check"; + bv = pdtValidationCheck.isSelected(); + if (bv != lrgsConfig.getDoPdtValidation()) + { + lrgsConfig.doPdtValidation = bv; + changed = true; + } + + fieldName = "PDT URL"; + sv = pdtUrlField.getText().trim(); + if (!sv.equals(lrgsConfig.getPdtUrl())) + { + lrgsConfig.pdtUrl = sv; + changed = true; + } + + fieldName = "CDT URL"; + sv = cdtUrlField.getText().trim(); + if (!sv.equals(lrgsConfig.getChannelMapUrl())) + { + lrgsConfig.channelMapUrl = sv; + changed = true; + } + + // DDS Server Tab + fieldName = "DDS Listen Port"; + iv = getIntFieldValue(getDdsListenPortField(), + lrgsConfig.def_ddsListenPort); + if (lrgsConfig.ddsListenPort != iv) + { + lrgsConfig.ddsListenPort = iv; + changed = true; + } + + fieldName = "DDS Bind Addr"; + sv = getStringFieldValue(getDdsBindAddrField(), + lrgsConfig.def_ddsBindAddr); + if (!TextUtil.strEqual(lrgsConfig.ddsBindAddr, sv)) + { + lrgsConfig.ddsBindAddr = sv; + changed = true; + } + + fieldName = "DDS Max Clients"; + iv = getIntFieldValue(getDdsMaxClientsField(), + lrgsConfig.def_ddsMaxClients); + if (lrgsConfig.ddsMaxClients != iv) + { + lrgsConfig.ddsMaxClients = iv; + changed = true; + } + + fieldName = "DDS User Parent Dir"; + sv = getStringFieldValue(getDdsParentDirectoryField(), + lrgsConfig.def_ddsUserRootDir); + if (!TextUtil.strEqual(lrgsConfig.ddsUserRootDir, sv)) + { + lrgsConfig.ddsUserRootDir = sv; + changed = true; + } + + fieldName = "DDS Usage Log"; + sv = getStringFieldValue(getDdsLogFileField(), + lrgsConfig.def_ddsUsageLog); + if (!TextUtil.strEqual(lrgsConfig.ddsUsageLog, sv)) + { + lrgsConfig.ddsUsageLog = sv; + changed = true; + } + + fieldName = "DDS Require Auth"; + bv = getDdsRequireAuthCheck().isSelected(); + if (lrgsConfig.ddsRequireAuth != bv) + { + lrgsConfig.ddsRequireAuth = bv; + changed = true; + } + + fieldName = "DDS Local Admin Only"; + bv = localAdminOnlyCheck.isSelected(); + if (lrgsConfig.localAdminOnly != bv) + { + lrgsConfig.localAdminOnly = bv; + changed = true; + } + + bv = requireStrongAuthCheck.isSelected(); + if (lrgsConfig.reqStrongEncryption != bv) + { + lrgsConfig.reqStrongEncryption = bv; + changed = true; + } + + fieldName = "Local DDS User Dir"; + sv = getStringFieldValue(localSandboxDir, + lrgsConfig.def_ddsUserRootDirLocal); + if (!TextUtil.strEqual(lrgsConfig.ddsUserRootDirLocal, sv)) + { + lrgsConfig.ddsUserRootDirLocal = sv; + changed = true; + } + + // on the DDS Recv Tab + // MJM OpenDCS 6.2 does not support Outage recovery + lrgsConfig.recoverOutages = false; + + bv = enableDDSReceiveCheck.isSelected(); + if (lrgsConfig.enableDdsRecv != bv) + { + lrgsConfig.enableDdsRecv = bv; + changed = true; + } + + fieldName = "DDS Recv Timeout"; + iv = getIntFieldValue(ddsTimeoutField, 90); + if (ddsSettings.timeout != iv) + { + ddsSettings.timeout = iv; + changed = true; + } + + fieldName = "DDS Min Hourly"; + iv = getIntFieldValue(ddsMinHourlyField, 0); + if (lrgsConfig.ddsMinHourly != iv) + { + lrgsConfig.ddsMinHourly = iv; + changed = true; + } + + fieldName = "DRGS Min Hourly"; + iv = getIntFieldValue(drgsMinHourlyField, 0); + if (lrgsConfig.drgsMinHourly != iv) + { + lrgsConfig.drgsMinHourly = iv; + changed = true; + } + + + // On the DRGS Tab + bv = enableDRGSCheck.isSelected(); + if (lrgsConfig.enableDrgsRecv != bv) + { + lrgsConfig.enableDrgsRecv = bv; + changed = true; + } + + // On the Network Dcp tab + bv = networkDcpCfgPanel.networkDcpEnable(); + if (lrgsConfig.networkDcpEnable != bv) + { + lrgsConfig.networkDcpEnable = bv; + changed = true; + } + + // On the 'misc' tab + if (miscPanel.hasChanged()) + { + miscPanel.saveChanges(); + changed = true; + } + } + catch(ParseException ex) + { + String msg = LoadResourceBundle.sprintf( + labels.getString("LrgsConfigDialog.invalidValueErr"), + fieldName); + showError(msg); + throw new ParseException(msg, 0); + } + return changed; + } + + /** + * Copy data from controls back to the DdsRecvSettings object. + * @return true if anything was changed. + */ + private boolean copyBackDdsSettings() + { + if (!ddsTableModel.modified && !netlistsModified) + return false; + + ddsSettings.resetToDefaults(); + for(DdsRecvConnectCfg cc : ddsTableModel.cons) + ddsSettings.connectCfgs.add(cc); + + //DDS Receive tab + + for(int i = 0; i < netlistTableModel.getRowCount(); i++) + { + String netlistName = (String)netlistTableModel.getValueAt(i,0); + netlistName = netlistName.trim(); + if (netlistName.length() == 0) + continue; + + String group = (String)netlistTableModel.getValueAt(i,1); + if (group == null || group.trim().length() == 0) + group = NetlistGroupAssoc.DEFAULT_GROUP; + + ddsSettings.addNetlistAssoc(netlistName, group); + } + + return true; + } + + /** + * Copy data from controls back to the DrgsSettings object. + * @return true if anything was changed. + */ + private boolean copyBackDrgsConfig() + { + if (!drgsTableModel.modified) + return false; + + drgsSettings.resetToDefaults(); + + for (DrgsConnectCfg cc : drgsTableModel.cons) + drgsSettings.connections.add(cc); + return true; + } + + /** + * Copy data from controls back to the Network DCP Settings object. + * @return true if anything was changed. + */ + private boolean copyBackNetworkDcpConfig() + { + // On the Network DCP Tab + if (!networkDcpCfgPanel.hasChanged()) + return false; + + networkDcpSettings.resetToDefaults(); + for(DrgsConnectCfg dcc : networkDcpCfgPanel.getConnections()) + networkDcpSettings.connections.add(dcc); + + return true; + } + + public void setDdsClientIf(DdsClientIf dcif) + { + ddsClientIf = dcif; + } + + /** + * This method initializes tabbedPane + * + * @return javax.swing.JTabbedPane + */ + private JTabbedPane getTabbedPane() + { + if (tabbedPane == null) + { + tabbedPane = new JTabbedPane(); + tabbedPane.addTab(labels.getString("LrgsConfigDialog.archiveTab"), + null, getArchiveConfigTab(), null); + tabbedPane.addTab(labels.getString("LrgsConfigDialog.DDSServerTab"), + null, getDdsServerConfigTab(), null); + tabbedPane.addTab(labels.getString("LrgsConfigDialog.DDSReceiveTab"), + null, getDdsRecvConfigTab(), null); + tabbedPane.addTab(labels.getString("LrgsConfigDialog.DRGSTab"), + null, getDrgsConfigTab(), null); + tabbedPane.addTab(labels.getString("LrgsConfigDialog.networkDcpTab"), + null, getNetworkDcpTab(), null); + noaaConfigTab = new NoaaportConfigPanel(this); + tabbedPane.addTab(noaaConfigTab.getLabel(), noaaConfigTab); + iridiumCfgTab = new IridiumCfgPanel(this); + tabbedPane.addTab(iridiumCfgTab.getLabel(), iridiumCfgTab); + lritCfgPanel = new LritCfgPanel(this); + tabbedPane.addTab(lritCfgPanel.getLabel(), lritCfgPanel); + hritFileCfgPanel = new HritFileCfgPanel(this); + tabbedPane.addTab(hritFileCfgPanel.getLabel(), hritFileCfgPanel); + edlConfigPanel = new EdlConfigPanel(this); + tabbedPane.addTab(edlConfigPanel.getLabel(), edlConfigPanel); + + tabbedPane.addTab(labels.getString("LrgsConfigDialog.miscTab"), + null, getMiscConfigTab(), + labels.getString("LrgsConfigDialog.miscPars")); + + } + return tabbedPane; + } + + /** + * This method initializes buttonPanel + * + * @return javax.swing.JPanel + */ + private JPanel getButtonPanel() { + if (buttonPanel == null) { + FlowLayout flowLayout = new FlowLayout(); + flowLayout.setHgap(20); + flowLayout.setVgap(10); + buttonPanel = new JPanel(); + buttonPanel.setLayout(flowLayout); + buttonPanel.setSize(new Dimension(238, 75)); + buttonPanel.add(getOkButton(), null); + buttonPanel.add(getCancelButton(), null); + buttonPanel.add(getApplyButton(), null); + } + return buttonPanel; + } + + /** + * This method initializes okButton + * + * @return javax.swing.JButton + */ + private JButton getOkButton() + { + if (okButton == null) + { + okButton = new JButton(); + okButton.setText(genericLabels.getString("OK")); + okButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + okPressed(); + } + }); + } + return okButton; + } + + /** + * This method initializes cancelButton + * + * @return javax.swing.JButton + */ + private JButton getCancelButton() + { + if (cancelButton == null) + { + cancelButton = new JButton(); + cancelButton.setText(genericLabels.getString("cancel")); + cancelButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + cancelPressed(); + } + }); + } + return cancelButton; + } + + /** + * This method initializes applyButton + * + * @return javax.swing.JButton + */ + private JButton getApplyButton() + { + if (applyButton == null) + { + applyButton = new JButton(); + applyButton.setText(labels.getString("LrgsConfigDialog.apply")); + applyButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + applyPressed(true); + } + }); + } + return applyButton; + } + + /** + * This method initializes archiveConfigTab + * + * @return javax.swing.JPanel + */ + private JPanel getArchiveConfigTab() { + if (archiveConfigTab == null) { + archiveConfigTab = new JPanel(); + archiveConfigTab.setLayout(new BoxLayout(getArchiveConfigTab(), BoxLayout.Y_AXIS)); + archiveConfigTab.add(getLrgsArchiveConfigPanel(), null); + archiveConfigTab.add(getContainerPanel(),null); + } + return archiveConfigTab; + } + + /** + * This method initializes ddsServerConfigTab + * + * @return javax.swing.JPanel + */ + private JPanel getDdsServerConfigTab() + { + if (ddsServerConfigTab == null) + { + ddsServerConfigTab = new JPanel(); + ddsServerConfigTab.setLayout(new GridBagLayout()); + ddsServerConfigTab.setBorder(BorderFactory.createTitledBorder(null, + labels.getString("LrgsConfigDialog.ddsLRGSDDSTitle"), + TitledBorder.CENTER, TitledBorder.BELOW_TOP, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); + + ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsListeningPort")), + new GridBagConstraints(0, 0, 1, 1, 0, .5, + GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, + new Insets(6, 0, 6, 2), 0, 0)); + ddsServerConfigTab.add(getDdsListenPortField(), + new GridBagConstraints(1, 0, 1, 1, .25, 0., + GridBagConstraints.SOUTHWEST, GridBagConstraints.HORIZONTAL, + new Insets(6, 0, 6, 0), 0, 0)); + + ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsBindIPAddress")), + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(6, 0, 6, 2), 0, 0)); + ddsServerConfigTab.add(getDdsBindAddrField(), + new GridBagConstraints(1, 1, 1, 1, 0.5, 0.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(6, 0, 6, 0), 80, 0)); + ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsMultiNICSystems")), + new GridBagConstraints(2, 1, 1, 1, 0.5, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(6, 0, 6, 10), 0, 0)); + + ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsMaxClients")), + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(6, 10, 6, 2), 0, 0)); + ddsServerConfigTab.add(getDdsMaxClientsField(), + new GridBagConstraints(1, 2, 1, 1, 0.5, 0.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(6, 0, 6, 0), 0, 0)); + + ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsSandboxDir")), + new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(6, 10, 6, 2), 0, 0)); + ddsServerConfigTab.add(getDdsParentDirectoryField(), + new GridBagConstraints(1, 3, 2, 1, 1.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(6, 0, 6, 40), 0, 0)); + + ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsUsageLogFile")), + new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(6, 10, 6, 2), 0, 0)); + ddsServerConfigTab.add(getDdsLogFileField(), + new GridBagConstraints(1, 4, 2, 1, 1.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(6, 0, 6, 40), 0, 0)); + + ddsServerConfigTab.add(getDdsRequireAuthCheck(), + new GridBagConstraints(1, 5, 2, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(6, 0, 6, 0), 0, 0)); + + localAdminOnlyCheck.setText("Local Administrators Only"); + localAdminOnlyCheck.setToolTipText( + "Do not allow administration from remotely shared accounts."); + ddsServerConfigTab.add(localAdminOnlyCheck, + new GridBagConstraints(1, 6, 2, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(6, 0, 6, 5), 0, 0)); + + requireStrongAuthCheck.setText("Require SHA-256 Authentication"); + ddsServerConfigTab.add(requireStrongAuthCheck, + new GridBagConstraints(1, 7, 2, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(6, 0, 6, 5), 0, 0)); + + JLabel lb = new JLabel("Local Sandbox Directory:"); + ddsServerConfigTab.add(lb, + new GridBagConstraints(0, 8, 1, 1, 0.0, 0.5, + GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(6, 10, 6, 2), 0, 0)); + ddsServerConfigTab.add(localSandboxDir, + new GridBagConstraints(1, 8, 1, 1, 1.0, 0.5, + GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + new Insets(5, 0, 5, 40), 0, 0)); + } + return ddsServerConfigTab; + } + + /** + * This method initializes ddsRecvConfigTab + * + * @return javax.swing.JPanel + */ + private JPanel getDdsRecvConfigTab() { + if (ddsRecvConfigTab == null) { + ddsRecvConfigTab = new JPanel(); + ddsRecvConfigTab.setLayout(new BoxLayout(getDdsRecvConfigTab(), BoxLayout.Y_AXIS)); + ddsRecvConfigTab.add(getRecoverPanel(), null); + ddsRecvConfigTab.add(getConnectionsPanel(),null); + ddsRecvConfigTab.add(getNetworkListsPanel(),null); + } + return ddsRecvConfigTab; + } + + /** + * This method initializes drgsConfigTab + * + * @return javax.swing.JPanel + */ + private JPanel getDrgsConfigTab() { + if (drgsConfigTab == null) { + drgsConfigTab = new JPanel(); + drgsConfigTab.setLayout( + new BoxLayout(drgsConfigTab, BoxLayout.Y_AXIS)); + drgsConfigTab.add(getJPanel(), null); + } + return drgsConfigTab; + } + + private JPanel getMiscConfigTab() + { + BorderLayout bl = new BorderLayout(); + miscConfigTab = new JPanel(bl); + JLabel lab = new JLabel(labels.getString( + "LrgsConfigDialog.miscPars")); + miscConfigTab.add(lab, BorderLayout.NORTH); + miscPanel = new PropertiesEditPanel(new Properties()); + miscConfigTab.add(miscPanel, BorderLayout.CENTER); + return miscConfigTab; + } + + private JPanel getNetworkDcpTab() + { + networkDcpTab = new JPanel(new BorderLayout()); + networkDcpCfgPanel = new NetworkDcpCfgPanel(this); + networkDcpTab.add(networkDcpCfgPanel, BorderLayout.CENTER); + return networkDcpTab; + } + + /** + * This method initializes lrgsArchiveConfigPanel + * + * @return javax.swing.JPanel + */ + private JPanel getLrgsArchiveConfigPanel() { + if (lrgsArchiveConfigPanel == null) { + GridBagConstraints archiveDirectoryLabelConstraints = new GridBagConstraints(); + archiveDirectoryLabelConstraints.gridx = 0; + archiveDirectoryLabelConstraints.gridy = 0; + archiveDirectoryLabelConstraints.anchor = GridBagConstraints.SOUTHEAST; + archiveDirectoryLabelConstraints.weightx = 1.0; + archiveDirectoryLabelConstraints.weighty = 0.5; + archiveDirectoryLabelConstraints.insets = new Insets(2, 0, 2, 2); + archiveDirectoryLabelConstraints.fill = GridBagConstraints.NONE; + archiveDirectoryLabel = new JLabel(); + archiveDirectoryLabel.setText(labels.getString( + "LrgsConfigDialog.archiveDirectory")); + + GridBagConstraints archiveDirFieldConstraints = new GridBagConstraints(); + archiveDirFieldConstraints.gridx = 1; + archiveDirFieldConstraints.gridy = 0; + archiveDirFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + archiveDirFieldConstraints.weightx = 1.0; + archiveDirFieldConstraints.weighty = 0.5; + archiveDirFieldConstraints.gridwidth = 3; + archiveDirFieldConstraints.anchor = GridBagConstraints.SOUTHWEST; + archiveDirFieldConstraints.insets = new Insets(2, 0, 2, 40); + + GridBagConstraints emptyLabel2Constraints = new GridBagConstraints(); + emptyLabel2Constraints.gridx = 2; + emptyLabel2Constraints.fill = GridBagConstraints.BOTH; + emptyLabel2Constraints.weightx = 2.0D; + emptyLabel2Constraints.gridy = 2; + emptyLabel2 = new JLabel(); + emptyLabel2.setText(""); + + GridBagConstraints emptyLabel1Constraints = new GridBagConstraints(); + emptyLabel1Constraints.gridx = 3; + emptyLabel1Constraints.weightx = 2.0D; + emptyLabel1Constraints.fill = GridBagConstraints.BOTH; + emptyLabel1Constraints.gridwidth = 1; + emptyLabel1Constraints.gridy = 1; + emptyLabel1 = new JLabel(); + emptyLabel1.setText(""); + + GridBagConstraints statusPeriodFieldConstraints = new GridBagConstraints(); + statusPeriodFieldConstraints.fill = GridBagConstraints.BOTH; + statusPeriodFieldConstraints.gridy = 4; + statusPeriodFieldConstraints.weightx = 1.0; + statusPeriodFieldConstraints.anchor = GridBagConstraints.WEST; + statusPeriodFieldConstraints.insets = new Insets(2, 0, 2, 0); + statusPeriodFieldConstraints.gridx = 1; + + GridBagConstraints localStatusFileFieldConstraints = new GridBagConstraints(); + localStatusFileFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + localStatusFileFieldConstraints.gridy = 3; + localStatusFileFieldConstraints.weightx = 2.0D; + localStatusFileFieldConstraints.insets = new Insets(2, 0, 2, 40); + localStatusFileFieldConstraints.gridwidth = 3; + localStatusFileFieldConstraints.gridx = 1; + + GridBagConstraints archiveTimeoutFieldConstraints = new GridBagConstraints(); + archiveTimeoutFieldConstraints.fill = GridBagConstraints.BOTH; + archiveTimeoutFieldConstraints.gridy = 2; + archiveTimeoutFieldConstraints.weightx = 1.0; + archiveTimeoutFieldConstraints.anchor = GridBagConstraints.WEST; + archiveTimeoutFieldConstraints.insets = new Insets(2, 0, 2, 0); + archiveTimeoutFieldConstraints.gridx = 1; + + GridBagConstraints archiveLengthFieldConstraints = new GridBagConstraints(); + archiveLengthFieldConstraints.fill = GridBagConstraints.BOTH; + archiveLengthFieldConstraints.gridy = 1; + archiveLengthFieldConstraints.weightx = 1.0; + archiveLengthFieldConstraints.anchor = GridBagConstraints.WEST; + archiveLengthFieldConstraints.insets = new Insets(2, 0, 2, 0); + archiveLengthFieldConstraints.gridx = 1; + + + GridBagConstraints statusPeriodLabelConstraints = new GridBagConstraints(); + statusPeriodLabelConstraints.gridx = 0; + statusPeriodLabelConstraints.anchor = GridBagConstraints.EAST; + statusPeriodLabelConstraints.weightx = 1.0D; + statusPeriodLabelConstraints.insets = new Insets(2, 0, 3, 2); + statusPeriodLabelConstraints.gridy = 4; + statusPeriodLabel = new JLabel(); + statusPeriodLabel.setText(labels.getString( + "LrgsConfigDialog.statusPeriod")); + + GridBagConstraints localStatusFileLabelConstraints = new GridBagConstraints(); + localStatusFileLabelConstraints.gridx = 0; + localStatusFileLabelConstraints.anchor = GridBagConstraints.EAST; + localStatusFileLabelConstraints.weightx = 1.0D; + localStatusFileLabelConstraints.insets = new Insets(2, 0, 3, 2); + localStatusFileLabelConstraints.gridy = 3; + localStatusFileLabel = new JLabel(); + localStatusFileLabel.setText(labels.getString( + "LrgsConfigDialog.localStatusFile")); + + GridBagConstraints archiveTimeoutLabelConstraints = new GridBagConstraints(); + archiveTimeoutLabelConstraints.gridx = 0; + archiveTimeoutLabelConstraints.anchor = GridBagConstraints.EAST; + archiveTimeoutLabelConstraints.weightx = 1.0D; + archiveTimeoutLabelConstraints.insets = new Insets(2, 40, 3, 2); + archiveTimeoutLabelConstraints.gridy = 2; + archiveTimeoutLabel = new JLabel(); + archiveTimeoutLabel.setText(labels.getString( + "LrgsConfigDialog.archiveTimeout")); + + GridBagConstraints archiveLengthLabelConstraints = new GridBagConstraints(); + archiveLengthLabelConstraints.gridx = 0; + archiveLengthLabelConstraints.anchor = GridBagConstraints.EAST; + archiveLengthLabelConstraints.weightx = 1.0D; + archiveLengthLabelConstraints.insets = new Insets(2, 0, 3, 2); + archiveLengthLabelConstraints.gridy = 1; + archiveLengthLabel = new JLabel(); + archiveLengthLabel.setText(labels.getString( + "LrgsConfigDialog.archiveLength")); + archiveLengthLabel.setHorizontalTextPosition(SwingConstants.RIGHT); + archiveLengthLabel.setHorizontalAlignment(SwingConstants.RIGHT); + + GridBagConstraints sharedNetlistDirectoryLabelConstraints = new GridBagConstraints(); + sharedNetlistDirectoryLabelConstraints.gridx = 0; + sharedNetlistDirectoryLabelConstraints.anchor = GridBagConstraints.EAST; + sharedNetlistDirectoryLabelConstraints.weightx = 1.0D; + sharedNetlistDirectoryLabelConstraints.weighty = 0.5; + sharedNetlistDirectoryLabelConstraints.insets = new Insets(2, 0, 2, 2); + sharedNetlistDirectoryLabelConstraints.gridy = 5; + sharedNetlistDirectoryLabel = new JLabel(); + sharedNetlistDirectoryLabel.setText(labels.getString( + "LrgsConfigDialog.sharedNetlistDir")); + + GridBagConstraints sharedNetlistDirectoryFieldConstraints = new GridBagConstraints(); + sharedNetlistDirectoryFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + sharedNetlistDirectoryFieldConstraints.anchor = GridBagConstraints.WEST; + sharedNetlistDirectoryFieldConstraints.gridy = 5; + sharedNetlistDirectoryFieldConstraints.weightx = 2.0D; + sharedNetlistDirectoryFieldConstraints.weighty = 0.5; + sharedNetlistDirectoryFieldConstraints.insets = new Insets(2, 0, 2, 40); + sharedNetlistDirectoryFieldConstraints.gridwidth = 3; + sharedNetlistDirectoryFieldConstraints.gridx = 1; + + lrgsArchiveConfigPanel = new JPanel(); + lrgsArchiveConfigPanel.setLayout(new GridBagLayout()); + lrgsArchiveConfigPanel.setBorder(BorderFactory.createTitledBorder(null, + labels.getString("LrgsConfigDialog.archiveConfigTitle"), + TitledBorder.CENTER, TitledBorder.BELOW_TOP, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); + lrgsArchiveConfigPanel.add(archiveDirectoryLabel, archiveDirectoryLabelConstraints); + lrgsArchiveConfigPanel.add(archiveLengthLabel, archiveLengthLabelConstraints); + lrgsArchiveConfigPanel.add(archiveTimeoutLabel, archiveTimeoutLabelConstraints); + lrgsArchiveConfigPanel.add(localStatusFileLabel, localStatusFileLabelConstraints); + lrgsArchiveConfigPanel.add(statusPeriodLabel, statusPeriodLabelConstraints); + lrgsArchiveConfigPanel.add(sharedNetlistDirectoryLabel, sharedNetlistDirectoryLabelConstraints); + lrgsArchiveConfigPanel.add(getArchiveDirField(), archiveDirFieldConstraints); + lrgsArchiveConfigPanel.add(getArchiveLengthField(), archiveLengthFieldConstraints); + lrgsArchiveConfigPanel.add(getArchiveTimeoutField(), archiveTimeoutFieldConstraints); + lrgsArchiveConfigPanel.add(getLocalStatusFileField(), localStatusFileFieldConstraints); + lrgsArchiveConfigPanel.add(getStatusPeriodField(), statusPeriodFieldConstraints); + lrgsArchiveConfigPanel.add(getSharedNetlistDirectoryField(), sharedNetlistDirectoryFieldConstraints); + lrgsArchiveConfigPanel.add(emptyLabel1, emptyLabel1Constraints); + lrgsArchiveConfigPanel.add(emptyLabel2, emptyLabel2Constraints); + + lrgsArchiveConfigPanel.add(pdtValidationCheck, + new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(2, 0, 2, 15), 0, 0)); + + lrgsArchiveConfigPanel.add( + new JLabel(labels.getString("LrgsConfigDialog.PDTURL")), + new GridBagConstraints(0, 7, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(2, 10, 2, 2), 0, 0)); + + lrgsArchiveConfigPanel.add(pdtUrlField, + new GridBagConstraints(1, 7, 1, 1, 1.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 0, 2, 20), 0, 0)); + + lrgsArchiveConfigPanel.add( + new JLabel(labels.getString("LrgsConfigDialog.CDTURL")), + new GridBagConstraints(0, 8, 1, 1, 0.0, 0.5, + GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, + new Insets(2, 10, 2, 2), 0, 0)); + + lrgsArchiveConfigPanel.add(cdtUrlField, + new GridBagConstraints(1, 8, 1, 1, 1.0, 0.5, + GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 0, 2, 20), 0, 0)); + } + return lrgsArchiveConfigPanel; + } + + /** + * This method initializes dataSourcePrefPanel + * + * @return javax.swing.JPanel + */ + private JPanel getDataSourcePrefPanel() { + if (dataSourcePrefPanel == null) { + GridBagConstraints pref4ComboConstraints = new GridBagConstraints(); + pref4ComboConstraints.fill = GridBagConstraints.HORIZONTAL; + pref4ComboConstraints.gridy = 4; + pref4ComboConstraints.weightx = 1.0; + pref4ComboConstraints.anchor = GridBagConstraints.WEST; + pref4ComboConstraints.insets = new Insets(2, 0, 2, 10); + pref4ComboConstraints.gridx = 1; + pref4ComboConstraints.ipadx = 50; + GridBagConstraints pref3ComboConstraints = new GridBagConstraints(); + pref3ComboConstraints.fill = GridBagConstraints.HORIZONTAL; + pref3ComboConstraints.gridy = 3; + pref3ComboConstraints.weightx = 1.0; + pref3ComboConstraints.anchor = GridBagConstraints.WEST; + pref3ComboConstraints.insets = new Insets(2, 0, 2, 10); + pref3ComboConstraints.gridx = 1; + pref3ComboConstraints.ipadx = 50; + GridBagConstraints pref2ComboConstraints = new GridBagConstraints(); + pref2ComboConstraints.fill = GridBagConstraints.HORIZONTAL; + pref2ComboConstraints.gridy = 2; + pref2ComboConstraints.weightx = 1.0; + pref2ComboConstraints.anchor = GridBagConstraints.WEST; + pref2ComboConstraints.insets = new Insets(2, 0, 2, 10); + pref2ComboConstraints.gridx = 1; + pref2ComboConstraints.ipadx = 50; + GridBagConstraints preference4LabelConstraints = new GridBagConstraints(); + preference4LabelConstraints.gridx = 0; + preference4LabelConstraints.weightx = 0.5D; + preference4LabelConstraints.anchor = GridBagConstraints.EAST; + preference4LabelConstraints.insets = new Insets(0, 10, 0, 2); + preference4LabelConstraints.gridy = 4; + preference4Label = new JLabel(); + preference4Label.setText(labels.getString( + "LrgsConfigDialog.preference4")); + GridBagConstraints preference3LabelConstraints = new GridBagConstraints(); + preference3LabelConstraints.gridx = 0; + preference3LabelConstraints.weightx = 0.5D; + preference3LabelConstraints.anchor = GridBagConstraints.EAST; + preference3LabelConstraints.insets = new Insets(0, 10, 0, 2); + preference3LabelConstraints.gridy = 3; + preference3Label = new JLabel(); + preference3Label.setText(labels.getString( + "LrgsConfigDialog.preference3")); + GridBagConstraints preference2LabelConstraints = new GridBagConstraints(); + preference2LabelConstraints.gridx = 0; + preference2LabelConstraints.weightx = 0.5D; + preference2LabelConstraints.anchor = GridBagConstraints.EAST; + preference2LabelConstraints.insets = new Insets(0, 10, 0, 2); + preference2LabelConstraints.gridy = 2; + preference2Label = new JLabel(); + preference2Label.setText(labels.getString( + "LrgsConfigDialog.preference2")); + dataSourcePrefPanel = new JPanel(); + dataSourcePrefPanel.setLayout(new GridBagLayout()); + dataSourcePrefPanel.setBorder( + BorderFactory.createTitledBorder( + BorderFactory.createBevelBorder(BevelBorder.LOWERED), + labels.getString("LrgsConfigDialog.dataSourcePref"), + TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); + + preferredGoodCheck.setText( + labels.getString("LrgsConfigDialog.preferGood")); + dataSourcePrefPanel.add(preferredGoodCheck, + new GridBagConstraints(0, 0, 2, 1, 0.5, 0.0, + GridBagConstraints.SOUTH, GridBagConstraints.NONE, + new Insets(5, 10, 10, 5), 0, 0)); + + dataSourcePrefPanel.add( + new JLabel(labels.getString("LrgsConfigDialog.preference1")), + new GridBagConstraints(0, 1, 1, 1, 0.5, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(0, 10, 0, 2), 0, 0)); + + dataSourcePrefPanel.add(getMergePref1Combo(), + new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, + new Insets(2, 0, 2, 10), 50, 0)); + + dataSourcePrefPanel.add(preference2Label, preference2LabelConstraints); + dataSourcePrefPanel.add(preference3Label, preference3LabelConstraints); + dataSourcePrefPanel.add(preference4Label, preference4LabelConstraints); + dataSourcePrefPanel.add(getMergePref2Combo(), pref2ComboConstraints); + dataSourcePrefPanel.add(getMergePref3Combo(), pref3ComboConstraints); + dataSourcePrefPanel.add(getMergePref4Combo(), pref4ComboConstraints); + } + return dataSourcePrefPanel; + } + + /** + * This method initializes archiveDirField + * + * @return javax.swing.JTextField + */ + private JTextField getArchiveDirField() { + if (archiveDirField == null) { + archiveDirField = new JTextField(); + //archiveDirField.setPreferredSize(new Dimension(500, 20)); + } + return archiveDirField; + } + + /** + * This method initializes archiveLengthField + * + * @return javax.swing.JTextField + */ + private JTextField getArchiveLengthField() { + if (archiveLengthField == null) { + archiveLengthField = new JTextField(); + //archiveLengthField.setPreferredSize(new Dimension(4, 20)); + } + return archiveLengthField; + } + + /** + * This method initializes archiveTimeoutField + * + * @return javax.swing.JTextField + */ + private JTextField getArchiveTimeoutField() { + if (archiveTimeoutField == null) { + archiveTimeoutField = new JTextField(); + } + return archiveTimeoutField; + } + + /** + * This method initializes localStatusFileField + * + * @return javax.swing.JTextField + */ + private JTextField getLocalStatusFileField() { + if (localStatusFileField == null) { + localStatusFileField = new JTextField(); + } + return localStatusFileField; + } + + /** + * This method initializes statusPeriodField + * + * @return javax.swing.JTextField + */ + private JTextField getStatusPeriodField() { + if (statusPeriodField == null) { + statusPeriodField = new JTextField(); + } + return statusPeriodField; + } + + /** + * This method initializes sharedNetlistDirectoryField + * + * @return javax.swing.JTextField + */ + private JTextField getSharedNetlistDirectoryField() { + if (sharedNetlistDirectoryField == null) { + sharedNetlistDirectoryField = new JTextField(); + } + return sharedNetlistDirectoryField; + } + + /** + * This method initializes mergePref1Combo + * + * @return javax.swing.JComboBox + */ + private JComboBox getMergePref1Combo() { + if (mergePref1Combo == null) { + mergePref1Combo = new JComboBox(mergePrefs); + } + return mergePref1Combo; + } + + /** + * This method initializes mergePref2Combo + * + * @return javax.swing.JComboBox + */ + private JComboBox getMergePref2Combo() { + if (mergePref2Combo == null) { + mergePref2Combo = new JComboBox(mergePrefs); + } + return mergePref2Combo; + } + + /** + * This method initializes mergePref3Combo + * + * @return javax.swing.JComboBox + */ + private JComboBox getMergePref3Combo() { + if (mergePref3Combo == null) { + mergePref3Combo = new JComboBox(mergePrefs); + } + return mergePref3Combo; + } + + /** + * This method initializes mergePref4Combo + * + * @return javax.swing.JComboBox + */ + private JComboBox getMergePref4Combo() { + if (mergePref4Combo == null) { + mergePref4Combo = new JComboBox(); + mergePref4Combo.addItem("(unspecified)"); + mergePref4Combo.addItem("DRGS"); + mergePref4Combo.addItem("HRIT"); + mergePref4Combo.addItem("DDS Receive"); + } + return mergePref4Combo; + } + +// /** +// * This method initializes initializeDOMSATcheck +// * +// * @return javax.swing.JCheckBox +// */ +// private JCheckBox getInitializeDOMSATcheck() { +// if (initializeDOMSATcheck == null) { +// initializeDOMSATcheck = new JCheckBox(); +// initializeDOMSATcheck.setText(labels.getString( +// "LrgsConfigDialog.initDOMSATCheckBox")); +// } +// return initializeDOMSATcheck; +// } + +// /** +// * This method initializes domsatLinkCheck +// * +// * @return javax.swing.JCheckBox +// */ +// private JCheckBox getDomsatLinkCheck() { +// if (domsatLinkCheck == null) { +// domsatLinkCheck = new JCheckBox(); +// domsatLinkCheck.setText(labels.getString( +// "LrgsConfigDialog.enableDOMSATLink")); +// } +// return domsatLinkCheck; +// } + +// /** +// * This method initializes domsatHardwareCombo +// * +// * @return javax.swing.JComboBox +// */ +// private JComboBox getDomsatHardwareCombo() +// { +// if (domsatHardwareCombo == null) +// { +// domsatHardwareCombo = new JComboBox(); +// domsatHardwareCombo.addItem("lrgs.domsatrecv.DomsatSangoma"); +// domsatHardwareCombo.addItem("lrgs.domsatrecv.DomsatDpc"); +// domsatHardwareCombo.addItem("lrgs.domsatrecv.DomsatFranklin"); +// +// domsatHardwareCombo.addActionListener( +// new java.awt.event.ActionListener() +// { +// public void actionPerformed(java.awt.event.ActionEvent e) +// { +// chkDpcEnabled(); +// } +// }); // -// fieldName = "DOMSAT Class"; -// sv = (String)getDomsatHardwareCombo().getSelectedItem(); -// if (!TextUtil.strEqual(lrgsConfig.domsatClass, sv)) -// { -// lrgsConfig.domsatClass = sv; -// changed = true; -// } -// sv = domsatDpcHost.getText().trim(); -// if (sv.length() == 0) -// sv = null; -// if (!TextUtil.strEqual(sv, lrgsConfig.dpcHost)) -// { -// lrgsConfig.dpcHost = sv; -// changed = true; -// } - -// try -// { -// int p = Integer.parseInt(domsatDpcPort.getText().trim()); -// if (p != lrgsConfig.dpcPort) -// { -// lrgsConfig.dpcPort = p; -// changed = true; -// } -// } -// catch(Exception ex) { } +// } +// return domsatHardwareCombo; +// } + +// private void chkDpcEnabled() +// { +// String cn = (String)domsatHardwareCombo.getSelectedItem(); +// boolean isDpc = +// cn != null && cn.equals("lrgs.domsatrecv.DomsatDpc"); +// domsatDpcPort.setEnabled(isDpc); +// domsatDpcHost.setEnabled(isDpc); +// } + +// /** +// * This method initializes domsatTimeoutField +// * +// * @return javax.swing.JTextField +// */ +// private JTextField getDomsatTimeoutField() { +// if (domsatTimeoutField == null) { +// domsatTimeoutField = new JTextField(); +// } +// return domsatTimeoutField; +// } // -// fieldName = "DOMSAT Enable"; -// bv = getDomsatLinkCheck().isSelected(); -// if (lrgsConfig.enableDomsatRecv != bv) -// { -// lrgsConfig.enableDomsatRecv = bv; -// changed = true; -// } -// -// fieldName = "DOMSAT Timeout"; -// iv = getIntFieldValue(getDomsatTimeoutField(), -// lrgsConfig.def_domsatTimeout); -// if (lrgsConfig.domsatTimeout != iv) -// { -// lrgsConfig.domsatTimeout = iv; -// changed = true; -// } -// -// bv = acceptDomsatARMsCheck.isSelected(); -// if (lrgsConfig.acceptDomsatARMs != bv) -// { -// lrgsConfig.acceptDomsatARMs = bv; -// changed = true; -// } - - // DDS Server Tab - fieldName = "DDS Listen Port"; - iv = getIntFieldValue(getDdsListenPortField(), - lrgsConfig.def_ddsListenPort); - if (lrgsConfig.ddsListenPort != iv) - { - lrgsConfig.ddsListenPort = iv; - changed = true; - } - - fieldName = "DDS Bind Addr"; - sv = getStringFieldValue(getDdsBindAddrField(), - lrgsConfig.def_ddsBindAddr); - if (!TextUtil.strEqual(lrgsConfig.ddsBindAddr, sv)) - { - lrgsConfig.ddsBindAddr = sv; - changed = true; - } - - fieldName = "DDS Max Clients"; - iv = getIntFieldValue(getDdsMaxClientsField(), - lrgsConfig.def_ddsMaxClients); - if (lrgsConfig.ddsMaxClients != iv) - { - lrgsConfig.ddsMaxClients = iv; - changed = true; - } - - fieldName = "DDS User Parent Dir"; - sv = getStringFieldValue(getDdsParentDirectoryField(), - lrgsConfig.def_ddsUserRootDir); - if (!TextUtil.strEqual(lrgsConfig.ddsUserRootDir, sv)) - { - lrgsConfig.ddsUserRootDir = sv; - changed = true; - } - - fieldName = "DDS Usage Log"; - sv = getStringFieldValue(getDdsLogFileField(), - lrgsConfig.def_ddsUsageLog); - if (!TextUtil.strEqual(lrgsConfig.ddsUsageLog, sv)) - { - lrgsConfig.ddsUsageLog = sv; - changed = true; - } - - fieldName = "DDS Require Auth"; - bv = getDdsRequireAuthCheck().isSelected(); - if (lrgsConfig.ddsRequireAuth != bv) - { - lrgsConfig.ddsRequireAuth = bv; - changed = true; - } - - fieldName = "DDS Local Admin Only"; - bv = localAdminOnlyCheck.isSelected(); - if (lrgsConfig.localAdminOnly != bv) - { - lrgsConfig.localAdminOnly = bv; - changed = true; - } - - bv = requireStrongAuthCheck.isSelected(); - if (lrgsConfig.reqStrongEncryption != bv) - { - lrgsConfig.reqStrongEncryption = bv; - changed = true; - } - - fieldName = "Local DDS User Dir"; - sv = getStringFieldValue(localSandboxDir, - lrgsConfig.def_ddsUserRootDirLocal); - if (!TextUtil.strEqual(lrgsConfig.ddsUserRootDirLocal, sv)) - { - lrgsConfig.ddsUserRootDirLocal = sv; - changed = true; - } - - // on the DDS Recv Tab - // MJM OpenDCS 6.2 does not support Outage recovery -// iv = recoveryCombo.getSelectedIndex(); -// bv = iv == 0 ? false : true; -// if (lrgsConfig.recoverOutages != bv) -// { -// lrgsConfig.recoverOutages = bv; -// changed = true; -// } - lrgsConfig.recoverOutages = false; - - bv = enableDDSReceiveCheck.isSelected(); - if (lrgsConfig.enableDdsRecv != bv) - { - lrgsConfig.enableDdsRecv = bv; - changed = true; - } - - fieldName = "DDS Recv Timeout"; - iv = getIntFieldValue(ddsTimeoutField, 90); - if (ddsSettings.timeout != iv) - { - ddsSettings.timeout = iv; - changed = true; - } - - fieldName = "DDS Min Hourly"; - iv = getIntFieldValue(ddsMinHourlyField, 0); - if (lrgsConfig.ddsMinHourly != iv) - { - lrgsConfig.ddsMinHourly = iv; - changed = true; - } - - fieldName = "DRGS Min Hourly"; - iv = getIntFieldValue(drgsMinHourlyField, 0); - if (lrgsConfig.drgsMinHourly != iv) - { - lrgsConfig.drgsMinHourly = iv; - changed = true; - } - - - // On the DRGS Tab - bv = enableDRGSCheck.isSelected(); - if (lrgsConfig.enableDrgsRecv != bv) - { - lrgsConfig.enableDrgsRecv = bv; - changed = true; - } - - // On the Network Dcp tab - bv = networkDcpCfgPanel.networkDcpEnable(); - if (lrgsConfig.networkDcpEnable != bv) - { - lrgsConfig.networkDcpEnable = bv; - changed = true; - } - - // On the 'misc' tab - if (miscPanel.hasChanged()) - { - miscPanel.saveChanges(); - changed = true; - } - } - catch(ParseException ex) - { - String msg = LoadResourceBundle.sprintf( - labels.getString("LrgsConfigDialog.invalidValueErr"), - fieldName); - showError(msg); - throw new ParseException(msg, 0); - } - return changed; - } - - /** - * Copy data from controls back to the DdsRecvSettings object. - * @return true if anything was changed. - */ - private boolean copyBackDdsSettings() - { - if (!ddsTableModel.modified && !netlistsModified) - return false; - - ddsSettings.resetToDefaults(); - for(DdsRecvConnectCfg cc : ddsTableModel.cons) - ddsSettings.connectCfgs.add(cc); - - //DDS Receive tab - - for(int i = 0; i < netlistTableModel.getRowCount(); i++) - { - String netlistName = (String)netlistTableModel.getValueAt(i,0); - netlistName = netlistName.trim(); - if (netlistName.length() == 0) - continue; - - String group = (String)netlistTableModel.getValueAt(i,1); - if (group == null || group.trim().length() == 0) - group = NetlistGroupAssoc.DEFAULT_GROUP; - - ddsSettings.addNetlistAssoc(netlistName, group); - } - - return true; - } - - /** - * Copy data from controls back to the DrgsSettings object. - * @return true if anything was changed. - */ - private boolean copyBackDrgsConfig() - { - if (!drgsTableModel.modified) - return false; - - drgsSettings.resetToDefaults(); - - for (DrgsConnectCfg cc : drgsTableModel.cons) - drgsSettings.connections.add(cc); - return true; - } - - /** - * Copy data from controls back to the Network DCP Settings object. - * @return true if anything was changed. - */ - private boolean copyBackNetworkDcpConfig() - { - // On the Network DCP Tab - if (!networkDcpCfgPanel.hasChanged()) - return false; - - networkDcpSettings.resetToDefaults(); - for(DrgsConnectCfg dcc : networkDcpCfgPanel.getConnections()) - networkDcpSettings.connections.add(dcc); - - return true; - } - - public void setDdsClientIf(DdsClientIf dcif) - { - ddsClientIf = dcif; - } - - /** - * This method initializes tabbedPane - * - * @return javax.swing.JTabbedPane - */ - private JTabbedPane getTabbedPane() - { - if (tabbedPane == null) - { - tabbedPane = new JTabbedPane(); - tabbedPane.addTab(labels.getString("LrgsConfigDialog.archiveTab"), - null, getArchiveConfigTab(), null); -// tabbedPane.addTab(labels.getString("LrgsConfigDialog.DOMSATTab"), -// null, getDomsatConfigTab(), null); - tabbedPane.addTab(labels.getString("LrgsConfigDialog.DDSServerTab"), - null, getDdsServerConfigTab(), null); - tabbedPane.addTab(labels.getString("LrgsConfigDialog.DDSReceiveTab"), - null, getDdsRecvConfigTab(), null); - tabbedPane.addTab(labels.getString("LrgsConfigDialog.DRGSTab"), - null, getDrgsConfigTab(), null); - tabbedPane.addTab(labels.getString("LrgsConfigDialog.networkDcpTab"), - null, getNetworkDcpTab(), null); - noaaConfigTab = new NoaaportConfigPanel(this); - tabbedPane.addTab(noaaConfigTab.getLabel(), noaaConfigTab); - iridiumCfgTab = new IridiumCfgPanel(this); - tabbedPane.addTab(iridiumCfgTab.getLabel(), iridiumCfgTab); - lritCfgPanel = new LritCfgPanel(this); - tabbedPane.addTab(lritCfgPanel.getLabel(), lritCfgPanel); - hritFileCfgPanel = new HritFileCfgPanel(this); - tabbedPane.addTab(hritFileCfgPanel.getLabel(), hritFileCfgPanel); - edlConfigPanel = new EdlConfigPanel(this); - tabbedPane.addTab(edlConfigPanel.getLabel(), edlConfigPanel); - - tabbedPane.addTab(labels.getString("LrgsConfigDialog.miscTab"), - null, getMiscConfigTab(), - labels.getString("LrgsConfigDialog.miscPars")); - - } - return tabbedPane; - } - - /** - * This method initializes buttonPanel - * - * @return javax.swing.JPanel - */ - private JPanel getButtonPanel() { - if (buttonPanel == null) { - FlowLayout flowLayout = new FlowLayout(); - flowLayout.setHgap(20); - flowLayout.setVgap(10); - buttonPanel = new JPanel(); - buttonPanel.setLayout(flowLayout); - buttonPanel.setSize(new Dimension(238, 75)); - buttonPanel.add(getOkButton(), null); - buttonPanel.add(getCancelButton(), null); - buttonPanel.add(getApplyButton(), null); - } - return buttonPanel; - } - - /** - * This method initializes okButton - * - * @return javax.swing.JButton - */ - private JButton getOkButton() - { - if (okButton == null) - { - okButton = new JButton(); - okButton.setText(genericLabels.getString("OK")); - okButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - okPressed(); - } - }); - } - return okButton; - } - - /** - * This method initializes cancelButton - * - * @return javax.swing.JButton - */ - private JButton getCancelButton() - { - if (cancelButton == null) - { - cancelButton = new JButton(); - cancelButton.setText(genericLabels.getString("cancel")); - cancelButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - cancelPressed(); - } - }); - } - return cancelButton; - } - - /** - * This method initializes applyButton - * - * @return javax.swing.JButton - */ - private JButton getApplyButton() - { - if (applyButton == null) - { - applyButton = new JButton(); - applyButton.setText(labels.getString("LrgsConfigDialog.apply")); - applyButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - applyPressed(true); - } - }); - } - return applyButton; - } - - /** - * This method initializes archiveConfigTab - * - * @return javax.swing.JPanel - */ - private JPanel getArchiveConfigTab() { - if (archiveConfigTab == null) { - archiveConfigTab = new JPanel(); - archiveConfigTab.setLayout(new BoxLayout(getArchiveConfigTab(), BoxLayout.Y_AXIS)); - archiveConfigTab.add(getLrgsArchiveConfigPanel(), null); - archiveConfigTab.add(getContainerPanel(),null); - } - return archiveConfigTab; - } - - /** - * This method initializes domsatConfigTab - * - * @return javax.swing.JPanel - */ -// private JPanel getDomsatConfigTab() -// { -// if (domsatConfigTab == null) -// { -// domsatHardwareLabel = new JLabel(); -// domsatHardwareLabel.setText(labels.getString( -// "LrgsConfigDialog.DHardwareInterface")); -// -// domsatTimeoutLabel = new JLabel(); -// domsatTimeoutLabel.setText(labels.getString( -// "LrgsConfigDialog.DTimeout")); -// -// domsatConfigTab = new JPanel(); -// domsatConfigTab.setLayout(new GridBagLayout()); -// domsatConfigTab.setBorder(BorderFactory.createTitledBorder(null, -// labels.getString("LrgsConfigDialog.DOMSATConfigurationTitle"), -// TitledBorder.CENTER, -// TitledBorder.BELOW_TOP, new Font("Dialog", Font.BOLD, 14), -// new Color(51, 51, 51))); -// -// -// domsatConfigTab.add(getInitializeDOMSATcheck(), -// new GridBagConstraints(0, 0, 2, 1, 0.0, 0.5, -// GridBagConstraints.SOUTHWEST, GridBagConstraints.NONE, -// new Insets(10, 10, 5, 10), 0, 0)); -// domsatConfigTab.add(domsatHardwareLabel, -// new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, -// GridBagConstraints.EAST, GridBagConstraints.NONE, -// new Insets(5, 40, 5, 2), 0, 0)); -// domsatConfigTab.add(getDomsatHardwareCombo(), -// new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, -// GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, -// new Insets(5, 0, 5, 20), 0, 0)); -// -// JLabel dpcHostLabel = new JLabel( -// labels.getString("LrgsConfigDialog.DOMSATDpcHost")); -// domsatConfigTab.add(dpcHostLabel, -// new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, -// GridBagConstraints.EAST, GridBagConstraints.NONE, -// new Insets(5, 40, 5, 2), 0, 0)); -// domsatConfigTab.add(domsatDpcHost, -// new GridBagConstraints(1, 2, 1, 1, 1.0, 0.0, -// GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, -// new Insets(5, 0, 5, 20), 0, 0)); -// -// JLabel dpcPortLabel = new JLabel( -// labels.getString("LrgsConfigDialog.DOMSATDpcPort")); -// domsatConfigTab.add(dpcPortLabel, -// new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, -// GridBagConstraints.EAST, GridBagConstraints.NONE, -// new Insets(5, 40, 5, 2), 0, 0)); -// domsatConfigTab.add(domsatDpcPort, -// new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, -// GridBagConstraints.EAST, GridBagConstraints.HORIZONTAL, -// new Insets(5, 0, 5, 20), 0, 0)); -// -// domsatConfigTab.add(getDomsatLinkCheck(), -// new GridBagConstraints(0, 4, 2, 1, 0.0, 0.0, -// GridBagConstraints.WEST, GridBagConstraints.NONE, -// new Insets(10, 10, 5, 10), 0, 0)); -// domsatConfigTab.add(domsatTimeoutLabel, -// new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, -// GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, -// new Insets(5, 40, 10, 2), 0, 0)); -// domsatConfigTab.add(getDomsatTimeoutField(), -// new GridBagConstraints(1, 5, 1, 1, 0.0, 0.0, -// GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, -// new Insets(5, 0, 10, 20), 50, 0)); -// -// acceptDomsatARMsCheck.setText( -// labels.getString("LrgsConfigDialog.acceptDomsatARMs")); -// -// domsatConfigTab.add(acceptDomsatARMsCheck, -// new GridBagConstraints(0, 6, 2, 1, 0.0, 0.5, -// GridBagConstraints.NORTHWEST, GridBagConstraints.NONE, -// new Insets(10, 10, 5, 10), 0, 0)); -// -// } -// return domsatConfigTab; -// } - - /** - * This method initializes ddsServerConfigTab - * - * @return javax.swing.JPanel - */ - private JPanel getDdsServerConfigTab() - { - if (ddsServerConfigTab == null) - { - ddsServerConfigTab = new JPanel(); - ddsServerConfigTab.setLayout(new GridBagLayout()); - ddsServerConfigTab.setBorder(BorderFactory.createTitledBorder(null, - labels.getString("LrgsConfigDialog.ddsLRGSDDSTitle"), - TitledBorder.CENTER, TitledBorder.BELOW_TOP, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); - - ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsListeningPort")), - new GridBagConstraints(0, 0, 1, 1, 0, .5, - GridBagConstraints.SOUTHEAST, GridBagConstraints.NONE, - new Insets(6, 0, 6, 2), 0, 0)); - ddsServerConfigTab.add(getDdsListenPortField(), - new GridBagConstraints(1, 0, 1, 1, .25, 0., - GridBagConstraints.SOUTHWEST, GridBagConstraints.HORIZONTAL, - new Insets(6, 0, 6, 0), 0, 0)); - - ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsBindIPAddress")), - new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(6, 0, 6, 2), 0, 0)); - ddsServerConfigTab.add(getDdsBindAddrField(), - new GridBagConstraints(1, 1, 1, 1, 0.5, 0.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(6, 0, 6, 0), 80, 0)); - ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsMultiNICSystems")), - new GridBagConstraints(2, 1, 1, 1, 0.5, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(6, 0, 6, 10), 0, 0)); - - ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsMaxClients")), - new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(6, 10, 6, 2), 0, 0)); - ddsServerConfigTab.add(getDdsMaxClientsField(), - new GridBagConstraints(1, 2, 1, 1, 0.5, 0.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(6, 0, 6, 0), 0, 0)); - - ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsSandboxDir")), - new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(6, 10, 6, 2), 0, 0)); - ddsServerConfigTab.add(getDdsParentDirectoryField(), - new GridBagConstraints(1, 3, 2, 1, 1.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(6, 0, 6, 40), 0, 0)); - - ddsServerConfigTab.add(new JLabel(labels.getString("LrgsConfigDialog.ddsUsageLogFile")), - new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(6, 10, 6, 2), 0, 0)); - ddsServerConfigTab.add(getDdsLogFileField(), - new GridBagConstraints(1, 4, 2, 1, 1.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(6, 0, 6, 40), 0, 0)); - - ddsServerConfigTab.add(getDdsRequireAuthCheck(), - new GridBagConstraints(1, 5, 2, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(6, 0, 6, 0), 0, 0)); - - localAdminOnlyCheck.setText("Local Administrators Only"); - localAdminOnlyCheck.setToolTipText( - "Do not allow administration from remotely shared accounts."); - ddsServerConfigTab.add(localAdminOnlyCheck, - new GridBagConstraints(1, 6, 2, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(6, 0, 6, 5), 0, 0)); - - requireStrongAuthCheck.setText("Require SHA-256 Authentication"); - ddsServerConfigTab.add(requireStrongAuthCheck, - new GridBagConstraints(1, 7, 2, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(6, 0, 6, 5), 0, 0)); - - JLabel lb = new JLabel("Local Sandbox Directory:"); - ddsServerConfigTab.add(lb, - new GridBagConstraints(0, 8, 1, 1, 0.0, 0.5, - GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, - new Insets(6, 10, 6, 2), 0, 0)); - ddsServerConfigTab.add(localSandboxDir, - new GridBagConstraints(1, 8, 1, 1, 1.0, 0.5, - GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, - new Insets(5, 0, 5, 40), 0, 0)); - } - return ddsServerConfigTab; - } - - /** - * This method initializes ddsRecvConfigTab - * - * @return javax.swing.JPanel - */ - private JPanel getDdsRecvConfigTab() { - if (ddsRecvConfigTab == null) { - ddsRecvConfigTab = new JPanel(); - ddsRecvConfigTab.setLayout(new BoxLayout(getDdsRecvConfigTab(), BoxLayout.Y_AXIS)); - ddsRecvConfigTab.add(getRecoverPanel(), null); - ddsRecvConfigTab.add(getConnectionsPanel(),null); - ddsRecvConfigTab.add(getNetworkListsPanel(),null); - } - return ddsRecvConfigTab; - } - - /** - * This method initializes drgsConfigTab - * - * @return javax.swing.JPanel - */ - private JPanel getDrgsConfigTab() { - if (drgsConfigTab == null) { - drgsConfigTab = new JPanel(); - drgsConfigTab.setLayout( - new BoxLayout(drgsConfigTab, BoxLayout.Y_AXIS)); - drgsConfigTab.add(getJPanel(), null); - } - return drgsConfigTab; - } - - private JPanel getMiscConfigTab() - { - BorderLayout bl = new BorderLayout(); - miscConfigTab = new JPanel(bl); - JLabel lab = new JLabel(labels.getString( - "LrgsConfigDialog.miscPars")); - miscConfigTab.add(lab, BorderLayout.NORTH); - miscPanel = new PropertiesEditPanel(new Properties()); - miscConfigTab.add(miscPanel, BorderLayout.CENTER); - return miscConfigTab; - } - - private JPanel getNetworkDcpTab() - { - networkDcpTab = new JPanel(new BorderLayout()); - networkDcpCfgPanel = new NetworkDcpCfgPanel(this); - networkDcpTab.add(networkDcpCfgPanel, BorderLayout.CENTER); - return networkDcpTab; - } - - /** - * This method initializes lrgsArchiveConfigPanel - * - * @return javax.swing.JPanel - */ - private JPanel getLrgsArchiveConfigPanel() { - if (lrgsArchiveConfigPanel == null) { - GridBagConstraints archiveDirectoryLabelConstraints = new GridBagConstraints(); - archiveDirectoryLabelConstraints.gridx = 0; - archiveDirectoryLabelConstraints.gridy = 0; - archiveDirectoryLabelConstraints.anchor = GridBagConstraints.SOUTHEAST; - archiveDirectoryLabelConstraints.weightx = 1.0; - archiveDirectoryLabelConstraints.weighty = 0.5; - archiveDirectoryLabelConstraints.insets = new Insets(2, 0, 2, 2); - archiveDirectoryLabelConstraints.fill = GridBagConstraints.NONE; - archiveDirectoryLabel = new JLabel(); - archiveDirectoryLabel.setText(labels.getString( - "LrgsConfigDialog.archiveDirectory")); - //archiveDirectoryLabel.setHorizontalTextPosition(SwingConstants.RIGHT); - //archiveDirectoryLabel.setHorizontalAlignment(SwingConstants.RIGHT); - - GridBagConstraints archiveDirFieldConstraints = new GridBagConstraints(); - archiveDirFieldConstraints.gridx = 1; - archiveDirFieldConstraints.gridy = 0; - archiveDirFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - archiveDirFieldConstraints.weightx = 1.0; - archiveDirFieldConstraints.weighty = 0.5; - archiveDirFieldConstraints.gridwidth = 3; - archiveDirFieldConstraints.anchor = GridBagConstraints.SOUTHWEST; - archiveDirFieldConstraints.insets = new Insets(2, 0, 2, 40); - - GridBagConstraints emptyLabel2Constraints = new GridBagConstraints(); - emptyLabel2Constraints.gridx = 2; - emptyLabel2Constraints.fill = GridBagConstraints.BOTH; - emptyLabel2Constraints.weightx = 2.0D; - emptyLabel2Constraints.gridy = 2; - emptyLabel2 = new JLabel(); - emptyLabel2.setText(""); - - GridBagConstraints emptyLabel1Constraints = new GridBagConstraints(); - emptyLabel1Constraints.gridx = 3; - emptyLabel1Constraints.weightx = 2.0D; - emptyLabel1Constraints.fill = GridBagConstraints.BOTH; - emptyLabel1Constraints.gridwidth = 1; - emptyLabel1Constraints.gridy = 1; - emptyLabel1 = new JLabel(); - emptyLabel1.setText(""); - - GridBagConstraints statusPeriodFieldConstraints = new GridBagConstraints(); - statusPeriodFieldConstraints.fill = GridBagConstraints.BOTH; - statusPeriodFieldConstraints.gridy = 4; - statusPeriodFieldConstraints.weightx = 1.0; - statusPeriodFieldConstraints.anchor = GridBagConstraints.WEST; - statusPeriodFieldConstraints.insets = new Insets(2, 0, 2, 0); - statusPeriodFieldConstraints.gridx = 1; - - GridBagConstraints localStatusFileFieldConstraints = new GridBagConstraints(); - localStatusFileFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - localStatusFileFieldConstraints.gridy = 3; - localStatusFileFieldConstraints.weightx = 2.0D; - localStatusFileFieldConstraints.insets = new Insets(2, 0, 2, 40); - localStatusFileFieldConstraints.gridwidth = 3; - localStatusFileFieldConstraints.gridx = 1; - - GridBagConstraints archiveTimeoutFieldConstraints = new GridBagConstraints(); - archiveTimeoutFieldConstraints.fill = GridBagConstraints.BOTH; - archiveTimeoutFieldConstraints.gridy = 2; - archiveTimeoutFieldConstraints.weightx = 1.0; - archiveTimeoutFieldConstraints.anchor = GridBagConstraints.WEST; - archiveTimeoutFieldConstraints.insets = new Insets(2, 0, 2, 0); - archiveTimeoutFieldConstraints.gridx = 1; - - GridBagConstraints archiveLengthFieldConstraints = new GridBagConstraints(); - archiveLengthFieldConstraints.fill = GridBagConstraints.BOTH; - archiveLengthFieldConstraints.gridy = 1; - archiveLengthFieldConstraints.weightx = 1.0; - archiveLengthFieldConstraints.anchor = GridBagConstraints.WEST; - archiveLengthFieldConstraints.insets = new Insets(2, 0, 2, 0); - archiveLengthFieldConstraints.gridx = 1; - - - GridBagConstraints statusPeriodLabelConstraints = new GridBagConstraints(); - statusPeriodLabelConstraints.gridx = 0; - statusPeriodLabelConstraints.anchor = GridBagConstraints.EAST; - statusPeriodLabelConstraints.weightx = 1.0D; - statusPeriodLabelConstraints.insets = new Insets(2, 0, 3, 2); - statusPeriodLabelConstraints.gridy = 4; - statusPeriodLabel = new JLabel(); - statusPeriodLabel.setText(labels.getString( - "LrgsConfigDialog.statusPeriod")); - - GridBagConstraints localStatusFileLabelConstraints = new GridBagConstraints(); - localStatusFileLabelConstraints.gridx = 0; - localStatusFileLabelConstraints.anchor = GridBagConstraints.EAST; - localStatusFileLabelConstraints.weightx = 1.0D; - localStatusFileLabelConstraints.insets = new Insets(2, 0, 3, 2); - localStatusFileLabelConstraints.gridy = 3; - localStatusFileLabel = new JLabel(); - localStatusFileLabel.setText(labels.getString( - "LrgsConfigDialog.localStatusFile")); - - GridBagConstraints archiveTimeoutLabelConstraints = new GridBagConstraints(); - archiveTimeoutLabelConstraints.gridx = 0; - archiveTimeoutLabelConstraints.anchor = GridBagConstraints.EAST; - archiveTimeoutLabelConstraints.weightx = 1.0D; - archiveTimeoutLabelConstraints.insets = new Insets(2, 40, 3, 2); - archiveTimeoutLabelConstraints.gridy = 2; - archiveTimeoutLabel = new JLabel(); - archiveTimeoutLabel.setText(labels.getString( - "LrgsConfigDialog.archiveTimeout")); - - GridBagConstraints archiveLengthLabelConstraints = new GridBagConstraints(); - archiveLengthLabelConstraints.gridx = 0; - archiveLengthLabelConstraints.anchor = GridBagConstraints.EAST; - archiveLengthLabelConstraints.weightx = 1.0D; - archiveLengthLabelConstraints.insets = new Insets(2, 0, 3, 2); - archiveLengthLabelConstraints.gridy = 1; - archiveLengthLabel = new JLabel(); - archiveLengthLabel.setText(labels.getString( - "LrgsConfigDialog.archiveLength")); - archiveLengthLabel.setHorizontalTextPosition(SwingConstants.RIGHT); - archiveLengthLabel.setHorizontalAlignment(SwingConstants.RIGHT); - - GridBagConstraints sharedNetlistDirectoryLabelConstraints = new GridBagConstraints(); - sharedNetlistDirectoryLabelConstraints.gridx = 0; - sharedNetlistDirectoryLabelConstraints.anchor = GridBagConstraints.EAST; - sharedNetlistDirectoryLabelConstraints.weightx = 1.0D; - sharedNetlistDirectoryLabelConstraints.weighty = 0.5; - sharedNetlistDirectoryLabelConstraints.insets = new Insets(2, 0, 2, 2); - sharedNetlistDirectoryLabelConstraints.gridy = 5; - sharedNetlistDirectoryLabel = new JLabel(); - sharedNetlistDirectoryLabel.setText(labels.getString( - "LrgsConfigDialog.sharedNetlistDir")); - - GridBagConstraints sharedNetlistDirectoryFieldConstraints = new GridBagConstraints(); - sharedNetlistDirectoryFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - sharedNetlistDirectoryFieldConstraints.anchor = GridBagConstraints.WEST; - sharedNetlistDirectoryFieldConstraints.gridy = 5; - sharedNetlistDirectoryFieldConstraints.weightx = 2.0D; - sharedNetlistDirectoryFieldConstraints.weighty = 0.5; - sharedNetlistDirectoryFieldConstraints.insets = new Insets(2, 0, 2, 40); - sharedNetlistDirectoryFieldConstraints.gridwidth = 3; - sharedNetlistDirectoryFieldConstraints.gridx = 1; - - lrgsArchiveConfigPanel = new JPanel(); - lrgsArchiveConfigPanel.setLayout(new GridBagLayout()); - lrgsArchiveConfigPanel.setBorder(BorderFactory.createTitledBorder(null, - labels.getString("LrgsConfigDialog.archiveConfigTitle"), - TitledBorder.CENTER, TitledBorder.BELOW_TOP, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); - lrgsArchiveConfigPanel.add(archiveDirectoryLabel, archiveDirectoryLabelConstraints); - lrgsArchiveConfigPanel.add(archiveLengthLabel, archiveLengthLabelConstraints); - lrgsArchiveConfigPanel.add(archiveTimeoutLabel, archiveTimeoutLabelConstraints); - lrgsArchiveConfigPanel.add(localStatusFileLabel, localStatusFileLabelConstraints); - lrgsArchiveConfigPanel.add(statusPeriodLabel, statusPeriodLabelConstraints); - lrgsArchiveConfigPanel.add(sharedNetlistDirectoryLabel, sharedNetlistDirectoryLabelConstraints); - lrgsArchiveConfigPanel.add(getArchiveDirField(), archiveDirFieldConstraints); - lrgsArchiveConfigPanel.add(getArchiveLengthField(), archiveLengthFieldConstraints); - lrgsArchiveConfigPanel.add(getArchiveTimeoutField(), archiveTimeoutFieldConstraints); - lrgsArchiveConfigPanel.add(getLocalStatusFileField(), localStatusFileFieldConstraints); - lrgsArchiveConfigPanel.add(getStatusPeriodField(), statusPeriodFieldConstraints); - lrgsArchiveConfigPanel.add(getSharedNetlistDirectoryField(), sharedNetlistDirectoryFieldConstraints); - lrgsArchiveConfigPanel.add(emptyLabel1, emptyLabel1Constraints); - lrgsArchiveConfigPanel.add(emptyLabel2, emptyLabel2Constraints); - - lrgsArchiveConfigPanel.add(pdtValidationCheck, - new GridBagConstraints(1, 6, 1, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(2, 0, 2, 15), 0, 0)); - - lrgsArchiveConfigPanel.add( - new JLabel(labels.getString("LrgsConfigDialog.PDTURL")), - new GridBagConstraints(0, 7, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(2, 10, 2, 2), 0, 0)); - - lrgsArchiveConfigPanel.add(pdtUrlField, - new GridBagConstraints(1, 7, 1, 1, 1.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 0, 2, 20), 0, 0)); - - lrgsArchiveConfigPanel.add( - new JLabel(labels.getString("LrgsConfigDialog.CDTURL")), - new GridBagConstraints(0, 8, 1, 1, 0.0, 0.5, - GridBagConstraints.NORTHEAST, GridBagConstraints.NONE, - new Insets(2, 10, 2, 2), 0, 0)); - - lrgsArchiveConfigPanel.add(cdtUrlField, - new GridBagConstraints(1, 8, 1, 1, 1.0, 0.5, - GridBagConstraints.NORTHWEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 0, 2, 20), 0, 0)); - } - return lrgsArchiveConfigPanel; - } - - /** - * This method initializes dataSourcePrefPanel - * - * @return javax.swing.JPanel - */ - private JPanel getDataSourcePrefPanel() { - if (dataSourcePrefPanel == null) { - GridBagConstraints pref4ComboConstraints = new GridBagConstraints(); - pref4ComboConstraints.fill = GridBagConstraints.HORIZONTAL; - pref4ComboConstraints.gridy = 4; - pref4ComboConstraints.weightx = 1.0; - pref4ComboConstraints.anchor = GridBagConstraints.WEST; - pref4ComboConstraints.insets = new Insets(2, 0, 2, 10); - pref4ComboConstraints.gridx = 1; - pref4ComboConstraints.ipadx = 50; - GridBagConstraints pref3ComboConstraints = new GridBagConstraints(); - pref3ComboConstraints.fill = GridBagConstraints.HORIZONTAL; - pref3ComboConstraints.gridy = 3; - pref3ComboConstraints.weightx = 1.0; - pref3ComboConstraints.anchor = GridBagConstraints.WEST; - pref3ComboConstraints.insets = new Insets(2, 0, 2, 10); - pref3ComboConstraints.gridx = 1; - pref3ComboConstraints.ipadx = 50; - GridBagConstraints pref2ComboConstraints = new GridBagConstraints(); - pref2ComboConstraints.fill = GridBagConstraints.HORIZONTAL; - pref2ComboConstraints.gridy = 2; - pref2ComboConstraints.weightx = 1.0; - pref2ComboConstraints.anchor = GridBagConstraints.WEST; - pref2ComboConstraints.insets = new Insets(2, 0, 2, 10); - pref2ComboConstraints.gridx = 1; - pref2ComboConstraints.ipadx = 50; - GridBagConstraints preference4LabelConstraints = new GridBagConstraints(); - preference4LabelConstraints.gridx = 0; - preference4LabelConstraints.weightx = 0.5D; - preference4LabelConstraints.anchor = GridBagConstraints.EAST; - preference4LabelConstraints.insets = new Insets(0, 10, 0, 2); - preference4LabelConstraints.gridy = 4; - preference4Label = new JLabel(); - preference4Label.setText(labels.getString( - "LrgsConfigDialog.preference4")); - GridBagConstraints preference3LabelConstraints = new GridBagConstraints(); - preference3LabelConstraints.gridx = 0; - preference3LabelConstraints.weightx = 0.5D; - preference3LabelConstraints.anchor = GridBagConstraints.EAST; - preference3LabelConstraints.insets = new Insets(0, 10, 0, 2); - preference3LabelConstraints.gridy = 3; - preference3Label = new JLabel(); - preference3Label.setText(labels.getString( - "LrgsConfigDialog.preference3")); - GridBagConstraints preference2LabelConstraints = new GridBagConstraints(); - preference2LabelConstraints.gridx = 0; - preference2LabelConstraints.weightx = 0.5D; - preference2LabelConstraints.anchor = GridBagConstraints.EAST; - preference2LabelConstraints.insets = new Insets(0, 10, 0, 2); - preference2LabelConstraints.gridy = 2; - preference2Label = new JLabel(); - preference2Label.setText(labels.getString( - "LrgsConfigDialog.preference2")); - dataSourcePrefPanel = new JPanel(); - dataSourcePrefPanel.setLayout(new GridBagLayout()); - dataSourcePrefPanel.setBorder( - BorderFactory.createTitledBorder( - BorderFactory.createBevelBorder(BevelBorder.LOWERED), - labels.getString("LrgsConfigDialog.dataSourcePref"), - TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); - - preferredGoodCheck.setText( - labels.getString("LrgsConfigDialog.preferGood")); - dataSourcePrefPanel.add(preferredGoodCheck, - new GridBagConstraints(0, 0, 2, 1, 0.5, 0.0, - GridBagConstraints.SOUTH, GridBagConstraints.NONE, - new Insets(5, 10, 10, 5), 0, 0)); - - dataSourcePrefPanel.add( - new JLabel(labels.getString("LrgsConfigDialog.preference1")), - new GridBagConstraints(0, 1, 1, 1, 0.5, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(0, 10, 0, 2), 0, 0)); - - dataSourcePrefPanel.add(getMergePref1Combo(), - new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, - new Insets(2, 0, 2, 10), 50, 0)); - - dataSourcePrefPanel.add(preference2Label, preference2LabelConstraints); - dataSourcePrefPanel.add(preference3Label, preference3LabelConstraints); - dataSourcePrefPanel.add(preference4Label, preference4LabelConstraints); - dataSourcePrefPanel.add(getMergePref2Combo(), pref2ComboConstraints); - dataSourcePrefPanel.add(getMergePref3Combo(), pref3ComboConstraints); - dataSourcePrefPanel.add(getMergePref4Combo(), pref4ComboConstraints); - } - return dataSourcePrefPanel; - } - - /** - * This method initializes archiveDirField - * - * @return javax.swing.JTextField - */ - private JTextField getArchiveDirField() { - if (archiveDirField == null) { - archiveDirField = new JTextField(); - //archiveDirField.setPreferredSize(new Dimension(500, 20)); - } - return archiveDirField; - } - - /** - * This method initializes archiveLengthField - * - * @return javax.swing.JTextField - */ - private JTextField getArchiveLengthField() { - if (archiveLengthField == null) { - archiveLengthField = new JTextField(); - //archiveLengthField.setPreferredSize(new Dimension(4, 20)); - } - return archiveLengthField; - } - - /** - * This method initializes archiveTimeoutField - * - * @return javax.swing.JTextField - */ - private JTextField getArchiveTimeoutField() { - if (archiveTimeoutField == null) { - archiveTimeoutField = new JTextField(); - } - return archiveTimeoutField; - } - - /** - * This method initializes localStatusFileField - * - * @return javax.swing.JTextField - */ - private JTextField getLocalStatusFileField() { - if (localStatusFileField == null) { - localStatusFileField = new JTextField(); - } - return localStatusFileField; - } - - /** - * This method initializes statusPeriodField - * - * @return javax.swing.JTextField - */ - private JTextField getStatusPeriodField() { - if (statusPeriodField == null) { - statusPeriodField = new JTextField(); - } - return statusPeriodField; - } - - /** - * This method initializes sharedNetlistDirectoryField - * - * @return javax.swing.JTextField - */ - private JTextField getSharedNetlistDirectoryField() { - if (sharedNetlistDirectoryField == null) { - sharedNetlistDirectoryField = new JTextField(); - } - return sharedNetlistDirectoryField; - } - - /** - * This method initializes mergePref1Combo - * - * @return javax.swing.JComboBox - */ - private JComboBox getMergePref1Combo() { - if (mergePref1Combo == null) { - mergePref1Combo = new JComboBox(mergePrefs); - } - return mergePref1Combo; - } - - /** - * This method initializes mergePref2Combo - * - * @return javax.swing.JComboBox - */ - private JComboBox getMergePref2Combo() { - if (mergePref2Combo == null) { - mergePref2Combo = new JComboBox(mergePrefs); - } - return mergePref2Combo; - } - - /** - * This method initializes mergePref3Combo - * - * @return javax.swing.JComboBox - */ - private JComboBox getMergePref3Combo() { - if (mergePref3Combo == null) { - mergePref3Combo = new JComboBox(mergePrefs); - } - return mergePref3Combo; - } - - /** - * This method initializes mergePref4Combo - * - * @return javax.swing.JComboBox - */ - private JComboBox getMergePref4Combo() { - if (mergePref4Combo == null) { - mergePref4Combo = new JComboBox(); - mergePref4Combo.addItem("(unspecified)"); - mergePref4Combo.addItem("DRGS"); - mergePref4Combo.addItem("HRIT"); - mergePref4Combo.addItem("DDS Receive"); - } - return mergePref4Combo; - } - -// /** -// * This method initializes initializeDOMSATcheck -// * -// * @return javax.swing.JCheckBox -// */ -// private JCheckBox getInitializeDOMSATcheck() { -// if (initializeDOMSATcheck == null) { -// initializeDOMSATcheck = new JCheckBox(); -// initializeDOMSATcheck.setText(labels.getString( -// "LrgsConfigDialog.initDOMSATCheckBox")); -// } -// return initializeDOMSATcheck; -// } - -// /** -// * This method initializes domsatLinkCheck -// * -// * @return javax.swing.JCheckBox -// */ -// private JCheckBox getDomsatLinkCheck() { -// if (domsatLinkCheck == null) { -// domsatLinkCheck = new JCheckBox(); -// domsatLinkCheck.setText(labels.getString( -// "LrgsConfigDialog.enableDOMSATLink")); -// } -// return domsatLinkCheck; -// } - -// /** -// * This method initializes domsatHardwareCombo -// * -// * @return javax.swing.JComboBox -// */ -// private JComboBox getDomsatHardwareCombo() -// { -// if (domsatHardwareCombo == null) -// { -// domsatHardwareCombo = new JComboBox(); -// domsatHardwareCombo.addItem("lrgs.domsatrecv.DomsatSangoma"); -// domsatHardwareCombo.addItem("lrgs.domsatrecv.DomsatDpc"); -// domsatHardwareCombo.addItem("lrgs.domsatrecv.DomsatFranklin"); -// -// domsatHardwareCombo.addActionListener( -// new java.awt.event.ActionListener() -// { -// public void actionPerformed(java.awt.event.ActionEvent e) -// { -// chkDpcEnabled(); -// } -// }); -// -// } -// return domsatHardwareCombo; -// } - -// private void chkDpcEnabled() -// { -// String cn = (String)domsatHardwareCombo.getSelectedItem(); -// boolean isDpc = -// cn != null && cn.equals("lrgs.domsatrecv.DomsatDpc"); -// domsatDpcPort.setEnabled(isDpc); -// domsatDpcHost.setEnabled(isDpc); -// } - -// /** -// * This method initializes domsatTimeoutField -// * -// * @return javax.swing.JTextField -// */ -// private JTextField getDomsatTimeoutField() { -// if (domsatTimeoutField == null) { -// domsatTimeoutField = new JTextField(); -// } -// return domsatTimeoutField; -// } -// - /** - * This method initializes ddsListenPortField - * - * @return javax.swing.JTextField - */ - private JTextField getDdsListenPortField() { - if (ddsListenPortField == null) { - ddsListenPortField = new JTextField(); - } - return ddsListenPortField; - } - - /** - * This method initializes ddsBindAddrField - * - * @return javax.swing.JTextField - */ - private JTextField getDdsBindAddrField() { - if (ddsBindAddrField == null) { - ddsBindAddrField = new JTextField(); - } - return ddsBindAddrField; - } - - /** - * This method initializes ddsMaxClientsField - * - * @return javax.swing.JTextField - */ - private JTextField getDdsMaxClientsField() { - if (ddsMaxClientsField == null) { - ddsMaxClientsField = new JTextField(); - } - return ddsMaxClientsField; - } - - /** - * This method initializes ddsParentDirectoryField - * - * @return javax.swing.JTextField - */ - private JTextField getDdsParentDirectoryField() { - if (ddsParentDirectoryField == null) { - ddsParentDirectoryField = new JTextField(); - } - return ddsParentDirectoryField; - } - - /** - * This method initializes ddsLogFileField - * - * @return javax.swing.JTextField - */ - private JTextField getDdsLogFileField() { - if (ddsLogFileField == null) { - ddsLogFileField = new JTextField(); - } - return ddsLogFileField; - } - - /** - * This method initializes ddsRequireAuthCheck - * - * @return javax.swing.JCheckBox - */ - private JCheckBox getDdsRequireAuthCheck() { - if (ddsRequireAuthCheck == null) { - ddsRequireAuthCheck = new JCheckBox(); - ddsRequireAuthCheck.setText(labels.getString( - "LrgsConfigDialog.reqClientPasswdAuth")); - } - return ddsRequireAuthCheck; - } - - /** - * This method initializes recoverPanel - * - * @return javax.swing.JPanel - */ - private JPanel getRecoverPanel() - { - if (recoverPanel == null) - { - recoverPanel = new JPanel(new GridBagLayout()); - recoverPanel.setBorder(BorderFactory.createTitledBorder(null, - labels.getString( - "LrgsConfigDialog.LRGSDDSBackupTitle"), TitledBorder.CENTER, TitledBorder.BELOW_TOP, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); - recoverPanel.add(new JLabel(genericLabels.getString("timeout")), - new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(10, 10, 4, 2), 0, 0)); - recoverPanel.add(ddsTimeoutField, - new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(10, 0, 4, 10), 0, 0)); - recoverPanel.add(new JLabel(labels.getString("minHourly")), - new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(4, 10, 4, 2), 0, 0)); - recoverPanel.add(ddsMinHourlyField, - new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(4, 0, 4, 10), 0, 0)); - - recoverPanel.add(getEnableDDSReceiveCheck(), - new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(0, 40, 0, 0), 0, 0)); - } - return recoverPanel; - } - -// /** -// * This method initializes recoveryCombo -// * -// * @return javax.swing.JComboBox -// */ -// private JComboBox getRecoveryCombo() { -// if (recoveryCombo == null) { -// recoveryCombo = new JComboBox(); -// recoveryCombo.addItem("Real - Time Stream"); -// recoveryCombo.addItem("Recover from Outages"); -// } -// return recoveryCombo; -// } - - /** - * This method initializes enableDDSReceiveCheck - * - * @return javax.swing.JCheckBox - */ - private JCheckBox getEnableDDSReceiveCheck() { - if (enableDDSReceiveCheck == null) { - enableDDSReceiveCheck = new JCheckBox(); - enableDDSReceiveCheck.setText(labels.getString( - "LrgsConfigDialog.enableDDSReceivConn")); - } - return enableDDSReceiveCheck; - } - - /** - * This method initializes connectionsPanel - * - * @return javax.swing.JPanel - */ - private JPanel getConnectionsPanel() { - if (connectionsPanel == null) { - connectionsPanel = new JPanel(); - connectionsPanel.setLayout(new BorderLayout()); - connectionsPanel.setSize(new Dimension(150, 129)); - connectionsPanel.add(getConnectionsButtonPanel(), BorderLayout.EAST); - connectionsPanel.add(getDdsReceiveScrollPane(), BorderLayout.CENTER); - } - return connectionsPanel; - } - - /** - * This method initializes connectionsButtonPanel - * - * @return javax.swing.JPanel - */ - private JPanel getConnectionsButtonPanel() { - if (connectionsButtonPanel == null) { - GridBagConstraints ddsConMoveDownButtonConstraints = new GridBagConstraints(); - ddsConMoveDownButtonConstraints.gridx = 0; - ddsConMoveDownButtonConstraints.insets = new Insets(2, 5, 2, 5); - ddsConMoveDownButtonConstraints.weighty = 0.0D; - //ddsConMoveDownButtonConstraints.anchor = GridBagConstraints.NORTH; - ddsConMoveDownButtonConstraints.gridy = 4; - GridBagConstraints ddsConMoveUpButtonConstraints = new GridBagConstraints(); - ddsConMoveUpButtonConstraints.gridx = 0; - ddsConMoveUpButtonConstraints.insets = new Insets(2, 5, 2, 5); - ddsConMoveUpButtonConstraints.gridy = 3; - GridBagConstraints ddsConDeleteButtonConstraints = new GridBagConstraints(); - ddsConDeleteButtonConstraints.gridx = 0; - ddsConDeleteButtonConstraints.insets = new Insets(2, 5, 2, 5); - ddsConDeleteButtonConstraints.gridy = 2; - GridBagConstraints ddsConEditButtonConstraints = new GridBagConstraints(); - ddsConEditButtonConstraints.gridx = 0; - ddsConEditButtonConstraints.insets = new Insets(2, 5, 2, 5); - ddsConEditButtonConstraints.gridy = 1; - GridBagConstraints addButtonConstraints = new GridBagConstraints(); - addButtonConstraints.gridx = 0; - addButtonConstraints.gridwidth = 1; - addButtonConstraints.insets = new Insets(20, 5, 2, 5); - addButtonConstraints.weighty = 0.0D; - addButtonConstraints.gridy = 0; - - GridBagConstraints testButtonConstraints = new GridBagConstraints(); - testButtonConstraints.gridx = 0; - testButtonConstraints.gridwidth = 1; - testButtonConstraints.insets = new Insets(2, 5, 2, 5); - testButtonConstraints.weighty = 1.0D; - testButtonConstraints.anchor = GridBagConstraints.NORTH; - testButtonConstraints.gridy = 5; - - connectionsButtonPanel = new JPanel(); - connectionsButtonPanel.setLayout(new GridBagLayout()); - connectionsButtonPanel.add(getConnectionsButtonAdd(), addButtonConstraints); - connectionsButtonPanel.add(getConnectionsButtonEdit(), ddsConEditButtonConstraints); - connectionsButtonPanel.add(getConnectionsButtonDelete(), ddsConDeleteButtonConstraints); - connectionsButtonPanel.add(getConnectionsButtonMoveUp(), ddsConMoveUpButtonConstraints); - connectionsButtonPanel.add(getConnectionsButtonMoveDown(), ddsConMoveDownButtonConstraints); - connectionsButtonPanel.add(getConnectionsButtonTest(),testButtonConstraints); - } - return connectionsButtonPanel; - } - - private JButton getConnectionsButtonTest() { - if (ddsConTestButton == null) { - ddsConTestButton = new JButton(); - ddsConTestButton.setText(genericLabels.getString("test")); - ddsConTestButton.setMnemonic(KeyEvent.VK_UNDEFINED); - ddsConTestButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - testButtonPressed(); - } - }); - } - return ddsConTestButton; - } - private void testButtonPressed() - { - int idx = ddsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectConnEditErr")); - return; - } - DdsRecvConnectCfg cfg = (DdsRecvConnectCfg)ddsTableModel.getRowObject(idx); - - LddsClient myClient = new LddsClient(cfg.host,cfg.port); - - //TODO add option for password sending - LrgsConnectionTest myTester = new LrgsConnectionTest(this, myClient, cfg.username,null); - myTester.startConnect(); - - } - - /** - * This method initializes ddsConAddButton - * - * @return javax.swing.JButton - */ - private JButton getConnectionsButtonAdd() { - if (ddsConAddButton == null) { - ddsConAddButton = new JButton(); - ddsConAddButton.setText(genericLabels.getString("add")); - ddsConAddButton.setMnemonic(KeyEvent.VK_UNDEFINED); - ddsConAddButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - launchDdsRecvConDialog(false); - } - }); - } - return ddsConAddButton; - } - - private void launchDdsRecvConDialog(boolean edit) - { - DdsRecvConDialog dlg = new DdsRecvConDialog(this); - DdsRecvConnectCfg cfg = null; - if (edit) - { - int idx = ddsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectConnEditErr")); - return; - } - cfg = (DdsRecvConnectCfg)ddsTableModel.getRowObject(idx); - } - else // add - { - cfg = new DdsRecvConnectCfg(ddsTableModel.getRowCount(), ""); - } - dlg.setInfo(cfg); - launchDialog(dlg); - if (dlg.okPressed()) - { - if (!edit) - ddsTableModel.add(cfg); - else - ddsTableModel.modified(); - } - } - - private void deleteDdsCon() - { - int idx = ddsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectDDSConnDelErr")); - return; - } - DdsRecvConnectCfg cfg = - (DdsRecvConnectCfg)ddsTableModel.getRowObject(idx); - if( JOptionPane.showConfirmDialog(this, - LoadResourceBundle.sprintf(labels.getString( - "LrgsConfigDialog.DDSConnDel"),cfg.name), - labels.getString( - "LrgsConfigDialog.confirmDelete"), JOptionPane.YES_NO_OPTION) - == JOptionPane.YES_OPTION) - { - ddsTableModel.deleteAt(idx); - } - } - - private void moveDdsConUp() - { - int idx = ddsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectDDSConnMoveErr")); - return; - } - if (ddsTableModel.moveUpAt(idx)) - ddsConTable.setRowSelectionInterval(idx-1, idx-1); - } - - private void moveDdsConDown() - { - int idx = ddsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectDDSConnMoveErr")); - return; - } - if (ddsTableModel.moveDownAt(idx)) - ddsConTable.setRowSelectionInterval(idx+1, idx+1); - } - - /** - * This method initializes ddsConEditButton - * - * @return javax.swing.JButton - */ - private JButton getConnectionsButtonEdit() { - if (ddsConEditButton == null) { - ddsConEditButton = new JButton(); - ddsConEditButton.setText(genericLabels.getString("edit")); -// ddsConEditButton.setPreferredSize(new Dimension(110, 26)); - ddsConEditButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - launchDdsRecvConDialog(true); - } - }); - } - return ddsConEditButton; - } - - /** - * This method initializes ddsConDeleteButton - * - * @return javax.swing.JButton - */ - private JButton getConnectionsButtonDelete() { - if (ddsConDeleteButton == null) { - ddsConDeleteButton = new JButton(); - ddsConDeleteButton.setText(genericLabels.getString("delete")); -// ddsConDeleteButton.setPreferredSize(new Dimension(110, 26)); - ddsConDeleteButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - deleteDdsCon(); - } - }); - } - return ddsConDeleteButton; - } - - /** - * This method initializes ddsConMoveUpButton - * - * @return javax.swing.JButton - */ - private JButton getConnectionsButtonMoveUp() - { - if (ddsConMoveUpButton == null) { - ddsConMoveUpButton = new JButton(); - ddsConMoveUpButton.setText(labels.getString( - "LrgsConfigDialog.moveUp")); -// ddsConMoveUpButton.setPreferredSize(new Dimension(110, 26)); - ddsConMoveUpButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - moveDdsConUp(); - } - }); - } - return ddsConMoveUpButton; - } - - /** - * This method initializes ddsConMoveDownButton - * - * @return javax.swing.JButton - */ - private JButton getConnectionsButtonMoveDown() { - if (ddsConMoveDownButton == null) { - ddsConMoveDownButton = new JButton(); - ddsConMoveDownButton.setText(labels.getString( - "LrgsConfigDialog.moveDn")); -// ddsConMoveDownButton.setPreferredSize(new Dimension(110, 26)); - ddsConMoveDownButton.addActionListener( - new java.awt.event.ActionListener() - { - public void actionPerformed(java.awt.event.ActionEvent e) - { - moveDdsConDown(); - } - }); - } - return ddsConMoveDownButton; - } - - /** - * This method initializes networkListsPanel - * - * @return javax.swing.JPanel - */ - private JPanel getNetworkListsPanel() { - if (networkListsPanel == null) { - networkListsPanel = new JPanel(); - networkListsPanel.setLayout(new BorderLayout()); - networkListsPanel.setSize(new Dimension(176, 177)); - networkListsPanel.setBorder(BorderFactory.createTitledBorder(null, - labels.getString("LrgsConfigDialog.DDSNetListTextArea"), - TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51))); - networkListsPanel.add(getNetworkListsButtonPanel(), BorderLayout.EAST); - networkListsPanel.add(getNetworkListsScrollPane(), BorderLayout.CENTER); - } - return networkListsPanel; - } - - /** - * This method initializes networkListsButtonPanel - * - * @return javax.swing.JPanel - */ - private JPanel getNetworkListsButtonPanel() { - if (networkListsButtonPanel == null) { - GridBagConstraints networkListsDeleteButtonConstraints = new GridBagConstraints(); - networkListsDeleteButtonConstraints.gridx = 0; - networkListsDeleteButtonConstraints.insets = new Insets(2, 5, 2, 5); - networkListsDeleteButtonConstraints.weighty = 1.0D; - networkListsDeleteButtonConstraints.anchor = GridBagConstraints.NORTH; - networkListsDeleteButtonConstraints.gridy = 1; - GridBagConstraints networkListsAddButtonConstraints = new GridBagConstraints(); - networkListsAddButtonConstraints.gridx = 0; - networkListsAddButtonConstraints.insets = new Insets(2, 5, 2, 5); - networkListsAddButtonConstraints.gridy = 0; - networkListsButtonPanel = new JPanel(); - networkListsButtonPanel.setLayout(new GridBagLayout()); - networkListsButtonPanel.add(getNetworkListsAddButton(), networkListsAddButtonConstraints); - networkListsButtonPanel.add(getNetworkListsDeleteButton(), networkListsDeleteButtonConstraints); - } - return networkListsButtonPanel; - } - - /** - * This method initializes networkListsAddButton - * - * @return javax.swing.JButton - */ - private JButton getNetworkListsAddButton() { - if (networkListsAddButton == null) { - networkListsAddButton = new JButton(); - networkListsAddButton.setText(genericLabels.getString("add")); -// networkListsAddButton.setPreferredSize(new Dimension(110, 26)); - networkListsAddButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) { - - //Now metwork list can be associated with thr groups, primary, secondary or both - JPanel panel = new JPanel(new GridLayout(4,1)); - panel.add(new JLabel(labels.getString("LrgsConfigDialog.enterNLToAdd"))); - JTextField netlist = new JTextField(); - panel.add(netlist); - Object[] items = {"Primary", "Secondary","Both"}; - - JComboBox jcb = new JComboBox(items); - - jcb.setEditable(false); - panel.add(new JLabel("Group")); - panel.add(jcb); - - Integer res = (Integer)JOptionPane.showOptionDialog(new JFrame(), panel, "Network List",JOptionPane.OK_CANCEL_OPTION,JOptionPane.PLAIN_MESSAGE,null,null,null); - if(res.intValue()==0 && netlist.getText()!=null && netlist.getText().trim().length()>0 ) - { - Object[] rowData = {netlist.getText(), jcb.getSelectedItem()}; - netlistTableModel.addRow(rowData); - netlistsModified = true; - } - /* - JOptionPane mypane = new JOptionPane(); - netlistListModel.addElement(mypane.showInputDialog( - labels.getString("LrgsConfigDialog.enterNLToAdd"))); - netlistsModified = true;*/ - } - }); - } - return networkListsAddButton; - } - - /** - * This method initializes networkListsDeleteButton - * - * @return javax.swing.JButton - */ - private JButton getNetworkListsDeleteButton() { - if (networkListsDeleteButton == null) { - networkListsDeleteButton = new JButton(); - networkListsDeleteButton.setText( - genericLabels.getString("delete")); -// networkListsDeleteButton.setPreferredSize(new Dimension(110, 26)); - networkListsDeleteButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) - { - //removeNetworkListAt(getNetworkList().getSelectedIndex()); - removeNetworkListAt(getNetworkListTable().getSelectedRow()); - netlistsModified = true; - } - }); - } - return networkListsDeleteButton; - } - - /** - * This method initializes jPanel - * - * @return javax.swing.JPanel - */ - private JPanel getJPanel() { - if (jPanel == null) { - jPanel = new JPanel(); - jPanel.setLayout(new BoxLayout(getJPanel(), BoxLayout.Y_AXIS)); - jPanel.add(getDrgsConfigPanel(), null); - } - return jPanel; - } - - /** - * This method initializes drgsConfigPanel - * - * @return javax.swing.JPanel - */ - private JPanel getDrgsConfigPanel() - { - if (drgsConfigPanel == null) { - drgsConfigPanel = new JPanel(); - drgsConfigPanel.setLayout(new BorderLayout()); - drgsConfigPanel.setBorder( - BorderFactory.createTitledBorder(null, - labels.getString("LrgsConfigDialog.DRGSConfTitle"), - TitledBorder.CENTER, TitledBorder.BELOW_TOP, - new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); - drgsConfigPanel.add(getDrgsTablePanel(), BorderLayout.CENTER); - } - return drgsConfigPanel; - } - - /** - * This method initializes drgsButtonPanel - * - * @return javax.swing.JPanel - */ - private JPanel getDrgsButtonPanel() { - if (drgsButtonPanel == null) { - - GridBagConstraints addButtonConstraints = - new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, - GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, - new Insets(10, 4, 2, 4), 0, 0); - - GridBagConstraints drgsEditButtonConstraints = - new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, - GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, - new Insets(2, 4, 2, 4), 0, 0); - - GridBagConstraints drgsDeleteButtonConstraints = - new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, - GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, - new Insets(2, 4, 2, 4), 0, 0); - GridBagConstraints drgsTestButtonConstraints = - new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0, - GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, - new Insets(2, 4, 2, 4), 0, 0); - - - drgsButtonPanel = new JPanel(); - drgsButtonPanel.setLayout(new GridBagLayout()); - drgsButtonPanel.add(getDrgsAddButton(), addButtonConstraints); - drgsButtonPanel.add(getDrgsEditButton(), drgsEditButtonConstraints); - drgsButtonPanel.add(getDrgsDeleteButton(), drgsDeleteButtonConstraints); - drgsButtonPanel.add(getDrgsTestButton(), drgsTestButtonConstraints); - } - return drgsButtonPanel; - } - - private JButton getDrgsTestButton() { - if (drgsTestButton == null) { - drgsTestButton = new JButton(); - drgsTestButton.setText(genericLabels.getString("test")); - drgsTestButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) - { - drgsTestButtonPressed(); - } - }); - } - return drgsTestButton; - } - - private void drgsTestButtonPressed() - { - int idx = drgsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectConnEditErr")); - return; - } - DrgsConnectCfg cfg = (DrgsConnectCfg)drgsTableModel.getRowObject(idx); - - BasicClient myClient = new BasicClient(cfg.host,cfg.msgPort); - - //TODO add option for password sending - LrgsConnectionTest myTester = new LrgsConnectionTest(this, myClient); - myTester.startConnect(); - } - - /** - * This method initializes drgsAddButton - * - * @return javax.swing.JButton - */ - private JButton getDrgsAddButton() { - if (drgsAddButton == null) { - drgsAddButton = new JButton(); - drgsAddButton.setText(genericLabels.getString("add")); - drgsAddButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) - { - launchDrgsConDialog(false); - } - }); - } - return drgsAddButton; - } - - /** - * This method initializes drgsEditButton - * - * @return javax.swing.JButton - */ - private JButton getDrgsEditButton() { - if (drgsEditButton == null) { - drgsEditButton = new JButton(); - drgsEditButton.setText(genericLabels.getString("edit")); -// drgsEditButton.setPreferredSize(new Dimension(82, 26)); - drgsEditButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) - { - launchDrgsConDialog(true); - } - }); - } - return drgsEditButton; - } - - private void launchDrgsConDialog(boolean edit) - { - DrgsConDialog dlg = new DrgsConDialog(this); - DrgsConnectCfg cfg = null; - if (edit) - { - int idx = drgsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectConnEditErr")); - return; - } - cfg = (DrgsConnectCfg)drgsTableModel.getRowObject(idx); - dlg.setInfo(cfg); - } - else // add - { - cfg = new DrgsConnectCfg(drgsConTable.getRowCount(), ""); - dlg.setInfo(cfg); - } - launchDialog(dlg); - if (dlg.okPressed()) - { - if (!edit) - drgsTableModel.add(cfg); - else - drgsTableModel.modified(); - } - } - - private void deleteDrgsCon() - { - int idx = drgsConTable.getSelectedRow(); - if (idx == -1) - { - showError(labels.getString( - "LrgsConfigDialog.selectDRGSConnDelErr")); - return; - } - DrgsConnectCfg cfg = - (DrgsConnectCfg)drgsTableModel.getRowObject(idx); - if( JOptionPane.showConfirmDialog(this, - LoadResourceBundle.sprintf( - labels.getString("LrgsConfigDialog.DRGSConnDel"), - cfg.name), - labels.getString("LrgsConfigDialog.confirmDelete"), - JOptionPane.YES_NO_OPTION) - == JOptionPane.YES_OPTION) - { - drgsTableModel.deleteAt(idx); - } - } - - - - /** - * This method initializes drgsDeleteButton - * - * @return javax.swing.JButton - */ - private JButton getDrgsDeleteButton() { - if (drgsDeleteButton == null) { - drgsDeleteButton = new JButton(); - drgsDeleteButton.setText(genericLabels.getString("delete")); -// drgsDeleteButton.setPreferredSize(new Dimension(82, 26)); - drgsDeleteButton.addActionListener(new java.awt.event.ActionListener() { - public void actionPerformed(java.awt.event.ActionEvent e) - { - deleteDrgsCon(); - } - }); - } - return drgsDeleteButton; - } - - /** - * This method initializes networkListsScrollPane - * - * @return javax.swing.JScrollPane - */ - private JScrollPane getNetworkListsScrollPane() { - if (networkListsScrollPane == null) { - networkListsScrollPane = new JScrollPane(); - //networkListsScrollPane.setViewportView(getNetworkList()); - networkListsScrollPane.setViewportView(getNetworkListTable()); - } - return networkListsScrollPane; - } - - /** - * This method initializes networkList - * - * @return javax.swing.JList - */ - private JList getNetworkList() { - if (networkList == null) { - networkList = new JList(netlistListModel); - } - return networkList; - } - - - /** - * This method initializes networkList - * - * @return javax.swing.JList - */ - private JTable getNetworkListTable() { - - - - - - if (networkListTable == null) { - networkListTable = new JTable(netlistTableModel); - TableColumn tblCol = new TableColumn(); - netlistTableModel.addColumn("Network List Name"); - netlistTableModel.addColumn("Group"); - JTableHeader header =networkListTable.getTableHeader(); - header.setBorder( BorderFactory.createRaisedBevelBorder()); - header.setEnabled(false); - header.setBackground(Color.white); - header.setFocusable(false); - networkListTable.setTableHeader(header); - - networkListTable.setVisible(true); - - } - return networkListTable; - } - - - /** - * This method initializes drgsTablePanel - * - * @return javax.swing.JPanel - */ - private JPanel getDrgsTablePanel() - { - if (drgsTablePanel == null) - { - drgsTablePanel = new JPanel(new GridBagLayout()); - - drgsTablePanel.add(new JLabel(labels.getString("minHourly")), - new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, - GridBagConstraints.EAST, GridBagConstraints.NONE, - new Insets(10, 10, 2, 0), 0, 0)); - drgsTablePanel.add(drgsMinHourlyField, - new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(10, 1, 2, 10), 0, 0)); - - drgsTablePanel.add(getEnableDRGSCheck(), - new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0, - GridBagConstraints.WEST, GridBagConstraints.NONE, - new Insets(4, 10, 2, 10), 0, 0)); - - drgsTablePanel.add(getConnectionsScrollPane(), - new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, - GridBagConstraints.WEST, GridBagConstraints.BOTH, - new Insets(5, 5, 5, 5), 0, 0)); - - - drgsTablePanel.add(getDrgsButtonPanel(), - new GridBagConstraints(2, 2, 1, 1, 0.0, 1.0, - GridBagConstraints.NORTH, GridBagConstraints.NONE, - new Insets(5, 5, 5, 5), 0, 0)); - } - return drgsTablePanel; - } - - /** - * This method initializes enableDRGSCheck - * - * @return javax.swing.JCheckBox - */ - private JCheckBox getEnableDRGSCheck() { - if (enableDRGSCheck == null) { - enableDRGSCheck = new JCheckBox(); - enableDRGSCheck.setText(labels.getString( - "LrgsConfigDialog.enableDRGSConn")); - } - return enableDRGSCheck; - } - - - - /** - * This method initializes drgsConTable - * - * @return javax.swing.JTable - */ - private JTable getConnectionsTable() { - if (drgsConTable == null) { - drgsTableModel = new DrgsSortingListTableModel(); - drgsConTable = new SortingListTable(drgsTableModel,drgsTableModel.columnWidths); - - - } - return drgsConTable; - } - - - - - /** - * This method initializes ddsConTable - * - * @return javax.swing.JTable - */ - private JTable getDdsReceiveTable() { - if (ddsConTable == null) { - ddsTableModel = new DdsSortingListTableModel(); - ddsConTable = new SortingListTable(ddsTableModel,ddsTableModel.columnWidths); - - } - return ddsConTable; - } - - /** - * This method initializes SqlDatabasePanel - * - * @return javax.swing.JPanel - */ - private JPanel getSqlDatabasePanel() { - if (SqlDatabasePanel == null) { - - GridBagConstraints sqlUrlFieldConstraints = new GridBagConstraints(); - sqlUrlFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - sqlUrlFieldConstraints.anchor = GridBagConstraints.SOUTHWEST; - sqlUrlFieldConstraints.gridx = 1; - sqlUrlFieldConstraints.gridy = 0; - sqlUrlFieldConstraints.weightx = 1.0; - sqlUrlFieldConstraints.weighty = 0.5; - sqlUrlFieldConstraints.insets = new Insets(2, 0, 2, 10); - sqlUrlFieldConstraints.gridwidth = 2; - - GridBagConstraints sqlKeyFieldConstraints = new GridBagConstraints(); - sqlKeyFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - sqlKeyFieldConstraints.anchor = GridBagConstraints.WEST; - sqlKeyFieldConstraints.gridy = 5; - sqlKeyFieldConstraints.weightx = 1.0; - sqlKeyFieldConstraints.weighty = 0.5; - sqlKeyFieldConstraints.insets = new Insets(2, 0, 2, 10); - sqlKeyFieldConstraints.gridx = 2; - - GridBagConstraints sqlDriverFieldConstraints = new GridBagConstraints(); - sqlDriverFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - sqlDriverFieldConstraints.gridy = 4; - sqlDriverFieldConstraints.weightx = 1.0; - sqlDriverFieldConstraints.insets = new Insets(2, 0, 2, 10); - sqlDriverFieldConstraints.gridx = 2; - - GridBagConstraints sqlTimeZoneComboConstraints = new GridBagConstraints(); - sqlTimeZoneComboConstraints.fill = GridBagConstraints.HORIZONTAL; - sqlTimeZoneComboConstraints.gridy = 3; - sqlTimeZoneComboConstraints.weightx = 1.0; - sqlTimeZoneComboConstraints.insets = new Insets(2, 0, 2, 10); - sqlTimeZoneComboConstraints.gridx = 2; - - GridBagConstraints sqlWriteFieldConstraints = new GridBagConstraints(); - sqlWriteFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - sqlWriteFieldConstraints.gridy = 2; - sqlWriteFieldConstraints.weightx = 1.0; - sqlWriteFieldConstraints.insets = new Insets(2, 0, 2, 10); - sqlWriteFieldConstraints.gridx = 2; - - GridBagConstraints sqlReadFieldConstraints = new GridBagConstraints(); - sqlReadFieldConstraints.fill = GridBagConstraints.HORIZONTAL; - sqlReadFieldConstraints.gridy = 1; - sqlReadFieldConstraints.weightx = 1.0; - sqlReadFieldConstraints.insets = new Insets(2, 0, 2, 10); - sqlReadFieldConstraints.gridx = 2; - - GridBagConstraints sqlKeyLabelConstraints = new GridBagConstraints(); - sqlKeyLabelConstraints.gridx = 0; - sqlKeyLabelConstraints.gridwidth = 2; - sqlKeyLabelConstraints.anchor = GridBagConstraints.EAST; - sqlKeyLabelConstraints.weighty = 0.5; - sqlKeyLabelConstraints.insets = new Insets(2, 2, 3, 2); - sqlKeyLabelConstraints.gridy = 5; - sqlKeyLabel = new JLabel(); - sqlKeyLabel.setText(labels.getString( - "LrgsConfigDialog.keyGeneratorClass")); - - GridBagConstraints sqlTimeZoneLabelConstraints = new GridBagConstraints(); - sqlTimeZoneLabelConstraints.gridx = 0; - sqlTimeZoneLabelConstraints.anchor = GridBagConstraints.EAST; - sqlTimeZoneLabelConstraints.gridwidth = 2; - sqlTimeZoneLabelConstraints.insets = new Insets(2, 2, 3, 2); - sqlTimeZoneLabelConstraints.gridy = 3; - sqlTimeZoneLabel = new JLabel(); - sqlTimeZoneLabel.setText(labels.getString( - "LrgsConfigDialog.SQLTimeZone")); - - GridBagConstraints sqlDriverLabelConstraints = new GridBagConstraints(); - sqlDriverLabelConstraints.gridx = 0; - sqlDriverLabelConstraints.anchor = GridBagConstraints.EAST; - sqlDriverLabelConstraints.gridwidth = 2; - sqlDriverLabelConstraints.insets = new Insets(2, 2, 3, 2); - sqlDriverLabelConstraints.gridy = 4; - sqlDriverLabel = new JLabel(); - sqlDriverLabel.setText(labels.getString( - "LrgsConfigDialog.JDBCDriverClass")); - - - GridBagConstraints sqlWriteLabelConstraints = new GridBagConstraints(); - sqlWriteLabelConstraints.gridx = 0; - sqlWriteLabelConstraints.anchor = GridBagConstraints.EAST; - sqlWriteLabelConstraints.gridwidth = 2; - sqlWriteLabelConstraints.insets = new Insets(2, 2, 3, 2); - sqlWriteLabelConstraints.gridy = 2; - sqlWriteLabel = new JLabel(); - sqlWriteLabel.setText(labels.getString( - "LrgsConfigDialog.writeTimeFormat")); - GridBagConstraints sqlReadLabelConstraints = new GridBagConstraints(); - sqlReadLabelConstraints.gridx = 0; - sqlReadLabelConstraints.insets = new Insets(2, 40, 3, 2); - sqlReadLabelConstraints.anchor = GridBagConstraints.EAST; - sqlReadLabelConstraints.gridwidth = 2; - sqlReadLabelConstraints.gridy = 1; - sqlReadLabel = new JLabel(); - sqlReadLabel.setText(labels.getString( - "LrgsConfigDialog.readTimeFormat")); - - GridBagConstraints sqlUrlLabelConstraints = new GridBagConstraints(); - sqlUrlLabelConstraints.gridx = 0; - sqlUrlLabelConstraints.anchor = GridBagConstraints.SOUTHEAST; - sqlUrlLabelConstraints.insets = new Insets(2, 40, 3, 2); - sqlUrlLabelConstraints.gridy = 0; - sqlUrlLabelConstraints.weighty = 0.5; - sqlUrlLabel = new JLabel(); - sqlUrlLabel.setText(labels.getString( - "LrgsConfigDialog.URL")); - - SqlDatabasePanel = new JPanel(); - SqlDatabasePanel.setLayout(new GridBagLayout()); - SqlDatabasePanel.setBorder(BorderFactory.createTitledBorder( - BorderFactory.createBevelBorder(BevelBorder.LOWERED), - labels.getString("LrgsConfigDialog.SQLDBPref"), - TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); - SqlDatabasePanel.add(sqlUrlLabel, sqlUrlLabelConstraints); - SqlDatabasePanel.add(sqlReadLabel, sqlReadLabelConstraints); - SqlDatabasePanel.add(sqlWriteLabel, sqlWriteLabelConstraints); - SqlDatabasePanel.add(getSqlUrlField(), sqlUrlFieldConstraints); - SqlDatabasePanel.add(getSqlReadField(), sqlReadFieldConstraints); - SqlDatabasePanel.add(getSqlWriteField(), sqlWriteFieldConstraints); - SqlDatabasePanel.add(sqlTimeZoneLabel, sqlTimeZoneLabelConstraints); - SqlDatabasePanel.add(getSqlTimeZoneCombo(), sqlTimeZoneComboConstraints); - SqlDatabasePanel.add(sqlDriverLabel, sqlDriverLabelConstraints); - SqlDatabasePanel.add(sqlKeyLabel, sqlKeyLabelConstraints); - SqlDatabasePanel.add(getSqlDriverField(), sqlDriverFieldConstraints); - SqlDatabasePanel.add(getSqlKeyField(), sqlKeyFieldConstraints); - - SqlDatabasePanel.add(goesXmitCheck, - new GridBagConstraints(0, 6, 2, 1, 0.0, 0.5, - GridBagConstraints.CENTER, GridBagConstraints.NORTH, - new Insets(5, 20, 5, 2), 0, 0)); - } - return SqlDatabasePanel; - } - - - - - - - - /** - * This method initializes containerPanel - * - * @return javax.swing.JPanel - */ - private JPanel getContainerPanel() { - if (containerPanel == null) { - containerPanel = new JPanel(); - containerPanel.setLayout(new BoxLayout(getContainerPanel(), BoxLayout.X_AXIS)); - containerPanel.setSize(new Dimension(230, 145)); - containerPanel.add(getDataSourcePrefPanel(), null); - containerPanel.add(getSqlDatabasePanel(),null); - } - return containerPanel; - } - - - - - - - - /** - * This method initializes sqlUrlField - * - * @return javax.swing.JTextField - */ - private JTextField getSqlUrlField() { - if (sqlUrlField == null) { - sqlUrlField = new JTextField(); - } - return sqlUrlField; - } - - - - - - - - /** - * This method initializes sqlReadField - * - * @return javax.swing.JTextField - */ - private JTextField getSqlReadField() { - if (sqlReadField == null) { - sqlReadField = new JTextField(); - } - return sqlReadField; - } - - - - - - - - /** - * This method initializes sqlWriteField - * - * @return javax.swing.JTextField - */ - private JTextField getSqlWriteField() { - if (sqlWriteField == null) { - sqlWriteField = new JTextField(); - } - return sqlWriteField; - } - - - - - - - - /** - * This method initializes sqlTimeZoneCombo - * - * @return javax.swing.JComboBox - */ - private JComboBox getSqlTimeZoneCombo() - { - if (sqlTimeZoneCombo == null) - { - sqlTimeZoneCombo = new TimeZoneSelector(); - sqlTimeZoneCombo.setTZ("UTC"); - } - return sqlTimeZoneCombo; - } - - /** - * This method initializes sqlDriverField - * - * @return javax.swing.JTextField - */ - private JTextField getSqlDriverField() { - if (sqlDriverField == null) { - sqlDriverField = new JTextField(); - } - return sqlDriverField; - } - - /** - * This method initializes sqlKeyField - * - * @return javax.swing.JTextField - */ - private JTextField getSqlKeyField() { - if (sqlKeyField == null) { - sqlKeyField = new JTextField(); - } - return sqlKeyField; - } - - /** - * This method initializes connectionsScrollPane - * - * @return javax.swing.JScrollPane - */ - private JScrollPane getConnectionsScrollPane() { - if (connectionsScrollPane == null) { - connectionsScrollPane = new JScrollPane(); - connectionsScrollPane.setViewportView(getConnectionsTable()); - } - return connectionsScrollPane; - } - - /** - * This method initializes ddsReceiveScrollPane - * - * @return javax.swing.JScrollPane - */ - private JScrollPane getDdsReceiveScrollPane() { - if (ddsReceiveScrollPane == null) { - ddsReceiveScrollPane = new JScrollPane(getDdsReceiveTable()); - //ddsReceiveScrollPane.setViewportView(getDdsReceiveTable()); - - } - return ddsReceiveScrollPane; - } - - private void removeNetworkListAt(int idx) - { - if (idx == -1) - return; - //netlistListModel.remove(idx); - netlistTableModel.removeRow(idx); - } - - private void okPressed() - { - if (applyPressed(false)) - setVisible(false); - } - - private void cancelPressed() - { - setVisible(false); - } - - private boolean applyPressed(boolean force) - { - try - { - boolean extraChanges = false; - - if (noaaConfigTab.hasChanged()) - { - extraChanges = true; - noaaConfigTab.saveChanges(); - } - if (iridiumCfgTab.hasChanged()) - { - extraChanges = true; - iridiumCfgTab.saveChanges(); - } - if (lritCfgPanel.hasChanged()) - { - extraChanges = true; - lritCfgPanel.saveChanges(); - } - if (hritFileCfgPanel.hasChanged()) - { - extraChanges = true; - hritFileCfgPanel.saveChanges(); - } - if (edlConfigPanel.hasChanged()) - { - extraChanges = true; - edlConfigPanel.saveChanges(); - } - if (copyBackLrgsConfig() || force || extraChanges) - ddsClientIf.applyLrgsConfig(lrgsConfig); - - if (copyBackDdsSettings() || force) - ddsClientIf.applyDdsRecvSettings(ddsSettings); - - if (copyBackDrgsConfig() || force) - ddsClientIf.applyDrgsInputSettings(drgsSettings); - - if (copyBackNetworkDcpConfig() || force) - ddsClientIf.applyNetworkDcpSettings(networkDcpSettings); - - return true; - } - catch(ParseException ex) - { - showError(labels.getString( - "LrgsConfigDialog.correctErrRetry")); - return false; - } - catch(AuthException ex) - { - showError(labels.getString( - "LrgsConfigDialog.applyChangesErr") + ex); - return false; - } - } + /** + * This method initializes ddsListenPortField + * + * @return javax.swing.JTextField + */ + private JTextField getDdsListenPortField() { + if (ddsListenPortField == null) { + ddsListenPortField = new JTextField(); + } + return ddsListenPortField; + } + + /** + * This method initializes ddsBindAddrField + * + * @return javax.swing.JTextField + */ + private JTextField getDdsBindAddrField() { + if (ddsBindAddrField == null) { + ddsBindAddrField = new JTextField(); + } + return ddsBindAddrField; + } + + /** + * This method initializes ddsMaxClientsField + * + * @return javax.swing.JTextField + */ + private JTextField getDdsMaxClientsField() { + if (ddsMaxClientsField == null) { + ddsMaxClientsField = new JTextField(); + } + return ddsMaxClientsField; + } + + /** + * This method initializes ddsParentDirectoryField + * + * @return javax.swing.JTextField + */ + private JTextField getDdsParentDirectoryField() { + if (ddsParentDirectoryField == null) { + ddsParentDirectoryField = new JTextField(); + } + return ddsParentDirectoryField; + } + + /** + * This method initializes ddsLogFileField + * + * @return javax.swing.JTextField + */ + private JTextField getDdsLogFileField() { + if (ddsLogFileField == null) { + ddsLogFileField = new JTextField(); + } + return ddsLogFileField; + } + + /** + * This method initializes ddsRequireAuthCheck + * + * @return javax.swing.JCheckBox + */ + private JCheckBox getDdsRequireAuthCheck() { + if (ddsRequireAuthCheck == null) { + ddsRequireAuthCheck = new JCheckBox(); + ddsRequireAuthCheck.setText(labels.getString( + "LrgsConfigDialog.reqClientPasswdAuth")); + } + return ddsRequireAuthCheck; + } + + /** + * This method initializes recoverPanel + * + * @return javax.swing.JPanel + */ + private JPanel getRecoverPanel() + { + if (recoverPanel == null) + { + recoverPanel = new JPanel(new GridBagLayout()); + recoverPanel.setBorder(BorderFactory.createTitledBorder(null, + labels.getString( + "LrgsConfigDialog.LRGSDDSBackupTitle"), TitledBorder.CENTER, TitledBorder.BELOW_TOP, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); + recoverPanel.add(new JLabel(genericLabels.getString("timeout")), + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(10, 10, 4, 2), 0, 0)); + recoverPanel.add(ddsTimeoutField, + new GridBagConstraints(1, 1, 1, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(10, 0, 4, 10), 0, 0)); + recoverPanel.add(new JLabel(labels.getString("minHourly")), + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(4, 10, 4, 2), 0, 0)); + recoverPanel.add(ddsMinHourlyField, + new GridBagConstraints(1, 2, 1, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(4, 0, 4, 10), 0, 0)); + + recoverPanel.add(getEnableDDSReceiveCheck(), + new GridBagConstraints(0, 3, 2, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(0, 40, 0, 0), 0, 0)); + } + return recoverPanel; + } + + /** + * This method initializes enableDDSReceiveCheck + * + * @return javax.swing.JCheckBox + */ + private JCheckBox getEnableDDSReceiveCheck() { + if (enableDDSReceiveCheck == null) { + enableDDSReceiveCheck = new JCheckBox(); + enableDDSReceiveCheck.setText(labels.getString( + "LrgsConfigDialog.enableDDSReceivConn")); + } + return enableDDSReceiveCheck; + } + + /** + * This method initializes connectionsPanel + * + * @return javax.swing.JPanel + */ + private JPanel getConnectionsPanel() { + if (connectionsPanel == null) { + connectionsPanel = new JPanel(); + connectionsPanel.setLayout(new BorderLayout()); + connectionsPanel.setSize(new Dimension(150, 129)); + connectionsPanel.add(getConnectionsButtonPanel(), BorderLayout.EAST); + connectionsPanel.add(getDdsReceiveScrollPane(), BorderLayout.CENTER); + } + return connectionsPanel; + } + + /** + * This method initializes connectionsButtonPanel + * + * @return javax.swing.JPanel + */ + private JPanel getConnectionsButtonPanel() { + if (connectionsButtonPanel == null) { + GridBagConstraints ddsConMoveDownButtonConstraints = new GridBagConstraints(); + ddsConMoveDownButtonConstraints.gridx = 0; + ddsConMoveDownButtonConstraints.insets = new Insets(2, 5, 2, 5); + ddsConMoveDownButtonConstraints.weighty = 0.0D; + //ddsConMoveDownButtonConstraints.anchor = GridBagConstraints.NORTH; + ddsConMoveDownButtonConstraints.gridy = 4; + GridBagConstraints ddsConMoveUpButtonConstraints = new GridBagConstraints(); + ddsConMoveUpButtonConstraints.gridx = 0; + ddsConMoveUpButtonConstraints.insets = new Insets(2, 5, 2, 5); + ddsConMoveUpButtonConstraints.gridy = 3; + GridBagConstraints ddsConDeleteButtonConstraints = new GridBagConstraints(); + ddsConDeleteButtonConstraints.gridx = 0; + ddsConDeleteButtonConstraints.insets = new Insets(2, 5, 2, 5); + ddsConDeleteButtonConstraints.gridy = 2; + GridBagConstraints ddsConEditButtonConstraints = new GridBagConstraints(); + ddsConEditButtonConstraints.gridx = 0; + ddsConEditButtonConstraints.insets = new Insets(2, 5, 2, 5); + ddsConEditButtonConstraints.gridy = 1; + GridBagConstraints addButtonConstraints = new GridBagConstraints(); + addButtonConstraints.gridx = 0; + addButtonConstraints.gridwidth = 1; + addButtonConstraints.insets = new Insets(20, 5, 2, 5); + addButtonConstraints.weighty = 0.0D; + addButtonConstraints.gridy = 0; + + GridBagConstraints testButtonConstraints = new GridBagConstraints(); + testButtonConstraints.gridx = 0; + testButtonConstraints.gridwidth = 1; + testButtonConstraints.insets = new Insets(2, 5, 2, 5); + testButtonConstraints.weighty = 1.0D; + testButtonConstraints.anchor = GridBagConstraints.NORTH; + testButtonConstraints.gridy = 5; + + connectionsButtonPanel = new JPanel(); + connectionsButtonPanel.setLayout(new GridBagLayout()); + connectionsButtonPanel.add(getConnectionsButtonAdd(), addButtonConstraints); + connectionsButtonPanel.add(getConnectionsButtonEdit(), ddsConEditButtonConstraints); + connectionsButtonPanel.add(getConnectionsButtonDelete(), ddsConDeleteButtonConstraints); + connectionsButtonPanel.add(getConnectionsButtonMoveUp(), ddsConMoveUpButtonConstraints); + connectionsButtonPanel.add(getConnectionsButtonMoveDown(), ddsConMoveDownButtonConstraints); + connectionsButtonPanel.add(getConnectionsButtonTest(),testButtonConstraints); + } + return connectionsButtonPanel; + } + + private JButton getConnectionsButtonTest() { + if (ddsConTestButton == null) { + ddsConTestButton = new JButton(); + ddsConTestButton.setText(genericLabels.getString("test")); + ddsConTestButton.setMnemonic(KeyEvent.VK_UNDEFINED); + ddsConTestButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + testButtonPressed(); + } + }); + } + return ddsConTestButton; + } + private void testButtonPressed() + { + int idx = ddsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectConnEditErr")); + return; + } + DdsRecvConnectCfg cfg = (DdsRecvConnectCfg)ddsTableModel.getRowObject(idx); + + LddsClient myClient = new LddsClient(cfg.host,cfg.port); + + //TODO add option for password sending + LrgsConnectionTest myTester = new LrgsConnectionTest(this, myClient, cfg.username,null); + myTester.startConnect(); + + } + + /** + * This method initializes ddsConAddButton + * + * @return javax.swing.JButton + */ + private JButton getConnectionsButtonAdd() + { + if (ddsConAddButton == null) + { + ddsConAddButton = new JButton(); + ddsConAddButton.setText(genericLabels.getString("add")); + ddsConAddButton.setMnemonic(KeyEvent.VK_UNDEFINED); + ddsConAddButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + launchDdsRecvConDialog(false); + } + }); + } + return ddsConAddButton; + } + + private void launchDdsRecvConDialog(boolean edit) + { + DdsRecvConDialog dlg = new DdsRecvConDialog(this); + DdsRecvConnectCfg cfg = null; + if (edit) + { + int idx = ddsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectConnEditErr")); + return; + } + cfg = (DdsRecvConnectCfg)ddsTableModel.getRowObject(idx); + } + else // add + { + cfg = new DdsRecvConnectCfg(ddsTableModel.getRowCount(), ""); + } + dlg.setInfo(cfg); + launchDialog(dlg); + if (dlg.okPressed()) + { + if (!edit) + ddsTableModel.add(cfg); + else + ddsTableModel.modified(); + } + } + + private void deleteDdsCon() + { + int idx = ddsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectDDSConnDelErr")); + return; + } + DdsRecvConnectCfg cfg = + (DdsRecvConnectCfg)ddsTableModel.getRowObject(idx); + if( JOptionPane.showConfirmDialog(this, + LoadResourceBundle.sprintf(labels.getString( + "LrgsConfigDialog.DDSConnDel"),cfg.name), + labels.getString( + "LrgsConfigDialog.confirmDelete"), JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + { + ddsTableModel.deleteAt(idx); + } + } + + private void moveDdsConUp() + { + int idx = ddsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectDDSConnMoveErr")); + return; + } + if (ddsTableModel.moveUpAt(idx)) + ddsConTable.setRowSelectionInterval(idx-1, idx-1); + } + + private void moveDdsConDown() + { + int idx = ddsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectDDSConnMoveErr")); + return; + } + if (ddsTableModel.moveDownAt(idx)) + ddsConTable.setRowSelectionInterval(idx+1, idx+1); + } + + /** + * This method initializes ddsConEditButton + * + * @return javax.swing.JButton + */ + private JButton getConnectionsButtonEdit() { + if (ddsConEditButton == null) { + ddsConEditButton = new JButton(); + ddsConEditButton.setText(genericLabels.getString("edit")); + ddsConEditButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + launchDdsRecvConDialog(true); + } + }); + } + return ddsConEditButton; + } + + /** + * This method initializes ddsConDeleteButton + * + * @return javax.swing.JButton + */ + private JButton getConnectionsButtonDelete() { + if (ddsConDeleteButton == null) { + ddsConDeleteButton = new JButton(); + ddsConDeleteButton.setText(genericLabels.getString("delete")); + ddsConDeleteButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + deleteDdsCon(); + } + }); + } + return ddsConDeleteButton; + } + + /** + * This method initializes ddsConMoveUpButton + * + * @return javax.swing.JButton + */ + private JButton getConnectionsButtonMoveUp() + { + if (ddsConMoveUpButton == null) { + ddsConMoveUpButton = new JButton(); + ddsConMoveUpButton.setText(labels.getString( + "LrgsConfigDialog.moveUp")); + ddsConMoveUpButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + moveDdsConUp(); + } + }); + } + return ddsConMoveUpButton; + } + + /** + * This method initializes ddsConMoveDownButton + * + * @return javax.swing.JButton + */ + private JButton getConnectionsButtonMoveDown() + { + if (ddsConMoveDownButton == null) + { + ddsConMoveDownButton = new JButton(); + ddsConMoveDownButton.setText(labels.getString( + "LrgsConfigDialog.moveDn")); + ddsConMoveDownButton.addActionListener( + new java.awt.event.ActionListener() + { + public void actionPerformed(java.awt.event.ActionEvent e) + { + moveDdsConDown(); + } + }); + } + return ddsConMoveDownButton; + } + + /** + * This method initializes networkListsPanel + * + * @return javax.swing.JPanel + */ + private JPanel getNetworkListsPanel() + { + if (networkListsPanel == null) + { + networkListsPanel = new JPanel(); + networkListsPanel.setLayout(new BorderLayout()); + networkListsPanel.setSize(new Dimension(176, 177)); + networkListsPanel.setBorder(BorderFactory.createTitledBorder(null, + labels.getString("LrgsConfigDialog.DDSNetListTextArea"), + TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 12), new Color(51, 51, 51))); + networkListsPanel.add(getNetworkListsButtonPanel(), BorderLayout.EAST); + networkListsPanel.add(getNetworkListsScrollPane(), BorderLayout.CENTER); + } + return networkListsPanel; + } + + /** + * This method initializes networkListsButtonPanel + * + * @return javax.swing.JPanel + */ + private JPanel getNetworkListsButtonPanel() + { + if (networkListsButtonPanel == null) + { + GridBagConstraints networkListsDeleteButtonConstraints = new GridBagConstraints(); + networkListsDeleteButtonConstraints.gridx = 0; + networkListsDeleteButtonConstraints.insets = new Insets(2, 5, 2, 5); + networkListsDeleteButtonConstraints.weighty = 1.0D; + networkListsDeleteButtonConstraints.anchor = GridBagConstraints.NORTH; + networkListsDeleteButtonConstraints.gridy = 1; + GridBagConstraints networkListsAddButtonConstraints = new GridBagConstraints(); + networkListsAddButtonConstraints.gridx = 0; + networkListsAddButtonConstraints.insets = new Insets(2, 5, 2, 5); + networkListsAddButtonConstraints.gridy = 0; + networkListsButtonPanel = new JPanel(); + networkListsButtonPanel.setLayout(new GridBagLayout()); + networkListsButtonPanel.add(getNetworkListsAddButton(), networkListsAddButtonConstraints); + networkListsButtonPanel.add(getNetworkListsDeleteButton(), networkListsDeleteButtonConstraints); + } + return networkListsButtonPanel; + } + + /** + * This method initializes networkListsAddButton + * + * @return javax.swing.JButton + */ + private JButton getNetworkListsAddButton() + { + if (networkListsAddButton == null) + { + networkListsAddButton = new JButton(); + networkListsAddButton.setText(genericLabels.getString("add")); + networkListsAddButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) { + + //Now network list can be associated with the groups, primary, secondary or both + JPanel panel = new JPanel(new GridLayout(4,1)); + panel.add(new JLabel(labels.getString("LrgsConfigDialog.enterNLToAdd"))); + JTextField netlist = new JTextField(); + panel.add(netlist); + Object[] items = {"Primary", "Secondary","Both"}; + + JComboBox jcb = new JComboBox(items); + + jcb.setEditable(false); + panel.add(new JLabel("Group")); + panel.add(jcb); + + Integer res = (Integer)JOptionPane.showOptionDialog( + new JFrame(), panel, "Network List",JOptionPane.OK_CANCEL_OPTION, + JOptionPane.PLAIN_MESSAGE,null,null,null + ); + if(res.intValue()==0 && netlist.getText()!=null && netlist.getText().trim().length()>0 ) + { + Object[] rowData = {netlist.getText(), jcb.getSelectedItem()}; + netlistTableModel.addRow(rowData); + netlistsModified = true; + } + } + }); + } + return networkListsAddButton; + } + + /** + * This method initializes networkListsDeleteButton + * + * @return javax.swing.JButton + */ + private JButton getNetworkListsDeleteButton() + { + if (networkListsDeleteButton == null) + { + networkListsDeleteButton = new JButton(); + networkListsDeleteButton.setText( + genericLabels.getString("delete")); + networkListsDeleteButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) + { + //removeNetworkListAt(getNetworkList().getSelectedIndex()); + removeNetworkListAt(getNetworkListTable().getSelectedRow()); + netlistsModified = true; + } + }); + } + return networkListsDeleteButton; + } + + /** + * This method initializes jPanel + * + * @return javax.swing.JPanel + */ + private JPanel getJPanel() + { + if (jPanel == null) + { + jPanel = new JPanel(); + jPanel.setLayout(new BoxLayout(getJPanel(), BoxLayout.Y_AXIS)); + jPanel.add(getDrgsConfigPanel(), null); + } + return jPanel; + } + + /** + * This method initializes drgsConfigPanel + * + * @return javax.swing.JPanel + */ + private JPanel getDrgsConfigPanel() + { + if (drgsConfigPanel == null) + { + drgsConfigPanel = new JPanel(); + drgsConfigPanel.setLayout(new BorderLayout()); + drgsConfigPanel.setBorder( + BorderFactory.createTitledBorder(null, + labels.getString("LrgsConfigDialog.DRGSConfTitle"), + TitledBorder.CENTER, TitledBorder.BELOW_TOP, + new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); + drgsConfigPanel.add(getDrgsTablePanel(), BorderLayout.CENTER); + } + return drgsConfigPanel; + } + + /** + * This method initializes drgsButtonPanel + * + * @return javax.swing.JPanel + */ + private JPanel getDrgsButtonPanel() + { + if (drgsButtonPanel == null) + { + GridBagConstraints addButtonConstraints = + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, + GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(10, 4, 2, 4), 0, 0); + + GridBagConstraints drgsEditButtonConstraints = + new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, + GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 4, 2, 4), 0, 0); + + GridBagConstraints drgsDeleteButtonConstraints = + new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, + GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL, + new Insets(2, 4, 2, 4), 0, 0); + GridBagConstraints drgsTestButtonConstraints = + new GridBagConstraints(0, 3, 1, 1, 0.0, 1.0, + GridBagConstraints.NORTH, GridBagConstraints.HORIZONTAL, + new Insets(2, 4, 2, 4), 0, 0); + + + drgsButtonPanel = new JPanel(); + drgsButtonPanel.setLayout(new GridBagLayout()); + drgsButtonPanel.add(getDrgsAddButton(), addButtonConstraints); + drgsButtonPanel.add(getDrgsEditButton(), drgsEditButtonConstraints); + drgsButtonPanel.add(getDrgsDeleteButton(), drgsDeleteButtonConstraints); + drgsButtonPanel.add(getDrgsTestButton(), drgsTestButtonConstraints); + } + return drgsButtonPanel; + } + + private JButton getDrgsTestButton() { + if (drgsTestButton == null) { + drgsTestButton = new JButton(); + drgsTestButton.setText(genericLabels.getString("test")); + drgsTestButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) + { + drgsTestButtonPressed(); + } + }); + } + return drgsTestButton; + } + + private void drgsTestButtonPressed() + { + int idx = drgsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectConnEditErr")); + return; + } + DrgsConnectCfg cfg = (DrgsConnectCfg)drgsTableModel.getRowObject(idx); + + BasicClient myClient = new BasicClient(cfg.host,cfg.msgPort); + + //TODO add option for password sending + LrgsConnectionTest myTester = new LrgsConnectionTest(this, myClient); + myTester.startConnect(); + } + + /** + * This method initializes drgsAddButton + * + * @return javax.swing.JButton + */ + private JButton getDrgsAddButton() + { + if (drgsAddButton == null) + { + drgsAddButton = new JButton(); + drgsAddButton.setText(genericLabels.getString("add")); + drgsAddButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) + { + launchDrgsConDialog(false); + } + }); + } + return drgsAddButton; + } + + /** + * This method initializes drgsEditButton + * + * @return javax.swing.JButton + */ + private JButton getDrgsEditButton() + { + if (drgsEditButton == null) + { + drgsEditButton = new JButton(); + drgsEditButton.setText(genericLabels.getString("edit")); + drgsEditButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) + { + launchDrgsConDialog(true); + } + }); + } + return drgsEditButton; + } + + private void launchDrgsConDialog(boolean edit) + { + DrgsConDialog dlg = new DrgsConDialog(this); + DrgsConnectCfg cfg = null; + if (edit) + { + int idx = drgsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectConnEditErr")); + return; + } + cfg = (DrgsConnectCfg)drgsTableModel.getRowObject(idx); + dlg.setInfo(cfg); + } + else // add + { + cfg = new DrgsConnectCfg(drgsConTable.getRowCount(), ""); + dlg.setInfo(cfg); + } + launchDialog(dlg); + if (dlg.okPressed()) + { + if (!edit) + drgsTableModel.add(cfg); + else + drgsTableModel.modified(); + } + } + + private void deleteDrgsCon() + { + int idx = drgsConTable.getSelectedRow(); + if (idx == -1) + { + showError(labels.getString( + "LrgsConfigDialog.selectDRGSConnDelErr")); + return; + } + DrgsConnectCfg cfg = + (DrgsConnectCfg)drgsTableModel.getRowObject(idx); + if( JOptionPane.showConfirmDialog(this, + LoadResourceBundle.sprintf( + labels.getString("LrgsConfigDialog.DRGSConnDel"), + cfg.name), + labels.getString("LrgsConfigDialog.confirmDelete"), + JOptionPane.YES_NO_OPTION) + == JOptionPane.YES_OPTION) + { + drgsTableModel.deleteAt(idx); + } + } + + + + /** + * This method initializes drgsDeleteButton + * + * @return javax.swing.JButton + */ + private JButton getDrgsDeleteButton() + { + if (drgsDeleteButton == null) + { + drgsDeleteButton = new JButton(); + drgsDeleteButton.setText(genericLabels.getString("delete")); + drgsDeleteButton.addActionListener(new java.awt.event.ActionListener() { + public void actionPerformed(java.awt.event.ActionEvent e) + { + deleteDrgsCon(); + } + }); + } + return drgsDeleteButton; + } + + /** + * This method initializes networkListsScrollPane + * + * @return javax.swing.JScrollPane + */ + private JScrollPane getNetworkListsScrollPane() + { + if (networkListsScrollPane == null) + { + networkListsScrollPane = new JScrollPane(); + networkListsScrollPane.setViewportView(getNetworkListTable()); + } + return networkListsScrollPane; + } + + /** + * This method initializes networkList + * + * @return javax.swing.JList + */ + private JTable getNetworkListTable() + { + if (networkListTable == null) + { + networkListTable = new JTable(netlistTableModel); + netlistTableModel.addColumn("Network List Name"); + netlistTableModel.addColumn("Group"); + JTableHeader header =networkListTable.getTableHeader(); + header.setBorder( BorderFactory.createRaisedBevelBorder()); + header.setEnabled(false); + header.setBackground(Color.white); + header.setFocusable(false); + networkListTable.setTableHeader(header); + networkListTable.setVisible(true); + } + return networkListTable; + } + + /** + * This method initializes drgsTablePanel + * + * @return javax.swing.JPanel + */ + private JPanel getDrgsTablePanel() + { + if (drgsTablePanel == null) + { + drgsTablePanel = new JPanel(new GridBagLayout()); + + drgsTablePanel.add(new JLabel(labels.getString("minHourly")), + new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, + GridBagConstraints.EAST, GridBagConstraints.NONE, + new Insets(10, 10, 2, 0), 0, 0)); + drgsTablePanel.add(drgsMinHourlyField, + new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(10, 1, 2, 10), 0, 0)); + + drgsTablePanel.add(getEnableDRGSCheck(), + new GridBagConstraints(0, 1, 2, 1, 0.0, 0.0, + GridBagConstraints.WEST, GridBagConstraints.NONE, + new Insets(4, 10, 2, 10), 0, 0)); + + drgsTablePanel.add(getConnectionsScrollPane(), + new GridBagConstraints(0, 2, 2, 1, 1.0, 1.0, + GridBagConstraints.WEST, GridBagConstraints.BOTH, + new Insets(5, 5, 5, 5), 0, 0)); + + + drgsTablePanel.add(getDrgsButtonPanel(), + new GridBagConstraints(2, 2, 1, 1, 0.0, 1.0, + GridBagConstraints.NORTH, GridBagConstraints.NONE, + new Insets(5, 5, 5, 5), 0, 0)); + } + return drgsTablePanel; + } + + /** + * This method initializes enableDRGSCheck + * + * @return javax.swing.JCheckBox + */ + private JCheckBox getEnableDRGSCheck() + { + if (enableDRGSCheck == null) + { + enableDRGSCheck = new JCheckBox(); + enableDRGSCheck.setText(labels.getString("LrgsConfigDialog.enableDRGSConn")); + } + return enableDRGSCheck; + } + + /** + * This method initializes drgsConTable + * + * @return javax.swing.JTable + */ + private JTable getConnectionsTable() + { + if (drgsConTable == null) + { + drgsTableModel = new DrgsSortingListTableModel(); + drgsConTable = new SortingListTable(drgsTableModel,drgsTableModel.columnWidths); + } + return drgsConTable; + } + + /** + * This method initializes ddsConTable + * + * @return javax.swing.JTable + */ + private JTable getDdsReceiveTable() + { + if (ddsConTable == null) + { + ddsTableModel = new DdsSortingListTableModel(); + ddsConTable = new SortingListTable(ddsTableModel,ddsTableModel.columnWidths); + } + return ddsConTable; + } + + /** + * This method initializes SqlDatabasePanel + * + * @return javax.swing.JPanel + */ + private JPanel getSqlDatabasePanel() + { + if (SqlDatabasePanel == null) + { + GridBagConstraints sqlUrlFieldConstraints = new GridBagConstraints(); + sqlUrlFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + sqlUrlFieldConstraints.anchor = GridBagConstraints.SOUTHWEST; + sqlUrlFieldConstraints.gridx = 1; + sqlUrlFieldConstraints.gridy = 0; + sqlUrlFieldConstraints.weightx = 1.0; + sqlUrlFieldConstraints.weighty = 0.5; + sqlUrlFieldConstraints.insets = new Insets(2, 0, 2, 10); + sqlUrlFieldConstraints.gridwidth = 2; + + GridBagConstraints sqlKeyFieldConstraints = new GridBagConstraints(); + sqlKeyFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + sqlKeyFieldConstraints.anchor = GridBagConstraints.WEST; + sqlKeyFieldConstraints.gridy = 5; + sqlKeyFieldConstraints.weightx = 1.0; + sqlKeyFieldConstraints.weighty = 0.5; + sqlKeyFieldConstraints.insets = new Insets(2, 0, 2, 10); + sqlKeyFieldConstraints.gridx = 2; + + GridBagConstraints sqlDriverFieldConstraints = new GridBagConstraints(); + sqlDriverFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + sqlDriverFieldConstraints.gridy = 4; + sqlDriverFieldConstraints.weightx = 1.0; + sqlDriverFieldConstraints.insets = new Insets(2, 0, 2, 10); + sqlDriverFieldConstraints.gridx = 2; + + GridBagConstraints sqlTimeZoneComboConstraints = new GridBagConstraints(); + sqlTimeZoneComboConstraints.fill = GridBagConstraints.HORIZONTAL; + sqlTimeZoneComboConstraints.gridy = 3; + sqlTimeZoneComboConstraints.weightx = 1.0; + sqlTimeZoneComboConstraints.insets = new Insets(2, 0, 2, 10); + sqlTimeZoneComboConstraints.gridx = 2; + + GridBagConstraints sqlWriteFieldConstraints = new GridBagConstraints(); + sqlWriteFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + sqlWriteFieldConstraints.gridy = 2; + sqlWriteFieldConstraints.weightx = 1.0; + sqlWriteFieldConstraints.insets = new Insets(2, 0, 2, 10); + sqlWriteFieldConstraints.gridx = 2; + + GridBagConstraints sqlReadFieldConstraints = new GridBagConstraints(); + sqlReadFieldConstraints.fill = GridBagConstraints.HORIZONTAL; + sqlReadFieldConstraints.gridy = 1; + sqlReadFieldConstraints.weightx = 1.0; + sqlReadFieldConstraints.insets = new Insets(2, 0, 2, 10); + sqlReadFieldConstraints.gridx = 2; + + GridBagConstraints sqlKeyLabelConstraints = new GridBagConstraints(); + sqlKeyLabelConstraints.gridx = 0; + sqlKeyLabelConstraints.gridwidth = 2; + sqlKeyLabelConstraints.anchor = GridBagConstraints.EAST; + sqlKeyLabelConstraints.weighty = 0.5; + sqlKeyLabelConstraints.insets = new Insets(2, 2, 3, 2); + sqlKeyLabelConstraints.gridy = 5; + sqlKeyLabel = new JLabel(); + sqlKeyLabel.setText(labels.getString( + "LrgsConfigDialog.keyGeneratorClass")); + + GridBagConstraints sqlTimeZoneLabelConstraints = new GridBagConstraints(); + sqlTimeZoneLabelConstraints.gridx = 0; + sqlTimeZoneLabelConstraints.anchor = GridBagConstraints.EAST; + sqlTimeZoneLabelConstraints.gridwidth = 2; + sqlTimeZoneLabelConstraints.insets = new Insets(2, 2, 3, 2); + sqlTimeZoneLabelConstraints.gridy = 3; + sqlTimeZoneLabel = new JLabel(); + sqlTimeZoneLabel.setText(labels.getString( + "LrgsConfigDialog.SQLTimeZone")); + + GridBagConstraints sqlDriverLabelConstraints = new GridBagConstraints(); + sqlDriverLabelConstraints.gridx = 0; + sqlDriverLabelConstraints.anchor = GridBagConstraints.EAST; + sqlDriverLabelConstraints.gridwidth = 2; + sqlDriverLabelConstraints.insets = new Insets(2, 2, 3, 2); + sqlDriverLabelConstraints.gridy = 4; + sqlDriverLabel = new JLabel(); + sqlDriverLabel.setText(labels.getString( + "LrgsConfigDialog.JDBCDriverClass")); + + + GridBagConstraints sqlWriteLabelConstraints = new GridBagConstraints(); + sqlWriteLabelConstraints.gridx = 0; + sqlWriteLabelConstraints.anchor = GridBagConstraints.EAST; + sqlWriteLabelConstraints.gridwidth = 2; + sqlWriteLabelConstraints.insets = new Insets(2, 2, 3, 2); + sqlWriteLabelConstraints.gridy = 2; + sqlWriteLabel = new JLabel(); + sqlWriteLabel.setText(labels.getString( + "LrgsConfigDialog.writeTimeFormat")); + GridBagConstraints sqlReadLabelConstraints = new GridBagConstraints(); + sqlReadLabelConstraints.gridx = 0; + sqlReadLabelConstraints.insets = new Insets(2, 40, 3, 2); + sqlReadLabelConstraints.anchor = GridBagConstraints.EAST; + sqlReadLabelConstraints.gridwidth = 2; + sqlReadLabelConstraints.gridy = 1; + sqlReadLabel = new JLabel(); + sqlReadLabel.setText(labels.getString( + "LrgsConfigDialog.readTimeFormat")); + + GridBagConstraints sqlUrlLabelConstraints = new GridBagConstraints(); + sqlUrlLabelConstraints.gridx = 0; + sqlUrlLabelConstraints.anchor = GridBagConstraints.SOUTHEAST; + sqlUrlLabelConstraints.insets = new Insets(2, 40, 3, 2); + sqlUrlLabelConstraints.gridy = 0; + sqlUrlLabelConstraints.weighty = 0.5; + sqlUrlLabel = new JLabel(); + sqlUrlLabel.setText(labels.getString( + "LrgsConfigDialog.URL")); + + SqlDatabasePanel = new JPanel(); + SqlDatabasePanel.setLayout(new GridBagLayout()); + SqlDatabasePanel.setBorder(BorderFactory.createTitledBorder( + BorderFactory.createBevelBorder(BevelBorder.LOWERED), + labels.getString("LrgsConfigDialog.SQLDBPref"), + TitledBorder.DEFAULT_JUSTIFICATION, TitledBorder.DEFAULT_POSITION, new Font("Dialog", Font.BOLD, 14), new Color(51, 51, 51))); + SqlDatabasePanel.add(sqlUrlLabel, sqlUrlLabelConstraints); + SqlDatabasePanel.add(sqlReadLabel, sqlReadLabelConstraints); + SqlDatabasePanel.add(sqlWriteLabel, sqlWriteLabelConstraints); + SqlDatabasePanel.add(getSqlUrlField(), sqlUrlFieldConstraints); + SqlDatabasePanel.add(getSqlReadField(), sqlReadFieldConstraints); + SqlDatabasePanel.add(getSqlWriteField(), sqlWriteFieldConstraints); + SqlDatabasePanel.add(sqlTimeZoneLabel, sqlTimeZoneLabelConstraints); + SqlDatabasePanel.add(getSqlTimeZoneCombo(), sqlTimeZoneComboConstraints); + SqlDatabasePanel.add(sqlDriverLabel, sqlDriverLabelConstraints); + SqlDatabasePanel.add(sqlKeyLabel, sqlKeyLabelConstraints); + SqlDatabasePanel.add(getSqlDriverField(), sqlDriverFieldConstraints); + SqlDatabasePanel.add(getSqlKeyField(), sqlKeyFieldConstraints); + + SqlDatabasePanel.add(goesXmitCheck, + new GridBagConstraints(0, 6, 2, 1, 0.0, 0.5, + GridBagConstraints.CENTER, GridBagConstraints.NORTH, + new Insets(5, 20, 5, 2), 0, 0)); + } + return SqlDatabasePanel; + } + + + + + + + + /** + * This method initializes containerPanel + * + * @return javax.swing.JPanel + */ + private JPanel getContainerPanel() + { + if (containerPanel == null) + { + containerPanel = new JPanel(); + containerPanel.setLayout(new BoxLayout(getContainerPanel(), BoxLayout.X_AXIS)); + containerPanel.setSize(new Dimension(230, 145)); + containerPanel.add(getDataSourcePrefPanel(), null); + containerPanel.add(getSqlDatabasePanel(),null); + } + return containerPanel; + } + + /** + * This method initializes sqlUrlField + * + * @return javax.swing.JTextField + */ + private JTextField getSqlUrlField() + { + if (sqlUrlField == null) + { + sqlUrlField = new JTextField(); + } + return sqlUrlField; + } + + /** + * This method initializes sqlReadField + * + * @return javax.swing.JTextField + */ + private JTextField getSqlReadField() + { + if (sqlReadField == null) + { + sqlReadField = new JTextField(); + } + return sqlReadField; + } + + /** + * This method initializes sqlWriteField + * + * @return javax.swing.JTextField + */ + private JTextField getSqlWriteField() + { + if (sqlWriteField == null) + { + sqlWriteField = new JTextField(); + } + return sqlWriteField; + } + + /** + * This method initializes sqlTimeZoneCombo + * + * @return javax.swing.JComboBox + */ + private JComboBox getSqlTimeZoneCombo() + { + if (sqlTimeZoneCombo == null) + { + sqlTimeZoneCombo = new TimeZoneSelector(); + sqlTimeZoneCombo.setTZ("UTC"); + } + return sqlTimeZoneCombo; + } + + /** + * This method initializes sqlDriverField + * + * @return javax.swing.JTextField + */ + private JTextField getSqlDriverField() + { + if (sqlDriverField == null) + { + sqlDriverField = new JTextField(); + } + return sqlDriverField; + } + + /** + * This method initializes sqlKeyField + * + * @return javax.swing.JTextField + */ + private JTextField getSqlKeyField() + { + if (sqlKeyField == null) + { + sqlKeyField = new JTextField(); + } + return sqlKeyField; + } + + /** + * This method initializes connectionsScrollPane + * + * @return javax.swing.JScrollPane + */ + private JScrollPane getConnectionsScrollPane() + { + if (connectionsScrollPane == null) + { + connectionsScrollPane = new JScrollPane(); + connectionsScrollPane.setViewportView(getConnectionsTable()); + } + return connectionsScrollPane; + } + + /** + * This method initializes ddsReceiveScrollPane + * + * @return javax.swing.JScrollPane + */ + private JScrollPane getDdsReceiveScrollPane() + { + if (ddsReceiveScrollPane == null) + { + ddsReceiveScrollPane = new JScrollPane(getDdsReceiveTable()); + } + return ddsReceiveScrollPane; + } + + private void removeNetworkListAt(int idx) + { + if (idx == -1) + return; + //netlistListModel.remove(idx); + netlistTableModel.removeRow(idx); + } + + private void okPressed() + { + if (applyPressed(false)) + { + setVisible(false); + } + } + + private void cancelPressed() + { + setVisible(false); + } + + private boolean applyPressed(boolean force) + { + try + { + boolean extraChanges = false; + + if (noaaConfigTab.hasChanged()) + { + extraChanges = true; + noaaConfigTab.saveChanges(); + } + if (iridiumCfgTab.hasChanged()) + { + extraChanges = true; + iridiumCfgTab.saveChanges(); + } + if (lritCfgPanel.hasChanged()) + { + extraChanges = true; + lritCfgPanel.saveChanges(); + } + if (hritFileCfgPanel.hasChanged()) + { + extraChanges = true; + hritFileCfgPanel.saveChanges(); + } + if (edlConfigPanel.hasChanged()) + { + extraChanges = true; + edlConfigPanel.saveChanges(); + } + if (copyBackLrgsConfig() || force || extraChanges) + { + ddsClientIf.applyLrgsConfig(lrgsConfig); + } + + if (copyBackDdsSettings() || force) + { + ddsClientIf.applyDdsRecvSettings(ddsSettings); + } + + if (copyBackDrgsConfig() || force) + { + ddsClientIf.applyDrgsInputSettings(drgsSettings); + } + + if (copyBackNetworkDcpConfig() || force) + { + ddsClientIf.applyNetworkDcpSettings(networkDcpSettings); + } + + return true; + } + catch(ParseException ex) + { + showError(labels.getString( + "LrgsConfigDialog.correctErrRetry")); + return false; + } + catch(AuthException ex) + { + showError(labels.getString( + "LrgsConfigDialog.applyChangesErr") + ex); + return false; + } + } } -class DdsSortingListTableModel - extends AbstractTableModel implements SortingListTableModel +class DdsSortingListTableModel extends AbstractTableModel + implements SortingListTableModel { - private static ResourceBundle labels = - RtStat.getLabels(); - String columnNames[] = null; - int columnWidths[] = { 10, 20, 35, 15, 20, 10, 10, 10,10}; - ArrayList cons; - boolean modified = false; - - public DdsSortingListTableModel() - { - columnNames = new String[9]; - columnNames[0] = labels.getString("LrgsConfigDialog.useColumn"); - columnNames[1] = labels.getString("LrgsConfigDialog.nameColumn"); - columnNames[2] = labels.getString("LrgsConfigDialog.hostIPAddrColumn"); - columnNames[3] = labels.getString("LrgsConfigDialog.portColumn"); - columnNames[4] = labels.getString("LrgsConfigDialog.userColumn"); - columnNames[5] = labels.getString("LrgsConfigDialog.pwColumn"); - columnNames[6] = labels.getString("LrgsConfigDialog.seqColumn"); - columnNames[7] = "ARMs?"; - columnNames[8] = labels.getString("LrgsConfigDialog.group"); - - cons = new ArrayList(); - } - - public void clear() - { - cons.clear(); - } - - public void add(DdsRecvConnectCfg cfg) - { - cons.add(cfg); - modified(); - } - - public void modified() - { - super.fireTableDataChanged(); - modified = true; - } - - public void deleteAt(int idx) - { - if (idx < 0 || idx >= cons.size()) - return; - cons.remove(idx); - for(int i=idx; i= cons.size()) - return false; - DdsRecvConnectCfg con = cons.remove(idx); - cons.add(idx-1, con); - for(int i=0; i= cons.size()-1) - return false; - DdsRecvConnectCfg con = cons.remove(idx); - cons.add(idx+1, con); - for(int i=0; i=0 && r < cons.size()) - return cons.get(r); - return null; - } - - public String getColumnName(int col) - { - return columnNames[col]; - } - - - public int getColumnCount() - { - return columnNames.length; - } + private static ResourceBundle labels = RtStat.getLabels(); + String columnNames[] = null; + int columnWidths[] = { 10, 20, 35, 15, 20, 10, 10, 10,10}; + ArrayList cons; + boolean modified = false; + + public DdsSortingListTableModel() + { + columnNames = new String[9]; + columnNames[0] = labels.getString("LrgsConfigDialog.useColumn"); + columnNames[1] = labels.getString("LrgsConfigDialog.nameColumn"); + columnNames[2] = labels.getString("LrgsConfigDialog.hostIPAddrColumn"); + columnNames[3] = labels.getString("LrgsConfigDialog.portColumn"); + columnNames[4] = labels.getString("LrgsConfigDialog.userColumn"); + columnNames[5] = labels.getString("LrgsConfigDialog.pwColumn"); + columnNames[6] = labels.getString("LrgsConfigDialog.seqColumn"); + columnNames[7] = "ARMs?"; + columnNames[8] = labels.getString("LrgsConfigDialog.group"); + + cons = new ArrayList(); + } + + public void clear() + { + cons.clear(); + } + + public void add(DdsRecvConnectCfg cfg) + { + cons.add(cfg); + modified(); + } + + public void modified() + { + super.fireTableDataChanged(); + modified = true; + } + + public void deleteAt(int idx) + { + if (idx < 0 || idx >= cons.size()) + { + return; + } + cons.remove(idx); + for(int i=idx; i= cons.size()) + { + return false; + } + DdsRecvConnectCfg con = cons.remove(idx); + cons.add(idx-1, con); + for(int i=0; i= cons.size()-1) + { + return false; + } + DdsRecvConnectCfg con = cons.remove(idx); + cons.add(idx+1, con); + for(int i=0; i=0 && r < cons.size()) + { + return cons.get(r); + } + return null; + } + + public String getColumnName(int col) + { + return columnNames[col]; + } + + + public int getColumnCount() + { + return columnNames.length; + } } -class DrgsSortingListTableModel - extends AbstractTableModel implements SortingListTableModel +class DrgsSortingListTableModel extends AbstractTableModel + implements SortingListTableModel { - private static ResourceBundle labels = - RtStat.getLabels(); - - String columnNames[] = null; - int columnWidths[] = { 10, 20, 30, 10, 10, 20}; - ArrayList cons; - boolean modified = false; - - public DrgsSortingListTableModel() - { - columnNames = new String[6]; - columnNames[0] = labels.getString("LrgsConfigDialog.useColumn"); - columnNames[1] = labels.getString("LrgsConfigDialog.nameColumn"); - columnNames[2] = labels.getString("LrgsConfigDialog.hostIPAddrColumn"); - columnNames[3] = labels.getString("LrgsConfigDialog.msgPortColumn"); - columnNames[4] = labels.getString("LrgsConfigDialog.evtsColumn"); - columnNames[5] = labels.getString("LrgsConfigDialog.chanCfgColumn"); - - cons = new ArrayList(); - } - - public void setContents(DrgsInputSettings settings) - { - cons.clear(); - for(DrgsConnectCfg con : settings.connections) - cons.add(new DrgsConnectCfg(con)); - Collections.sort(cons); - } - - public void clear() - { - cons.clear(); - } - - public void add(DrgsConnectCfg cfg) - { - cons.add(cfg); - modified(); - } - - public void modified() - { - super.fireTableDataChanged(); - modified = true; - } - - public void deleteAt(int idx) - { - if (idx < 0 || idx >= cons.size()) - return; - cons.remove(idx); - for(int i=idx; i=0 && r < cons.size()) - return cons.get(r); - return null; - } - - public String getColumnName(int col) - { - return columnNames[col]; - } - - public Object getValueAt(int r, int c) - { - DrgsConnectCfg cfg = (DrgsConnectCfg)getRowObject(r); - if (cfg == null) - return ""; - - switch(c) - { - case 0: return "" + cfg.msgEnabled; - case 1: return cfg.name == null ? "" : cfg.name; - case 2: return cfg.host == null ? "" : cfg.host; - case 3: return "" + cfg.msgPort; - case 4: return "" + cfg.evtEnabled; - case 5: return cfg.cfgFile == null ? "" : cfg.cfgFile; - default: return ""; - } - } - - public int getColumnCount() { - return columnNames.length; - } + private static ResourceBundle labels = RtStat.getLabels(); + + String columnNames[] = null; + int columnWidths[] = { 10, 20, 30, 10, 10, 20}; + ArrayList cons; + boolean modified = false; + + public DrgsSortingListTableModel() + { + columnNames = new String[6]; + columnNames[0] = labels.getString("LrgsConfigDialog.useColumn"); + columnNames[1] = labels.getString("LrgsConfigDialog.nameColumn"); + columnNames[2] = labels.getString("LrgsConfigDialog.hostIPAddrColumn"); + columnNames[3] = labels.getString("LrgsConfigDialog.msgPortColumn"); + columnNames[4] = labels.getString("LrgsConfigDialog.evtsColumn"); + columnNames[5] = labels.getString("LrgsConfigDialog.chanCfgColumn"); + + cons = new ArrayList(); + } + + public void setContents(DrgsInputSettings settings) + { + cons.clear(); + for(DrgsConnectCfg con : settings.connections) + { + cons.add(new DrgsConnectCfg(con)); + } + Collections.sort(cons); + } + + public void clear() + { + cons.clear(); + } + + public void add(DrgsConnectCfg cfg) + { + cons.add(cfg); + modified(); + } + + public void modified() + { + super.fireTableDataChanged(); + modified = true; + } + + public void deleteAt(int idx) + { + if (idx < 0 || idx >= cons.size()) + { + return; + } + cons.remove(idx); + for(int i=idx; i=0 && r < cons.size()) + { + return cons.get(r); + } + return null; + } + + public String getColumnName(int col) + { + return columnNames[col]; + } + + public Object getValueAt(int r, int c) + { + DrgsConnectCfg cfg = (DrgsConnectCfg)getRowObject(r); + if (cfg == null) + { + return ""; + } + + switch(c) + { + case 0: return "" + cfg.msgEnabled; + case 1: return cfg.name == null ? "" : cfg.name; + case 2: return cfg.host == null ? "" : cfg.host; + case 3: return "" + cfg.msgPort; + case 4: return "" + cfg.evtEnabled; + case 5: return cfg.cfgFile == null ? "" : cfg.cfgFile; + default: return ""; + } + } + + public int getColumnCount() + { + return columnNames.length; + } } diff --git a/src/main/java/lrgs/rtstat/RtStatCmdLineArgs.java b/src/main/java/lrgs/rtstat/RtStatCmdLineArgs.java index c9ae5eb7d..f5d32ab51 100644 --- a/src/main/java/lrgs/rtstat/RtStatCmdLineArgs.java +++ b/src/main/java/lrgs/rtstat/RtStatCmdLineArgs.java @@ -12,7 +12,6 @@ import ilex.cmdline.*; import ilex.util.Logger; -import ilex.util.FileLogger; import ilex.util.EnvExpander; public class RtStatCmdLineArgs diff --git a/src/main/java/lrgs/rtstat/RtStatFrame.java b/src/main/java/lrgs/rtstat/RtStatFrame.java index 70f1f2702..0cbff5a5f 100644 --- a/src/main/java/lrgs/rtstat/RtStatFrame.java +++ b/src/main/java/lrgs/rtstat/RtStatFrame.java @@ -21,7 +21,6 @@ import java.util.Date; import java.util.ResourceBundle; import java.util.StringTokenizer; -import java.util.Enumeration; import java.util.Properties; import org.w3c.dom.Document; @@ -35,7 +34,6 @@ import ilex.util.AsciiUtil; import ilex.util.AuthException; import ilex.util.DesEncrypter; -import ilex.util.EnvExpander; import ilex.util.Logger; import ilex.util.PropertiesUtil; import ilex.util.TextUtil; @@ -71,7 +69,6 @@ public class RtStatFrame private JMenuItem fileUserAdmin = new JMenuItem(); private JMenuItem fileLrgsConfig = new JMenuItem(); private JMenuItem jMenuFileExit = new JMenuItem(); -// private JMenuItem fileOutageMaintenance = new JMenuItem(); private JMenuItem fileNetworkLists = new JMenuItem(); private JMenu jMenuHelp = new JMenu(); private JMenuItem jMenuHelpAbout = new JMenuItem(); @@ -133,7 +130,6 @@ public class RtStatFrame /** Constructor. */ public RtStatFrame(int scanPeriod, String iconFile, String headerFile) { -// enableEvents(AWTEvent.WINDOW_EVENT_MASK); exitOnClose = true; try { @@ -275,16 +271,6 @@ public void actionPerformed(ActionEvent e) } }); -// fileOutageMaintenance.setText( -// labels.getString("RtStatFrame.outages")); -// fileOutageMaintenance.addActionListener( -// new java.awt.event.ActionListener() -// { -// public void actionPerformed(ActionEvent e) -// { -// fileOutageMaintenance_actionPerformed(); -// } -// }); fileNetworkLists.setText( labels.getString("RtStatFrame.networkLists")); fileNetworkLists.addActionListener( @@ -315,19 +301,11 @@ public void actionPerformed(ActionEvent e) topPanel.setLayout(gridBagLayout1); portLabel.setText( labels.getString("RtStatFrame.port")); -// portField.setMinimumSize(new Dimension(60, 23)); -// portField.setPreferredSize(new Dimension(60, 23)); portField.setText("16003"); userLabel.setText( labels.getString("RtStatFrame.user")); -// userField.setMinimumSize(new Dimension(90, 23)); -// userField.setPreferredSize(new Dimension(90, 23)); -// passwordField.setMinimumSize(new Dimension(90, 23)); -// passwordField.setPreferredSize(new Dimension(90, 23)); connectButton.setText( labels.getString("RtStatFrame.connectButton")); -// connectButton.setMinimumSize(new Dimension(100, 27)); -// connectButton.setPreferredSize(new Dimension(100, 27)); connectButton.addActionListener( new java.awt.event.ActionListener() { @@ -336,8 +314,7 @@ public void actionPerformed(ActionEvent e) connectButton_actionPerformed(e); } }); -// pauseButton.setMinimumSize(new Dimension(100, 27)); -// pauseButton.setPreferredSize(new Dimension(100, 27)); + pauseButton.setText( labels.getString("RtStatFrame.pause")); pauseButton.addActionListener( @@ -367,7 +344,6 @@ public void actionPerformed(ActionEvent e) if (canConfig) { jMenuFile.add(fileLrgsConfig); -// jMenuFile.add(fileOutageMaintenance); jMenuFile.add(fileNetworkLists); } jMenuFile.addSeparator(); @@ -417,7 +393,9 @@ private void jMenuFileExit_actionPerformed(ActionEvent e) { dispose(); if (exitOnClose) + { System.exit(0); + } } //Help | About action performed @@ -433,18 +411,6 @@ private void jMenuHelpAbout_actionPerformed(ActionEvent e) dlg.show(); } - //Overridden so we can exit when window is closed -// protected void processWindowEvent(WindowEvent e) -// { -// if (exitOnClose) -// System.exit(0); -// super.processWindowEvent(e); -// if (e.getID() == WindowEvent.WINDOW_CLOSING) -// { -// jMenuFileExit_actionPerformed(null); -// } -// } - public synchronized void connectButton_actionPerformed(ActionEvent e) { final String thost = ((String)hostCombo.getSelectedItem()).trim(); @@ -458,7 +424,10 @@ public synchronized void connectButton_actionPerformed(ActionEvent e) String ps = portField.getText().trim(); if (ps.length() > 0) { - try { p = Integer.parseInt(ps); } + try + { + p = Integer.parseInt(ps); + } catch(NumberFormatException ex) { showError(labels.getString( "RtStatFrame.portNumErr")); @@ -470,8 +439,7 @@ public synchronized void connectButton_actionPerformed(ActionEvent e) user = userField.getText().trim(); if (user.length() == 0) { - showError( - labels.getString("RtStatFrame.userEmptyErr")); + showError(labels.getString("RtStatFrame.userEmptyErr")); return; } @@ -481,8 +449,7 @@ public synchronized void connectButton_actionPerformed(ActionEvent e) passwd = passwordField.getText().trim(); if (passwd.length() == 0) { - showError( - labels.getString("RtStatFrame.passAuthErr")); + showError(labels.getString("RtStatFrame.passAuthErr")); return; } } @@ -501,9 +468,10 @@ private void doConnect() } client = null; final LddsClient tclient = new LddsClient(host, port); - final JobDialog dlg = - new JobDialog(this, - labels.getString("RtStatFrame.connectingToInfo") + host, true); + final JobDialog dlg = new JobDialog( + this, + labels.getString("RtStatFrame.connectingToInfo") + host, + true); dlg.setCanCancel(true); Thread backgroundJob = @@ -590,8 +558,6 @@ public void run() displayEvent("Connected to " + host + ":" + port + " as user '" + user + "'"); } - - //rtStatPanel.setPage("file:///C:/tmp/lrgsstatus.html"); } /** @@ -603,8 +569,13 @@ public void run() public synchronized byte[] getStatus() { if (client == null || isPaused) + { return null; - try { return client.getStatus(); } + } + try + { + return client.getStatus(); + } catch(final Exception ex) { client.disconnect(); @@ -625,8 +596,9 @@ public synchronized ArrayList getUsers() throws AuthException { if (client == null || isPaused) - throw new AuthException( - labels.getString("RtStatFrame.listUsersErr")); + { + throw new AuthException(labels.getString("RtStatFrame.listUsersErr")); + } return client.getUsers(); } @@ -634,8 +606,9 @@ public synchronized void modUser(DdsUser ddsUser, String pw) throws AuthException { if (client == null || isPaused) - throw new AuthException( - labels.getString("RtStatFrame.listUsersErr")); + { + throw new AuthException(labels.getString("RtStatFrame.listUsersErr")); + } client.modUser(ddsUser, pw); } @@ -643,8 +616,9 @@ public void rmUser(String userName) throws AuthException { if (client == null || isPaused) - throw new AuthException( - labels.getString("RtStatFrame.listUsersErr")); + { + throw new AuthException(labels.getString("RtStatFrame.listUsersErr")); + } client.rmUser(userName); } @@ -657,8 +631,13 @@ public void rmUser(String userName) public synchronized String[] getEvents() { if (client == null || isPaused) + { return null; - try { return client.getEvents(); } + } + try + { + return client.getEvents(); + } catch(final Exception ex) { client.disconnect(); @@ -685,11 +664,12 @@ public synchronized void applyLrgsConfig(LrgsConfig lrgsConfig) Properties props = new Properties(); PropertiesUtil.storeInProps(lrgsConfig, props, null); ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { props.store(baos, "LRGS Configuration Modified on "+new Date());} + try{ + props.store(baos, "LRGS Configuration Modified on "+new Date()); + } catch(IOException ex) { - throw new AuthException( - labels.getString("RtStatFrame.constructConfigArrayErr" +ex)); + throw new AuthException(labels.getString("RtStatFrame.constructConfigArrayErr" +ex)); } byte cfgData[] = baos.toByteArray(); client.installConfig("lrgs", cfgData); @@ -702,12 +682,16 @@ public synchronized void applyDdsRecvSettings(DdsRecvSettings settings) throws AuthException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { settings.storeToXml(baos); } + try + { + settings.storeToXml(baos); + } catch(IOException ex) { throw new AuthException( - labels.getString("RtStatFrame.constructddsConfigArrayErr") - + ex); + labels.getString("RtStatFrame.constructddsConfigArrayErr") + ex.getLocalizedMessage(), + ex + ); } byte cfgData[] = baos.toByteArray(); client.installConfig("ddsrecv", cfgData); @@ -720,12 +704,15 @@ public synchronized void applyDrgsInputSettings(DrgsInputSettings settings) throws AuthException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { settings.storeToXml(baos); } + try + { + settings.storeToXml(baos); + } catch(IOException ex) { throw new AuthException( - labels.getString("RtStatFrame.constructdrgsConfigArrayErr") - + ex); + labels.getString("RtStatFrame.constructdrgsConfigArrayErr") + ex.getLocalizedMessage(), + ex); } byte cfgData[] = baos.toByteArray(); client.installConfig("drgs", cfgData); @@ -736,14 +723,19 @@ public void applyNetworkDcpSettings(DrgsInputSettings settings) { // There was no networkDCP config prior to version 10. if (client.getServerProtoVersion() < 10) + { return; + } ByteArrayOutputStream baos = new ByteArrayOutputStream(); - try { settings.storeToXml(baos); } + try + { + settings.storeToXml(baos); + } catch(IOException ex) { throw new AuthException( - labels.getString("RtStatFrame.constructdrgsConfigArrayErr") - + ex); + labels.getString("RtStatFrame.constructdrgsConfigArrayErr") + ex.getLocalizedMessage(), + ex); } byte cfgData[] = baos.toByteArray(); client.installConfig("networkDcp", cfgData); @@ -902,7 +894,10 @@ public synchronized void deleteNetlist(String listname) public ArrayList getOutages() throws AuthException { - try { return client.getOutages(null, null); } + try + { + return client.getOutages(null, null); + } catch(Exception ex) { throw new AuthException(labels.getString( @@ -927,8 +922,9 @@ public void assertOutages(ArrayList outages) } catch(Exception ex) { - throw new AuthException(labels.getString( - "RtStatFrame.assertOutagesErr") + ex); + throw new AuthException( + labels.getString("RtStatFrame.assertOutagesErr") + ex.getLocalizedMessage(), + ex); } } @@ -989,7 +985,6 @@ public void displayEvent(String event) public static void loadConnectionsField(JComboBox hostCombo, Properties connectionList, String connectedHostName) { -//System.out.println("loadConnectionsField connected='" + connectedHostName + "'"); String fn = LddsClient.getLddsConnectionsFile(); File file = new File(fn); try @@ -1004,8 +999,7 @@ public static void loadConnectionsField(JComboBox hostCombo, Properties connecti System.out.println("No previously recorded connections"); } - class ht - implements Comparable + class ht implements Comparable { long lastUse; String hostname; @@ -1013,11 +1007,16 @@ class ht public int compareTo(ht o) { if (lastUse > o.lastUse) + { return -1; + } else if (lastUse < o.lastUse) + { return 1; + } return hostname.compareTo(o.hostname); } + public ht(long lastUse, String hostname) { super(); @@ -1033,13 +1032,21 @@ public ht(long lastUse, String hostname) long lastUse = 0L; String f[] = v.split(" "); if (f != null && f.length >= 3) - try { lastUse = Long.parseLong(f[2]); } - catch(NumberFormatException ex) {} + { + try + { + lastUse = Long.parseLong(f[2]); + } + catch(NumberFormatException ex) + { + // Ignore + } + } hosts.add(new ht(lastUse, host)); } Collections.sort(hosts); int selected = -1; -//MJM Added: to put a black selection in the start of the list. + //MJM Added: to put a black selection in the start of the list. hostCombo.addItem(""); for(int i = 0; i data = getOutages(); - OutageMaintenanceDialog dlg = new OutageMaintenanceDialog(this); - dlg.startDialog(this, data); - launch(dlg); - } - catch(AuthException ex) - { - showError( - labels.getString("RtStatFrame.noPermissionOnServerErr") - + ex.toString()); - } - } + } private void fileNetworkLists_actionPerformed() { @@ -1383,9 +1387,13 @@ public void hyperlinkUpdate(HyperlinkEvent hevt) URL url = hevt.getURL(); String f = url.getFile(); if (f == null) + { return; + } if (f.contains("showNetworkDcps")) + { showNetworkDcps(); + } } } } @@ -1399,12 +1407,13 @@ private void showNetworkDcps() //System.out.println("Created networkDcpStatusFrame"); } else + { networkDcpStatusFrame.toFront(); + } } public void networkDcpStatusFrameClosed() { networkDcpStatusFrame = null; - //System.out.println("networkDcpStatusFrameClosed"); } } diff --git a/src/main/java/lrgs/rtstat/RtStatPanel.java b/src/main/java/lrgs/rtstat/RtStatPanel.java index 1c3c47634..2ac1ba32a 100644 --- a/src/main/java/lrgs/rtstat/RtStatPanel.java +++ b/src/main/java/lrgs/rtstat/RtStatPanel.java @@ -7,7 +7,6 @@ import java.net.*; import java.awt.*; -import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.text.html.*; @@ -126,16 +125,6 @@ public void setPage(String surl) */ public void updateStatus(String htmlstat) { - -// final Point p = scrollPane.getViewport().getViewPosition(); htmlPanel.setText(htmlstat); -// SwingUtilities.invokeLater( -// new Runnable() -// { -// public void run() -// { -// scrollPane.getViewport().setViewPosition(p); -// } -// }); } } diff --git a/src/main/java/lrgs/rtstat/RtSummaryStatFrame.java b/src/main/java/lrgs/rtstat/RtSummaryStatFrame.java index 69d4e44bf..092246f55 100644 --- a/src/main/java/lrgs/rtstat/RtSummaryStatFrame.java +++ b/src/main/java/lrgs/rtstat/RtSummaryStatFrame.java @@ -7,31 +7,14 @@ import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; -import java.io.ByteArrayOutputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; import java.io.IOException; import java.net.URL; -import java.util.ArrayList; -import java.util.Date; import java.util.HashSet; import java.util.ResourceBundle; -import java.util.StringTokenizer; -import java.util.Enumeration; -import java.util.Properties; -import org.w3c.dom.Document; - -import ilex.gui.JobDialog; import ilex.util.AsciiUtil; -import ilex.util.AuthException; -import ilex.util.ByteUtil; -import ilex.util.EnvExpander; import ilex.util.LoadResourceBundle; import ilex.util.ProcWaiterCallback; import ilex.util.ProcWaiterThread; -import ilex.util.PropertiesUtil; /** diff --git a/src/main/java/lrgs/rtstat/RtSummaryStatPanel.java b/src/main/java/lrgs/rtstat/RtSummaryStatPanel.java index 0b49fd0d3..c80644263 100644 --- a/src/main/java/lrgs/rtstat/RtSummaryStatPanel.java +++ b/src/main/java/lrgs/rtstat/RtSummaryStatPanel.java @@ -7,14 +7,10 @@ import java.net.*; import java.awt.*; -import java.awt.event.*; import javax.swing.*; -import javax.swing.border.*; import javax.swing.text.html.*; import javax.swing.text.DefaultCaret; -import ilex.util.EnvExpander; - /** This is the HTML panel in which the summary status snapshot is displayed. */ @@ -40,40 +36,15 @@ public RtSummaryStatPanel() HTMLEditorKit hek = (HTMLEditorKit)htmlPanel.getEditorKit(); HTMLDocument doc = (HTMLDocument)hek.createDefaultDocument(); -// /* -// Kludge to set the parsers document base so that it will be able -// to find the icons sub directory. -// */ -// try -// { -// String path = -// EnvExpander.expand("$DECODES_INSTALL_DIR") + "/base.html"; -// File base = new File(path); -// FileWriter fw = new FileWriter(base); -// fw.write("dummy lrgs status page\n"); -// fw.close(); -// -// StringBuffer sb = new StringBuffer("file://" + path); -// if (sb.charAt(7) != '/') -// sb.insert(7, '/'); -// for(int i=7; i 0) { - try { htmlPanel.setPage(url); } + try + { + htmlPanel.setPage(url); + } catch(Exception ex) { System.err.println("Cannot read '" + url + "': " + ex);