示例#1
0
 public void secureDelete() {
   int rw = tblItems.getSelectedRow();
   if (rw == -1) {
     JOptionPane.showMessageDialog(frm, "No item selected", "Error", JOptionPane.ERROR_MESSAGE);
     return;
   }
   int idx = tblItems.convertRowIndexToModel(rw);
   if (JOptionPane.showConfirmDialog(
           frm,
           "Delete " + store.plainName(idx) + "?",
           "Confirm Delete",
           JOptionPane.YES_NO_OPTION)
       != JOptionPane.YES_OPTION) return;
   File del = store.delete(idx);
   store.fireTableDataChanged();
   if (del != null) {
     if (del.delete()) {
       // successful
       needsSave = true;
     } else {
       System.err.println("Delete " + del.getAbsolutePath() + " failed");
     }
   }
   updateStatus();
 }
示例#2
0
  public void setFileName(int row, String name) {
    // avoid moving a File by renaming it !!
    if (name.indexOf("..") < 0 && name.indexOf("/") < 0 && name.indexOf("\\") < 0) {
      File oldFile = getFile(filenames[row]);
      File newFile = new File(oldFile.getParent() + File.separator + name);

      filenames[row] = name;

      oldFile.renameTo(newFile);
    }
  }
示例#3
0
 /**
  * public char[] jetPass(){ JPasswordField psf = new JPasswordField(); psf.grabFocus(); int opt =
  * JOptionPane.showConfirmDialog(frm, psf, "Password", JOptionPane.PLAIN_MESSAGE); if(opt ==
  * JOptionPane.OK_OPTION) return psf.getPassword(); return null; }
  *
  * <p>public String jetString(String msg, String ttl){ return JOptionPane.showInputDialog(frm,
  * msg, ttl, JOptionPane.QUESTION_MESSAGE); }*
  */
 public static String jobString(String job) {
   if (job.charAt(0) == IMPORT_FLAG) {
     String[] brk = job.split(",", 4); // 4 parts to an import string
     File inf = new File(brk[1]);
     return "import " + inf.getName();
   } else {
     String[] brk = job.split(",", 3); // 3 parts to export string
     File plf = new File(brk[2]);
     return "export " + plf.getName();
   }
 }
示例#4
0
 public void totalExport() {
   File expf = new File("export");
   if (expf.exists()) rmrf(expf);
   expf.mkdirs();
   for (int sto = 0; sto < storeLocs.size(); sto++) {
     try {
       String sl =
           storeLocs.get(sto).getAbsolutePath().replaceAll("/", "-").replaceAll("\\\\", "-");
       File estore = new File(expf, sl);
       estore.mkdir();
       File log = new File(estore, LIBRARY_NAME);
       PrintWriter pw = new PrintWriter(log);
       for (int i = 0; i < store.getRowCount(); i++)
         if (store.curStore(i) == sto) {
           File enc = store.locate(i);
           File dec = sec.prepareMainFile(enc, estore, false);
           pw.println(dec.getName());
           pw.println(store.getValueAt(i, Storage.COL_DATE));
           pw.println(store.getValueAt(i, Storage.COL_TAGS));
           synchronized (jobs) {
             jobs.addLast(expJob(enc, dec));
           }
         }
       pw.close();
     } catch (IOException exc) {
       exc.printStackTrace();
       JOptionPane.showMessageDialog(frm, "Exporting Failed");
       return;
     }
   }
   JOptionPane.showMessageDialog(frm, "Exporting to:\n   " + expf.getAbsolutePath());
 }
示例#5
0
 public boolean edtExport(File cip, File pla) {
   if (!cip.exists()) {
     System.err.println(
         "export: file " + cip.getAbsolutePath() + " doesnt exist for " + pla.getName());
     pla.delete();
     return false;
   }
   File save = sec.encryptSpecialFile(cip, pla, false);
   if (save == null) {
     System.err.println("export: Encryption failure");
     pla.delete();
     return false;
   }
   return true;
 }
示例#6
0
 public void secureExport(int i) {
   File expf = getExportTempFile(store.plainName(i));
   // check if its already been exported
   if (expf.exists()) secureUse(expf);
   else { // otherwise add to work queue
     File cipf = store.locate(i);
     if (cipf != null) {
       synchronized (jobs) {
         if (priorityExport) jobs.addFirst(expJob(cipf, expf));
         else jobs.addLast(expJob(cipf, expf));
       }
     } else System.err.println("Cannot export, missing encrypted file");
   }
   updateStatus();
 }
示例#7
0
  public static void stringToFile(String file, String string) {
    try {
      if (file.lastIndexOf('\\') != -1) {
        File par = new File(file.substring(0, file.lastIndexOf('\\')));
        par.mkdirs();
      }

      FileWriter fw = new FileWriter(file);
      fw.write(string);
      fw.flush();
      fw.close();
    } catch (IOException e) {
      System.out.println("Failed to save file.");
    }
  }
示例#8
0
  /**
   * Load a file of a particular type. It's a pretty standard helper function, which uses DarwinCSV
   * and setCurrentCSV(...) to make file loading happen with messaging and whatnot. We can also
   * reset the display: just call loadFile(null).
   *
   * @param file The file to load.
   * @param type The type of file (see DarwinCSV's constants).
   */
  private void loadFile(File file, short type) {
    // If the file was reset, reset the display and keep going.
    if (file == null) {
      mainFrame.setTitle(basicTitle);
      setCurrentCSV(null);
      return;
    }

    // Load up a new DarwinCSV and set current CSV.
    try {
      setCurrentCSV(new DarwinCSV(file, type));

    } catch (IOException ex) {
      MessageBox.messageBox(
          mainFrame,
          "Could not read file '" + file + "'",
          "Unable to read file '" + file + "': " + ex);
    }

    // Set the main frame title, based on the filename and the index.
    mainFrame.setTitle(
        basicTitle
            + ": "
            + file.getName()
            + " ("
            + String.format("%,d", currentCSV.getRowIndex().getRowCount())
            + " rows)");
  }
    /** 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
 public static void storeImage(BufferedImage image, String s) {
   String ext;
   File f;
   try {
     ext = s.substring(s.lastIndexOf(".") + 1);
     f = new File(s);
     f.mkdirs();
   } catch (Exception e) {
     System.out.println(e);
     return;
   }
   if (!ext.equals("gif") && !ext.equals("jpg") && !ext.equals("png")) {
     System.out.println("Cannot write to file: Illegal extension " + ext);
     return;
   }
   try {
     ImageIO.write(image, ext, f);
   } catch (Exception e) {
     System.out.println(e);
   }
 }
示例#11
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);
        }
      }
    }
示例#12
0
  /**
   * Save the document to a file.
   *
   * @see #write
   */
  public boolean save(String filename) {

    try {
      setFilename(filename);

      // write to tmp file
      File tmpfile = File.createTempFile("gwb", null);
      write(new FileOutputStream(tmpfile));

      // copy to dest file and delete tmp file
      FileUtils.copy(tmpfile, new File(filename));
      tmpfile.delete();

      //

      //
      fireDocumentInit();
      return true;
    } catch (Exception e) {
      LogUtils.report(e);
      return false;
    }
  }
示例#13
0
 public static boolean rmrf(File fi) {
   if (fi.isDirectory()) {
     boolean done = true;
     for (File subfi : fi.listFiles()) {
       if (!rmrf(subfi)) {
         done = false;
       }
     }
     if (!done) return false;
     return fi.delete();
   } else {
     boolean done = true;
     for (int i = 0; i < 10; i++) {
       done = fi.delete();
       if (done) break;
       try {
         Thread.sleep(100);
       } catch (InterruptedException e) {
         // do nothing
       }
     }
     return done;
   }
 }
示例#14
0
  public void setDirectory(File d, FilenameFilter f) {
    if (d == null || !d.isDirectory()) {
      directory = null;
      filenames = new String[0];
    } else {
      if (f != null) {
        filenameFilter = f;
      }

      directory = d;
      filenames = directory.list(filenameFilter);
      if (filenames != null) { // cannot access directory ?
        Arrays.sort(filenames);
        dirType = new boolean[filenames.length];
        for (int i = 0; i < filenames.length; ++i) {
          // I hate generating objects like this..
          dirType[i] = (new File(d, filenames[i])).isDirectory();
        }
      } else {
        filenames = new String[0];
      }
    }
    fireTableStructureChanged();
  }
  public void actionPerformed(ActionEvent e) {
    JButton b = (JButton) e.getSource();
    if (b == bu) {
      j14 = new JLabel("NEW IMAGE");
      j14.setBounds(840, 200, 300, 300);
      q.add(j14);

      JFileChooser filechooser = new JFileChooser();
      int result = filechooser.showOpenDialog(this);
      f = filechooser.getSelectedFile();
      try {
        String dir1 = f.getAbsolutePath();
        // setText(dir);
        str = dir1;
        // ResizeImage.resize(dir);
        f = new File(dir1);
      } catch (Exception e1) {
      }
      repaint();
      // b=(JButton)e.getSource();

    }
    if (b == ba) {
      try {
        read();
        patient.add(tadd.getText(), tsym.getText(), f, str);
        JOptionPane.showMessageDialog(null, "Patient ID: " + patient.pid + " Record Added");
      } catch (Exception e4) {
        System.out.println("" + e4);
      }
    }
    if (b == bm) {
      try {
        setVisible(false);
      } catch (Exception e4) {
        System.out.println("" + e4);
      }
    }
  }
示例#16
0
  /**
   * Read the document from a file.
   * @param merge if <code>true</code> the content of the file is
   * appended to the current document, when possible
   * @param warning if <code>true</true> report when the file cannot
   * be parsed
   * @see #read
   */
  public boolean open(File file, boolean merge, boolean warning) {
    try {
      FileInputStream fis = new FileInputStream(file);

      // read structure
      try {
        read(fis, merge);
      } catch (Exception e) {
        System.err.println("Got exception: " + e.getMessage());
        init();
        if (warning) throw e;
        return false;
      }

      //
      setFilename(file.getAbsolutePath());
      fireDocumentInit();
      return true;
    } catch (Exception e) {
      LogUtils.report(e);
      return false;
    }
  }
  public static void add(String a, String b, File x, String s) throws Exception {
    fis = new FileInputStream(x);

    pa.setString(1, "" + dt);
    pa.setInt(2, pid);
    pa.setString(3, pfnm);
    pa.setString(4, pmnm);
    pa.setString(5, plnm);
    pa.setString(6, gen);
    pa.setInt(7, age);
    pa.setString(8, wt);
    pa.setString(9, a);
    pa.setString(10, cno);
    pa.setString(11, dnm);
    pa.setString(12, b);
    pa.setString(13, dig);
    pa.setInt(14, fee);
    pa.setString(15, bg);
    pa.setString(17, s);
    pa.setBinaryStream(16, (InputStream) fis, (int) (x.length()));

    pa.executeUpdate();
  }
  public static void mod(File x, String s) throws Exception {

    try {
      System.out.println(x);
      fis = new FileInputStream(x);
      // tmp=con.prepareStatement("update patient set
      // dt=?,pfnm=?,pmnm=?,plnm=?,gen=?,age=?,wt=?,addr=?,cno=?,dnnm=?,sym=?,dig=?,fee=? where
      // pid=1");
      tmp =
          con.prepareStatement(
              "update patient set dt=?,pfnm=?,pmnm=?,plnm=?,gen=?,age=?,wt=?,addr=?,cno=?,dnm=?,sym=?,dig=?,fee=?,bg=?,i=?,path=? where pid="
                  + pid);
      // tmp.setString(1,pfnm);
      tmp.setString(1, "" + dt);
      tmp.setString(2, pfnm);
      tmp.setString(3, pmnm);
      tmp.setString(4, plnm);
      tmp.setString(5, gen);
      tmp.setInt(6, age);
      tmp.setString(7, wt);
      tmp.setString(8, addr);
      tmp.setString(9, cno);
      tmp.setString(10, dnm);
      tmp.setString(11, sym);
      tmp.setString(12, dig);
      tmp.setInt(13, fee);
      tmp.setString(14, bg);

      tmp.setString(16, s);
      tmp.setBinaryStream(15, (InputStream) fis, (int) (x.length()));

      tmp.executeUpdate();
    } catch (Exception ee) {
      System.out.println("mod123 " + ee);
    }
  }
示例#19
0
 public void secureImport() {
   JFileChooser imp = new JFileChooser();
   imp.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
   imp.setMultiSelectionEnabled(true);
   int ret = imp.showOpenDialog(frm);
   if (ret != JFileChooser.APPROVE_OPTION) {
     return;
   }
   File[] fis = imp.getSelectedFiles();
   ArrayList<String> impJobs = new ArrayList<String>();
   boolean dirs = false;
   for (File fi : fis) {
     if (fi.isDirectory()) {
       dirs = true;
       File lib = new File(fi, LIBRARY_NAME);
       if (lib.exists()) {
         try {
           Scanner sca = new Scanner(lib);
           while (sca.hasNextLine()) {
             String nm = sca.nextLine();
             String date = sca.nextLine();
             String tags = sca.nextLine();
             File addr = new File(fi, nm);
             if (addr.exists() && !addr.isDirectory()) impJobs.add(impJob(addr, date, tags));
           }
           sca.close();
         } catch (IOException exc) {
           // add nothing?
         }
       } else {
         for (File cont : fi.listFiles())
           if (!cont.isDirectory()) impJobs.add(impJob(cont, null, null));
       }
     } else {
       impJobs.add(impJob(fi, null, null));
     }
   }
   if (impJobs.size() > 1 || dirs) { // dont bother user if selected single file
     String shw = "Importing:";
     if (impJobs.size() > 30) shw = null;
     int pcount = 0;
     for (String jb : impJobs) {
       String[] prts = jb.split(",", 4); // import jobs have 4 parts, import, name, date, tags
       if (shw != null) shw = shw + "\n  - " + new File(prts[1]).getName();
       if (!prts[3].equalsIgnoreCase(Storage.NEW_TAG)) {
         pcount++;
         if (shw != null) shw = shw + " []";
       }
     }
     if (shw == null) shw = "importing ";
     else shw = shw + "\n";
     shw = shw + impJobs.size() + "(" + pcount + ") files";
     if (JOptionPane.showConfirmDialog(frm, shw, "Confirm Import", JOptionPane.YES_NO_OPTION)
         != JOptionPane.YES_OPTION) return;
   }
   synchronized (jobs) {
     for (String j : impJobs) {
       if (priorityExport) jobs.addLast(j);
       else jobs.addFirst(j);
     }
   }
   updateStatus();
 }
示例#20
0
    protected void saveToFile() {
      if (this.fileChooser == null) {
        this.fileChooser = new JFileChooser();
        this.fileChooser.setCurrentDirectory(new File(Configuration.getUserHomeDirectory()));
      }

      this.fileChooser.setDialogTitle("Choose Directory to Place Airspaces");
      this.fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      this.fileChooser.setMultiSelectionEnabled(false);
      int status = this.fileChooser.showSaveDialog(null);
      if (status != JFileChooser.APPROVE_OPTION) return;

      final File dir = this.fileChooser.getSelectedFile();
      if (dir == null) return;

      if (!dir.exists()) {
        //noinspection ResultOfMethodCallIgnored
        dir.mkdirs();
      }

      final Iterable<AirspaceEntry> entries = this.getModel().getEntries();

      Thread t =
          new Thread(
              new Runnable() {
                public void run() {
                  try {
                    java.text.DecimalFormat f = new java.text.DecimalFormat("####");
                    f.setMinimumIntegerDigits(4);
                    int counter = 0;

                    for (AirspaceEntry entry : entries) {
                      Airspace a = entry.getAirspace();
                      AirspaceAttributes currentAttribs = a.getAttributes();
                      a.setAttributes(entry.getAttributes());

                      String xmlString = a.getRestorableState();
                      if (xmlString != null) {
                        try {
                          PrintWriter of =
                              new PrintWriter(
                                  new File(
                                      dir,
                                      a.getClass().getName()
                                          + "-"
                                          + entry.getName()
                                          + "-"
                                          + f.format(counter++)
                                          + ".xml"));
                          of.write(xmlString);
                          of.flush();
                          of.close();
                        } catch (Exception e) {
                          e.printStackTrace();
                        }
                      }

                      a.setAttributes(currentAttribs);
                    }
                  } finally {
                    SwingUtilities.invokeLater(
                        new Runnable() {
                          public void run() {
                            setEnabled(true);
                            getApp().setCursor(null);
                            getApp().getWwd().redraw();
                          }
                        });
                  }
                }
              });
      this.setEnabled(false);
      getApp().setCursor(new Cursor(Cursor.WAIT_CURSOR));
      t.start();
    }
示例#21
0
 public void run() {
   going = true;
   while (going) {
     String chose = null;
     synchronized (jobs) {
       chose = jobs.poll();
     }
     if (chose != null) {
       cur = chose;
       updateStatus();
       long time = System.currentTimeMillis();
       String op = "export";
       String targ = null;
       boolean success = false;
       if (chose.charAt(0) == IMPORT_FLAG) {
         String[] brk = chose.split(",", 4); // 4 parts to an import string
         File imp = new File(brk[1]);
         targ = imp.getName();
         if (edtImport(imp, brk[2], brk[3])) {
           // import successful
           success = true;
           if (checkImports) op = "import & check";
           else op = "import (fast)";
           store.fireTableDataChanged();
         } else {
           // no import
         }
       } else {
         String[] brk = chose.split(",", 3); // 3 parts to an export string
         File pla = new File(brk[2]);
         targ = pla.getName();
         if (edtExport(new File(brk[1]), pla)) {
           // export succeeded
           success = true;
           // System.out.println(pla.getParentFile().getAbsolutePath() + ", " +
           // tempLoc.getAbsolutePath() + ", " + pla.getParentFile().equals(tempLoc));
           try {
             if (pla.getParentFile().getCanonicalPath().equals(tempLoc.getCanonicalPath()))
               secureUse(pla);
           } catch (IOException exc) {
             System.err.println("Failed to retrieve canonical path?");
           }
         } else {
           // export failed
         }
       }
       if (success)
         System.out.println(
             "Completed " + op + " in " + (System.currentTimeMillis() - time) + "ms - " + targ);
       cur = null;
       updateStatus();
     } else {
       if (needsSave && idx == 0) {
         boolean alldone = true;
         for (int i = 0; i < numThreads; i++) {
           if (encryptDecryptThreads[i].getCur() != null) {
             alldone = false;
             break;
           }
         }
         if (alldone) {
           System.out.println("Automatically saving");
           try {
             store.saveAll(tempLoc);
           } catch (IOException e) {
             System.err.println("Automatic save failed");
           }
           needsSave = false;
         }
       }
       try {
         Thread.sleep(500);
       } catch (InterruptedException e) {
         // do nothing
       }
     }
   }
 }
示例#22
0
 public boolean edtImport(File fi, String date, String tags) {
   if (!fi.exists()) {
     System.err.println("import: file " + fi.getAbsolutePath() + " doesnt exist");
     return false;
   }
   String pname = fi.getName();
   if (store.containsEntry(pname)) {
     System.err.println("import: already have a file named " + pname);
     return false;
   }
   long size = fi.length() / KILOBYTE;
   File save = sec.encryptMainFile(fi, storeLocs.get(0), true);
   if (save == null) {
     System.err.println("import: Encryption failure");
     return false;
   }
   if (checkImports) {
     boolean success = true;
     File checkfi = new File(idx + ".check");
     File checkOut = sec.encryptSpecialFile(save, checkfi, false);
     if (checkOut == null) success = false;
     else {
       String fiHash = sec.digest(fi);
       String outHash = sec.digest(checkOut);
       if (fiHash == null || outHash == null || fiHash.length() < 1 || !fiHash.equals(outHash))
         success = false;
     }
     checkfi.delete();
     if (!success) {
       save.delete();
       if (JOptionPane.showConfirmDialog(
               frm,
               "Confirming "
                   + fi.getName()
                   + "failed\n\n - Would you like to re-import the file?",
               "Import failed",
               JOptionPane.YES_NO_OPTION)
           == JOptionPane.YES_OPTION) {
         String j = impJob(fi, date, tags);
         synchronized (jobs) {
           if (priorityExport) jobs.addLast(j);
           else jobs.addFirst(j);
         }
       }
       return false;
     }
   }
   if (!fi.delete()) {
     System.err.println("import: Couldnt delete old file - continuing");
   }
   store.add(save.getName(), pname, date, size, tags, 0);
   needsSave = true;
   return true;
 }
示例#23
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);
        }
      }
    }
示例#24
0
 public static String expJob(File cip, File plain) {
   return EXPORT_FLAG + "," + cip.getAbsolutePath() + "," + plain.getAbsolutePath();
 }
示例#25
0
 public static String impJob(File fi, String date, String tags) {
   if (date == null) date = Storage.curDate();
   if (tags == null) tags = Storage.NEW_TAG;
   return IMPORT_FLAG + "," + fi.getAbsolutePath() + "," + date + "," + tags;
 }
示例#26
0
  public Ssys3() {
    store = new Storage();
    tableSorter = new TableRowSorter<Storage>(store);
    jobs = new LinkedList<String>();

    makeGUI();
    frm.setSize(800, 600);
    frm.addWindowListener(
        new WindowListener() {
          public void windowActivated(WindowEvent evt) {}

          public void windowClosed(WindowEvent evt) {
            try {
              System.out.println("joining EDT's");
              for (EDT edt : encryptDecryptThreads) {
                edt.weakStop();
                try {
                  edt.join();
                  System.out.println("  - joined");
                } catch (InterruptedException e) {
                  System.out.println("  - Not joined");
                }
              }
              System.out.println("saving storage");
              store.saveAll(tempLoc);
            } catch (IOException e) {
              e.printStackTrace();
              System.err.println(
                  "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n\nFailed to save properly\n\n!!!!!!!!!!!!!!!!!!!!!!!!!");
              System.exit(1);
            }
            clean();
            System.exit(0);
          }

          public void windowClosing(WindowEvent evt) {
            windowClosed(evt);
          }

          public void windowDeactivated(WindowEvent evt) {}

          public void windowDeiconified(WindowEvent evt) {}

          public void windowIconified(WindowEvent evt) {}

          public void windowOpened(WindowEvent evt) {}
        });
    ImageIcon ico = new ImageIcon(ICON_NAME);
    frm.setIconImage(ico.getImage());
    frm.setLocationRelativeTo(null);
    frm.setVisible(true);

    // load config
    storeLocs = new ArrayList<File>();
    String ossl = "openssl";
    int numThreadTemp = 2;
    boolean priorityDecryptTemp = true;
    boolean allowExportTemp = false;
    boolean checkImportTemp = true;
    try {
      Scanner sca = new Scanner(CONF_FILE);
      while (sca.hasNextLine()) {
        String ln = sca.nextLine();
        if (ln.startsWith(CONF_SSL)) {
          ossl = ln.substring(CONF_SSL.length());
        } else if (ln.startsWith(CONF_THREAD)) {
          try {
            numThreadTemp = Integer.parseInt(ln.substring(CONF_THREAD.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.equals(CONF_STORE)) {
          while (sca.hasNextLine()) storeLocs.add(new File(sca.nextLine()));
        } else if (ln.startsWith(CONF_PRIORITY)) {
          try {
            priorityDecryptTemp = Boolean.parseBoolean(ln.substring(CONF_PRIORITY.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.startsWith(CONF_EXPORT)) {
          try {
            allowExportTemp = Boolean.parseBoolean(ln.substring(CONF_EXPORT.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        } else if (ln.startsWith(CONF_CONFIRM)) {
          try {
            checkImportTemp = Boolean.parseBoolean(ln.substring(CONF_CONFIRM.length()));
          } catch (Exception exc) {
            // do Nothing
          }
        }
      }
      sca.close();
    } catch (IOException e) {

    }
    String osslWorks = OpenSSLCommander.test(ossl);
    while (osslWorks == null) {
      ossl =
          JOptionPane.showInputDialog(
              frm,
              "Please input the command used to run open ssl\n  We will run \"<command> version\" to confirm\n  Previous command: "
                  + ossl,
              "Find open ssl",
              JOptionPane.OK_CANCEL_OPTION);
      if (ossl == null) {
        System.err.println("Refused to provide openssl executable location");
        System.exit(1);
      }
      osslWorks = OpenSSLCommander.test(ossl);
      if (osslWorks == null)
        JOptionPane.showMessageDialog(
            frm, "Command " + ossl + " unsuccessful", "Unsuccessful", JOptionPane.ERROR_MESSAGE);
    }
    if (storeLocs.size() < 1)
      JOptionPane.showMessageDialog(
          frm,
          "Please select an initial sotrage location\nIf one already exists, or there are more than one, please select it");
    while (storeLocs.size() < 1) {
      JFileChooser jfc = new JFileChooser();
      jfc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
      if (jfc.showOpenDialog(frm) != JFileChooser.APPROVE_OPTION) {
        System.err.println("Refused to provide an initial store folder");
        System.exit(1);
      }
      File sel = jfc.getSelectedFile();
      if (sel.isDirectory()) storeLocs.add(sel);
    }
    numThreads = numThreadTemp;
    priorityExport = priorityDecryptTemp;
    allowExport = allowExportTemp;
    checkImports = checkImportTemp;

    try {
      PrintWriter pw = new PrintWriter(CONF_FILE);
      pw.println(CONF_SSL + ossl);
      pw.println(CONF_THREAD + numThreads);
      pw.println(CONF_PRIORITY + priorityExport);
      pw.println(CONF_EXPORT + allowExport);
      pw.println(CONF_CONFIRM + checkImports);
      pw.println(CONF_STORE);
      for (File fi : storeLocs) {
        pw.println(fi.getAbsolutePath());
      }
      pw.close();
    } catch (IOException e) {
      System.err.println("Failed to save config");
    }

    File chk = null;
    for (File fi : storeLocs) {
      File lib = new File(fi, LIBRARY_NAME);
      if (lib.exists()) {
        chk = lib;
        // break;
      }
    }

    char[] pass = null;
    if (chk == null) {
      JOptionPane.showMessageDialog(
          frm,
          "First time run\n  Create your password",
          "Create Password",
          JOptionPane.INFORMATION_MESSAGE);
      char[] p1 = askPassword();
      char[] p2 = askPassword();
      boolean same = p1.length == p2.length;
      for (int i = 0; i < Math.min(p1.length, p2.length); i++) {
        if (p1[i] != p2[i]) same = false;
      }
      if (same) {
        JOptionPane.showMessageDialog(
            frm, "Password created", "Create Password", JOptionPane.INFORMATION_MESSAGE);
        pass = p1;
      } else {
        JOptionPane.showMessageDialog(
            frm, "Passwords dont match", "Create Password", JOptionPane.ERROR_MESSAGE);
        System.exit(1);
      }
    } else {
      pass = askPassword();
    }
    sec = OpenSSLCommander.getCommander(chk, pass, ossl);
    if (sec == null) {
      System.err.println("Wrong Password");
      System.exit(1);
    }
    store.useSecurity(sec);
    store.useStorage(storeLocs);

    tempLoc = new File("temp");
    if (!tempLoc.exists()) tempLoc.mkdirs();
    // load stores
    try {
      store.loadAll(tempLoc);
      store.fireTableDataChanged();
    } catch (IOException e) {
      System.err.println("Storage loading failure");
      System.exit(1);
    }

    needsSave = false;
    encryptDecryptThreads = new EDT[numThreads];
    for (int i = 0; i < encryptDecryptThreads.length; i++) {
      encryptDecryptThreads[i] = new EDT(i);
      encryptDecryptThreads[i].start();
    }

    updateStatus();
    txaSearch.grabFocus();
  }