private static int getBuildNumber(File installDirectory) {
    installDirectory = installDirectory.getAbsoluteFile();

    File buildTxt = new File(installDirectory, BUILD_NUMBER_FILE);
    if ((!buildTxt.exists()) || (buildTxt.isDirectory())) {
      buildTxt = new File(new File(installDirectory, BIN_FOLDER), BUILD_NUMBER_FILE);
    }

    if (buildTxt.exists() && !buildTxt.isDirectory()) {
      int buildNumber = -1;
      String buildNumberText = getContent(buildTxt);
      if (buildNumberText != null) {
        try {
          if (buildNumberText.length() > 1) {
            buildNumberText = buildNumberText.trim();
            buildNumber = Integer.parseInt(buildNumberText);
          }
        } catch (Exception e) {
          // OK
        }
      }
      return buildNumber;
    }

    return -1;
  }
Ejemplo n.º 2
0
 private void fixConfigSchema() {
   File configFile;
   File ctpDir = new File(directory, "CTP");
   if (ctpDir.exists()) configFile = new File(ctpDir, "config.xml");
   else configFile = new File(directory, "config.xml");
   if (configFile.exists()) {
     try {
       Document doc = getDocument(configFile);
       Element root = doc.getDocumentElement();
       Element server = getFirstNamedChild(root, "Server");
       moveAttributes(server, sslAttrs, "SSL");
       moveAttributes(server, proxyAttrs, "ProxyServer");
       moveAttributes(server, ldapAttrs, "LDAP");
       if (programName.equals("ISN")) fixRSNAROOT(server);
       if (isMIRC(root)) fixFileServiceAnonymizerID(root);
       setFileText(configFile, toString(doc));
     } catch (Exception ex) {
       cp.appendln(Color.red, "\nUnable to convert the config file schema.");
       cp.appendln(Color.black, "");
     }
   } else {
     cp.appendln(Color.red, "\nUnable to find the config file to check the schema.");
     cp.appendln(Color.black, "");
   }
 }
Ejemplo n.º 3
0
  public GalaxyViewer(Settings settings, boolean animatorFrame) throws Exception {
    super("Stars GalaxyViewer");
    this.settings = settings;
    this.animatorFrame = animatorFrame;
    if (settings.gameName.equals("")) throw new Exception("GameName not defined in settings.");
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    File dir = new File(settings.directory);
    File map = new File(dir, settings.getGameName() + ".MAP");
    if (map.exists() == false) {
      File f = new File(dir.getParentFile(), settings.getGameName() + ".MAP");
      if (f.exists()) map = f;
      else {
        String error = "Could not find " + map.getAbsolutePath() + "\n";
        error += "Export this file from Stars! (Only needs to be done one time pr game)";
        throw new Exception(error);
      }
    }
    Vector<File> mFiles = new Vector<File>();
    Vector<File> hFiles = new Vector<File>();
    for (File f : dir.listFiles()) {
      if (f.getName().toUpperCase().endsWith("MAP")) continue;
      if (f.getName().toUpperCase().endsWith("HST")) continue;
      if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".M")) mFiles.addElement(f);
      else if (f.getName().toUpperCase().startsWith(settings.getGameName() + ".H"))
        hFiles.addElement(f);
    }
    if (mFiles.size() == 0) throw new Exception("No M-files found matching game name.");
    if (hFiles.size() == 0) throw new Exception("No H-files found matching game name.");
    parseMapFile(map);
    Vector<File> files = new Vector<File>();
    files.addAll(mFiles);
    files.addAll(hFiles);
    p = new Parser(files);
    calculateColors();

    // UI:
    JPanel cp = (JPanel) getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(universe, BorderLayout.CENTER);
    JPanel south = createPanel(0, hw, new JLabel("Search: "), search, names, zoom, colorize);
    search.setPreferredSize(new Dimension(100, -1));
    cp.add(south, BorderLayout.SOUTH);
    hw.addActionListener(this);
    names.addActionListener(this);
    zoom.addChangeListener(this);
    search.addKeyListener(this);
    colorize.addActionListener(this);
    setSize(800, 600);
    Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
    setLocation((screen.width - getWidth()) / 2, (screen.height - getHeight()) / 2);
    setVisible(animatorFrame == false);
    if (animatorFrame) names.setSelected(false);
  }
Ejemplo n.º 4
0
  /**
   * A little method that checks the file path to see if it exists, and modifies it with the
   * imageSuffix if it doesn't have one specified by the user. Asks the user if it's OK to overwrite
   * if the file exists.
   *
   * @param filePath absolute file path to check.
   * @param imageSuffix suffix to append to filePath if it doesn't already have one. This word
   *     should not contain a starting '.'.
   * @return null if name is no good, a String to use if good.
   */
  protected String checkFileName(String filePath, String imageSuffix) {

    String fileName = filePath.substring(filePath.lastIndexOf(File.separator));
    String newFilePath;

    if (fileName.indexOf('.') == -1) {
      newFilePath = filePath + "." + imageSuffix;
    } else {
      // else leave it alone, user specified suffix
      newFilePath = filePath;
    }

    File file = new File(newFilePath);
    if (file.exists()) {
      // Check to see if it is alright to overwrite.
      int choice =
          JOptionPane.showConfirmDialog(
              null,
              "The file " + newFilePath + " exists, replace?",
              "Confirm File Replacement",
              JOptionPane.YES_NO_OPTION);
      if (choice != JOptionPane.YES_OPTION) {
        newFilePath = null;
      }
    }

    return newFilePath;
  }
Ejemplo n.º 5
0
  boolean doSaveNcml(String text, String filename) {
    if (debugNcmlWrite) {
      System.out.println("filename=" + filename);
      System.out.println("text=" + text);
    }

    File out = new File(filename);
    if (out.exists()) {
      int val =
          JOptionPane.showConfirmDialog(
              null,
              filename + " already exists. Do you want to overwrite?",
              "WARNING",
              JOptionPane.YES_NO_OPTION);
      if (val != JOptionPane.YES_OPTION) return false;
    }

    try {
      IO.writeToFile(text, out);
      JOptionPane.showMessageDialog(this, "File successfully written");
      return true;
    } catch (IOException ioe) {
      JOptionPane.showMessageDialog(this, "ERROR: " + ioe.getMessage());
      ioe.printStackTrace();
      return false;
    }
    // saveNcmlDialog.setVisible(false);
  }
  protected void getImages() {
    File directory = new File(this.saveDirectory);

    // BufferedImage img = null;

    images = new ArrayList<String>();
    if (directory.exists() && directory.isDirectory()) {
      // File[] files = directory.listFiles();
      String[] files = directory.list();

      for (int i = 0; i < files.length; i++) {
        // System.out.println(files[i]);
        // try {
        // if(files[i].getName().startsWith("cam"))
        if (files[i].startsWith("cam")) {
          // Windows spesific
          images.add(this.saveDirectory + "\\" + files[i]);
          /*
          img = ImageIO.read(files[i]);
          images.add(img);*/
        }
        // } catch (IOException e) {
        //	System.err.println("Failed on reading image. IOException.");
        // }
      }
    }

    System.out.println("Total image count = " + images.size());
    gotImages = true;
  }
Ejemplo n.º 7
0
  public CryoBay reconnectServer(ORB o, ReconnectThread rct) {

    BufferedReader reader;
    File file;
    ORB orb;
    org.omg.CORBA.Object obj;

    orb = o;

    obj = null;
    cryoB = null;

    try {
      // instantiate ModuleAccessor
      file = new File("/vnmr/acqqueue/cryoBay.CORBAref");
      if (file.exists()) {
        reader = new BufferedReader(new FileReader(file));
        obj = orb.string_to_object(reader.readLine());
      }

      if (obj != null) {
        cryoB = CryoBayHelper.narrow(obj);
      }

      if (cryoB != null) {
        if (!(cryoB._non_existent())) {
          // System.out.println("reconnected!!!!");
          rct.reconnected = true;
        }
      }
    } catch (Exception e) {
      // System.out.println("Got error: " + e);
    }
    return cryoB;
  }
  private static boolean validateOldConfigDir(
      @Nullable File installationHome,
      @Nullable File oldConfigDir,
      @NotNull ConfigImportSettings settings) {
    if (oldConfigDir == null) {
      if (installationHome != null) {
        JOptionPane.showMessageDialog(
            JOptionPane.getRootFrame(),
            ApplicationBundle.message(
                "error.invalid.installation.home",
                installationHome.getAbsolutePath(),
                settings.getProductName(ThreeState.YES)));
      }
      return false;
    }

    if (!oldConfigDir.exists()) {
      JOptionPane.showMessageDialog(
          JOptionPane.getRootFrame(),
          ApplicationBundle.message("error.no.settings.path", oldConfigDir.getAbsolutePath()),
          ApplicationBundle.message("title.settings.import.failed"),
          JOptionPane.WARNING_MESSAGE);
      return false;
    }
    return true;
  }
Ejemplo n.º 9
0
    public void actionPerformed(ActionEvent e) {
      if (readOnly) {
        return;
      }
      JFileChooser fc = getFileChooser();
      File currentDirectory = fc.getCurrentDirectory();

      if (!currentDirectory.exists()) {
        JOptionPane.showMessageDialog(
            fc,
            newFolderParentDoesntExistText,
            newFolderParentDoesntExistTitleText,
            JOptionPane.WARNING_MESSAGE);
        return;
      }

      File newFolder;
      try {
        newFolder = fc.getFileSystemView().createNewFolder(currentDirectory);
        if (fc.isMultiSelectionEnabled()) {
          fc.setSelectedFiles(new File[] {newFolder});
        } else {
          fc.setSelectedFile(newFolder);
        }
      } catch (IOException exc) {
        JOptionPane.showMessageDialog(
            fc,
            newFolderErrorText + newFolderErrorSeparator + exc,
            newFolderErrorText,
            JOptionPane.ERROR_MESSAGE);
        return;
      }

      fc.rescanCurrentDirectory();
    }
Ejemplo n.º 10
0
 private void saveBin() {
   fileChooser.resetChoosableFileFilters();
   fileChooser.addChoosableFileFilter(binFilter);
   fileChooser.setFileFilter(binFilter);
   if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
     try {
       File file = fileChooser.getSelectedFile();
       if (fileChooser.getFileFilter() == binFilter && !binFilter.accept(file)) {
         file = new File(file.getAbsolutePath() + binFilter.getExtensions()[0]);
       }
       if (file.exists()) {
         if (JOptionPane.showConfirmDialog(
                 frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION)
             != JOptionPane.YES_OPTION) {
           return;
         }
       }
       FileOutputStream output = new FileOutputStream(file);
       for (char i : binary) {
         output.write(i & 0xff);
         output.write((i >> 8) & 0xff);
       }
       output.close();
     } catch (IOException e1) {
       JOptionPane.showMessageDialog(
           frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE);
       e1.printStackTrace();
     }
   }
 }
Ejemplo n.º 11
0
 private void saveSrc() {
   fileChooser.resetChoosableFileFilters();
   fileChooser.addChoosableFileFilter(asmFilter);
   fileChooser.setFileFilter(asmFilter);
   if (fileChooser.showSaveDialog(frame) == JFileChooser.APPROVE_OPTION) {
     try {
       File file = fileChooser.getSelectedFile();
       if (fileChooser.getFileFilter() == asmFilter && !asmFilter.accept(file)) {
         file = new File(file.getAbsolutePath() + asmFilter.getExtensions()[0]);
       }
       if (file.exists()) {
         if (JOptionPane.showConfirmDialog(
                 frame, "File exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION)
             != JOptionPane.YES_OPTION) {
           return;
         }
       }
       PrintStream output = new PrintStream(file);
       output.print(sourceTextarea.getText());
       output.close();
     } catch (IOException e1) {
       JOptionPane.showMessageDialog(
           frame, "Unable to open file", "Error", JOptionPane.ERROR_MESSAGE);
       e1.printStackTrace();
     }
   }
 }
  public static boolean isInstallationHomeOrConfig(
      @NotNull final String installationHome, @NotNull final ConfigImportSettings settings) {
    if (new File(installationHome, OPTIONS_XML).exists()) return true;
    if (new File(installationHome, CONFIG_RELATED_PATH + OPTIONS_XML).exists()) return true;

    if (!new File(installationHome, BIN_FOLDER).exists()) {
      return false;
    }

    File libFolder = new File(installationHome, "lib");
    boolean quickTest = false;
    String[] mainJarNames = settings.getMainJarNames();
    for (String name : mainJarNames) {
      String mainJarName = StringUtil.toLowerCase(name) + ".jar";
      //noinspection HardCodedStringLiteral
      if (new File(libFolder, mainJarName).exists()) {
        quickTest = true;
        break;
      }
    }
    if (!quickTest) return false;

    File[] files = getLaunchFilesCandidates(new File(installationHome), settings);
    for (File file : files) {
      if (file.exists()) return true;
    }

    return false;
  }
Ejemplo n.º 13
0
  //    public static final String showElementTreeAction = "showElementTree";
  // -------------------------------------------------------------
  public void openFile(String currDirStr, String currFileStr) {

    if (fileDialog == null) {
      fileDialog = new FileDialog(this);
    }
    fileDialog.setMode(FileDialog.LOAD);
    if (!(currDirStr.equals(""))) {
      fileDialog.setDirectory(currDirStr);
    }
    if (!(currFileStr.equals(""))) {
      fileDialog.setFile(currFileStr);
    }
    fileDialog.show();

    String file = fileDialog.getFile(); // cancel pushed
    if (file == null) {
      return;
    }
    String directory = fileDialog.getDirectory();
    File f = new File(directory, file);
    if (f.exists()) {
      Document oldDoc = getEditor().getDocument();
      if (oldDoc != null)
        // oldDoc.removeUndoableEditListener(undoHandler);
        /*
          if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
          }
        */
        getEditor().setDocument(new PlainDocument());
      fileDialog.setTitle(file);
      Thread loader = new FileLoader(f, editor1.getDocument());
      loader.start();
    }
  }
Ejemplo n.º 14
0
  // Raises the Save As dialog to have the user identify the location to save groups of things.
  public File determineSaveLocation(String dialogTitle, String defaultFolderName) {
    String defaultPath = this.getFileChooser().getCurrentDirectory().getPath();
    if (!WWUtil.isEmpty(defaultPath)) defaultPath += File.separatorChar + defaultFolderName;

    File outFile;

    while (true) {
      this.getFileChooser().setDialogTitle(dialogTitle);
      this.getFileChooser().setSelectedFile(new File(defaultPath));
      this.getFileChooser().setMultiSelectionEnabled(false);
      this.getFileChooser().setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

      int status = this.getFileChooser().showSaveDialog(this.getFrame());
      if (status != JFileChooser.APPROVE_OPTION) return null;

      outFile = this.getFileChooser().getSelectedFile();
      if (outFile == null) {
        this.showMessageDialog("No location selected", "No Selection", JOptionPane.ERROR_MESSAGE);
        continue;
      }

      break;
    }

    if (!outFile.exists())
      //noinspection ResultOfMethodCallIgnored
      outFile.mkdir();

    return outFile;
  }
Ejemplo n.º 15
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());
 }
Ejemplo n.º 16
0
  /** Get the default folder */
  public File getDefaultFolder() {
    final File recentFolder = _folderTracker.getMostRecentFile();

    if (recentFolder != null && recentFolder.exists()) {
      if (_subfolderName != null) {
        final File defaultFolder = new File(recentFolder, _subfolderName);
        if (!defaultFolder.exists()) {
          defaultFolder.mkdir();
        }
        return defaultFolder;
      } else {
        return recentFolder;
      }
    }

    return null;
  }
Ejemplo n.º 17
0
    public static Settings init() throws Exception {
      File f = new File("galaxyviewer.ini");
      if (f.getAbsoluteFile().getParentFile().getName().equals("bin"))
        f = new File("..", "galaxyviewer.ini");
      Settings settings;
      if (f.exists()) {
        settings = new Settings();
        BufferedReader in = new BufferedReader(new FileReader(f));
        while (true) {
          String s = in.readLine();
          if (s == null) break;
          if (s.contains("=") == false) continue;
          String[] el = s.split("=", -1);
          if (el[0].equalsIgnoreCase("PlayerNr"))
            settings.playerNr = Integer.parseInt(el[1].trim()) - 1;
          if (el[0].equalsIgnoreCase("GameName")) settings.gameName = el[1].trim();
          if (el[0].equalsIgnoreCase("GameDir")) settings.directory = el[1].trim();
        }
        in.close();
      } else settings = new Settings();

      JTextField pNr = new JTextField("" + (settings.playerNr + 1));
      JTextField gName = new JTextField(settings.gameName);
      JTextField dir = new JTextField("" + settings.directory);

      JPanel p = new JPanel();
      p.setLayout(new GridLayout(3, 2));
      p.add(new JLabel("Player nr"));
      p.add(pNr);
      p.add(new JLabel("Game name"));
      p.add(gName);
      p.add(new JLabel("Game directory"));
      p.add(dir);
      gName.setToolTipText("Do not include file extensions");
      String[] el = {"Ok", "Cancel"};
      int ok =
          JOptionPane.showOptionDialog(
              null,
              p,
              "Choose settings",
              JOptionPane.OK_CANCEL_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              el,
              el[0]);
      if (ok != 0) System.exit(0);
      settings.playerNr = Integer.parseInt(pNr.getText().trim()) - 1;
      settings.directory = dir.getText().trim();
      settings.gameName = gName.getText().trim();
      BufferedWriter out = new BufferedWriter(new FileWriter(f));
      out.write("PlayerNr=" + (settings.playerNr + 1) + "\n");
      out.write("GameName=" + settings.gameName + "\n");
      out.write("GameDir=" + settings.directory + "\n");
      out.flush();
      out.close();
      return settings;
    }
Ejemplo n.º 18
0
 public static void main(String[] args) {
   boolean sender = false;
   File fi = null;
   try {
     if (args.length == 0) {
       int ret =
           JOptionPane.showConfirmDialog(
               null,
               "Are you the sender? (no = reciever)",
               "Send/Recieve",
               JOptionPane.YES_NO_OPTION);
       JFileChooser chooser = new JFileChooser();
       if (ret == JOptionPane.YES_OPTION) {
         chooser.showOpenDialog(null);
         sender = true;
       } else {
         chooser.showSaveDialog(null);
         sender = false;
       }
       fi = chooser.getSelectedFile();
     } else {
       if (args[0].equalsIgnoreCase("-s")) {
         sender = true;
       } else if (args[0].equalsIgnoreCase("-r")) {
         sender = false;
       }
       fi = new File(args[1]);
     }
   } catch (Exception e) {
     e.printStackTrace();
     exit();
   }
   if (sender && !fi.exists()) {
     System.err.println("Cannot send, file doesn't exist");
     exit();
   }
   try {
     if (sender) {
       ServerSocket ss = new ServerSocket(DEFAULT_PORT);
       Socket sck = ss.accept();
       byte[] hsh = SecureUtils.hash(fi);
       System.out.println(SecureUtils.hexify(hsh));
       sendFile(sck, fi, hsh);
       sck.close();
     } else {
       Socket sck = new Socket("localhost", DEFAULT_PORT);
       byte[] hsh = recvFile(sck, fi);
       System.out.println(SecureUtils.hexify(hsh));
       sck.close();
     }
   } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 19
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;
 }
Ejemplo n.º 20
0
 @Override
 public void run() {
   if (settingsFile != null && !isSavingSettings) {
     File file = new File(settingsFile);
     if (file.exists() && file.lastModified() > lastSettingsLoad) {
       log.info("Reloading updated settings file");
       initSettings(settingsFile);
       SoapUI.updateProxyFromSettings();
     }
   }
 }
Ejemplo n.º 21
0
  /** Returns false if Exception is thrown. */
  private boolean setDirectory() {
    String pathStr = dirTF.getText().trim();
    if (pathStr.equals("")) pathStr = System.getProperty("user.dir");
    try {
      File dirPath = new File(pathStr);
      if (!dirPath.isDirectory()) {
        if (!dirPath.exists()) {
          if (recursiveCheckBox.isSelected())
            throw new NotDirectoryException(dirPath.getAbsolutePath());
          else throw new NotFileException(dirPath.getAbsolutePath());
        } else {
          convertSet.setFile(dirPath);
          convertSet.setDestinationPath(dirPath.getParentFile());
        }
      } else {
        // Set the descriptors
        setMatchingFileNames();

        FlexFilter flexFilter = new FlexFilter();
        flexFilter.addDescriptors(descriptors);
        flexFilter.setFilesOnly(!recursiveCheckBox.isSelected());

        convertSet.setSourcePath(dirPath, flexFilter);
        convertSet.setDestinationPath(dirPath);
      }
    } catch (NotDirectoryException e1) {
      final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption1");

      MessageFormat formatter;
      String info_msg;
      if (pathStr.equals("")) {
        info_msg = ResourceHandler.getMessage("notdirectory_dialog.info5");
      } else {
        formatter = new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info0"));
        info_msg = formatter.format(new Object[] {pathStr});
      }
      final String info = info_msg;

      JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE);
      return false;
    } catch (NotFileException e2) {
      final String caption = ResourceHandler.getMessage("notdirectory_dialog.caption0");

      MessageFormat formatter =
          new MessageFormat(ResourceHandler.getMessage("notdirectory_dialog.info1"));
      final String info = formatter.format(new Object[] {pathStr});

      JOptionPane.showMessageDialog(this, info, caption, JOptionPane.ERROR_MESSAGE);
      return false;
    }

    return true; // no exception thrown
  }
Ejemplo n.º 22
0
 private static void invalidateIndex() {
   LOG.info("Marking VFS as corrupted");
   final File indexRoot = PathManager.getIndexRoot();
   if (indexRoot.exists()) {
     final String[] children = indexRoot.list();
     if (children != null && children.length > 0) {
       // create index corruption marker only if index directory exists and is non-empty
       // It is incorrect to consider non-existing indices "corrupted"
       FileUtil.createIfDoesntExist(new File(PathManager.getIndexRoot(), "corruption.marker"));
     }
   }
 }
    @Override
    public void actionPerformed(ActionEvent e) {
      if (fc == null) {
        fc = new IDEFileChooser();
        fc.setFileView(new IDEFileView());
        fc.setAcceptAllFileFilterUsed(false);
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fc.setMultiSelectionEnabled(false);
        fc.setDialogTitle(
            messagesBundle.getString("ImageViewerPanelSaveAction.Choose_filename_to_save_4"));

        //$NON-NLS-1$

        // prepare file filters
        IIORegistry theRegistry = IIORegistry.getDefaultInstance();
        Iterator it = theRegistry.getServiceProviders(ImageWriterSpi.class, false);
        while (it.hasNext()) {
          ImageWriterSpi writer = (ImageWriterSpi) it.next();
          if ((imageType == BufferedImage.TYPE_INT_ARGB
                  || imageType == BufferedImage.TYPE_INT_ARGB_PRE)
              && "JPEG".equals(writer.getFormatNames()[0].toUpperCase())) continue;
          ImageWriterSpiFileFilter ff = new ImageWriterSpiFileFilter(writer);
          fc.addChoosableFileFilter(ff);
        }
      }

      if (fc.showSaveDialog(viewerPanel) == JFileChooser.APPROVE_OPTION) {
        File selectedFile = fc.getSelectedFile();

        if (selectedFile != null) {
          String fileName = selectedFile.getAbsolutePath();
          ImageWriterSpiFileFilter ff = (ImageWriterSpiFileFilter) fc.getFileFilter();
          if (!ff.hasCorrectSuffix(fileName)) fileName = ff.addSuffix(fileName);
          selectedFile = new File(fileName);
          if (selectedFile.exists()) {
            String message =
                MessageFormat.format(
                    messagesBundle.getString("ImageViewerPanelSaveAction.Overwrite_question_5"),
                    //$NON-NLS-1$
                    fileName);
            if (JOptionPane.NO_OPTION
                == JOptionPane.showConfirmDialog(
                    viewerPanel,
                    message,
                    messagesBundle.getString("ImageViewerPanelSaveAction.Warning_6"),
                    //$NON-NLS-1$
                    JOptionPane.YES_NO_OPTION,
                    JOptionPane.WARNING_MESSAGE)) return;
          }
          writeToFile(selectedFile, ff);
        }
      }
    }
 private static List<String> readLinesFrom(File file) throws IOException {
   if (!file.exists()) file.createNewFile();
   ArrayList<String> result = new ArrayList<>();
   BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
   try {
     String line;
     while ((line = reader.readLine()) != null) result.add(line);
     return result;
   } finally {
     reader.close();
   }
 }
Ejemplo n.º 25
0
 private void adjustConfiguration(Element root, File dir) {
   // If this is an ISN installation and the Edge Server
   // keystore and truststore files do not exist, then set the configuration
   // to use the keystore.jks and truststore.jks files instead of the ones
   // in the default installation. If the Edge Server files do exist, then
   // delete the keystore.jks and truststore.jks files, just to avoid
   // confusion.
   if (programName.equals("ISN")) {
     Element server = getFirstNamedChild(root, "Server");
     Element ssl = getFirstNamedChild(server, "SSL");
     String rsnaroot = System.getenv("RSNA_ROOT");
     rsnaroot = (rsnaroot == null) ? "/usr/local/edgeserver" : rsnaroot.trim();
     String keystore = rsnaroot + "/conf/keystore.jks";
     String truststore = rsnaroot + "/conf/truststore.jks";
     File keystoreFile = new File(keystore);
     File truststoreFile = new File(truststore);
     cp.appendln(Color.black, "Looking for " + keystore);
     if (keystoreFile.exists() || truststoreFile.exists()) {
       cp.appendln(Color.black, "...found it [This is an EdgeServer installation]");
       // Delete the default files, just to avoid confusion
       File ks = new File(dir, "keystore.jks");
       File ts = new File(dir, "truststore.jks");
       boolean ksok = ks.delete();
       boolean tsok = ts.delete();
       if (ksok && tsok) cp.appendln(Color.black, "...Unused default SSL files were removed");
       else {
         if (!ksok) cp.appendln(Color.black, "...Unable to delete " + ks);
         if (!tsok) cp.appendln(Color.black, "...Unable to delete " + ts);
       }
     } else {
       cp.appendln(Color.black, "...not found [OK, this is a non-EdgeServer installation]");
       ssl.setAttribute("keystore", "keystore.jks");
       ssl.setAttribute("keystorePassword", "edge1234");
       ssl.setAttribute("truststore", "truststore.jks");
       ssl.setAttribute("truststorePassword", "edge1234");
       cp.appendln(
           Color.black, "...SSL attributes were updated for a non-EdgeServer installation");
     }
   }
 }
  @Nullable
  private static File findOldConfigDir(
      @NotNull File configDir, @Nullable String customPathSelector) {
    final File selectorDir = CONFIG_RELATED_PATH.isEmpty() ? configDir : configDir.getParentFile();
    final File parent = selectorDir.getParentFile();
    if (parent == null || !parent.exists()) {
      return null;
    }
    File maxFile = null;
    long lastModified = 0;
    final String selector =
        PathManager.getPathsSelector() != null
            ? PathManager.getPathsSelector()
            : selectorDir.getName();

    final String prefix = getPrefixFromSelector(selector);
    final String customPrefix =
        customPathSelector != null ? getPrefixFromSelector(customPathSelector) : null;
    for (File file :
        parent.listFiles(
            new FilenameFilter() {
              @Override
              public boolean accept(@NotNull File file, @NotNull String name) {
                return StringUtil.startsWithIgnoreCase(name, prefix)
                    || customPrefix != null && StringUtil.startsWithIgnoreCase(name, customPrefix);
              }
            })) {
      File options = new File(file, CONFIG_RELATED_PATH + OPTIONS_XML);
      if (!options.exists()) {
        continue;
      }

      long modified = options.lastModified();
      if (modified > lastModified) {
        lastModified = modified;
        maxFile = file;
      }
    }
    return maxFile != null ? new File(maxFile, CONFIG_RELATED_PATH) : null;
  }
Ejemplo n.º 27
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;
  }
Ejemplo n.º 28
0
  /**
   * Use a JFileChooser in Save mode to select files to open. Use a filter for FileFilter subclass
   * to select for "*.java" files. If a file is selected, then this file will be used as final
   * output
   */
  boolean saveFile() {
    File file = null;
    JFileChooser fc = new JFileChooser();

    // Start in current directory
    fc.setCurrentDirectory(new File("."));

    // Set filter for Java source files.
    fc.setFileFilter(fJavaFilter);

    // Set to a default name for save.
    fc.setSelectedFile(fFile);

    // Open chooser dialog
    int result = fc.showSaveDialog(this);

    if (result == JFileChooser.CANCEL_OPTION) {
      return true;
    } else if (result == JFileChooser.APPROVE_OPTION) {
      fFile = fc.getSelectedFile();
      String textFile = fFile.toString();
      if (fileNo.equalsIgnoreCase("SAVE")) {
        UpLoadFile.outputfile.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVE2")) {
        UpLoadMAGEMLFile.outputfile1.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVE3")) {
        UpLoadMAGEMLFile.outputfile2.setText(textFile);
      } else if (fileNo.equalsIgnoreCase("SAVEJPAG")) {
        JPEGFileName = textFile;
        // System.out.println ("JPG filename OpenFileDir= " +JPEGFileName);
        File fFile = new File(JPEGFileName);
        if (fFile.exists()) {
          int response =
              JOptionPane.showConfirmDialog(
                  null,
                  "Overwrite existing file " + JPEGFileName + " ??",
                  "Confirm Overwrite",
                  JOptionPane.OK_CANCEL_OPTION,
                  JOptionPane.QUESTION_MESSAGE);
          if (response == JOptionPane.CANCEL_OPTION) {
            /* go back to reload the file*/
            return false;
          }
        }
        SetUpPlotWindow.saveComponentAsJPEG(SetUpPlotWindow.content, JPEGFileName);
      }
      return true;

    } else {
      return false;
    }
  } // saveFile
Ejemplo n.º 29
0
 // 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;
 }
Ejemplo n.º 30
-1
  private void saveItem() {

    File f = new File("config.txt");

    if (f.exists() && !f.isDirectory()) {

      try (PrintWriter out =
          new PrintWriter(new BufferedWriter(new FileWriter("config.txt", true)))) {
        if (!searchName.getText().equals("") && !item.getText().equals("")) {

          out.println(
              searchName.getText()
                  + ","
                  + "http://www.reddit.com/r/hardwareswap/search?q="
                  + item.getText()
                  + "&sort=new&restrict_sr=on");
          addItem();

        } else {

          results.setText("Please provide all info for Search Name and Item");
        }

      } catch (IOException e1) {
        results.append("Error saving to file.");
      }

    } else {
      Main.checkFiles();
    }
  }