Exemplo n.º 1
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, "");
   }
 }
  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;
  }
Exemplo n.º 3
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;
  }
Exemplo n.º 4
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();
    }
Exemplo n.º 5
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;
  }
Exemplo n.º 6
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();
    }
  }
Exemplo n.º 7
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());
 }
Exemplo n.º 8
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;
  }
Exemplo n.º 9
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;
 }
Exemplo n.º 10
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
  }
    @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);
        }
      }
    }
Exemplo n.º 12
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");
     }
   }
 }
Exemplo n.º 13
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
Exemplo n.º 14
0
  protected String nextNewFilename(String fname) {
    String newName = fname;
    File f;
    try {
      do {
        newName = nextFilename(newName);
        f = new File(newName);
      } while (f.exists());
    } catch (SecurityException e) {
    }

    return newName;
  }
Exemplo n.º 15
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;
 }
  private boolean _assignValues(File fle) {
    String strMethod = "_assignValues(fle)";

    if (fle == null) {
      MySystem.s_printOutError(this, strMethod, "nil fle");
      return false;
    }

    if (!fle.exists()) {
      MySystem.s_printOutWarning(
          this, strMethod, "! fle.exists(), fle.getAbsolutePath()=" + fle.getAbsolutePath());

      String strBody = fle.getAbsolutePath();
      strBody += ":\nDirectory not found.";

      OPAbstract.s_showDialogWarning(super._frmParent_, strBody);

      return true;
    }

    if (!fle.isDirectory()) // statement should never be reached!!!
    {
      MySystem.s_printOutWarning(
          this, strMethod, "! fle.isDirectory(), fle.getAbsolutePath()=" + fle.getAbsolutePath());

      String strBody = fle.getAbsolutePath();
      strBody += ":\n  not a directory.";

      OPAbstract.s_showDialogWarning(super._frmParent_, strBody);

      return true;
    }

    if (super._tfdCurSelection_ == null) {
      MySystem.s_printOutError(this, strMethod, "nil super._tfdCurSelection_");
      return false;
    }

    super._tfdCurSelection_.setText(fle.getAbsolutePath());
    super._setSelectedValue_(true);

    if (!_enableButtonsSelectionDone_()) {
      MySystem.s_printOutError(this, strMethod, "failed");
      return false;
    }

    // --
    // ending
    return true;
  }
Exemplo n.º 17
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;
 }
Exemplo n.º 18
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();
 }
Exemplo n.º 19
0
 public File copyFileToBundle(String filename) {
   File f = new File(filename);
   String bundlePath = getSrcBundle();
   if (f.exists()) {
     try {
       File newFile = FileManager.smartCopy(filename, bundlePath);
       return newFile;
     } catch (IOException e) {
       Debug.error(
           me + "copyFileToBundle: Problem while trying to save %s\n%s", filename, e.getMessage());
       return f;
     }
   }
   return null;
 }
Exemplo n.º 20
0
 private void loadCursors() {
   Toolkit toolkit = Toolkit.getDefaultToolkit();
   String path = Prefs.getImageJDir() + "images/crosshair-cursor.gif";
   File f = new File(path);
   if (!f.exists()) return;
   // Image image = toolkit.getImage(path);
   ImageIcon icon = new ImageIcon(path);
   Image image = icon.getImage();
   if (image == null) return;
   int width = icon.getIconWidth();
   int height = icon.getIconHeight();
   Point hotSpot = new Point(width / 2, height / 2);
   Cursor crosshairCursor = toolkit.createCustomCursor(image, hotSpot, "crosshair-cursor.gif");
   ImageCanvas.setCursor(crosshairCursor, 0);
 }
Exemplo n.º 21
0
 public static boolean deleteAll(File file) {
   boolean b = true;
   if ((file != null) && file.exists()) {
     if (file.isDirectory()) {
       try {
         File[] files = file.listFiles();
         for (File f : files) b &= deleteAll(f);
       } catch (Exception e) {
         return false;
       }
     }
     b &= file.delete();
   }
   return b;
 }
Exemplo n.º 22
0
  private void updateLinuxServiceInstaller() {
    try {
      File dir = new File(directory, "CTP");
      if (suppressFirstPathElement) dir = dir.getParentFile();
      Properties props = new Properties();
      String ctpHome = dir.getAbsolutePath();
      cp.appendln(Color.black, "...CTP_HOME: " + ctpHome);
      ctpHome = ctpHome.replaceAll("\\\\", "\\\\\\\\");
      props.put("CTP_HOME", ctpHome);
      File javaHome = new File(System.getProperty("java.home"));
      String javaBin = (new File(javaHome, "bin")).getAbsolutePath();
      cp.appendln(Color.black, "...JAVA_BIN: " + javaBin);
      javaBin = javaBin.replaceAll("\\\\", "\\\\\\\\");
      props.put("JAVA_BIN", javaBin);

      File linux = new File(dir, "linux");
      File install = new File(linux, "ctpService-ubuntu.sh");
      cp.appendln(Color.black, "Linux service installer:");
      cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
      String bat = getFileText(install);
      bat = replace(bat, props); // do the substitutions
      bat = bat.replace("\r", "");
      setFileText(install, bat);

      // If this is an ISN installation, put the script in the correct place.
      String osName = System.getProperty("os.name").toLowerCase();
      if (programName.equals("ISN") && !osName.contains("windows")) {
        install = new File(linux, "ctpService-red.sh");
        cp.appendln(Color.black, "ISN service installer:");
        cp.appendln(Color.black, "...file: " + install.getAbsolutePath());
        bat = getFileText(install);
        bat = replace(bat, props); // do the substitutions
        bat = bat.replace("\r", "");
        File initDir = new File("/etc/init.d");
        File initFile = new File(initDir, "ctpService");
        if (initDir.exists()) {
          setOwnership(initDir, "edge", "edge");
          setFileText(initFile, bat);
          initFile.setReadable(true, false); // everybody can read //Java 1.6
          initFile.setWritable(true); // only the owner can write //Java 1.6
          initFile.setExecutable(true, false); // everybody can execute //Java 1.6
        }
      }
    } catch (Exception ex) {
      ex.printStackTrace();
      System.err.println("Unable to update the Linux service ctpService.sh file");
    }
  }
Exemplo n.º 23
0
  public JFileChooser createFileChooser() {
    // create a filechooser
    JFileChooser fc = new JFileChooser();
    if (getSwingSet2() != null && getSwingSet2().isDragEnabled()) {
      fc.setDragEnabled(true);
    }

    // set the current directory to be the images directory
    File swingFile = new File("resources/images/About.jpg");
    if (swingFile.exists()) {
      fc.setCurrentDirectory(swingFile);
      fc.setSelectedFile(swingFile);
    }

    return fc;
  }
Exemplo n.º 24
0
  // Constructor
  public Ballot(int index, int ID, int numCandidates, String title, ArrayList<String> candidates)
      throws IOException {
    _index = index;
    _ID = ID;
    _numCandidates = numCandidates;
    _votes = new int[_numCandidates];
    _title = title;
    _candidates = candidates;
    _usrVotes = new String[numCandidates];

    // if the ballot file already exists, read in the votes for that ballot
    // otherwise the number of votes for each candidate will default to 0
    file = new File(_ID + ".txt");
    if (file.exists()) {
      Scanner reader = new Scanner(file);
      int i = 0;
      while (reader.hasNextLine()) {
        String strLine = reader.nextLine();
        String arrLine[] = strLine.split(":");
        int vote = Integer.parseInt(arrLine[1]);
        _votes[i] = vote;

        i++;
      }
      reader.close();
    }

    _ballotPanel = new JPanel();
    _ballotPanel.setLayout(new GridLayout(_candidates.size() + 1, 1));

    _titleLabel = new JLabel(_title);
    _titleLabel.setHorizontalAlignment(JLabel.CENTER);
    _titleLabel.setFont(new Font("CourierNew", Font.PLAIN, 15));
    _ballotPanel.add(_titleLabel);

    for (int i = 0; i < _candidates.size(); i++) {
      // Make a JButton for each candidate in the ballot
      // Disable it by default. Will enable when the user logs in
      String cText = _candidates.get(i);
      JButton candidate = new JButton(cText);
      candidate.setEnabled(false);
      candidate.addActionListener(_buttonListener);

      _candidateButtons.add(candidate);
      _ballotPanel.add(candidate);
    }
  }
Exemplo n.º 25
0
  String[] scanDataFolderForFilesByType(String[] extensions) {
    ArrayList files = new ArrayList();
    File dataFolder = editor.getSketch().getDataFolder();

    if (!dataFolder.exists()) return null; // TODO no folder present .. warn?

    for (String ext : extensions) {
      String[] found = listFiles(dataFolder, true, ext);
      if (found == null || found.length == 0) continue;

      for (String f : found) {
        if (files.indexOf(f) == -1) files.add(f);
      }
    }

    return (String[]) files.toArray(new String[0]);
  }
Exemplo n.º 26
0
 public void save(String s, File f) {
   try {
     int saveNumber = 1;
     File file = new File(f.getAbsolutePath() + "/save.adv");
     while (file.exists()) {
       file = new File(f.getAbsolutePath() + "/save" + saveNumber + ".adv");
       saveNumber++;
     }
     file.createNewFile();
     FileWriter fWriter = new FileWriter(file.getAbsoluteFile());
     BufferedWriter bWriter = new BufferedWriter(fWriter);
     bWriter.write(s);
     bWriter.close();
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 27
0
 private void load() {
   File file = new File(filename);
   if (file.exists()) {
     try {
       Document doc = XmlUtil.getDocument(file);
       Element root = doc.getDocumentElement();
       Node child = root.getFirstChild();
       while (child != null) {
         if (child.getNodeType() == Node.ELEMENT_NODE) {
           Profile p = new Profile((Element) child);
           table.put(p.name, p);
         }
         child = child.getNextSibling();
       }
     } catch (Exception ignore) {
     }
   }
 }
Exemplo n.º 28
0
 // Get the installer program file by looking in the user.dir for [programName]-installer.jar.
 private File getInstallerProgramFile() {
   System.out.println("Looking for the installer program file");
   File programFile;
   try {
     programFile =
         new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
   } catch (Exception ex) {
     String name = getProgramName();
     programFile = new File(name + "-installer.jar");
   }
   programFile = new File(programFile.getAbsolutePath());
   if (programFile.exists()) System.out.println("...found " + programFile);
   else {
     System.err.println("...unable to find the program file " + programFile + "\n...exiting.");
     exit();
   }
   return programFile;
 }
Exemplo n.º 29
0
  private void browseAction() {
    if (selectedPath == null) {
      selectedPath = System.getenv("ROPE_SOURCES_DIR");
      if (selectedPath != null) {
        File dir = new File(selectedPath);
        if (!dir.exists() || !dir.isDirectory()) {
          String message =
              String.format(
                  "The sources path set in environment variable ROPE_SOURCES_DIR is not avaliable.\n%s",
                  selectedPath);
          JOptionPane.showMessageDialog(null, message, "ROPE", JOptionPane.WARNING_MESSAGE);
          selectedPath = null;
        } else {
          System.out.println("Source folder path set from ROPE_SOURCES_DIR: " + selectedPath);
        }
      }
      if (selectedPath == null) {
        selectedPath = System.getProperty("user.dir");

        System.out.println("Source folder path set to current directory: " + selectedPath);
      }
    }

    Vector<RopeFileFilter> filters = new Vector<RopeFileFilter>();
    filters.add(
        new RopeFileFilter(
            new String[] {".a", ".asm", ".aut", ".s"}, "Assembly files (*.a *.asm *.aut *.s)"));
    filters.add(new RopeFileFilter(new String[] {".m", ".mac"}, "Macro files (*.m *.mac)"));
    filters.add(new RopeFileFilter(new String[] {".lst"}, "List files (*.lst)"));
    filters.add(new RopeFileFilter(new String[] {".txt"}, "Text files (*.txt)"));

    RopeFileChooser chooser = new RopeFileChooser(selectedPath, null, filters);
    chooser.setDialogTitle("Source document selection");
    chooser.setFileFilter(filters.firstElement());
    chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);

    File file = chooser.open(this, fileText);
    if (file != null) {
      if (loadSourceFile(file)) {
        mainFrame.showExecWindow(baseName);
      }
    }
  }
Exemplo 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();
    }
  }