예제 #1
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());
 }
예제 #2
0
 public void startFile(String logfile) {
   File parent = new File(logfile).getParentFile();
   if (!parent.isDirectory() && !parent.mkdirs()) {
     logger.warning("Could not create log folder: " + parent);
   }
   Handler fileHandler = new RotatingFileHandler(logfile);
   fileHandler.setFormatter(new DateOutputFormatter(FILE_DATE));
   logger.addHandler(fileHandler);
 }
예제 #3
0
  private void setupHomeDir(String homeString) {
    if (homeString == null) {
      homeString = sysProps.getProperty("swingri.home");
    }

    if (homeString != null) {
      dataDir = new File(homeString);
    } else {
      userHome = new File(sysProps.getProperty("user.home"));
      String dataDirStr = props.getString("application.datadir", DEFAULT_HOME_DIR);
      dataDir = new File(userHome, dataDirStr);
    }

    if (!dataDir.isDirectory()) {
      String path = dataDir.getAbsolutePath();
      boolean create;
      if (props.hasUserRejectedCreatingLocalDataDir()) {
        create = false;
      } else if (getBoolean("application.showLocalStorageDialogs", true)) {
        create =
            Resources.showConfirmDialog(
                null,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.createNewDirectory",
                path);
        if (!create) props.setUserRejectedCreatingLocalDataDir();
      } else {
        // Always create local-storage directory if show user prompt dialog setting is false.
        create = true;
      }

      if (!create) {
        dataDir = null;
      } else {
        dataDir.mkdirs();
        if (!dataDir.isDirectory()) {
          // check to make sure that dialog should be shown on the error.
          if (getBoolean("application.showLocalStorageDialogs", true)) {
            Resources.showMessageDialog(
                null,
                JOptionPane.ERROR_MESSAGE,
                messageBundle,
                "fontManager.properties.title",
                "manager.properties.failedCreation",
                dataDir.getAbsolutePath());
          }
          dataDir = null;
        }
      }
    }
  }
예제 #4
0
파일: Installer.java 프로젝트: suever/CTP
 // Take a tree of files starting in a directory in a zip file
 // and copy them to a disk directory, recreating the tree.
 private int unpackZipFile(
     File inZipFile, String directory, String parent, boolean suppressFirstPathElement) {
   int count = 0;
   if (!inZipFile.exists()) return count;
   parent = parent.trim();
   if (!parent.endsWith(File.separator)) parent += File.separator;
   if (!directory.endsWith(File.separator)) directory += File.separator;
   File outFile = null;
   try {
     ZipFile zipFile = new ZipFile(inZipFile);
     Enumeration zipEntries = zipFile.entries();
     while (zipEntries.hasMoreElements()) {
       ZipEntry entry = (ZipEntry) zipEntries.nextElement();
       String name = entry.getName().replace('/', File.separatorChar);
       if (name.startsWith(directory)) {
         if (suppressFirstPathElement) name = name.substring(directory.length());
         outFile = new File(parent + name);
         // Create the directory, just in case
         if (name.indexOf(File.separatorChar) >= 0) {
           String p = name.substring(0, name.lastIndexOf(File.separatorChar) + 1);
           File dirFile = new File(parent + p);
           dirFile.mkdirs();
         }
         if (!entry.isDirectory()) {
           System.out.println("Installing " + outFile);
           // Copy the file
           BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFile));
           BufferedInputStream in = new BufferedInputStream(zipFile.getInputStream(entry));
           int size = 1024;
           int n = 0;
           byte[] b = new byte[size];
           while ((n = in.read(b, 0, size)) != -1) out.write(b, 0, n);
           in.close();
           out.flush();
           out.close();
           // Count the file
           count++;
         }
       }
     }
     zipFile.close();
   } catch (Exception e) {
     System.err.println("...an error occured while installing " + outFile);
     e.printStackTrace();
     System.err.println("Error copying " + outFile.getName() + "\n" + e.getMessage());
     return -count;
   }
   System.out.println(count + " files were installed.");
   return count;
 }
예제 #5
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.");
    }
  }
  public boolean createLogDirectory() {
    if (settings.logDirectoryName.length() == 0) {
      return true;
    }

    File logDirectory = new File(settings.logDirectoryName);

    if (!logDirectory.exists()) {
      try {
        return logDirectory.mkdirs();
      } catch (SecurityException e) {
        console.writeLine("Failed to create log directory, check read / write permissions.");
        return false;
      }
    }

    return true;
  }
예제 #7
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);
   }
 }
예제 #8
0
파일: Installer.java 프로젝트: suever/CTP
  private void cleanup(File directory) {
    // Clean up from old installations, removing or renaming files.
    // Note that directory is the parent of the CTP directory
    // unless the original installation was done by Bill Weadock's
    // all-in-one installer for Windows.

    // Get a file pointing to the CTP directory.
    // This might be the current directory, or
    // it might be the CTP child.
    File dir;
    if (directory.getName().equals("RSNA")) dir = directory;
    else dir = new File(directory, "CTP");

    // If CTP.jar exists in this directory, it is a really
    // old CTP main file - not used anymore
    File ctp = new File(dir, "CTP.jar");
    if (ctp.exists()) ctp.delete();

    // These are old names for the Launcher.jar file
    File launcher = new File(dir, "CTP-launcher.jar");
    if (launcher.exists()) launcher.delete();
    launcher = new File(dir, "TFS-launcher.jar");
    if (launcher.exists()) launcher.delete();

    // Delete the obsolete CTP-runner.jar file
    File runner = new File(dir, "CTP-runner.jar");
    if (runner.exists()) runner.delete();

    // Delete the obsolete MIRC-copier.jar file
    File copier = new File(dir, "MIRC-copier.jar");
    if (copier.exists()) copier.delete();

    // Rename the old versions of the properties files
    File oldprops = new File(dir, "CTP-startup.properties");
    File newprops = new File(dir, "CTP-launcher.properties");
    File correctprops = new File(dir, "Launcher.properties");
    if (oldprops.exists()) {
      if (newprops.exists() || correctprops.exists()) oldprops.delete();
      else oldprops.renameTo(correctprops);
    }
    if (newprops.exists()) {
      if (correctprops.exists()) newprops.delete();
      else newprops.renameTo(correctprops);
    }

    // Get rid of obsolete startup and shutdown programs
    File startup = new File(dir, "CTP-startup.jar");
    if (startup.exists()) startup.delete();
    File shutdown = new File(dir, "CTP-shutdown.jar");
    if (shutdown.exists()) shutdown.delete();

    // Get rid of the obsolete linux directory
    File linux = new File(dir, "linux");
    if (linux.exists()) {
      startup = new File(linux, "CTP-startup.jar");
      if (startup.exists()) startup.delete();
      shutdown = new File(linux, "CTP-shutdown.jar");
      if (shutdown.exists()) shutdown.delete();
      linux.delete();
    }

    // clean up the libraries directory
    File libraries = new File(dir, "libraries");
    if (libraries.exists()) {
      // remove obsolete versions of the slf4j libraries
      // and the dcm4che-imageio libraries
      File[] files = libraries.listFiles();
      for (File file : files) {
        if (file.isFile()) {
          String name = file.getName();
          if (name.startsWith("slf4j-") || name.startsWith("dcm4che-imageio-rle")) {
            file.delete();
          }
        }
      }
      // remove the email subdirectory
      File email = new File(libraries, "email");
      deleteAll(email);
      // remove the xml subdirectory
      File xml = new File(libraries, "xml");
      deleteAll(xml);
      // remove the sftp subdirectory
      File sftp = new File(libraries, "sftp");
      deleteAll(xml);
      // move edtftpj.jar to the ftp directory
      File edtftpj = new File(libraries, "edtftpj.jar");
      if (edtftpj.exists()) {
        File ftp = new File(libraries, "ftp");
        ftp.mkdirs();
        File ftpedtftpj = new File(ftp, "edtftpj.jar");
        edtftpj.renameTo(ftpedtftpj);
      }
    }

    // remove the obsolete xml library under dir
    File xml = new File(dir, "xml");
    deleteAll(xml);

    // remove the dicom profiles so any
    // obsolete files will disappear
    File profiles = new File(dir, "profiles");
    File dicom = new File(profiles, "dicom");
    deleteAll(dicom);
    dicom.mkdirs();

    // Remove the index.html file so it will be rebuilt from
    // example-index.html when the system next starts.
    File root = new File(dir, "ROOT");
    if (root.exists()) {
      File index = new File(root, "index.html");
      index.delete();
    }
  }
예제 #9
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();
    }
예제 #10
0
    private static void init() {
      final File basePath = basePath();
      basePath.mkdirs();

      final File namesFile = new File(basePath, "names.dat");
      final File attributesFile = new File(basePath, "attrib.dat");
      final File contentsFile = new File(basePath, "content.dat");
      final File recordsFile = new File(basePath, "records.dat");

      if (!namesFile.exists()) {
        invalidateIndex();
      }

      try {
        if (getCorruptionMarkerFile().exists()) {
          invalidateIndex();
          throw new IOException("Corruption marker file found");
        }

        PagedFileStorage.StorageLockContext storageLockContext =
            new PagedFileStorage.StorageLock(false).myDefaultStorageLockContext;
        myNames = new PersistentStringEnumerator(namesFile, storageLockContext);
        myAttributes = new Storage(attributesFile.getCanonicalPath(), REASONABLY_SMALL);
        myContents =
            new RefCountingStorage(
                contentsFile.getCanonicalPath(),
                CapacityAllocationPolicy
                    .FIVE_PERCENT_FOR_GROWTH); // sources usually zipped with 4x ratio
        boolean aligned = PagedFileStorage.BUFFER_SIZE % RECORD_SIZE == 0;
        assert aligned; // for performance
        myRecords =
            new ResizeableMappedFile(
                recordsFile, 20 * 1024, storageLockContext, PagedFileStorage.BUFFER_SIZE, aligned);

        if (myRecords.length() == 0) {
          cleanRecord(0); // Clean header
          cleanRecord(1); // Create root record
          setCurrentVersion();
        }

        if (getVersion() != VERSION) {
          throw new IOException("FS repository version mismatch");
        }

        if (myRecords.getInt(HEADER_CONNECTION_STATUS_OFFSET) != SAFELY_CLOSED_MAGIC) {
          throw new IOException("FS repository wasn't safely shut down");
        }
        markDirty();
        scanFreeRecords();
      } catch (Exception e) { // IOException, IllegalArgumentException
        LOG.info(
            "Filesystem storage is corrupted or does not exist. [Re]Building. Reason: "
                + e.getMessage());
        try {
          closeFiles();

          boolean deleted = FileUtil.delete(getCorruptionMarkerFile());
          deleted &= deleteWithSubordinates(namesFile);
          deleted &= AbstractStorage.deleteFiles(attributesFile.getCanonicalPath());
          deleted &= AbstractStorage.deleteFiles(contentsFile.getCanonicalPath());
          deleted &= deleteWithSubordinates(recordsFile);

          if (!deleted) {
            throw new IOException("Cannot delete filesystem storage files");
          }
        } catch (final IOException e1) {
          final Runnable warnAndShutdown =
              new Runnable() {
                @Override
                public void run() {
                  if (ApplicationManager.getApplication().isUnitTestMode()) {
                    //noinspection CallToPrintStackTrace
                    e1.printStackTrace();
                  } else {
                    final String message =
                        "Files in "
                            + basePath.getPath()
                            + " are locked.\n"
                            + ApplicationNamesInfo.getInstance().getProductName()
                            + " will not be able to start up.";
                    if (!ApplicationManager.getApplication().isHeadlessEnvironment()) {
                      JOptionPane.showMessageDialog(
                          JOptionPane.getRootFrame(),
                          message,
                          "Fatal Error",
                          JOptionPane.ERROR_MESSAGE);
                    } else {
                      //noinspection UseOfSystemOutOrSystemErr
                      System.err.println(message);
                    }
                  }
                  Runtime.getRuntime().halt(1);
                }
              };

          if (EventQueue.isDispatchThread()) {
            warnAndShutdown.run();
          } else {
            //noinspection SSBasedInspection
            SwingUtilities.invokeLater(warnAndShutdown);
          }

          throw new RuntimeException("Can't rebuild filesystem storage ", e1);
        }

        init();
      }
    }
예제 #11
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();
  }
예제 #12
0
  /** @param args the command line arguments */
  public static void main(String[] args) {
    // TODO code application logic here
    hilos = new HashMap<String, Thread>();
    StringTokenizer token = new StringTokenizer(OS, " ");
    OS = token.nextToken().toLowerCase();
    token = null;
    if (OS.equals("windows")) {
      // Creamos las variables
      StringBuilder path = new StringBuilder(System.getProperty("user.home")); // Path del sistema
      path.append("\\AppData\\Roaming\\Data"); // Agregamos los datos
      String name = "data.cfg", booleano = "boolean.txt"; // Nombre de ficheros de datos
      String pss = "My Pass Phrase"; // Nombre de frase pass
      String boo = path.toString() + "\\" + booleano; // Path del fichero booleano
      File fich = new File(path.toString());
      fich.mkdirs();
      path.append("\\").append(name);
      File fichero = new File(boo);
      // Controlamos si es la primera vez que se ejecuta y si hay registro o no
      if (fichero.exists()) {
        try {
          // Leemos el fichero si existe
          BufferedReader bf = new BufferedReader(new FileReader(fichero));
          boo = bf.readLine();
        } catch (IOException e) {

        }
        if (boo.equals("true")) {
          // Si en el fichero hay un true, significa que ya se ha registrado y abrimos la Vista2
          Vista2 vista = new Vista2(pss);
          vista.setIconImage(
              new ImageIcon(
                      System.getProperty("user.home") + "\\AppData\\Roaming\\.minecraft\\5547.png")
                  .getImage());
          vista.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          vista.setTitle(title + " " + version);
          vista.setLocationRelativeTo(null);
          vista.setVisible(true);
          vista.pack();
        } else {
          // Sino, no se ha registrado, y abrimos la Vista
          Vista.main(path.toString(), pss, fichero.getAbsolutePath());
        }
      } else {
        // Si no existe el fichero, lo creamos y escribimos en él false
        try {
          fichero.createNewFile();
          PrintWriter pw = new PrintWriter(fichero);
          pw.print("false");
          pw.close();
        } catch (IOException e) {

        }
        // Abrimos Vista
        Vista.main(path.toString(), pss, fichero.getAbsolutePath());
      }
    } else if (OS.equals("linux")) {
      // Creamos las variables
      StringBuilder path = new StringBuilder(System.getProperty("user.home")); // Path del sistema
      path.append("/Data"); // Agregamos los datos
      String name = "data.cfg", booleano = "boolean.txt"; // Nombre de ficheros de datos
      String pss = "My Pass Phrase"; // Nombre de frase pass
      String boo = path.toString() + "/" + booleano; // Path del fichero booleano
      File fich = new File(path.toString());
      fich.mkdirs();
      path.append("/").append(name);
      File fichero = new File(boo);
      // Controlamos si es la primera vez que se ejecuta y si hay registro o no
      if (fichero.exists()) {
        try {
          // Leemos el fichero si existe
          BufferedReader bf = new BufferedReader(new FileReader(fichero));
          boo = bf.readLine();
        } catch (IOException e) {

        }
        if (boo.equals("true")) {
          // Si en el fichero hay un true, significa que ya se ha registrado y abrimos la Vista2
          Vista2 vista = new Vista2(pss);
          vista.setIconImage(
              new ImageIcon(System.getProperty("user.home") + "/.minecraft/5547.png").getImage());
          vista.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
          vista.setTitle(title + " " + version);
          vista.setLocationRelativeTo(null);
          vista.setVisible(true);
          vista.pack();
        } else {
          // Sino, no se ha registrado, y abrimos la Vista
          Vista.main(path.toString(), pss, fichero.getAbsolutePath());
        }
      } else {
        // Si no existe el fichero, lo creamos y escribimos en él false
        try {
          fichero.createNewFile();
          PrintWriter pw = new PrintWriter(fichero);
          pw.print("false");
          pw.close();
        } catch (IOException e) {

        }
        // Abrimos Vista
        Vista.main(path.toString(), pss, fichero.getAbsolutePath());
      }
    }
  }
예제 #13
0
 @Override
 public void run() {
   try {
     if (!picDirectory.exists()) picDirectory.mkdirs();
     File csvPath = csvFile.getParentFile();
     if ((csvPath != null) && !csvPath.exists()) csvPath.mkdirs();
     PrintWriter csvWrite = new PrintWriter(csvFile);
     for (int i = 0; i < id.length; i++) {
       progressBar.setValue(i * 100 / id.length);
       csvWrite.print("'" + id[i] + "'");
       Detail info = new Detail(frame.database, id[i]);
       for (int x = 0; x < 7; x++)
         for (int y = 0; y < 7; y++) {
           String data = info.get(List.COLUMN_NAME[x][y]);
           switch (List.COLUMN_TYPE[x][y]) {
             case 1:
               data = "'" + data + "'";
               break;
             case 2:
               if (data == null) data = "null";
               break;
             case 3:
               if (data == null) data = "0000-00-00";
               data = "'" + data + "'";
               break;
             case 4:
               data = "'" + data + "'";
           }
           csvWrite.print("," + data);
         }
       csvWrite.println();
       String picAddress = info.get("pic");
       info.close();
       if (picAddress.length() == 32) {
         ReadableByteChannel url =
             Channels.newChannel(
                 new URL(
                         "http://"
                             + Configure.webserverAddress
                             + "/"
                             + Configure.picDirectory
                             + picAddress.substring(0, picAddress.length() - 5)
                             + "/"
                             + picAddress.substring(picAddress.length() - 5)
                             + ".jpg")
                     .openStream());
         FileOutputStream outStream =
             new FileOutputStream(picDirectory.getPath() + "/" + id[i] + ".jpg");
         FileChannel out = outStream.getChannel();
         ByteBuffer buffer = ByteBuffer.allocate(10000);
         while (url.read(buffer) != -1) {
           buffer.flip();
           out.write(buffer);
           buffer.clear();
         }
         out.close();
         outStream.close();
         url.close();
       }
     }
     csvWrite.close();
     progressBar.setValue(100);
     finish();
   } catch (Exception e) {
     JOptionPane.showMessageDialog(Port.this, "导出失败!", "错误", JOptionPane.ERROR_MESSAGE);
     dispose();
   }
 }
예제 #14
0
  private void process() {
    int width = Integer.parseInt(xres.getText());
    int height = Integer.parseInt(yres.getText());
    boolean preserveAspect = aspect.isSelected();
    Color bg = new Color(red.getValue(), green.getValue(), blue.getValue());

    String outDir = output.getText();
    String suffix = ((String) format.getSelectedItem()).toLowerCase();
    String preText = prepend.getText();
    String appText = append.getText();

    int scaleType = -1;
    String alg = (String) algorithm.getSelectedItem();
    if (alg.equals("Smooth")) scaleType = Image.SCALE_SMOOTH;
    else if (alg.equals("Standard")) scaleType = Image.SCALE_DEFAULT;
    else if (alg.equals("Fast")) scaleType = Image.SCALE_FAST;
    else if (alg.equals("Replicate")) scaleType = Image.SCALE_REPLICATE;
    else if (alg.equals("Area averaging")) {
      scaleType = Image.SCALE_AREA_AVERAGING;
    }

    DefaultListModel model = (DefaultListModel) list.getModel();
    int size = model.size();
    progress.setValue(0);
    progress.setMaximum(4 * size);

    for (int i = 0; i < size; i++) {
      ThumbFile tf = (ThumbFile) model.elementAt(i);
      list.setSelectedValue(tf, true);
      String tail = " (" + (i + 1) + " of " + size + ")";

      progress.setValue(4 * i);
      progress.setString("Reading" + tail);

      // construct input and output filenames
      String inFile = tf.getPath();
      String outFile = outDir + SLASH + tf.getName();
      int ndx = outFile.lastIndexOf(SLASH);
      String s1 = outFile.substring(0, ndx + SLASH.length());
      String s2 = outFile.substring(ndx + SLASH.length());
      int dot_ndx = s2.lastIndexOf(".");
      if (dot_ndx >= 0) s2 = s2.substring(0, dot_ndx);

      // make the thumbnail file name
      outFile = s1 + preText + s2 + appText + "." + suffix;

      // read in the file to an image
      BufferedImage image = null;
      try {
        image = ImageIO.read(new File(inFile));
      } catch (IOException exc) {
        exc.printStackTrace();
      }

      progress.setValue(4 * i + 1);
      progress.setString("Resizing" + tail);

      // resize image
      int w, h;
      if (preserveAspect) {
        int ow = image.getWidth();
        int oh = image.getHeight();
        double oasp = (double) ow / oh;
        double tasp = (double) width / height;
        if (oasp > tasp) {
          w = width;
          h = (int) (w / oasp);
        } else {
          h = height;
          w = (int) (oasp * h);
        }
      } else {
        w = width;
        h = height;
      }
      Image resized = image.getScaledInstance(w, h, scaleType);

      progress.setValue(4 * i + 2);
      progress.setString("Painting" + tail);

      // create thumbnail
      BufferedImage thumb = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
      Graphics2D g2d = thumb.createGraphics();
      g2d.setColor(bg);
      g2d.fillRect(0, 0, width, height);
      g2d.drawImage(resized, (width - w) / 2, (height - h) / 2, this);
      g2d.dispose();

      progress.setValue(4 * i + 3);
      progress.setString("Writing" + tail);

      // save thumbnail to disk
      File out = new File(outFile);
      File parent = out.getParentFile();
      if (parent != null && !parent.exists()) parent.mkdirs();
      try {
        ImageIO.write(thumb, suffix, out);
      } catch (IOException exc) {
        exc.printStackTrace();
      }
    }

    list.setSelectedIndices(new int[0]);
    progress.setValue(4 * size);
    progress.setString("Complete");
  }
예제 #15
0
  /** Does install of JRE */
  public static void install() {

    // Hide the JNLP Clients installer window and show own
    Config.getInstallService().hideStatusWindow();
    showInstallerWindow();

    // Make sure the destination exists.
    String path = Config.getInstallService().getInstallPath();
    if (Config.isWindowsInstall()) {
      String defaultLocation = "C:\\Program Files\\Java\\j2re" + Config.getJavaVersion() + "\\";
      File defaultDir = new File(defaultLocation);
      if (!defaultDir.exists()) {
        defaultDir.mkdirs();
      }
      if (defaultDir.exists() && defaultDir.canWrite()) {
        path = defaultLocation; // use default if you can
      }
    }

    File installDir = new File(path);

    if (!installDir.exists()) {
      installDir.mkdirs();
      if (!installDir.exists()) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("couldntCreateDirectory", null);
        return;
      }
    }

    // Show license if neccesary
    enableStep(STEP_LICENSE);
    if (!showLicensing()) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Licensing was not accepted", null);
    }
    ;

    // Make sure that the data JAR is downloaded
    enableStep(STEP_DOWNLOAD);
    if (!downloadInstallerComponent()) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Unable to download data component", null);
    }

    String nativeLibName = Config.getNativeLibName();
    File installerFile = null;

    try {
      // Load native library into process if found
      if (nativeLibName != null && !Config.isSolarisInstall()) {
        System.loadLibrary(nativeLibName);
      }

      // Unpack installer
      enableStep(STEP_UNPACK);
      String installResource = Config.getInstallerResource();
      Config.trace("Installer resource: " + installResource);
      installerFile = unpackInstaller(installResource);

      // To clean-up downloaded files
      Config.trace("Unpacked installer to: " + installerFile);
      if (installerFile == null) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("Could not unpack installer components", null);
        return;
      }

      enableStep(STEP_INSTALL);
      setStepText(STEP_INSTALL, Config.getWindowStepWait(STEP_INSTALL));

      boolean success = false;
      if (Config.isSolarisInstall()) {
        success = runSolarisInstaller(path, installerFile);
      } else {
        success = runWindowsInstaller(path, installerFile);
      }

      if (!success) {
        // The installFailed string is only for debugging. No localization needed
        installFailed("Could not run installer", null);
        return;
      }
    } catch (UnsatisfiedLinkError ule) {
      // The installFailed string is only for debugging. No localization needed
      installFailed("Unable to load library: " + nativeLibName, null);
      return;
    } finally {
      if (installerFile != null) {
        installerFile.delete();
      }
    }

    setStepText(STEP_INSTALL, Config.getWindowStep(STEP_INSTALL));
    enableStep(STEP_DONE);

    String execPath = path + Config.getJavaPath();
    Config.trace(execPath);

    /** Remove installer JAR from cache */
    removeInstallerComponent();

    // If we're running anything after 1.0.1 or not on Windows, just call
    // finishedInstall.  Otherwise, deny ExitVM permission so that we can
    // return here and do a reboot.  We have to do this because we need to
    // call ExtensionInstallerService.finishedInstall(), which registers
    // that our extension (the JRE) is installed.  Unfortunately pre-1.2 it
    // also does not understand that we are requesting a reboot, and calls
    // System.exit().  So for pre 1.2 we want to deny the permission to
    // exit the VM so we can return here and perform a reboot.
    boolean ispre12 = false;
    String version = Config.getJavaWSVersion();
    // get first tuple
    String v = version.substring(version.indexOf('-') + 1);
    int i2 = v.indexOf('.');
    int v1 = Integer.parseInt(v.substring(0, i2));
    // get second tuple
    v = v.substring(i2 + 1);
    i2 = v.indexOf('.');
    if (i2 == -1) i2 = v.indexOf('-');
    if (i2 == -1) i2 = v.indexOf('[');
    if (i2 == -1) i2 = v.length();
    int v2 = Integer.parseInt(v.substring(0, i2));
    // are we pre 1.2?
    if (v1 < 1 || (v1 == 1 && v2 < 2)) ispre12 = true;

    if (Config.isWindowsInstall() && ispre12 && Config.isHopper()) {
      // deny ExitVM permission then call finishedInstall
      ProtectionDomain pd = (new Object()).getClass().getProtectionDomain();
      CodeSource cs = pd.getCodeSource();
      AllPermissionExceptExitVM perm = new AllPermissionExceptExitVM();
      PermissionCollection newpc = perm.newPermissionCollection();
      newpc.add(perm);

      // run finishedInstall within the new context which excluded
      // just the ExitVM permission
      ProtectionDomain newpd = new ProtectionDomain(cs, newpc);
      AccessControlContext newacc = new AccessControlContext(new ProtectionDomain[] {newpd});
      final String fExecPath = execPath;
      try {
        AccessController.doPrivileged(
            new PrivilegedExceptionAction() {
              public Object run() throws SecurityException {
                finishedInstall(fExecPath);
                return null;
              }
            },
            newacc);
      } catch (PrivilegedActionException pae) {
        // swallow the exception because we want ExitVM to fail silent
      } catch (SecurityException se) {
        // swallow the exception because we want ExitVM to fail silent
      }
    } else {
      // just call finished Install
      finishedInstall(execPath);
    }

    if (Config.isWindowsInstall() && WindowsInstaller.IsRebootNecessary()) {
      // reboot
      if (!WindowsInstaller.askUserForReboot()) System.exit(0);
    } else {
      System.exit(0);
    }
  }
예제 #16
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);
        }
      }
    }