Beispiel #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());
    }
  } // ******************************
Beispiel #2
0
 /**
  * This method deletes a plugin file. If deletion fails - typically happens on Windows due to file
  * locking - the file is scheduled for deletion on the next startup.
  *
  * @param f The file to delete.
  * @return true if deletion was successful, false if scheduled for later.
  */
 public static boolean deletePluginFile(File f) {
   boolean success = f.delete();
   if (success) return true;
   else {
     schedulePluginForDeletion(f.getPath());
     return false;
   }
 }
Beispiel #3
0
 void finishConversion(File outFile, Date start) {
   isBusy = false;
   progressBar.setIndeterminate(false);
   Date end = new Date();
   textArea.append(
       format("Created %s in %s ms.%n", outFile.getPath(), end.getTime() - start.getTime()));
   JScrollBar scrollBar = scrollPane.getVerticalScrollBar();
   scrollBar.setValue(scrollBar.getMaximum());
 }
Beispiel #4
0
  /**
   * Build a list of installed plugins.
   *
   * @return a list of plugin names and version numbers.
   */
  public static EventList<NameAndVersion> findInstalledPlugins() {
    EventList<NameAndVersion> plugins = new BasicEventList<NameAndVersion>();
    if (!PluginCore.userPluginDir.exists()) return plugins;
    String[] files =
        PluginCore.userPluginDir.list(
            new FilenameFilter() {
              public boolean accept(File dir, String name) {
                return name.endsWith(".jar");
              }
            });

    HashMap<String, PluginDescriptor> urls = new HashMap<String, PluginDescriptor>();
    Collection<PluginDescriptor> descriptors =
        PluginCore.getManager().getRegistry().getPluginDescriptors();
    for (PluginDescriptor desc : descriptors) {
      if ((desc.getPluginClassName() == null)
          || !desc.getPluginClassName().equals("net.sf.jabref.plugin.core.JabRefPlugin")) {
        urls.put(desc.getId(), desc);
      }
    }

    for (String file1 : files) {
      File file = new File(PluginCore.userPluginDir, file1);
      String[] nav = getNameAndVersion(file);
      if (nav != null) {
        VersionNumber vn = nav[1] != null ? new VersionNumber(nav[1]) : null;
        NameAndVersion nameAndVersion = new NameAndVersion(nav[0], vn, true, file);
        for (Iterator<String> it = urls.keySet().iterator(); it.hasNext(); ) {
          String loc = it.next();
          if (loc.contains(nav[0])) {
            PluginDescriptor desc = urls.get(loc);
            // System.out.println("Accounted for: "+desc.getId()+" "+desc.getVersion().toString());
            if (!PluginCore.getManager().isPluginEnabled(urls.get(loc)))
              nameAndVersion.setStatus(BAD);
            else nameAndVersion.setStatus(LOADED);
            it.remove();
          }
        }
        plugins.add(nameAndVersion);
      }
    }

    for (String url : urls.keySet()) {
      PluginDescriptor desc = urls.get(url);
      File location = new File(desc.getLocation().getFile());
      if (location.getPath().contains(PluginCore.userPluginDir.getPath()))
        continue; // This must be a loaded user dir plugin that's been deleted.
      // System.out.println("File: "+desc.getLocation().getFile());
      NameAndVersion nameAndVersion =
          new NameAndVersion(
              desc.getId(), new VersionNumber(desc.getVersion().toString()), false, location);
      if (!PluginCore.getManager().isPluginEnabled(urls.get(url))) nameAndVersion.setStatus(BAD);
      else nameAndVersion.setStatus(LOADED);
      plugins.add(nameAndVersion);
    }
    return plugins;
  }
Beispiel #5
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 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");
   }
 }
Beispiel #9
0
  public static void main(String[] args) {

    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
      JOptionPane.showMessageDialog(null, "Fatal Error Occurred!");
      System.exit(1);
    }

    /*View.SplashWindow s = new View.SplashWindow();

    s.setVisible(true);*/

    String fPath = args.length == 0 ? JOptionPane.showInputDialog("Enter source path") : args[0];
    File f = new File(fPath);
    if (!f.exists()) {
      System.out.println("Path does not exist!");
      System.exit(1);
    }

    String fDrive = fPath.substring(0, 3);
    File dFile = new File(fDrive);

    File[] dirs = Drive.getAllDrives();
    ArrayList<Drive> drives = new ArrayList<Drive>();

    for (int i = 0; i < dirs.length; i++) {

      if (!dirs[i].getPath().equals(dFile.getPath())) {
        System.out.println("Loading Drive " + dirs[i].getPath() + "...");
        drives.add(new Drive(dirs[i]));
      }
    }
    System.out.println("Done! Loading Interface...");
    // s.setVisible(false);

    Drive[] dr = new Drive[drives.size()];

    for (int i = 0; i < dr.length; i++) {
      dr[i] = drives.get(i);
    }
    new View(dr, f);
  }
    /** 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);
        }
      }
    }
Beispiel #11
0
  public String getJLMPropertiesDir() {
    String jlmPropertiesDir = null;

    String value = Game.getProperty("jlm.configuration.file.path");
    if (value != null) {
      String paths[] = value.split(",");

      for (String localPath : paths) {
        localPath = localPath.replace("$HOME$", System.getProperty("user.home"));
        File localPropertiesFileParentDirectory = new File(localPath);
        File localPropertiesFileDirectory =
            new File(localPath, Game.getLocalPropertiesSubdirectory());

        if (!localPropertiesFileParentDirectory.exists()) {
          continue;
        } else if (localPropertiesFileDirectory.exists() || localPropertiesFileDirectory.mkdir()) {
          jlmPropertiesDir = localPropertiesFileParentDirectory.getPath();
          break;
        } else {
          Logger.log(
              "Game:storeProperties",
              "cannot create local properties store directory ("
                  + localPropertiesFileDirectory
                  + ")");
        }
      }
    } else {
      JOptionPane.showConfirmDialog(
          null,
          "No path provided in the property file (or property file not found)\n"
              + "You may want to export your session with the menu 'Session/Export session'\n"
              + "to save your work manually.\n\n"
              + "Quit without saving?",
          "Cannot save your changes. Quit without saving?",
          JOptionPane.YES_NO_OPTION,
          JOptionPane.ERROR_MESSAGE);
      return null;
    }
    return jlmPropertiesDir;
  }
    /** 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);
        }
      }
    }
  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;
  }
Beispiel #15
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;
  }
  /**
   * Updates the asset references for a shot within Maya and then in pipeline.
   *
   * @param shotName The name of the shot being processed.
   * @param pRemoveRef The list of assets being dereferenced from the shot.
   * @param pReplaceRef The list of assets being referenced into the shot.
   * @param nameMap
   */
  private void editShotReferences(
      String shotName,
      NodeMod targetMod,
      TreeSet<String> pRemoveRef,
      TreeSet<String> pReplaceRef,
      TreeMap<String, String> nameMap)
      throws PipelineException {
    logLine("Editing shot: " + shotName);
    boolean anim = !shotName.matches(lgtPattern);

    /* writing the mel script */
    if (anim) {
      File script = null;
      try {
        script = File.createTempFile("UpdateAssetGUI.", ".mel", PackageInfo.sTempPath.toFile());
        FileCleaner.add(script);
      } // end try
      catch (IOException ex) {
        throw new PipelineException(
            "Unable to create the temporary MEL script used to collect "
                + "texture information from the Maya scene!");
      } // end catch

      try {
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(script)));

        for (String asset : pReplaceRef) {
          String nameSpace;
          if (asset.endsWith(lr))
            nameSpace = nameMap.get(getShortName(asset.substring(0, asset.length() - 3)));
          else {
            System.err.println("This should not be happening, a hi res asset in a lo-res node.");
            continue;
            // nameSpace = nameMap.get(getShortName(asset));
          }
          out.println("print (\"referencing file: $WORKING" + asset + ".ma\");");
          out.println(
              "file -reference -namespace \"" + nameSpace + "\" \"$WORKING" + asset + ".ma\";");
        } // end for

        for (String asset : pRemoveRef) {
          out.println("print (\"dereferencing file: $WORKING" + asset + ".ma\");");
          out.println("file -rr \"$WORKING" + asset + ".ma\";");
        } // end for

        out.println("// SAVE");
        out.println("file -save;");

        out.close();
      } // end try
      catch (IOException ex) {
        throw new PipelineException(
            "Unable to write the temporary MEL script(" + script + ") used add the references!");
      } // end catch

      NodeID targetID = new NodeID(w.user, w.view, shotName);
      // NodeStatus targetStat = mclient.status(targetID);

      /* run Maya to collect the information */
      try {

        Path targetPath = getNodePath(shotName);
        ArrayList<String> args = new ArrayList<String>();
        args.add("-batch");
        args.add("-script");
        args.add(script.getPath());
        args.add("-file");
        args.add(targetPath.toOsString());

        Path wdir = new Path(PackageInfo.sProdPath.toOsString() + targetID.getWorkingParent());

        TreeMap<String, String> env =
            mclient.getToolsetEnvironment(
                w.user, w.view, targetMod.getToolset(), PackageInfo.sOsType);

        Map<String, String> nenv = env;
        String midefs = env.get("PIPELINE_MI_SHADER_PATH");
        if (midefs != null) {
          nenv = new TreeMap<String, String>(env);
          Path dpath = new Path(new Path(wdir, midefs));
          nenv.put("MI_CUSTOM_SHADER_PATH", dpath.toOsString());
        }

        String command = "maya";
        if (PackageInfo.sOsType.equals(OsType.Windows)) command += ".exe";

        SubProcessLight proc =
            new SubProcessLight("UpdateAssetGUI", command, args, env, wdir.toFile());
        try {
          proc.start();
          proc.join();
          if (!proc.wasSuccessful()) {
            throw new PipelineException(
                "Did not correctly edit the reference due to a maya error.!\n\n"
                    + proc.getStdOut()
                    + "\n\n"
                    + proc.getStdErr());
          } // end if
        } // end try
        catch (InterruptedException ex) {
          throw new PipelineException(ex);
        } // end catch
      } // end try
      catch (Exception ex) {
        throw new PipelineException(ex);
      } // end catch
    }

    /*-edit the references in pipeline once they are done in the file-*/
    BaseAction targetAction = targetMod.getAction();
    for (String asset : pReplaceRef) {
      mclient.link(
          w.user, w.view, shotName, asset, LinkPolicy.Reference, LinkRelationship.All, null);
      if (anim) {
        /*Set the namespaces*/
        String nameSpace = nameMap.get(getShortName(asset.substring(0, asset.length() - 3)));
        System.err.println(nameSpace);
        targetAction.initSourceParams(asset);
        targetAction.setSourceParamValue(asset, "PrefixName", nameSpace);
        targetMod.setAction(targetAction);
      }
    }
    w.mclient.modifyProperties(w.user, w.view, targetMod);

    for (String asset : pRemoveRef) mclient.unlink(w.user, w.view, shotName, asset);

    if (!anim) {
      System.err.println("Queuing the switchLgt node " + shotName);
      mclient.submitJobs(w.user, w.view, shotName, null);
    }
  } // end editShotReferences
Beispiel #17
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;
  }
    /** 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);
        }
      }
    }
  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;
    }
  }
  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;
  }
Beispiel #21
0
 public static void fileChosen(File file) {
   csvPath = file.getPath();
 }
Beispiel #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);
  }
}
Beispiel #23
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...");
    }
  }
  /** 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$
      }
    }
  }