Esempio n. 1
0
  public void restartApplication() {

    try {

      final String javaBin =
          System.getProperty("java.home") + File.separator + "bin" + File.separator + "javaw";
      final File currentJar =
          new File(network.class.getProtectionDomain().getCodeSource().getLocation().toURI());

      System.out.println("javaBin " + javaBin);
      System.out.println("currentJar " + currentJar);
      System.out.println("currentJar.getPath() " + currentJar.getPath());

      /* is it a jar file? */
      // if(!currentJar.getName().endsWith(".jar")){return;}

      try {

        // xmining = 0;
        // systemx.shutdown();

      } catch (Exception e) {
        e.printStackTrace();
      }

      /* Build command: java -jar application.jar */
      final ArrayList<String> command = new ArrayList<String>();
      command.add(javaBin);
      command.add("-jar");
      command.add("-Xms256m");
      command.add("-Xmx1024m");
      command.add(currentJar.getPath());

      final ProcessBuilder builder = new ProcessBuilder(command);
      builder.start();

      // try{Thread.sleep(10000);} catch (InterruptedException e){}

      // close and exit
      SystemTray.getSystemTray().remove(network.icon);
      System.exit(0);

    } // try
    catch (Exception e) {
      JOptionPane.showMessageDialog(null, e.getCause());
    }
  } // ******************************
Esempio n. 2
0
  // ask user for script file and name of new profile
  // return false if user cancelled operation
  private boolean getNewWkldInput(
      JFileChooser chooser, Object[] optionDlgMsg, StringBuffer name, StringBuffer scriptFile) {
    // let user select script file with queries
    boolean fileOk = false;
    int retval;
    File file = null;
    FileReader reader = null;
    while (!fileOk) {
      if ((retval = chooser.showDialog(this, "Ok")) != 0) {
        return false;
      }
      file = chooser.getSelectedFile();
      try {
        reader = new FileReader(file.getPath());
        fileOk = true;
        scriptFile.append(file.getPath());
      } catch (FileNotFoundException e) {
        JOptionPane.showMessageDialog(
            this,
            "Selected script file does not exist",
            "Error: New Profile",
            JOptionPane.ERROR_MESSAGE);
      }
    }

    // let user select filename for profile
    int response =
        JOptionPane.showOptionDialog(
            this,
            optionDlgMsg,
            "New Profile",
            JOptionPane.OK_CANCEL_OPTION,
            JOptionPane.PLAIN_MESSAGE,
            null,
            null,
            null);
    if (response != JOptionPane.OK_OPTION) {
      return false;
    }
    JTextField textFld = (JTextField) optionDlgMsg[1];
    name.append(file.getParent() + "/" + textFld.getText());
    return true;
  }
Esempio n. 3
0
  public void OpenFileToolbar() {
    JFileChooser fileChooser = new JFileChooser();
    int returnVal = fileChooser.showOpenDialog(this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();
      try {
        opentFile(file.getPath());

        Workspaces workspaces = Application.getInstance().getWorkspaces();
        Map<String, Workspaces.ViewFrame> frames = workspaces.getOpenFrames();
        Object[] objFrames = frames.values().toArray();
        ViewFrame[] viewFrames = new ViewFrame[objFrames.length];
        for (int i = 0; i < objFrames.length; i++) {
          viewFrames[i] = (ViewFrame) objFrames[i];
          if (viewFrames[i].isSelected()) viewFrames[i].setTitle(file.getPath());
        }
      } catch (Exception ex) {
        ex.printStackTrace();
      }
    }
  }
 public void loadImage(File f) {
   if (f == null) {
     thumbnail = null;
   } else {
     ImageIcon tmpIcon = new ImageIcon(f.getPath());
     if (tmpIcon.getIconWidth() > 90) {
       thumbnail =
           new ImageIcon(tmpIcon.getImage().getScaledInstance(90, -1, Image.SCALE_DEFAULT));
     } else {
       thumbnail = tmpIcon;
     }
   }
 }
  /**
   * Checks to see if the absolute path is availabe thru an application global static variable or
   * thru a system variable. If so, appends the relative path to the absolute path and returns the
   * String.
   */
  private String processSrcPath(String src) {
    String val = src;

    File imageFile = new File(src);
    if (imageFile.isAbsolute()) return src;

    // try to get application images path...
    if (MadChat.ApplicationImagePath != null) {
      String imagePath = MadChat.ApplicationImagePath;
      val = (new File(imagePath, imageFile.getPath())).toString();
    }
    // try to get system images path...
    else {
      String imagePath = System.getProperty("system.image.path.key");
      if (imagePath != null) {
        val = (new File(imagePath, imageFile.getPath())).toString();
      }
    }

    // System.out.println("src before: " + src + ", src after: " + val);
    return val;
  }
 public void actionPerformed(ActionEvent e) {
   int x = jfc.showSaveDialog(null);
   // int x=jfc.showOpenDialog(null);
   if (x == JFileChooser.APPROVE_OPTION) {
     File f = jfc.getSelectedFile();
     System.out.println(f.getPath());
     System.out.println(jfc.getName(f));
     File f1 = jfc.getCurrentDirectory();
     System.out.println(jfc.getName(f1));
   }
   if (x == JFileChooser.CANCEL_OPTION) {
     System.out.println("cancle");
   }
 }
Esempio n. 7
0
    /** Runs this thread. */
    public void run() {
      CommonFileChooser file_chooser = new CommonFileChooser();
      file_chooser.setDialogTitle("Save selected data.");
      file_chooser.setMultiSelectionEnabled(false);

      if (file_chooser.showSaveDialog(pane) == JFileChooser.APPROVE_OPTION) {
        try {
          File file = file_chooser.getSelectedFile();
          if (file.exists()) {
            String message = "Overwrite to " + file.getPath() + " ?";
            if (0
                != JOptionPane.showConfirmDialog(
                    pane, message, "Confirmation", JOptionPane.YES_NO_OPTION)) {
              return;
            }
          }

          AstrometricaWriter writer = new AstrometricaWriter(file);
          writer.open();

          int check_column = getCheckColumn();
          for (int i = 0; i < model.getRowCount(); i++) {
            if (((Boolean) getValueAt(i, check_column)).booleanValue()) {
              Variability record = (Variability) record_list.elementAt(index.get(i));
              writer.write(record.getStar());
            }
          }

          writer.close();

          String message = "Completed.";
          JOptionPane.showMessageDialog(pane, message);
        } catch (IOException exception) {
          String message = "Failed to save file.";
          JOptionPane.showMessageDialog(pane, message, "Error", JOptionPane.ERROR_MESSAGE);
        } catch (UnsupportedStarClassException exception) {
          String message = "Failed to save file.";
          JOptionPane.showMessageDialog(pane, message, "Error", JOptionPane.ERROR_MESSAGE);
        }
      }
    }
Esempio n. 8
0
    /** Runs this thread. */
    public void run() {
      CommonFileChooser file_chooser = new CommonFileChooser();
      file_chooser.setDialogTitle("Save package file.");
      file_chooser.setMultiSelectionEnabled(false);
      file_chooser.addChoosableFileFilter(new XmlFilter());
      file_chooser.setSelectedFile(new File("package.xml"));

      if (file_chooser.showSaveDialog(pane) == JFileChooser.APPROVE_OPTION) {
        try {
          File file = file_chooser.getSelectedFile();
          if (file.exists()) {
            String message = "Overwrite to " + file.getPath() + " ?";
            if (0
                != JOptionPane.showConfirmDialog(
                    pane, message, "Confirmation", JOptionPane.YES_NO_OPTION)) {
              return;
            }
          }

          // Outputs the variability XML file.

          XmlVariabilityHolder holder = new XmlVariabilityHolder();

          Variability[] records = getSelectedRecords();
          for (int i = 0; i < records.length; i++) {
            XmlVariability variability = new XmlVariability(records[i]);
            holder.addVariability(variability);
          }

          holder.write(file);

          String message = "Completed.";
          JOptionPane.showMessageDialog(pane, message);
        } catch (IOException exception) {
          String message = "Failed.";
          JOptionPane.showMessageDialog(pane, message, "Error", JOptionPane.ERROR_MESSAGE);
        }
      }
    }
Esempio n. 9
0
  /** @return true if file was saved, false if user canceled */
  boolean onSaveAsFileClicked() {
    try {

      JFileChooser fc = new JFileChooser();
      FileNameExtensionFilter filter1 =
          new FileNameExtensionFilter(strings.getString("filetype." + EXTENSION), EXTENSION);
      fc.setFileFilter(filter1);
      int rv = fc.showSaveDialog(this);

      if (rv == JFileChooser.APPROVE_OPTION) {
        currentFile = fc.getSelectedFile();
        if (!currentFile.getName().endsWith("." + EXTENSION)) {
          currentFile = new File(currentFile.getPath() + "." + EXTENSION);
        }
        doSave(currentFile);
        refresh();
        return true;
      }
    } catch (Exception e) {
      JOptionPane.showMessageDialog(
          this, e, strings.getString("main.error_caption"), JOptionPane.ERROR_MESSAGE);
    }
    return false;
  }
  private ObjectOutputStream getObjectOutputStream() {
    File f = new File(".");
    String loadDirectory = f.getAbsolutePath();

    JFileChooser chooser = new JFileChooser(loadDirectory);
    chooser.setDialogTitle("Save Generation File As...");
    chooser.setMultiSelectionEnabled(false);

    int result = chooser.showSaveDialog(this);
    File selectedFile = chooser.getSelectedFile();

    if (result == JFileChooser.APPROVE_OPTION) {
      try {
        FileOutputStream fileStream = new FileOutputStream(selectedFile.getPath());
        ObjectOutputStream objectStream = new ObjectOutputStream(fileStream);

        return objectStream;
      } catch (IOException e) {
        System.err.println(e);
      }
    }

    return null;
  }
Esempio n. 11
0
  public boolean loadSourceFile(File file) {
    boolean result = false;

    selectedPath = file.getParent();

    BufferedReader sourceFile = null;

    String directoryPath = file.getParent();
    String sourceName = file.getName();

    int idx = sourceName.lastIndexOf(".");
    fileExt = idx == -1 ? "" : sourceName.substring(idx + 1);
    baseName = idx == -1 ? sourceName.substring(0) : sourceName.substring(0, idx);
    String basePath = directoryPath + File.separator + baseName;

    DataOptions.directoryPath = directoryPath;

    sourcePath = file.getPath();

    AssemblerOptions.sourcePath = sourcePath;
    AssemblerOptions.listingPath = basePath + ".lst";
    AssemblerOptions.objectPath = basePath + ".cd";

    String var = System.getenv("ROPE_MACROS_DIR");
    if (var != null && !var.isEmpty()) {
      File dir = new File(var);
      if (dir.exists() && dir.isDirectory()) {
        AssemblerOptions.macroPath = var;
      } else {
        AssemblerOptions.macroPath = directoryPath;
      }
    } else {
      AssemblerOptions.macroPath = directoryPath;
    }

    DataOptions.inputPath = AssemblerOptions.objectPath;
    DataOptions.outputPath = basePath + ".out";
    DataOptions.readerPath = null;
    DataOptions.punchPath = basePath + ".pch";
    DataOptions.tape1Path = basePath + ".mt1";
    DataOptions.tape2Path = basePath + ".mt2";
    DataOptions.tape3Path = basePath + ".mt3";
    DataOptions.tape4Path = basePath + ".mt4";
    DataOptions.tape5Path = basePath + ".mt5";
    DataOptions.tape6Path = basePath + ".mt6";

    this.setTitle("EDIT: " + sourceName);
    fileText.setText(sourcePath);

    if (dialog == null) {
      dialog = new AssemblerDialog(mainFrame, "Assembler options");

      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      Dimension dialogSize = dialog.getSize();
      dialog.setLocation(
          (screenSize.width - dialogSize.width) / 2, (screenSize.height - dialogSize.height) / 2);
    }

    dialog.initialize();

    AssemblerOptions.command = dialog.buildCommand();

    sourceArea.setText(null);

    try {
      sourceFile = new BufferedReader(new FileReader(file));
      String line;

      while ((line = sourceFile.readLine()) != null) {
        sourceArea.append(line + "\n");
      }

      sourceArea.setCaretPosition(0);
      optionsButton.setEnabled(true);
      assembleButton.setEnabled(true);
      saveButton.setEnabled(true);

      setSourceChanged(false);
      undoMgr.discardAllEdits();

      result = true;
    } catch (IOException ex) {
      ex.printStackTrace();
    } finally {
      try {
        if (sourceFile != null) {
          sourceFile.close();
        }
      } catch (IOException ignore) {
      }
    }

    return result;
  }
Esempio n. 12
0
/**
 * Manage TDS logs
 *
 * @author caron
 * @since Mar 26, 2009
 */
public class TdsMonitor extends JPanel {
  private static final String FRAME_SIZE = "FrameSize";

  private static JFrame frame;
  private static PreferencesExt prefs;
  private static XMLStore store;

  private ucar.util.prefs.PreferencesExt mainPrefs;
  private JTabbedPane tabbedPane;
  private ManagePanel managePanel;
  private AccessLogPanel accessLogPanel;
  private ServletLogPanel servletLogPanel;
  private URLDumpPane urlDump;

  private JFrame parentFrame;
  private FileManager fileChooser;
  private ManageForm manage;

  private HTTPSession session;

  public TdsMonitor(ucar.util.prefs.PreferencesExt prefs, JFrame parentFrame) throws HTTPException {
    this.mainPrefs = prefs;
    this.parentFrame = parentFrame;

    makeCache();

    fileChooser =
        new FileManager(parentFrame, null, null, (PreferencesExt) prefs.node("FileManager"));

    // the top UI
    tabbedPane = new JTabbedPane(JTabbedPane.TOP);
    managePanel = new ManagePanel((PreferencesExt) mainPrefs.node("ManageLogs"));
    accessLogPanel = new AccessLogPanel((PreferencesExt) mainPrefs.node("LogTable"));
    servletLogPanel = new ServletLogPanel((PreferencesExt) mainPrefs.node("ServletLogPanel"));
    urlDump = new URLDumpPane((PreferencesExt) mainPrefs.node("urlDump"));

    tabbedPane.addTab("ManageLogs", managePanel);
    tabbedPane.addTab("AccessLogs", accessLogPanel);
    tabbedPane.addTab("ServletLogs", servletLogPanel);
    tabbedPane.addTab("UrlDump", urlDump);
    tabbedPane.setSelectedIndex(0);

    setLayout(new BorderLayout());
    add(tabbedPane, BorderLayout.CENTER);

    CredentialsProvider provider = new UrlAuthenticatorDialog(null);
    session = new HTTPSession("TdsMonitor");
    session.setCredentialsProvider(provider);
    session.setUserAgent("TdsMonitor");
  }

  public void exit() {
    session.close();

    if (dnsCache != null) {
      System.out.printf(" cache= %s%n", dnsCache.toString());
      System.out.printf(" cache.size= %d%n", dnsCache.getSize());
      System.out.printf(" cache.memorySize= %d%n", dnsCache.getMemoryStoreSize());
      Statistics stats = dnsCache.getStatistics();
      System.out.printf(" stats= %s%n", stats.toString());
    }

    cacheManager.shutdown();
    fileChooser.save();
    managePanel.save();
    accessLogPanel.save();
    servletLogPanel.save();
    urlDump.save();

    Rectangle bounds = frame.getBounds();
    prefs.putBeanObject(FRAME_SIZE, bounds);
    try {
      store.save();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }

    done = true; // on some systems, still get a window close event
    System.exit(0);
  }

  private void gotoUrlDump(String urlString) {
    urlDump.setURL(urlString);
    tabbedPane.setSelectedIndex(3);
  }

  ////////////////////////////////////////////////////////////////////////////////////

  private static TdsMonitor ui;
  private static boolean done = false;

  private static File ehLocation = LogLocalManager.getDirectory("cache", "dns");

  // private static String ehLocation = "C:\\data\\ehcache";
  // private static String ehLocation = "/machine/data/thredds/ehcache/";
  private static String config =
      "<ehcache>\n"
          + "    <diskStore path='"
          + ehLocation.getPath()
          + "'/>\n"
          + "    <defaultCache\n"
          + "              maxElementsInMemory='10000'\n"
          + "              eternal='false'\n"
          + "              timeToIdleSeconds='120'\n"
          + "              timeToLiveSeconds='120'\n"
          + "              overflowToDisk='true'\n"
          + "              maxElementsOnDisk='10000000'\n"
          + "              diskPersistent='false'\n"
          + "              diskExpiryThreadIntervalSeconds='120'\n"
          + "              memoryStoreEvictionPolicy='LRU'\n"
          + "              />\n"
          + "    <cache name='dns'\n"
          + "            maxElementsInMemory='5000'\n"
          + "            eternal='false'\n"
          + "            timeToIdleSeconds='86400'\n"
          + "            timeToLiveSeconds='864000'\n"
          + "            overflowToDisk='true'\n"
          + "            maxElementsOnDisk='0'\n"
          + "            diskPersistent='true'\n"
          + "            diskExpiryThreadIntervalSeconds='3600'\n"
          + "            memoryStoreEvictionPolicy='LRU'\n"
          + "            />\n"
          + "</ehcache>";

  private CacheManager cacheManager;
  private Cache dnsCache;

  void makeCache() {
    cacheManager = new CacheManager(new StringBufferInputStream(config));
    dnsCache = cacheManager.getCache("dns");
  }

  /////////////////////////

  private class ManagePanel extends JPanel {
    PreferencesExt prefs;

    ManagePanel(PreferencesExt p) {
      this.prefs = p;
      manage = new ManageForm(this.prefs);
      setLayout(new BorderLayout());
      add(manage, BorderLayout.CENTER);

      manage.addPropertyChangeListener(
          new PropertyChangeListener() {
            public void propertyChange(PropertyChangeEvent evt) {
              if (!evt.getPropertyName().equals("Download")) return;
              ManageForm.Data data = (ManageForm.Data) evt.getNewValue();
              try {
                manage.getTextArea().setText(""); // clear the text area
                manage.getStopButton().setCancel(false); // clear the cancel state

                if (data.wantAccess) {
                  TdsDownloader logManager =
                      new TdsDownloader(
                          manage.getTextArea(), data, TdsDownloader.Type.access, session);
                  logManager.getRemoteFiles(manage.getStopButton());
                }
                if (data.wantServlet) {
                  TdsDownloader logManager =
                      new TdsDownloader(
                          manage.getTextArea(), data, TdsDownloader.Type.thredds, session);
                  logManager.getRemoteFiles(manage.getStopButton());
                }

                if (data.wantRoots) {
                  String urls = data.getServerPrefix() + "/thredds/admin/log/dataroots.txt";
                  File localDir = LogLocalManager.getDirectory(data.server, "");
                  localDir.mkdirs();
                  File file = new File(localDir, "roots.txt");
                  HttpClientManager.copyUrlContentsToFile(session, urls, file);
                  String roots = IO.readFile(file.getPath());

                  JTextArea ta = manage.getTextArea();
                  ta.append("\nRoots:\n");
                  ta.append(roots);
                  LogCategorizer.setRoots(roots);
                }

              } catch (Throwable t) {
                t.printStackTrace();
              }

              if (manage.getStopButton().isCancel())
                manage.getTextArea().append("\nDownload canceled by user");
            }
          });
    }

    void save() {
      ComboBox servers = manage.getServersCB();
      servers.save();
    }
  }

  ///////////////////////////

  private abstract class OpPanel extends JPanel {
    PreferencesExt prefs;
    TextHistoryPane ta;
    IndependentWindow infoWindow;
    JComboBox serverCB;
    JTextArea startDateField, endDateField;
    JPanel topPanel;
    boolean isAccess;
    boolean removeTestReq;
    boolean problemsOnly;

    OpPanel(PreferencesExt prefs, boolean isAccess) {
      this.prefs = prefs;
      this.isAccess = isAccess;
      ta = new TextHistoryPane(true);
      infoWindow =
          new IndependentWindow("Details", BAMutil.getImage("netcdfUI"), new JScrollPane(ta));
      Rectangle bounds = (Rectangle) prefs.getBean(FRAME_SIZE, new Rectangle(200, 50, 500, 700));
      infoWindow.setBounds(bounds);

      topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT, 5, 0));

      // which server
      serverCB = new JComboBox();
      serverCB.setModel(manage.getServersCB().getModel());
      serverCB.addActionListener(
          new ActionListener() {
            public void actionPerformed(ActionEvent e) {
              String server = (String) serverCB.getSelectedItem();
              setServer(server);
            }
          });

      // serverCB.setModel(manage.getServers().getModel());
      topPanel.add(new JLabel("server:"));
      topPanel.add(serverCB);

      // the date selectors
      startDateField = new JTextArea("                    ");
      endDateField = new JTextArea("                    ");

      topPanel.add(new JLabel("Start Date:"));
      topPanel.add(startDateField);
      topPanel.add(new JLabel("End Date:"));
      topPanel.add(endDateField);

      AbstractAction showAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              showLogs();
            }
          };
      BAMutil.setActionProperties(showAction, "Import", "get logs", false, 'G', -1);
      BAMutil.addActionToContainer(topPanel, showAction);

      AbstractAction filterAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              Boolean state = (Boolean) getValue(BAMutil.STATE);
              removeTestReq = state.booleanValue();
            }
          };
      BAMutil.setActionProperties(filterAction, "time", "remove test Requests", true, 'F', -1);
      BAMutil.addActionToContainer(topPanel, filterAction);

      AbstractAction filter2Action =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              Boolean state = (Boolean) getValue(BAMutil.STATE);
              problemsOnly = state.booleanValue();
            }
          };
      BAMutil.setActionProperties(filter2Action, "time", "only show problems", true, 'F', -1);
      BAMutil.addActionToContainer(topPanel, filter2Action);

      AbstractAction infoAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              Formatter f = new Formatter();
              showInfo(f);
              ta.setText(f.toString());
              infoWindow.show();
            }
          };
      BAMutil.setActionProperties(
          infoAction, "Information", "info on selected logs", false, 'I', -1);
      BAMutil.addActionToContainer(topPanel, infoAction);

      setLayout(new BorderLayout());
      add(topPanel, BorderLayout.NORTH);
    }

    private LogLocalManager manager;

    public void setServer(String server) {
      manager = new LogLocalManager(server, isAccess);
      manager.getLocalFiles(null, null);
      setLocalManager(manager);
    }

    abstract void setLocalManager(LogLocalManager manager);

    abstract void showLogs();

    abstract void showInfo(Formatter f);

    abstract void resetLogs();

    void save() {
      if (infoWindow != null) prefs.putBeanObject(FRAME_SIZE, infoWindow.getBounds());
    }
  }

  /////////////////////////////////////////////////////////////////////
  String filterIP = "128.117.156,128.117.140,128.117.149";

  private class AccessLogPanel extends OpPanel {
    AccessLogTable logTable;

    AccessLogPanel(PreferencesExt p) {
      super(p, true);
      logTable = new AccessLogTable(startDateField, endDateField, p, dnsCache);
      logTable.addPropertyChangeListener(
          new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent e) {
              if (e.getPropertyName().equals("UrlDump")) {
                String path = (String) e.getNewValue();
                gotoUrlDump(path);
              }
            }
          });

      AbstractAction allAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              resetLogs();
            }
          };
      BAMutil.setActionProperties(allAction, "Refresh", "show All Logs", false, 'A', -1);
      BAMutil.addActionToContainer(topPanel, allAction);

      AbstractAction dnsAction =
          new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
              showDNS();
            }
          };
      BAMutil.setActionProperties(dnsAction, "Dataset", "lookup DNS", false, 'D', -1);
      BAMutil.addActionToContainer(topPanel, dnsAction);

      add(logTable, BorderLayout.CENTER);
    }

    @Override
    void setLocalManager(LogLocalManager manager) {
      logTable.setLocalManager(manager);
    }

    @Override
    void showLogs() {
      LogReader.LogFilter filter = null;
      if (removeTestReq) filter = new LogReader.IpFilter(filterIP.split(","), filter);
      if (problemsOnly) filter = new LogReader.ErrorOnlyFilter(filter);

      logTable.showLogs(filter);
    }

    void showInfo(Formatter f) {
      logTable.showInfo(f);
    }

    void resetLogs() {
      logTable.resetLogs();
    }

    void showDNS() {
      logTable.showDNS();
    }

    void save() {
      logTable.exit();
      super.save();
    }
  }

  /////////////////////////////////////////////////////////////////////

  private class ServletLogPanel extends OpPanel {
    ServletLogTable logTable;

    ServletLogPanel(PreferencesExt p) {
      super(p, false);
      logTable = new ServletLogTable(startDateField, endDateField, p, dnsCache);
      add(logTable, BorderLayout.CENTER);
    }

    @Override
    void setLocalManager(LogLocalManager manager) {
      logTable.setLocalManager(manager);
    }

    @Override
    void showLogs() {
      ServletLogTable.MergeFilter filter = null;
      if (removeTestReq) filter = new ServletLogTable.IpFilter(filterIP.split(","), filter);
      if (problemsOnly) filter = new ServletLogTable.ErrorOnlyFilter(filter);

      logTable.showLogs(filter);
    }

    void resetLogs() {}

    void showInfo(Formatter f) {
      logTable.showInfo(f);
    }

    void save() {
      logTable.exit();
      super.save();
    }
  }

  //////////////////////////////////////////////////////////////

  /*
   * Finds all files matching
   * a glob pattern.  This method recursively searches directories, allowing
   * for glob expressions like {@code "c:\\data\\200[6-7]\\*\\1*\\A*.nc"}.
   *
   * @param globExpression The glob expression
   * @return List of File objects matching the glob pattern.  This will never
   *         be null but might be empty
   * @throws Exception if the glob expression does not represent an absolute
   *                   path
   * @author Mike Grant, Plymouth Marine Labs; Jon Blower
   *
  java.util.List<File> globFiles(String globExpression) throws Exception {
    // Check that the glob expression is an absolute path.  Relative paths
    // would cause unpredictable and platform-dependent behaviour so
    // we disallow them.
    // If ds.getLocation() is a glob expression this test will still work
    // because we are not attempting to resolve the string to a real path.
    File globFile = new File(globExpression);
    if (!globFile.isAbsolute()) {
      throw new Exception("Dataset location " + globExpression +
              " must be an absolute path");
    }

    // Break glob pattern into path components.  To do this in a reliable
    // and platform-independent way we use methods of the File class, rather
    // than String.split().
    java.util.List<String> pathComponents = new ArrayList<String>();
    while (globFile != null) {
      // We "pop off" the last component of the glob pattern and place
      // it in the first component of the pathComponents List.  We therefore
      // ensure that the pathComponents end up in the right order.
      File parent = globFile.getParentFile();
      // For a top-level directory, getName() returns an empty string,
      // hence we use getPath() in this case
      String pathComponent = parent == null ? globFile.getPath() : globFile.getName();
      pathComponents.add(0, pathComponent);
      globFile = parent;
    }

    // We must have at least two path components: one directory and one
    // filename or glob expression
    java.util.List<File> searchPaths = new ArrayList<File>();
    searchPaths.add(new File(pathComponents.get(0)));
    int i = 1; // Index of the glob path component

    while (i < pathComponents.size()) {
      FilenameFilter globFilter = new GlobFilenameFilter(pathComponents.get(i));
      java.util.List<File> newSearchPaths = new ArrayList<File>();
      // Look for matches in all the current search paths
      for (File dir : searchPaths) {
        if (dir.isDirectory()) {
          // Workaround for automounters that don't make filesystems
          // appear unless they're poked
          // do a listing on searchpath/pathcomponent whether or not
          // it exists, then discard the results
          new File(dir, pathComponents.get(i)).list();

          for (File match : dir.listFiles(globFilter)) {
            newSearchPaths.add(match);
          }
        }
      }
      // Next time we'll search based on these new matches and will use
      // the next globComponent
      searchPaths = newSearchPaths;
      i++;
    }

    // Now we've done all our searching, we'll only retain the files from
    // the list of search paths
    java.util.List<File> filesToReturn = new ArrayList<File>();
    for (File path : searchPaths) {
      if (path.isFile()) filesToReturn.add(path);
    }

    return filesToReturn;
  } */

  //////////////////////////////////////////////

  public static void main(String args[]) throws HTTPException {

    // prefs storage
    try {
      String prefStore =
          ucar.util.prefs.XMLStore.makeStandardFilename(".unidata", "TdsMonitor.xml");
      store = ucar.util.prefs.XMLStore.createFromFile(prefStore, null);
      prefs = store.getPreferences();
      Debug.setStore(prefs.node("Debug"));
    } catch (IOException e) {
      System.out.println("XMLStore Creation failed " + e);
    }

    // initializations
    BAMutil.setResourcePath("/resources/nj22/ui/icons/");

    // put UI in a JFrame
    frame = new JFrame("TDS Monitor");
    ui = new TdsMonitor(prefs, frame);

    frame.setIconImage(BAMutil.getImage("netcdfUI"));
    frame.addWindowListener(
        new WindowAdapter() {
          public void windowClosing(WindowEvent e) {
            if (!done) ui.exit();
          }
        });

    frame.getContentPane().add(ui);
    Rectangle bounds = (Rectangle) prefs.getBean(FRAME_SIZE, new Rectangle(50, 50, 800, 450));
    frame.setBounds(bounds);

    frame.pack();
    frame.setBounds(bounds);
    frame.setVisible(true);
  }
}
  /** Handle the import action request. */
  public void onImport() {

    String finalFile = ""; // $NON-NLS-1$

    if (file == null) {
      UIFileFilter filter =
          new UIFileFilter(new String[] {"xml"}, "XML Files"); // $NON-NLS-1$ //$NON-NLS-2$

      UIFileChooser fileDialog = new UIFileChooser();
      fileDialog.setDialogTitle(
          LanguageProperties.getString(
              LanguageProperties.DIALOGS_BUNDLE,
              "UIImportFlashMeetingXMLDialog.chooseFile2")); //$NON-NLS-1$
      fileDialog.setFileFilter(filter);
      fileDialog.setApproveButtonText(
          LanguageProperties.getString(
              LanguageProperties.DIALOGS_BUNDLE,
              "UIImportFlashMeetingXMLDialog.importButton")); //$NON-NLS-1$
      fileDialog.setRequiredExtension(".xml"); // $NON-NLS-1$

      // FIX FOR MAC - NEEDS '/' ON END TO DENOTE A FOLDER
      if (!UIImportFlashMeetingXMLDialog.lastFileDialogDir.equals("")) { // $NON-NLS-1$
        File file =
            new File(UIImportFlashMeetingXMLDialog.lastFileDialogDir + ProjectCompendium.sFS);
        if (file.exists()) {
          fileDialog.setCurrentDirectory(file);
        }
      }

      UIUtilities.centerComponent(fileDialog, ProjectCompendium.APP);
      int retval = fileDialog.showOpenDialog(ProjectCompendium.APP);
      if (retval == JFileChooser.APPROVE_OPTION) {
        if ((fileDialog.getSelectedFile()) != null) {

          String fileName = fileDialog.getSelectedFile().getAbsolutePath();
          File fileDir = fileDialog.getCurrentDirectory();
          String dir = fileDir.getPath();

          if (fileName != null) {
            UIImportFlashMeetingXMLDialog.lastFileDialogDir = dir;
            finalFile = fileName;
          }
        }
      }
    } else {
      finalFile = file.getAbsolutePath();
    }

    if (finalFile != null) {
      if ((new File(finalFile)).exists()) {
        setVisible(false);
        Vector choices = new Vector();

        if (cbIncludeKeywords.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.KEYWORDS_LABEL);
        }
        if (cbIncludeAttendees.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.ATTENDEE_LABEL);
        }
        if (cbIncludePlayList.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.PLAYLIST_LABEL);
        }
        if (cbIncludeURLs.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.URL_LABEL);
        }
        if (cbIncludeChats.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.CHAT_LABEL);
        }
        if (cbIncludeWhiteboard.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.WHITEBOARD_LABEL);
        }
        if (cbIncludeFileData.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.FILEDATA_LABEL);
        }
        if (cbIncludeAnnotations.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.ANNOTATIONS_LABEL);
        }
        if (cbIncludeVotes.isSelected()) {
          choices.addElement(FlashMeetingXMLImport.VOTING_LABEL);
        }

        DBNode.setNodesMarkedSeen(cbMarkSeen.isSelected());

        FlashMeetingXMLImport xmlImport =
            new FlashMeetingXMLImport(finalFile, ProjectCompendium.APP.getModel(), choices);
        xmlImport.start();

        dispose();
        ProjectCompendium.APP.setStatus(""); // $NON-NLS-1$
      }
    }
  }
  public void actionPerformed(ActionEvent e) {
    JButton b = (JButton) e.getSource();
    if (b.getText() == "PLAY") {
      if (scoreP != null) scoreP.playScale(sp.getScale(), tempoP.getValue());
    } else if (b.getText() == "New") {
      try {
        saveUnsaved();
      } catch (SaveAbortedException ex) {
        return;
      }

      sp.notes.removeAllElements();
      sp.repaint();
      nameTF.setText("");
      loadedFile = null;
    } else if (b.getText() == "Save") {
      if (nameTF.getText().equals("")) {
        JOptionPane.showMessageDialog(
            this,
            new JLabel("Please type in the Scale Name"),
            "Warning",
            JOptionPane.WARNING_MESSAGE);
        return;
      }
      fileChooser.setFileFilter(filter);
      int option = fileChooser.showSaveDialog(this);
      if (option == JFileChooser.APPROVE_OPTION) {
        File target = fileChooser.getSelectedFile();
        if (target.getName().indexOf(".scl") == -1) target = new File(target.getPath() + ".scl");
        try {
          PrintStream stream = new PrintStream(new FileOutputStream(target), true);
          save(stream);
          stream.close();
        } catch (Exception ex) {
          JOptionPane.showMessageDialog(
              this, new JLabel("Error: " + ex.getMessage()), "Error", JOptionPane.ERROR_MESSAGE);
        }
      }
    } else if (b.getText() == "Load") {
      try {
        saveUnsaved();
      } catch (SaveAbortedException ex) {
        return;
      }

      fileChooser.setFileFilter(filter);
      int option = fileChooser.showOpenDialog(this);
      if (option == JFileChooser.APPROVE_OPTION) {
        loadedFile = fileChooser.getSelectedFile();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        ScaleParser handler = new ScaleParser(false);
        try {
          SAXParser parser = factory.newSAXParser();
          parser.parse(loadedFile, handler);
          // System.out.println("success");
        } catch (Exception ex) {
          // System.out.println("no!!!!!! exception: "+e);
          // System.out.println(ex.getMessage());
          ex.printStackTrace();
        }
        // -----now :P:P---------------
        System.out.println("name: " + handler.getName());
        nameTF.setText(handler.getName());
        sp.notes.removeAllElements();
        int[] scale = handler.getScale();
        for (int i = 0; i < scale.length; i++) {
          sp.addNote(scale[i]);
        }
        sp.repaint();
      } else loadedFile = null;
    }
  }
Esempio n. 15
0
    /** Runs this thread. */
    public void run() {
      CommonFileChooser file_chooser = new CommonFileChooser();
      file_chooser.setDialogTitle("Choose a directory.");
      file_chooser.setMultiSelectionEnabled(false);
      file_chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

      if (file_chooser.showSaveDialog(pane) == JFileChooser.APPROVE_OPTION) {
        try {
          File directory = file_chooser.getSelectedFile();
          directory.mkdirs();

          // Outputs the variability XML file.

          String path = FileManager.unitePath(directory.getAbsolutePath(), "package.xml");
          File file = new File(path);
          if (file.exists()) {
            String message = "Overwrite to " + file.getPath() + " ?";
            if (0
                != JOptionPane.showConfirmDialog(
                    pane, message, "Confirmation", JOptionPane.YES_NO_OPTION)) {
              return;
            }
          }

          XmlVariabilityHolder holder = new XmlVariabilityHolder();

          Variability[] records = getSelectedRecords();
          for (int i = 0; i < records.length; i++) {
            XmlVariability variability = new XmlVariability(records[i]);
            holder.addVariability(variability);
          }

          holder.write(file);

          // Copies the report XML document files.

          Hashtable hash_xml = new Hashtable();

          for (int i = 0; i < records.length; i++) {
            XmlMagRecord[] mag_records = records[i].getMagnitudeRecords();
            for (int j = 0; j < mag_records.length; j++)
              hash_xml.put(mag_records[j].getImageXmlPath(), this);
          }

          Vector failed_list = new Vector();

          Enumeration keys = hash_xml.keys();
          while (keys.hasMoreElements()) {
            String xml_path = (String) keys.nextElement();
            try {
              File src_file = desktop.getFileManager().newFile(xml_path);
              File dst_file =
                  new File(FileManager.unitePath(directory.getAbsolutePath(), xml_path));
              if (dst_file.exists() == false) FileManager.copy(src_file, dst_file);
            } catch (Exception exception) {
              failed_list.addElement(xml_path);
            }
          }

          if (failed_list.size() > 0) {
            String header = "Failed to copy the following XML files:";
            MessagesDialog dialog = new MessagesDialog(header, failed_list);
            dialog.show(pane, "Error", JOptionPane.ERROR_MESSAGE);
          }

          // Copies the image files.

          failed_list = new Vector();

          keys = hash_xml.keys();
          while (keys.hasMoreElements()) {
            path = (String) keys.nextElement();
            try {
              XmlInformation info =
                  XmlReport.readInformation(desktop.getFileManager().newFile(path));
              path = info.getImage().getContent();

              File src_file = desktop.getFileManager().newFile(path);
              File dst_file = new File(FileManager.unitePath(directory.getAbsolutePath(), path));
              if (dst_file.exists() == false) FileManager.copy(src_file, dst_file);
            } catch (Exception exception) {
              failed_list.addElement(path);
            }
          }

          if (failed_list.size() > 0) {
            String header = "Failed to copy the following image files:";
            MessagesDialog dialog = new MessagesDialog(header, failed_list);
            dialog.show(pane, "Error", JOptionPane.ERROR_MESSAGE);
          }

          // Creates the sub catalog database.

          try {
            DiskFileSystem file_system =
                new DiskFileSystem(
                    new File(
                        directory.getAbsolutePath(),
                        net.aerith.misao.pixy.Properties.getDatabaseDirectoryName()));
            CatalogDBManager new_manager = new GlobalDBManager(file_system).getCatalogDBManager();

            Hashtable hash_stars = new Hashtable();
            for (int i = 0; i < records.length; i++) {
              CatalogStar star = records[i].getStar();

              CatalogDBReader reader =
                  new CatalogDBReader(desktop.getDBManager().getCatalogDBManager());
              StarList list = reader.read(star.getCoor(), 0.5);
              for (int j = 0; j < list.size(); j++) {
                CatalogStar s = (CatalogStar) list.elementAt(j);
                hash_stars.put(s.getOutputString(), s);
              }
            }

            keys = hash_stars.keys();
            while (keys.hasMoreElements()) {
              String string = (String) keys.nextElement();
              CatalogStar star = (CatalogStar) hash_stars.get(string);
              new_manager.addElement(star);
            }
          } catch (Exception exception) {
            String message = "Failed to create sub catalog database.";
            JOptionPane.showMessageDialog(pane, message, "Error", JOptionPane.ERROR_MESSAGE);
          }

          String message = "Completed.";
          JOptionPane.showMessageDialog(pane, message);
        } catch (IOException exception) {
          String message = "Failed.";
          JOptionPane.showMessageDialog(pane, message, "Error", JOptionPane.ERROR_MESSAGE);
        }
      }
    }