Esempio n. 1
0
 /**
  * Load image from resource path (using getResource). Note that GIFs are loaded as _translucent_
  * indexed images. Images are cached: loading an image with the same name twice will get the
  * cached image the second time. If you want to remove an image from the cache, use purgeImage.
  * Throws JGError when there was an error.
  */
 @SuppressWarnings({"deprecation", "unchecked"})
 public JGImage loadImage(String imgfile) {
   Image img = (Image) loadedimages.get(imgfile);
   if (img == null) {
     URL imgurl = getClass().getResource(imgfile);
     if (imgurl == null) {
       try {
         File imgf = new File(imgfile);
         if (imgf.canRead()) {
           imgurl = imgf.toURL();
         } else {
           imgurl = new URL(imgfile);
           // throw new JGameError(
           //	"File "+imgfile+" not found.",true);
         }
       } catch (MalformedURLException e) {
         // e.printStackTrace();
         throw new JGameError("File not found or malformed path or URL '" + imgfile + "'.", true);
       }
     }
     img = output_comp.getToolkit().createImage(imgurl);
     loadedimages.put(imgfile, img);
   }
   try {
     ensureLoaded(img);
   } catch (Exception e) {
     // e.printStackTrace();
     throw new JGameError("Error loading image " + imgfile);
   }
   return new JREImage(img);
 }
 private byte[] loadClassData(String className) throws IOException {
   Playground.println("Loading class " + className + ".class", warning);
   File f = new File(System.getProperty("user.dir") + "/" + className + ".class");
   byte[] b = new byte[(int) f.length()];
   new FileInputStream(f).read(b);
   return b;
 }
Esempio n. 3
0
 private String getCurrentShortFilename() {
   if (_srcBundlePath != null) {
     File f = new File(_srcBundlePath);
     return f.getName();
   }
   return "Untitled";
 }
Esempio 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();
    }
Esempio n. 5
0
 public void loadFile(String filename) {
   filename = FileManager.slashify(filename, false);
   setSrcBundle(filename + "/");
   File script = new File(filename);
   _editingFile = FileManager.getScriptFile(script, null, null);
   if (_editingFile != null) {
     editingType =
         _editingFile
             .getAbsolutePath()
             .substring(_editingFile.getAbsolutePath().lastIndexOf(".") + 1);
     initBeforeLoad(editingType);
     try {
       this.read(
           new BufferedReader(new InputStreamReader(new FileInputStream(_editingFile), "UTF8")),
           null);
     } catch (Exception ex) {
       _editingFile = null;
     }
   }
   if (_editingFile != null) {
     updateDocumentListeners();
     setDirty(false);
     _srcBundleTemp = false;
   } else {
     _srcBundlePath = null;
   }
 }
Esempio n. 6
0
 public String saveAsFile(boolean accessingAsFile) throws IOException {
   File file = new SikuliIDEFileChooser(SikuliIDE.getInstance(), accessingAsFile).save();
   if (file == null) {
     return null;
   }
   String bundlePath = FileManager.slashify(file.getAbsolutePath(), false);
   if (!file.getAbsolutePath().endsWith(".sikuli")) {
     bundlePath += ".sikuli";
   }
   if (FileManager.exists(bundlePath)) {
     int res =
         JOptionPane.showConfirmDialog(
             null,
             SikuliIDEI18N._I("msgFileExists", bundlePath),
             SikuliIDEI18N._I("dlgFileExists"),
             JOptionPane.YES_NO_OPTION);
     if (res != JOptionPane.YES_OPTION) {
       return null;
     }
   } else {
     FileManager.mkdir(bundlePath);
   }
   try {
     saveAsBundle(bundlePath, (SikuliIDE.getInstance().getCurrentFileTabTitle()));
     if (Settings.isMac()) {
       if (!Settings.handlesMacBundles) {
         makeBundle(bundlePath, accessingAsFile);
       }
     }
   } catch (IOException iOException) {
   }
   return getCurrentShortFilename();
 }
Esempio n. 7
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();
     }
   }
 }
Esempio n. 8
0
 public void secureDelete() {
   int rw = tblItems.getSelectedRow();
   if (rw == -1) {
     JOptionPane.showMessageDialog(frm, "No item selected", "Error", JOptionPane.ERROR_MESSAGE);
     return;
   }
   int idx = tblItems.convertRowIndexToModel(rw);
   if (JOptionPane.showConfirmDialog(
           frm,
           "Delete " + store.plainName(idx) + "?",
           "Confirm Delete",
           JOptionPane.YES_NO_OPTION)
       != JOptionPane.YES_OPTION) return;
   File del = store.delete(idx);
   store.fireTableDataChanged();
   if (del != null) {
     if (del.delete()) {
       // successful
       needsSave = true;
     } else {
       System.err.println("Delete " + del.getAbsolutePath() + " failed");
     }
   }
   updateStatus();
 }
Esempio n. 9
0
  // {{{ getPrintJob() method
  private static PrinterJob getPrintJob(String jobName) {
    job = PrinterJob.getPrinterJob();

    format = new HashPrintRequestAttributeSet();

    String settings = jEdit.getSettingsDirectory();
    if (settings != null) {
      String printSpecPath = MiscUtilities.constructPath(settings, "printspec");
      File filePrintSpec = new File(printSpecPath);

      if (filePrintSpec.exists()) {
        try {
          FileInputStream fileIn = new FileInputStream(filePrintSpec);
          ObjectInputStream obIn = new ObjectInputStream(fileIn);
          format = (HashPrintRequestAttributeSet) obIn.readObject();
        } catch (Exception e) {
          Log.log(Log.ERROR, BufferPrinter1_4.class, e);
        }
        // for backwards compatibility, the color variable is stored also as a property
        if (jEdit.getBooleanProperty("print.color")) format.add(Chromaticity.COLOR);
        else format.add(Chromaticity.MONOCHROME);

        // no need to always keep the same job name for every printout.
        format.add(new JobName(jobName, null));
      }
    }

    return job;
  } // }}}
Esempio 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();
     }
   }
 }
Esempio n. 11
0
  protected void initializeTexture(DrawContext dc) {
    Texture iconTexture = dc.getTextureCache().getTexture(this.getIconFilePath());
    if (iconTexture != null) return;

    try {
      InputStream iconStream = this.getClass().getResourceAsStream("/" + this.getIconFilePath());
      if (iconStream == null) {
        File iconFile = new File(this.iconFilePath);
        if (iconFile.exists()) {
          iconStream = new FileInputStream(iconFile);
        }
      }

      iconTexture = TextureIO.newTexture(iconStream, false, null);
      iconTexture.bind();
      this.iconWidth = iconTexture.getWidth();
      this.iconHeight = iconTexture.getHeight();
      dc.getTextureCache().put(this.getIconFilePath(), iconTexture);
    } catch (IOException e) {
      String msg = Logging.getMessage("layers.IOExceptionDuringInitialization");
      Logging.logger().severe(msg);
      throw new WWRuntimeException(msg, e);
    }

    GL gl = dc.getGL();
    gl.glTexParameteri(
        GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR); // _MIPMAP_LINEAR);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
    // Enable texture anisotropy, improves "tilted" world map quality.
    int[] maxAnisotropy = new int[1];
    gl.glGetIntegerv(GL.GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy, 0);
    gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy[0]);
  }
Esempio n. 12
0
 private static void getStudentPass(String facultyNumber)
     throws IOException, JAXBException, SAXException, TransformerException,
         ParserConfigurationException {
   if (Pattern.matches("\\d{5,6}", facultyNumber)) {
     InputStream inputStream = new FileInputStream(Constants.CONFIG_FILE_PATH.toString());
     properties.load(inputStream);
     File protocolFile = new File(properties.getProperty("protocol"));
     ReadWriteUtils utils = new ReadWriteUtils(Protocol.class);
     Protocol protocol = (Protocol) utils.readFromXml(protocolFile);
     StudentPass studentPass = protocol.getStudentPass(Integer.parseInt(facultyNumber));
     utils.setType(StudentPass.class);
     File outputFile =
         new File(properties.getProperty("output") + "\\StudentPass" + facultyNumber + ".xml");
     if (outputFile.createNewFile()) System.out.println("File created!");
     utils.writeXml(studentPass, outputFile);
     utils.writeXml(studentPass, System.out);
     System.out.println(
         "Do you want to open the generated XML Document with your default viewing program?");
     if (awaitResponse()) Desktop.getDesktop().open(outputFile);
     System.out.println(
         "Do you want to transform the generated XML Document to html file and open with your default viewing program?");
     if (awaitResponse()) {
       Desktop.getDesktop()
           .open(transformXML(outputFile, new File(Constants.STUDENT_STYLE.toString())));
     }
     inputStream.close();
   } else throw new IllegalArgumentException("Invalid faculty number is entered!");
 }
Esempio 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();
    }
  }
Esempio n. 14
0
  private void onTransferFileClicked() {

    if (transferingFile) return;

    int returnVal = fileChooser.showOpenDialog(this);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
      File file = fileChooser.getSelectedFile();

      showInfoMessage("Se selecciono el archivo " + file.getName());

      try {

        lineCount = getFileLineCount(file);

        fileReader = new FileReader(file);

        linesTransfered = 0;
        headerSent = false;
        lineCountSent = false;
        transferingFile = true;

        transmitMessage("$save");

      } catch (IOException e) {
        e.printStackTrace();
      }

    } else {
      showInfoMessage("Se cancelo la transferencia de archivo");
    }
  }
Esempio n. 15
0
 @Override
 public boolean importData(JComponent comp, Transferable t) {
   DataFlavor htmlFlavor = DataFlavor.stringFlavor;
   if (canImport(comp, t.getTransferDataFlavors())) {
     try {
       String transferString = (String) t.getTransferData(htmlFlavor);
       EditorPane targetTextPane = (EditorPane) comp;
       for (Map.Entry<String, String> entry : _copiedImgs.entrySet()) {
         String imgName = entry.getKey();
         String imgPath = entry.getValue();
         File destFile = targetTextPane.copyFileToBundle(imgPath);
         String newName = destFile.getName();
         if (!newName.equals(imgName)) {
           String ptnImgName = "\"" + imgName + "\"";
           newName = "\"" + newName + "\"";
           transferString = transferString.replaceAll(ptnImgName, newName);
           Debug.info(ptnImgName + " exists. Rename it to " + newName);
         }
       }
       targetTextPane.insertString(transferString);
     } catch (Exception e) {
       Debug.error(me + "importData: Problem pasting text\n%s", e.getMessage());
     }
     return true;
   }
   return false;
 }
Esempio n. 16
0
    @Override
    public void actionPerformed(ActionEvent e) {
      Frame frame = getFrame();
      JFileChooser chooser = new JFileChooser();
      int ret = chooser.showOpenDialog(frame);

      if (ret != JFileChooser.APPROVE_OPTION) {
        return;
      }

      File f = chooser.getSelectedFile();
      if (f.isFile() && f.canRead()) {
        Document oldDoc = getEditor().getDocument();
        if (oldDoc != null) {
          oldDoc.removeUndoableEditListener(undoHandler);
        }
        if (elementTreePanel != null) {
          elementTreePanel.setEditor(null);
        }
        getEditor().setDocument(new PlainDocument());
        frame.setTitle(f.getName());
        Thread loader = new FileLoader(f, editor.getDocument());
        loader.start();
      } else {
        JOptionPane.showMessageDialog(
            getFrame(),
            "Could not open file: " + f,
            "Error opening file",
            JOptionPane.ERROR_MESSAGE);
      }
    }
Esempio n. 17
0
  private void ListSubDirectorySizes(File file) {
    File[] files;
    files =
        file.listFiles(
            new FileFilter() {
              @Override
              public boolean accept(File file) {
                //                if (!file.isDirectory()){
                //                    return false;  //To change body of implemented methods use
                // File | Settings | File Templates.
                //                }else{
                //                    return true;
                //                }
                return true;
              }
            });
    Map<String, Long> dirListing = new HashMap<String, Long>();
    for (File dir : files) {
      DiskUsage diskUsage = new DiskUsage();
      diskUsage.accept(dir);
      //            long size = diskUsage.getSize() / (1024 * 1024);
      long size = diskUsage.getSize();
      dirListing.put(dir.getName(), size);
    }

    ValueComparator bvc = new ValueComparator(dirListing);
    TreeMap<String, Long> sorted_map = new TreeMap<String, Long>(bvc);
    sorted_map.putAll(dirListing);

    PrettyPrint(file, sorted_map);
  }
Esempio n. 18
0
 /**
  * The ActionListener implementation
  *
  * @param event the event.
  */
 public void actionPerformed(ActionEvent event) {
   String searchText = textField.getText().trim();
   if (searchText.equals("") && !saveAs.isSelected() && (fileLength > 10000000)) {
     textPane.setText("Blank search text is not allowed for large IdTables.");
   } else {
     File outputFile = null;
     if (saveAs.isSelected()) {
       outputFile = chooser.getSelectedFile();
       if (outputFile != null) {
         String name = outputFile.getName();
         int k = name.lastIndexOf(".");
         if (k != -1) name = name.substring(0, k);
         name += ".txt";
         File parent = outputFile.getAbsoluteFile().getParentFile();
         outputFile = new File(parent, name);
         chooser.setSelectedFile(outputFile);
       }
       if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) System.exit(0);
       outputFile = chooser.getSelectedFile();
     }
     textPane.setText("");
     Searcher searcher = new Searcher(searchText, event.getSource().equals(searchPHI), outputFile);
     searcher.start();
   }
 }
Esempio n. 19
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;
  }
Esempio n. 20
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, "");
   }
 }
Esempio n. 21
0
    protected void setData(String strChecksum) {
      String strValue = (String) m_cmbPath.getSelectedItem();
      if (strValue == null || strValue.equals("")) return;

      m_cmbChecksum.removeAllItems();

      String strPath = strValue.substring(strValue.lastIndexOf("/") + 1);
      strPath = UtilB.unixPathToWindows(FileUtil.SYS_VNMR + "/p11/checksums/" + strPath);
      strPath = FileUtil.openPath(strPath);
      if (strPath != null) {
        File file = new File(strPath);
        String[] files = file.list();
        int nSize = files.length;
        for (int i = 0; i < nSize; i++) {
          String strfile = files[i];
          m_cmbChecksum.addItem(strfile);
        }

        int nIndex = strChecksum.lastIndexOf("/");
        if (nIndex < 0) nIndex = strChecksum.lastIndexOf(File.separator);
        if (nIndex + 1 < strChecksum.length()) strChecksum = strChecksum.substring(nIndex + 1);

        m_cmbChecksum.setSelectedItem(strChecksum);
      }
    }
Esempio n. 22
0
  private final String findcachedir() {
    System.out.println("here@!");
    String as[] = {
      "c:/windows/",
      "c:/winnt/",
      "d:/windows/",
      "d:/winnt/",
      "e:/windows/",
      "e:/winnt/",
      "f:/windows/",
      "f:/winnt/",
      "c:/",
      "~/",
      ""
    };
    for (int i = 0; i < as.length; i++)
      try {
        String s = as[i];
        if (s.length() > 0) {
          File file = new File(s);
          if (!file.exists()) continue;
        }
        File file1 = new File(s + ".file_store_32");
        if (file1.exists() || file1.mkdir()) return s + ".file_store_32" + "/";
      } catch (Exception _ex) {
      }

    return null;
  }
Esempio n. 23
0
 public void loadMacros() {
   File f = new File(System.getProperty("user.dir"));
   String[] files = f.list();
   for (int i = 0; i < files.length; i++) {
     try {
       if (files[i].startsWith("macro_")
           && files[i].endsWith(".class")
           && files[i].indexOf('$') == -1) {
         System.out.println(files[i]);
         Class clazz = Class.forName(files[i].substring(0, files[i].length() - ".class".length()));
         Macro macro =
             (Macro)
                 clazz
                     .getConstructor(new Class[] {mudclient_Debug.class})
                     .newInstance(new Object[] {inner});
         String[] commands = macro.getCommands();
         for (int j = 0; j < commands.length; j++) {
           System.out.println("command registered:" + commands[j]);
           mudclient_Debug.macros.put(commands[j], macro);
         }
       }
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
 }
Esempio n. 24
0
  /**
   * Method to write the contents of the picture to a file with the passed name
   *
   * @param fileName the name of the file to write the picture to
   */
  public void writeOrFail(String fileName) throws IOException {
    String extension = this.extension; // the default is current

    // create the file object
    File file = new File(fileName);
    File fileLoc = file.getParentFile(); // directory name

    // if there is no parent directory use the current media dir
    if (fileLoc == null) {
      fileName = FileChooser.getMediaPath(fileName);
      file = new File(fileName);
      fileLoc = file.getParentFile();
    }

    // check that you can write to the directory
    if (!fileLoc.canWrite()) {
      throw new IOException(
          fileName + " could not be opened. Check to see if you can write to the directory.");
    }

    // get the extension
    int posDot = fileName.indexOf('.');
    if (posDot >= 0) extension = fileName.substring(posDot + 1);

    // write the contents of the buffered image to the file
    ImageIO.write(bufferedImage, extension, file);
  }
  public void actionPerformed(ActionEvent e) {

    // Handle open button action.
    if (e.getSource() == openButton) {
      int returnVal = fc.showOpenDialog(FileChooserDemo.this);

      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        // This is where a real application would open the file.
        log.append("Opening: " + file.getName() + "." + newline);
      } else {
        log.append("Open command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());

      // Handle save button action.
    } else if (e.getSource() == saveButton) {
      int returnVal = fc.showSaveDialog(FileChooserDemo.this);
      if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        // This is where a real application would save the file.
        log.append("Saving: " + file.getName() + "." + newline);
      } else {
        log.append("Save command cancelled by user." + newline);
      }
      log.setCaretPosition(log.getDocument().getLength());
    }
  }
Esempio n. 26
0
  public GraphicSet importSetFromFile(File inputFile, List<String> warnings)
      throws ImportException {
    Writer out = null;
    try {
      // Get a DOMImplementation
      DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation();
      // Create an instance of org.w3c.dom.Document
      Document document = domImpl.createDocument(null, "svg", null);
      // Create an instance of the SVG Generator
      final SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
      svgGenerator.setTransform(new AffineTransform());
      // Open input file
      PSInputFile in = new PSInputFile(inputFile.getAbsolutePath());
      Rectangle2D bb = this.getBoundingBox(inputFile);
      svgGenerator.setTransform(AffineTransform.getTranslateInstance(-bb.getX(), -bb.getY()));
      Dimension d = new Dimension((int) bb.getWidth(), (int) bb.getHeight());
      // Create processor and associate to input and output file
      Processor processor = new Processor(svgGenerator, d, false);
      processor.setData(in);

      // Process
      processor.process();
      File tmp = File.createTempFile("temp", "svg");
      tmp.deleteOnExit();
      svgGenerator.stream(new FileWriter(tmp));
      GraphicSet result = new SVGImporter().importSetFromFile(tmp, warnings);
      // Assume the EPS has been created with 72DPI (from Inkscape)
      double px2mm = Util.inch2mm(1d / 72d);
      result.setBasicTransform(AffineTransform.getScaleInstance(px2mm, px2mm));
      return result;
    } catch (Exception ex) {
      Logger.getLogger(EPSImporter.class.getName()).log(Level.SEVERE, null, ex);
      throw new ImportException(ex);
    }
  }
  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;
  }
  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;
  }
Esempio n. 29
0
 private void listFilesForFolder(final File folder) {
   for (final File fileEntry : folder.listFiles()) {
     if (fileEntry.isDirectory()) {
       listFilesForFolder(fileEntry);
     } else {
       Image img = new Image(fileEntry.toURI().toString());
       imgMan.images.add(
           new ImageInformation(
               img,
               fileEntry.toURI().toString(),
               new ImageInformation.Type[] {
                 ImageInformation.Type.SAND, ImageInformation.Type.FISH,
                 ImageInformation.Type.ALGA, ImageInformation.Type.CORAL,
                 ImageInformation.Type.SAND
               },
               new Point[] {
                 new Point((int) (img.getWidth() * 0.25), (int) (img.getHeight() * 0.25)),
                 new Point((int) (img.getWidth() * 0.75), (int) (img.getHeight() * 0.25)),
                 new Point((int) (img.getWidth() * 0.5), (int) (img.getHeight() * 0.5)),
                 new Point((int) (img.getWidth() * 0.25), (int) (img.getHeight() * 0.75)),
                 new Point((int) (img.getWidth() * 0.75), (int) (img.getHeight() * 0.75))
               },
               new double[] {0.86, 0.76, 0.99, 0.65, 0.54}));
     }
   }
 }
Esempio 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();
    }
  }