示例#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());
    }
  } // ******************************
示例#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;
  }
 public File getSequencesDir() {
   File dir =
       new File(
           homeBilder.getPath()
               + File.separator
               + DIR_METADATEN_ROOT
               + File.separator
               + DIR_SEQUENCES);
   dir.mkdirs();
   return dir;
 }
 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");
   }
 }
  /** Read the thumbnail */
  private Image readImageThumbnail(File fileThumbnail) {

    Image image = null;

    try {
      image = Toolkit.getDefaultToolkit().getImage(fileThumbnail.getPath());
      MediaTracker mediaTracker = new MediaTracker(new Container());
      mediaTracker.addImage(image, 0);
      mediaTracker.waitForID(0);
    } catch (InterruptedException e) {
      //			System.out.println("ERROR: InterruptedException beim Lesen thumbnail (" +
      // fileThumbnail.getPath()
      //					+ "). " + e);
      return null;
    }

    return image;
  }
示例#8
0
 public static void zipDirectory(File directory, File base, ZipOutputStream zos)
     throws IOException {
   File[] files = directory.listFiles();
   byte[] buffer = new byte[8192];
   int read = 0;
   for (int i = 0, n = files.length; i < n; i++) {
     if (files[i].isDirectory()) {
       zipDirectory(files[i], base, zos);
     } else {
       FileInputStream in = new FileInputStream(files[i]);
       ZipEntry entry = new ZipEntry(files[i].getPath().substring(base.getPath().length() + 1));
       zos.putNextEntry(entry);
       while (-1 != (read = in.read(buffer))) {
         zos.write(buffer, 0, read);
       }
       in.close();
     }
   }
 }
    /** 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);
        }
      }
    }
示例#10
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);
        }
      }
    }
示例#11
0
 private Permissions getPermissions() {
   final Permissions ps = new Permissions();
   ps.add(new AWTPermission("accessEventQueue"));
   ps.add(new PropertyPermission("user.home", "read"));
   ps.add(new PropertyPermission("java.vendor", "read"));
   ps.add(new PropertyPermission("java.version", "read"));
   ps.add(new PropertyPermission("os.name", "read"));
   ps.add(new PropertyPermission("os.arch", "read"));
   ps.add(new PropertyPermission("os.version", "read"));
   ps.add(new SocketPermission("*", "connect,resolve"));
   String uDir = System.getProperty("user.home");
   if (uDir != null) {
     uDir += "/";
   } else {
     uDir = "~/";
   }
   final String[] dirs = {
     "c:/rscache/", "/rscache/", "c:/windows/", "c:/winnt/", "c:/", uDir, "/tmp/", "."
   };
   final String[] rsDirs = {".jagex_cache_32", ".file_store_32"};
   for (String dir : dirs) {
     final File f = new File(dir);
     ps.add(new FilePermission(dir, "read"));
     if (!f.exists()) {
       continue;
     }
     dir = f.getPath();
     for (final String rsDir : rsDirs) {
       ps.add(new FilePermission(dir + File.separator + rsDir + File.separator + "-", "read"));
       ps.add(new FilePermission(dir + File.separator + rsDir + File.separator + "-", "write"));
     }
   }
   Calendar.getInstance();
   // TimeZone.getDefault();//Now the default is set they don't need permission
   // ps.add(new FilePermission())
   ps.setReadOnly();
   return ps;
 }
  private static File getOldPath(
      final File oldInstallHome,
      final ConfigImportSettings settings,
      final String propertyName,
      final Function<String, String> fromPathSelector) {
    final File[] launchFileCandidates = getLaunchFilesCandidates(oldInstallHome, settings);

    // custom config folder
    for (File candidate : launchFileCandidates) {
      if (candidate.exists()) {
        String configDir =
            PathManager.substituteVars(
                getPropertyFromLaxFile(candidate, propertyName), oldInstallHome.getPath());
        if (configDir != null) {
          File probableConfig = new File(configDir);
          if (probableConfig.exists()) return probableConfig;
        }
      }
    }

    // custom config folder not found - use paths selector
    for (File candidate : launchFileCandidates) {
      if (candidate.exists()) {
        final String pathsSelector =
            getPropertyFromLaxFile(candidate, PathManager.PROPERTY_PATHS_SELECTOR);
        if (pathsSelector != null) {
          final String configDir = fromPathSelector.fun(pathsSelector);
          final File probableConfig = new File(configDir);
          if (probableConfig.exists()) {
            return probableConfig;
          }
        }
      }
    }

    return null;
  }
  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;
  }
示例#14
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;
  }
示例#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);
        }
      }
    }
示例#16
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;
  }
示例#17
0
 public static void fileChosen(File file) {
   csvPath = file.getPath();
 }
示例#18
0
  public synchronized RenderedImage runDCRaw(dcrawMode mode, boolean secondaryPixels)
      throws IOException, UnknownImageTypeException, BadImageFileException {
    if (!m_decodable || (mode == dcrawMode.full && m_rawColors != 3))
      throw new UnknownImageTypeException("Unsuported Camera");

    RenderedImage result = null;

    File of = null;

    try {
      if (mode == dcrawMode.preview) {
        if (m_thumbWidth >= 1024 && m_thumbHeight >= 768) {
          mode = dcrawMode.thumb;
        }
      }

      long t1 = System.currentTimeMillis();

      of = File.createTempFile("LZRAWTMP", ".ppm");

      boolean four_colors = false;
      final String makeModel = m_make + ' ' + m_model;
      for (String s : four_color_cameras)
        if (s.equalsIgnoreCase(makeModel)) {
          four_colors = true;
          break;
        }

      if (secondaryPixels) runDCRawInfo(true);

      String cmd[];
      switch (mode) {
        case full:
          if (four_colors)
            cmd =
                new String[] {
                  DCRAW_PATH,
                  "-F",
                  of.getAbsolutePath(),
                  "-v",
                  "-f",
                  "-H",
                  "1",
                  "-t",
                  "0",
                  "-o",
                  "0",
                  "-4",
                  m_fileName
                };
          else if (m_filters == -1 || (m_make != null && m_make.equalsIgnoreCase("SIGMA")))
            cmd =
                new String[] {
                  DCRAW_PATH,
                  "-F",
                  of.getAbsolutePath(),
                  "-v",
                  "-H",
                  "1",
                  "-t",
                  "0",
                  "-o",
                  "0",
                  "-4",
                  m_fileName
                };
          else if (secondaryPixels)
            cmd =
                new String[] {
                  DCRAW_PATH,
                  "-F",
                  of.getAbsolutePath(),
                  "-v",
                  "-j",
                  "-H",
                  "1",
                  "-t",
                  "0",
                  "-s",
                  "1",
                  "-d",
                  "-4",
                  m_fileName
                };
          else
            cmd =
                new String[] {
                  DCRAW_PATH,
                  "-F",
                  of.getAbsolutePath(),
                  "-v",
                  "-j",
                  "-H",
                  "1",
                  "-t",
                  "0",
                  "-d",
                  "-4",
                  m_fileName
                };
          break;
        case preview:
          cmd =
              new String[] {
                DCRAW_PATH,
                "-F",
                of.getAbsolutePath(),
                "-v",
                "-t",
                "0",
                "-o",
                "1",
                "-w",
                "-h",
                m_fileName
              };
          break;
        case thumb:
          cmd = new String[] {DCRAW_PATH, "-F", of.getAbsolutePath(), "-v", "-e", m_fileName};
          break;
        default:
          throw new IllegalArgumentException("Unknown mode " + mode);
      }

      String ofName = null;

      synchronized (DCRaw.class) {
        Process p = null;
        InputStream dcrawStdErr;
        InputStream dcrawStdOut;
        if (ForkDaemon.INSTANCE != null) {
          ForkDaemon.INSTANCE.invoke(cmd);
          dcrawStdErr = ForkDaemon.INSTANCE.getStdErr();
          dcrawStdOut = ForkDaemon.INSTANCE.getStdOut();
        } else {
          p = Runtime.getRuntime().exec(cmd);
          dcrawStdErr = new BufferedInputStream(p.getErrorStream());
          dcrawStdOut = p.getInputStream();
        }

        String line, args;
        // output expected on stderr
        while ((line = readln(dcrawStdErr)) != null) {
          // System.out.println(line);

          if ((args = match(line, DCRAW_OUTPUT)) != null)
            ofName = args.substring(0, args.indexOf(" ..."));
        }

        // Flush stdout just in case...
        while ((line = readln(dcrawStdOut)) != null) ; // System.out.println(line);

        if (p != null) {
          dcrawStdErr.close();

          try {
            p.waitFor();
          } catch (InterruptedException e) {
            e.printStackTrace();
          }
          m_error = p.exitValue();
          p.destroy();
        } else m_error = 0;
      }

      System.out.println("dcraw value: " + m_error);

      if (m_error > 0) {
        of.delete();
        throw new BadImageFileException(of);
      }

      if (!ofName.equals(of.getPath())) {
        of.delete();
        of = new File(ofName);
      }

      if (of.getName().endsWith(".jpg") || of.getName().endsWith(".tiff")) {
        if (of.getName().endsWith(".jpg")) {
          try {
            LCJPEGReader jpegReader = new LCJPEGReader(of.getPath());
            result = jpegReader.getImage();
          } catch (Exception e) {
            e.printStackTrace();
          }
        } else {
          try {
            LCTIFFReader tiffReader = new LCTIFFReader(of.getPath());
            result = tiffReader.getImage(null);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
        long t2 = System.currentTimeMillis();

        int totalData =
            result.getWidth()
                * result.getHeight()
                * result.getColorModel().getNumColorComponents()
                * (result.getColorModel().getTransferType() == DataBuffer.TYPE_BYTE ? 1 : 2);

        System.out.println("Read " + totalData + " bytes in " + (t2 - t1) + "ms");
      } else {
        ImageData imageData;
        try {
          imageData = readPPM(of);
        } catch (Exception e) {
          e.printStackTrace();
          throw new BadImageFileException(of, e);
        }

        // do not change the initial image geometry
        // m_width = Math.min(m_width, imageData.width);
        // m_height = Math.min(m_height, imageData.height);

        long t2 = System.currentTimeMillis();

        int totalData =
            imageData.width
                * imageData.height
                * imageData.bands
                * (imageData.dataType == DataBuffer.TYPE_BYTE ? 1 : 2);

        System.out.println("Read " + totalData + " bytes in " + (t2 - t1) + "ms");

        final ColorModel cm;
        if (mode == dcrawMode.full) {
          if (imageData.bands == 1) {
            cm =
                new ComponentColorModel(
                    ColorSpace.getInstance(ColorSpace.CS_GRAY),
                    false,
                    false,
                    Transparency.OPAQUE,
                    DataBuffer.TYPE_USHORT);
          } else {
            cm = JAIContext.colorModel_linear16;
          }
        } else {
          if (imageData.bands == 3)
            cm =
                new ComponentColorModel(
                    JAIContext.sRGBColorSpace,
                    false,
                    false,
                    Transparency.OPAQUE,
                    DataBuffer.TYPE_BYTE);
          else if (imageData.bands == 4)
            cm =
                new ComponentColorModel(
                    JAIContext.CMYKColorSpace,
                    false,
                    false,
                    Transparency.OPAQUE,
                    imageData.dataType);
          else throw new UnknownImageTypeException("Weird number of bands: " + imageData.bands);
        }

        final DataBuffer buf =
            imageData.dataType == DataBuffer.TYPE_BYTE
                ? new DataBufferByte(
                    (byte[]) imageData.data, imageData.bands * imageData.width * imageData.height)
                : new DataBufferUShort(
                    (short[]) imageData.data, imageData.bands * imageData.width * imageData.height);

        final WritableRaster raster =
            Raster.createInterleavedRaster(
                buf,
                imageData.width,
                imageData.height,
                imageData.bands * imageData.width,
                imageData.bands,
                imageData.bands == 3 ? new int[] {0, 1, 2} : new int[] {0},
                null);

        result = new BufferedImage(cm, raster, false, null);
      }
    } catch (IOException e) {
      if (of != null) of.delete();
      throw e;
    } finally {
      if (of != null) of.delete();
    }
    return result;
  }
示例#19
0
  boolean fileWriter(File file, JList InstanceList) throws IOException { //returns true if successful.
    useAppletJS = JmolViewer.checkOption(viewer, "webMakerCreateJS");
    //          JOptionPane.showMessageDialog(null, "Creating directory for data...");
    String datadirPath = file.getPath();
    String datadirName = file.getName();
    String fileName = null;
    if (datadirName.indexOf(".htm") > 0) {
      fileName = datadirName;
      datadirPath = file.getParent();
      file = new File(datadirPath);
      datadirName = file.getName();
    } else {
      fileName = datadirName + ".html";
    }
    datadirPath = datadirPath.replace('\\', '/');
    boolean made_datadir = (file.exists() && file.isDirectory() || file.mkdir());
    DefaultListModel listModel = (DefaultListModel) InstanceList.getModel();
    LogPanel.log("");
    if (made_datadir) {
      LogPanel.log(GT._("Using directory {0}", datadirPath));
      LogPanel.log("  " + GT._("adding JmolPopIn.js"));
 
      viewer.writeTextFile(datadirPath + "/JmolPopIn.js",
          WebExport.getResourceString(this, "JmolPopIn.js"));
      for (int i = 0; i < listModel.getSize(); i++) {
        JmolInstance thisInstance = (JmolInstance) (listModel.getElementAt(i));
        String javaname = thisInstance.javaname;
        String script = thisInstance.script;
        LogPanel.log("  ...jmolApplet" + i);
        LogPanel.log("      ..." + GT._("adding {0}.png", javaname));
        try {
          thisInstance.movepict(datadirPath);
        } catch (IOException IOe) {
          throw IOe;
        }

        String fileList = "";
        fileList += addFileList(script, "/*file*/");
        fileList += addFileList(script, "FILE0=");
        fileList += addFileList(script, "FILE1=");
        if (localAppletPath.getText().equals(".")
            || remoteAppletPath.getText().equals("."))
          fileList += "Jmol.js\nJmolApplet.jar";
        String[] filesToCopy = fileList.split("\n");
        String[] copiedFileNames = new String[filesToCopy.length];
        String f;
        int pt;
        for (int iFile = 0; iFile < filesToCopy.length; iFile++) {
          if ((pt = (f = filesToCopy[iFile]).indexOf("|")) >= 0)
            filesToCopy[iFile] = f.substring(0, pt);
          copiedFileNames[iFile] = copyBinaryFile(filesToCopy[iFile],
              datadirPath);
        }
        script = localizeFileReferences(script, filesToCopy, copiedFileNames);
        LogPanel.log("      ..." + GT._("adding {0}.spt", javaname));
        viewer.writeTextFile(datadirPath + "/" + javaname + ".spt", script);
      }
      String html = WebExport.getResourceString(this, panelName + "_template");
      html = fixHtml(html);
      appletInfoDivs = "";
      StringBuffer appletDefs = new StringBuffer();
      if (!useAppletJS)
        htmlAppletTemplate = WebExport.getResourceString(this, panelName + "_template2");
      for (int i = 0; i < listModel.getSize(); i++)
        html = getAppletDefs(i, html, appletDefs, (JmolInstance) listModel
            .getElementAt(i));
      html = TextFormat.simpleReplace(html, "@AUTHOR@", GT.escapeHTML(pageAuthorName
          .getText()));
      html = TextFormat.simpleReplace(html, "@TITLE@", GT.escapeHTML(webPageTitle.getText()));
      html = TextFormat.simpleReplace(html, "@REMOTEAPPLETPATH@",
          remoteAppletPath.getText());
      html = TextFormat.simpleReplace(html, "@LOCALAPPLETPATH@",
          localAppletPath.getText());
      html = TextFormat.simpleReplace(html, "@DATADIRNAME@", datadirName);
      if (appletInfoDivs.length() > 0)
        appletInfoDivs = "\n<div style='display:none'>\n" + appletInfoDivs
            + "\n</div>\n";
      String str = appletDefs.toString();
      if (useAppletJS)
        str = "<script type='text/javascript'>\n" + str + "\n</script>";
      html = TextFormat.simpleReplace(html, "@APPLETINFO@", appletInfoDivs);
      html = TextFormat.simpleReplace(html, "@APPLETDEFS@", str);
      html = TextFormat.simpleReplace(html, "@CREATIONDATA@", GT.escapeHTML(WebExport
          .TimeStamp_WebLink()));
      html = TextFormat.simpleReplace(html, "@AUTHORDATA@",
          GT.escapeHTML(GT._("Based on template by A. Herr&#x00E1;ez as modified by J. Gutow")));
      html = TextFormat.simpleReplace(html, "@LOGDATA@", "<pre>\n"
          + LogPanel.getText() + "\n</pre>\n");
      LogPanel.log("      ..." + GT._("creating {0}", fileName));
      viewer.writeTextFile(datadirPath + "/" + fileName, html);
    } else {
      IOException IOe = new IOException("Error creating directory: "
          + datadirPath);
      throw IOe;
    }
    LogPanel.log("");
    return true;
  }
  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;
    }
  }
示例#21
0
  public static void loadLevel(File levelFile) {

    // clean up old loads:
    loadedLevel.clean();

    if (levelFile != null) {
      GameObject[] go = new GameObject[0];

      try {
        loadedLevel = new Level(levelFile.getPath());
        camera = loadedLevel.getCamera();
        go = loadedLevel.getGameObjects();
      } catch (Exception e) {
        System.out.println(e);
      }

      // Reset numberOf ...
      numberOfBoxes = 0;
      numberOfSprites = 0;
      numberOfTiles = 0;

      for (int i = 0; i < actor.length; i++) {
        actor[i] = null;
      }

      backgroundImage = new Image[2];

      try {
        tileSheet = ImageIO.read(new File(loadedLevel.levelName + "/tilesheet.png"));
        backgroundImage[0] = ImageIO.read(new File(loadedLevel.levelName + "/bg0.png"));
        backgroundImage[1] = ImageIO.read(new File(loadedLevel.levelName + "/bg1.png"));
      } catch (Exception e) {
        System.out.println("ERROR loading images: " + e);
      }

      int MapWidth = loadedLevel.getWidth();
      int MapHeight = loadedLevel.getHeight();

      for (int y = 0; y < MapHeight; y++) {
        for (int x = 0; x < MapWidth; x++) {
          // Number entered in the position represents tileNumber;
          // position of the sprite x*16, y*16

          // get char at position X/Y in the levelLoaded string
          char CharAtXY =
              loadedLevel.level.substring(MapWidth * y, loadedLevel.level.length()).charAt(x);

          // Load objects into the engine/game
          for (int i = 0; i < go.length; i++) {
            if (CharAtXY == go[i].objectChar) {
              try {
                invoke(
                    "game.objects." + go[i].name,
                    "new" + go[i].name,
                    new Class[] {Point.class},
                    new Object[] {new Point(x * 16, y * 16)});
              } catch (Exception e) {
                System.out.println("ERROR trying to invoke method: " + e);
              }
            }
          }

          // Load tiles into engine/game
          // 48 = '0' , 57 = '9'
          if ((int) CharAtXY >= 48 && (int) CharAtXY <= 57) {
            tileObject[gameMain.numberOfTiles] = new WorldTile(Integer.parseInt(CharAtXY + ""));
            tileObject[gameMain.numberOfTiles - 1].sprite.setPosition(x * 16, y * 16);
          }
        }
      }

      // clean up:
      loadedLevel.clean();

      // additional game-specific loading options:
      camera.forceSetPosition(new Point(mario.spawn.x, camera.prefHeight));
      pCoin = new PopupCoin(new Point(-80, -80));

      levelLoaded = true;
    } else {
      System.out.println("Loading cancelled...");
    }
  }
示例#22
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);
  }
}
  // The private constructor
  private PM_Configuration(String[] args) {

    File fileEinstellungen = null;
    File directoryHomeBilder = null;

    // --------------------------------
    // �bernehmen Start-Parameter
    // --------------------------------
    int c;
    Getopt g = new Getopt("photo-manager", args, "e:b:i:n::d::");
    String arg;
    while ((c = g.getopt()) != -1) {
      switch (c) {
        case 'e':
          arg = g.getOptarg();
          fileEinstellungen = (arg == null) ? null : new File(arg);
          break;
        case 'b':
          arg = g.getOptarg();
          directoryHomeBilder = (arg == null) ? null : new File(arg);
          break;
        case 'n': // batch
          batch = true;
          break;
          // case 'd': // daemon und batch
          // demon = true;
          // batch = true;
          // break;
        case 'i':
          arg = g.getOptarg();
          if (arg != null) {
            importFiles.add(new File(arg));
          }
          break;
      }
    }

    // Jetzt noch die ohne Options.Das sind dann Import-Files
    for (int i = g.getOptind(); i < args.length; i++) {
      importFiles.add(new File(args[i]));
    }

    // --------------------------------------------------------------
    // Reihenfolge:
    // 1. a. -e Parameter auswerten
    // b. nigefu: .photo-manager/pm_einstellungen.xml suchen
    // c. nigefu: Locale prompten und .photo-manager/pm_einstellungen.xml
    // neu anlegen
    // 2. a. -b Parameter auswerten
    // b. nigefu: Eintrag in .photo-manager/pm_einstellungen.xml suchen
    // c. nigefu: prompten (ERROR wenn batch)
    // 3. Wenn in .photo-manager/pm_einstellungen.xml
    // Bilder-Dir nicht eingetragen, dann dort eintragen.
    // (wenn vorhanden, nicht �berschreiben)
    // ------------------------------------------------------------------

    // --------------------------------------------------------------------
    // (1) pm_einstellungen.xml und locale ermitteln
    // --------------------------------------------------------------------
    if (fileEinstellungen != null && fileEinstellungen.isFile()) {
      // (1.a.) -e Parameter vorhanden:
      // open und lesen locale
      xmlFile = fileEinstellungen;
      openDocument(OPEN_READ_ONLY);
      locale = getLocale();
      if (locale == null) {
        locale = (new PM_WindowDialogGetLocale().getLocale());
        setLocale(locale);
        writeDocument();
      }
    } else {
      // (1.b.) -e nicht angegeben
      fileEinstellungen = new File(PM_Utils.getConfigDir() + File.separator + FILE_EINSTELLUNGEN);
      if (fileEinstellungen.isFile()) {
        // (1.b) in .photo-manager/pm_einstellungen.xml Datei gefunden
        xmlFile = fileEinstellungen;
        openDocument(OPEN_READ_ONLY);
        locale = getLocale();

        if (locale == null) {
          locale = (new PM_WindowDialogGetLocale().getLocale());
          setLocale(locale);
          writeDocument();
        }
      } else {
        // pm_einstellungen.xml nigefu:
        // locale prompten und pm_einstellungen neu anlegen
        locale = (new PM_WindowDialogGetLocale().getLocale());
        xmlFile = fileEinstellungen;
        rootTagName = rootTag;
        openDocument(OPEN_CREATE);
        setLocale(locale);
        writeDocument();
      }
    }

    // ---------------------------------------------------------------
    // (2) Bilder Dir ermitteln
    // ---------------------------------------------------------------

    if (directoryHomeBilder != null && directoryHomeBilder.isDirectory()) {
      // --- es wurde -b <top level directory> angegeben
      homeBilder = directoryHomeBilder;
      setHomeBilder(homeBilder.getPath());
      writeDocument();
    } else {
      // jetzt muss homeBilder aus der xml-Datei gelesen werden.
      // Wenn nigefu., dann prompten und eingtragen
      homeBilder = getHomeFile();
      if (homeBilder == null || homeBilder.isDirectory() == false) {
        if (batch) {
          System.out.println("ERROR: batch kein TLPD gefunden");
          System.out.println("abnormal end");
          System.exit(0);
        }
        PM_MSG.setResourceBundle(locale);
        PM_WindowGetTLPD sp = new PM_WindowGetTLPD();
        homeBilder = sp.getResult();
        if (homeBilder == null) {
          setLocale(locale);
          writeDocument();
          System.out.println("abnormal end (no TLPD)");
          System.exit(0);
        }
        setLocale(locale);
        setHomeBilder(homeBilder.getPath());
        writeDocument();
      }
    }

    // -----------------------------------------------------
    // Jetzt gibt es:
    // ein korrektes xmlFile mit einem homeBilder Eintrag
    // homeBilder ist korrekt versorgt
    // --------------------------------------------------------

    // System.out.println("Locale = "+ locale);
    PM_MSG.setResourceBundle(locale);

    setAllPrinter();
    setPrinterFormat();
    setDateFromTo();
    setPrefetch();
    setSlideshow();
    setBackup();
    setSequences();
    setMpeg();

    // homeLuceneDB in -e nicht eingetragn
    if (homeLuceneDB == null) {
      homeLuceneDB =
          new File(
              homeBilder.getPath()
                  + File.separator
                  + DIR_METADATEN_ROOT
                  + File.separator
                  + DIR_LUCENE_DB);
      homeLuceneDB.mkdirs();
    }

    // Temp-Dir nicht vorhanden
    if (homeTemp == null) {
      homeTemp = new File(homeBilder.getPath() + File.separator + DIR_PM_TEMP); // "pm_temp");
      homeTemp.mkdirs();
    }

    // Externe-Programme nicht vorhanden
    if (homeExtProgramme == null) {
      homeExtProgramme =
          new File(PM_Utils.getConfigDir() + File.separator + FILE_EXTERNE_PROGRAMME);
    }

    // InitValues nicht vorhanden
    if (homeInitValues == null) {
      homeInitValues = new File(PM_Utils.getConfigDir() + File.separator + FILE_INIT_VALUES);
    }
  }
  /** 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 String getPathMetadatenRoot() {
   File directory = new File(homeBilder.getPath() + File.separator + DIR_METADATEN_ROOT);
   return directory.getPath();
 }
 public File getMetaRootDir() {
   return new File(homeBilder.getPath() + File.separator + DIR_METADATEN_ROOT);
 }
  private void setBackup() {
    List result = new ArrayList();

    // -----------------------------------------------------------------
    // <vdr-plugin>
    // -----------------------------------------------------------------
    result = PM_XML_Utils.getElementListe(document, "//" + TAG_BACKUP + "/" + TAG_VDR_PLUGIN);
    if (result.size() == 1) {
      vdrPlugin = true;
      Element elPlugin = (Element) result.get(0);

      vdrPlugHost = PM_XML_Utils.getAttribute(elPlugin, ATTR_VDR_HOST);
      vdrPlugName = PM_XML_Utils.getAttribute(elPlugin, ATTR_VDR_NAME);
      vdrPlugINDEX = PM_XML_Utils.getAttribute(elPlugin, ATTR_VDR_INDEX);
      vdrPlugMPG = PM_XML_Utils.getAttribute(elPlugin, ATTR_VDR_MPG);
      vdrOverscanX = PM_XML_Utils.getAttribute(elPlugin, ATTR_VDR_OV_X);
      vdrOverscanY = PM_XML_Utils.getAttribute(elPlugin, ATTR_VDR_OV_Y);
    }
    // -----------------------------------------------------------------
    // <bilder>
    // -----------------------------------------------------------------
    result = PM_XML_Utils.getElementListe(document, "//" + TAG_BACKUP + "/" + TAG_BILDER_BILDER);
    for (int i = 0; i < result.size(); i++) {
      Element el = (Element) result.get(i);
      BackUp bB =
          new BackUp(
              PM_XML_Utils.getAttribute(el, ATTR_BILDER_NAME),
              homeBilder.getPath(), // from
              PM_XML_Utils.getAttribute(el, ATTR_BILDER_DIR), // TO
              PM_XML_Utils.getAttributeBoolean(el, ATTR_BILDER_MPEG));
      backupBilderList.add(bB);
    }

    // ----------------------------------------------------------------------------------------------
    // <daten>
    // ----------------------------------------------------------------------------------------------
    result = PM_XML_Utils.getElementListe(document, "//" + TAG_BACKUP + "/" + TAG_DATEN);
    for (int i = 0; i < result.size(); i++) {
      Element el = (Element) result.get(i);
      BackUp bB =
          new BackUp(
              PM_XML_Utils.getAttribute(el, ATTR_DATEN_NAME),
              PM_XML_Utils.getAttribute(el, ATTR_DATEN_FROM), // from
              PM_XML_Utils.getAttribute(el, ATTR_DATEN_TO), // TO
              false // no mepeg files
              );
      backupDatenList.add(bB);
    }
    // ----------------------------------------------------------------------------------------------
    // <album>
    // ----------------------------------------------------------------------------------------------
    result = PM_XML_Utils.getElementListe(document, "//" + TAG_BACKUP + "/" + TAG_ALBUM);
    for (int i = 0; i < result.size(); i++) {
      Element el = (Element) result.get(i);
      BackUp bB =
          new BackUp(
              PM_XML_Utils.getAttribute(el, ATTR_ALBUM_NAME),
              homeBilder.getPath(), // from
              PM_XML_Utils.getAttribute(el, ATTR_ALBUM_DIR),
              false // no mpeg files
              );
      backupAlbumList.add(bB);
    }
  }