示例#1
0
  /**
   * Create a button to go inside of the toolbar. By default this will load an image resource. The
   * image filename is relative to the classpath (including the '.' directory if its a part of the
   * classpath), and may either be in a JAR file or a separate file.
   *
   * @param key The key in the resource file to serve as the basis of lookups.
   */
  protected JButton createToolbarButton(String key) {
    URL url = getResource(key + imageSuffix);
    JButton b =
        new JButton(new ImageIcon(url)) {

          @Override
          public float getAlignmentY() {
            return 0.5f;
          }
        };
    b.setRequestFocusEnabled(false);
    b.setMargin(new Insets(1, 1, 1, 1));

    String astr = getProperty(key + actionSuffix);
    if (astr == null) {
      astr = key;
    }
    Action a = getAction(astr);
    if (a != null) {
      b.setActionCommand(astr);
      b.addActionListener(a);
    } else {
      b.setEnabled(false);
    }

    String tip = getResourceString(key + tipSuffix);
    if (tip != null) {
      b.setToolTipText(tip);
    }

    return b;
  }
 /** Reset the interface layout */
 private void clearInterface() {
   epanetNetwork = null;
   inpFile = null;
   frame.setTitle(APP_TITTLE);
   textReservoirs.setText("0");
   textTanks.setText("0");
   textPipes.setText("0");
   textNodes.setText("0");
   textDuration.setText("00:00:00");
   textHydraulic.setText("00:00:00");
   textPattern.setText("00:00:00");
   textUnits.setText("NONE");
   textHeadloss.setText("NONE");
   textQuality.setText("NONE");
   textDemand.setText("0.0");
   saveAction.setEnabled(false);
   runAction.setEnabled(false);
   runSimulationButton.setEnabled(false);
 }
  /**
   * Creates a dialog where the user can specify the location of the database,including the type of
   * network connection (if this is a networked client)and IP address and port number; or search and
   * select the database on a local drive if this is a standalone client.
   *
   * @param parent Defines the Component that is to be the parent of this dialog box. For
   *     information on how this is used, see <code>JOptionPane</code>
   * @param connectionMode Specifies the type of connection (standalone or networked)
   * @see JOptionPane
   */
  public DatabaseLocationDialog(Frame parent, ApplicationMode connectionMode) {
    configOptions = (new ConfigOptions(connectionMode));
    configOptions.getObservable().addObserver(this);

    // load saved configuration
    SavedConfiguration config = SavedConfiguration.getSavedConfiguration();

    // the port and connection type are irrelevant in standalone mode
    if (connectionMode == ApplicationMode.STANDALONE_CLIENT) {
      validPort = true;
      validCnx = true;
      networkType = ConnectionType.DIRECT;
      location = config.getParameter(SavedConfiguration.DATABASE_LOCATION);
    } else {
      // there may not be a network connectivity type defined and, if
      // not, we do not set a default - force the user to make a choice
      // the at least for the first time they run this.
      String tmp = config.getParameter(SavedConfiguration.NETWORK_TYPE);
      if (tmp != null) {
        try {
          networkType = ConnectionType.valueOf(tmp);
          configOptions.setNetworkConnection(networkType);
          validCnx = true;
        } catch (IllegalArgumentException e) {
          log.warning("Unknown connection type: " + networkType);
        }
      }

      // there is always at least a default port number, so we don't have
      // to validate this.
      port = config.getParameter(SavedConfiguration.SERVER_PORT);
      configOptions.setPortNumberText(port);
      validPort = true;

      location = config.getParameter(SavedConfiguration.SERVER_ADDRESS);
    }

    // there may not be a default database location, so we had better
    // validate before using the returned value.
    if (location != null) {
      configOptions.setLocationFieldText(location);
      validDb = true;
    }

    options =
        new JOptionPane(configOptions, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION);

    connectButton.setActionCommand(CONNECT);
    connectButton.addActionListener(this);

    boolean allValid = validDb && validPort && validCnx;
    connectButton.setEnabled(allValid);

    exitButton.setActionCommand(EXIT);
    exitButton.addActionListener(this);

    options.setOptions(new Object[] {connectButton, exitButton});

    dialog = options.createDialog(parent, TITLE);
    dialog.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
    dialog.addWindowListener(this);
    dialog.setVisible(true);
  }
  /**
   * Callback method to process modifications in the common ConfigOptions panel. ConfigOptions was
   * developed to be common to many applications (even though we only have three modes), so it does
   * not have any knowledge of how we are using it within this dialog box. So ConfigOptions just
   * sends updates to registered Observers whenever anything changes. We can receive those
   * notifications here, and decide whether we have enough information to enable the "Connect"
   * button of the dialog box.
   */
  public void update(Observable o, Object arg) {
    // we are going to ignore the Observable object, since we are only
    // observing one object. All we are interested in is the argument.

    if (!(arg instanceof OptionUpdate)) {
      log.log(
          Level.WARNING,
          "DatabaseLocationDialog received update type: " + arg,
          new IllegalArgumentException());
      return;
    }

    OptionUpdate optionUpdate = (OptionUpdate) arg;

    // load saved configuration
    SavedConfiguration config = SavedConfiguration.getSavedConfiguration();

    switch (optionUpdate.getUpdateType()) {
      case DB_LOCATION_CHANGED:
        location = (String) optionUpdate.getPayload();
        if (configOptions.getApplicationMode() == ApplicationMode.STANDALONE_CLIENT) {
          File f = new File(location);
          if (f.exists() && f.canRead() && f.canWrite()) {
            validDb = true;
            log.info("File chosen " + location);
            config.setParameter(SavedConfiguration.DATABASE_LOCATION, location);
          } else {
            log.warning("Invalid file " + location);
          }
        } else {
          try {
            if (location.matches("\\d+\\.\\d+\\.\\d+\\.\\d+")) {
              // location given matches 4 '.' separated numbers
              // regex could be improved by limiting each quad to
              // no more than 3 digits.
              String[] quads = location.split("\\.");
              byte[] address = new byte[quads.length];
              for (int i = 0; i < quads.length; i++) {
                address[i] = new Integer(quads[i]).byteValue();
              }
              InetAddress.getByAddress(address);
            } else {
              InetAddress.getAllByName(location);
            }
            log.info("Server specified " + location);
            validDb = true;
            config.setParameter(SavedConfiguration.SERVER_ADDRESS, location);
          } catch (UnknownHostException uhe) {
            log.warning("Unknown host: " + location);
            validDb = false;
          }
        }
        break;
      case PORT_CHANGED:
        port = (String) optionUpdate.getPayload();
        int p = Integer.parseInt(port);

        if (p >= LOWEST_PORT && p < HIGHEST_PORT) {
          if (p < SYSTEM_PORT_BOUNDARY) {
            log.info("User chose System port " + port);
          } else if (p < IANA_PORT_BOUNDARY) {
            log.info("User chose IANA port " + port);
          } else {
            log.info("User chose dynamic port " + port);
          }
          validPort = true;
          config.setParameter(SavedConfiguration.SERVER_PORT, port);
        } else {
          validPort = false;
        }
        break;
      case NETWORK_CHOICE_MADE:
        networkType = (ConnectionType) optionUpdate.getPayload();
        switch (networkType) {
          case SOCKET:
            log.info("Server connection via Sockets");
            break;
          case RMI:
            log.info("Server connection via RMI");
            break;
          default:
            log.info("Unknown connection type: " + networkType);
            break;
        }
        config.setParameter(SavedConfiguration.NETWORK_TYPE, "" + networkType);
        validCnx = true;
        break;
      default:
        log.warning("Unknown update: " + optionUpdate);
        break;
    }

    boolean allValid = validDb && validPort && validCnx;
    connectButton.setEnabled(allValid);
  }
  /** Show the open dialog and open the INP/XLSX and XML files. */
  private void openEvent() {
    if (fileChooser == null) {
      // fileChooser = new FileDialog(frame);
      fileChooser = new JFileChooser(System.getProperty("user.dir"));
      fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      fileChooser.setAcceptAllFileFilterUsed(false);
      fileChooser.addChoosableFileFilter(new XLSXFilter());
      fileChooser.addChoosableFileFilter(new XMLFilter());
      fileChooser.addChoosableFileFilter(new MSXFilter());
      fileChooser.addChoosableFileFilter(new INPFilter());
      fileChooser.addChoosableFileFilter(new AllSuportedFilesFilter());
    }

    if (fileChooser.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {
      File netFile = fileChooser.getSelectedFile();
      String fileExtension = Utilities.getFileExtension(netFile.getName());

      if (fileExtension.equals("xlsx")
          || fileExtension.equals("inp")
          || fileExtension.equals("xml")) {
        inpFile = netFile;
        msxFile = null;
        msxName.setText("");

        Network.FileType netType = Network.FileType.INP_FILE;
        if (fileExtension.equals("xlsx")) netType = Network.FileType.EXCEL_FILE;
        else if (fileExtension.equals("xml")) {
          netType = Network.FileType.XML_FILE;
          JOptionPane.showMessageDialog(
              frame, "Not supported yet !", "Error", JOptionPane.OK_OPTION);
          return;
        }

        epanetNetwork = new Network();
        InputParser inpParser = InputParser.create(netType, log);
        try {
          inpParser.parse(epanetNetwork, inpFile);
        } catch (ENException en_ex) {
          JOptionPane.showMessageDialog(
              frame,
              en_ex.toString() + "\nCheck epanet.log for detailed error description",
              "Error",
              JOptionPane.OK_OPTION);
          clearInterface();
          inpFile = null;
          return;
        } catch (Exception egen) {
          JOptionPane.showMessageDialog(
              frame, "Unable to parse network configuration file", "Error", JOptionPane.OK_OPTION);
          log.log(ENLevels.ERROR, "openEvent", egen);
          clearInterface();
          inpFile = null;

          return;
        }

        int resrvCount = 0;
        int tanksCount = 0;

        for (Tank tank : epanetNetwork.getTanks())
          if (tank.getArea() == 0.0) resrvCount++;
          else tanksCount++;

        textReservoirs.setText(Integer.toString(resrvCount));
        textTanks.setText(Integer.toString(tanksCount));
        textPipes.setText(Integer.toString(epanetNetwork.getLinks().size()));
        textNodes.setText(Integer.toString(epanetNetwork.getNodes().size()));
        try {
          textDuration.setText(
              Utilities.getClockTime(epanetNetwork.getPropertiesMap().getDuration()));
          textUnits.setText(epanetNetwork.getPropertiesMap().getUnitsflag().name());
          textHeadloss.setText(epanetNetwork.getPropertiesMap().getFormflag().name());
          textQuality.setText(epanetNetwork.getPropertiesMap().getQualflag().name());
          textDemand.setText(epanetNetwork.getPropertiesMap().getDmult().toString());
          textHydraulic.setText(
              Utilities.getClockTime(epanetNetwork.getPropertiesMap().getHstep()));
          textPattern.setText(Utilities.getClockTime(epanetNetwork.getPropertiesMap().getPstep()));
        } catch (ENException ex) {
        }
        frame.setTitle(APP_TITTLE + inpFile.getName());
        inpName.setText(inpFile.getName());
        runSimulationButton.setEnabled(true);

        saveButton.setEnabled(true);
        reportOptions = null;
      } else if (fileExtension.equals("msx")) {
        if (inpFile == null) {
          JOptionPane.showMessageDialog(
              frame,
              "Load an INP or XLSX file with network configuration before opening the MSX file.",
              "Error",
              JOptionPane.OK_OPTION);
          return;
        }

        msxFile = netFile;
        msxName.setText(fileChooser.getSelectedFile().getName()); // fileChooser.getFile());
        reportOptions = null;
      }

      saveAction.setEnabled(true);
      runAction.setEnabled(true);
    }
  }