Ejemplo n.º 1
0
  /**
   * Opens a file. If the file can be opened, get a drawing time estimate, update recent files list,
   * and repaint the preview tab.
   *
   * @param filename what file to open
   */
  public void LoadGCode(String filename) {
    CloseFile();

    try {
      Scanner scanner = new Scanner(new FileInputStream(filename));
      linesTotal = 0;
      gcode = new ArrayList<String>();
      try {
        while (scanner.hasNextLine()) {
          gcode.add(scanner.nextLine());
          ++linesTotal;
        }
      } finally {
        scanner.close();
      }
    } catch (IOException e) {
      Log("<span style='color:red'>File could not be opened.</span>\n");
      RemoveRecentFile(filename);
      return;
    }

    previewPane.setGCode(gcode);
    fileOpened = true;

    EstimateDrawTime();
    UpdateRecentFiles(filename);
    Halt();
  }
Ejemplo n.º 2
0
  public static void main(String[] args) throws IOException {

    // First reads in the lines from the .txt file.  The first and second lines determine the start
    // and ending point of the maze.
    // The rest of the lines give the locations of the corners of each convex polygon in the maze.

    //        Example map input:
    //        1, 3
    //        34, 19
    //        0, 14; 6, 19; 9, 15; 7, 8; 1, 9
    //        2, 6; 17, 6; 17, 1; 2, 1
    //        12, 15; 14, 8; 10, 8
    //        14, 19; 18, 20; 20, 17; 14, 13
    //        18, 10; 23, 6; 19, 3
    //        22, 19; 28, 19; 28, 9; 22, 9
    //        25, 6; 29, 8; 31, 6; 31, 2; 28, 1; 25, 2
    //        31, 19; 34, 16; 32, 8; 29, 17

    // Open specified text file
    List<String> list = new ArrayList<String>();
    File library = new File(args[0]);
    Scanner sc = new Scanner(library);

    // Reads in every line of the text file
    // creates a new String for every line, then adds it to an arraylist
    while (sc.hasNextLine()) {
      String line;
      line = sc.nextLine();
      list.add(line);
    }

    // Takes the first and second lines as the start and goal points
    int count = 0;

    sPoint = list.get(0);
    ePoint = list.get(1);

    sPoint = sPoint.replace(" ", "");
    ePoint = ePoint.replace(" ", "");

    // remove the first line from the polygon list
    list.remove(0);

    // Create a 2 element array for the start point
    String[] Starter = sPoint.split(",");
    String[] Ender = ePoint.split(",");
    Startx = Double.parseDouble(Starter[0]);
    Starty = Double.parseDouble(Starter[1]);

    Polygon[] FinalPolygons = ListPolygons(list);

    // Text Graph of the polygon maze and the Start/End points
    graph(FinalPolygons);

    // A* search algorithm is performed to find the shortest path
    AStarSearch(FinalPolygons);
  }
Ejemplo n.º 3
0
 public void readFile(String name) { // reads the file and puts everything in the stats list
   Scanner inFile = null;
   stats = new ArrayList<String>();
   chars = new ArrayList<String>();
   powerUps = new ArrayList<String>();
   try {
     inFile = new Scanner(new BufferedReader(new FileReader(name + ".txt")));
     while (inFile.hasNextLine()) {
       stats.add(inFile.nextLine());
     }
   } catch (IOException ex) {
     System.out.println("Did you forget to make the" + name + ".txt file?");
   }
 }
Ejemplo n.º 4
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);
    }
  }
 @Override
 public StringBuilder doInBackground() throws IOException, InterruptedException {
   int lineNumber = 0;
   try (Scanner in = new Scanner(new FileInputStream(file))) {
     while (in.hasNextLine()) {
       String line = in.nextLine();
       lineNumber++;
       text.append(line);
       text.append("\n");
       ProgressData data = new ProgressData();
       data.number = lineNumber;
       data.line = line;
       publish(data);
       Thread.sleep(1); // to test cancellation; no need to do this
       // in your programs
     }
   }
   return text;
 }
Ejemplo n.º 6
0
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
Ejemplo n.º 7
0
  public Ssys3() {
    store = new Storage();
    tableSorter = new TableRowSorter<Storage>(store);
    jobs = new LinkedList<String>();

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

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

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

          public void windowDeactivated(WindowEvent evt) {}

          public void windowDeiconified(WindowEvent evt) {}

          public void windowIconified(WindowEvent evt) {}

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

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

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

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

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

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

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

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

    updateStatus();
    txaSearch.grabFocus();
  }
Ejemplo n.º 8
0
 public void secureImport() {
   JFileChooser imp = new JFileChooser();
   imp.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
   imp.setMultiSelectionEnabled(true);
   int ret = imp.showOpenDialog(frm);
   if (ret != JFileChooser.APPROVE_OPTION) {
     return;
   }
   File[] fis = imp.getSelectedFiles();
   ArrayList<String> impJobs = new ArrayList<String>();
   boolean dirs = false;
   for (File fi : fis) {
     if (fi.isDirectory()) {
       dirs = true;
       File lib = new File(fi, LIBRARY_NAME);
       if (lib.exists()) {
         try {
           Scanner sca = new Scanner(lib);
           while (sca.hasNextLine()) {
             String nm = sca.nextLine();
             String date = sca.nextLine();
             String tags = sca.nextLine();
             File addr = new File(fi, nm);
             if (addr.exists() && !addr.isDirectory()) impJobs.add(impJob(addr, date, tags));
           }
           sca.close();
         } catch (IOException exc) {
           // add nothing?
         }
       } else {
         for (File cont : fi.listFiles())
           if (!cont.isDirectory()) impJobs.add(impJob(cont, null, null));
       }
     } else {
       impJobs.add(impJob(fi, null, null));
     }
   }
   if (impJobs.size() > 1 || dirs) { // dont bother user if selected single file
     String shw = "Importing:";
     if (impJobs.size() > 30) shw = null;
     int pcount = 0;
     for (String jb : impJobs) {
       String[] prts = jb.split(",", 4); // import jobs have 4 parts, import, name, date, tags
       if (shw != null) shw = shw + "\n  - " + new File(prts[1]).getName();
       if (!prts[3].equalsIgnoreCase(Storage.NEW_TAG)) {
         pcount++;
         if (shw != null) shw = shw + " []";
       }
     }
     if (shw == null) shw = "importing ";
     else shw = shw + "\n";
     shw = shw + impJobs.size() + "(" + pcount + ") files";
     if (JOptionPane.showConfirmDialog(frm, shw, "Confirm Import", JOptionPane.YES_NO_OPTION)
         != JOptionPane.YES_OPTION) return;
   }
   synchronized (jobs) {
     for (String j : impJobs) {
       if (priorityExport) jobs.addLast(j);
       else jobs.addFirst(j);
     }
   }
   updateStatus();
 }
Ejemplo n.º 9
0
  @Override
  public void actionPerformed(ActionEvent action) {
    // Get the file the user wants to use and store it.
    if (action.getSource() == chooseFile) {
      // *sigh* I spent like 10 minutes trying to figure out why my if statement was not working
      // and then I found a semicolon on the end...noob mistake...
      // I had written a paragraph about it to send you too.
      if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
        try {
          System.out.println(
              "File: "
                  + fileChooser.getSelectedFile()
                  + "\nInt: "
                  + fileChooser.showOpenDialog(this));
          file = fileChooser.getSelectedFile();
          inputFile = new Scanner(file);
          if (JOptionPane.showConfirmDialog(
                  this,
                  "Overwrite orginal file?",
                  "Overwrite Confimration",
                  JOptionPane.YES_NO_OPTION)
              == JOptionPane.YES_OPTION) {
            outputFile = new PrintWriter(file);
          } else {
            fileChooser.showOpenDialog(this);
            outputFile = new PrintWriter(fileChooser.getSelectedFile());
          }
          // Enable the buttons now that a file has been chosen.
          sort.setEnabled(true);
          next.setEnabled(true);
        } catch (FileNotFoundException exception) {
          JOptionPane.showMessageDialog(this, "Error: Could not find or open file.");
          exception.printStackTrace();
        }
        // Just in case something weird happens and all those files don't get linked correctly,
        // this will get called and prevent the buttons from being enabled.  Essentially, the user
        // won't see anything.
        catch (NullPointerException exception) {
          sort.setEnabled(false);
          next.setEnabled(false);
          exception.printStackTrace();
        }
      }
    } else if (action.getSource() == sort) {
      // Call the quicksort method to sort, and handle the file writing.
      while (inputFile.hasNextLine()) {
        arrayList.add(inputFile.nextLine());
      }
      inputFile.close();
      temp = new String[arrayList.size()];
      array = arrayList.toArray(temp);
      sorter.quicksort(array, 0, array.length - 1);

      for (int i = 0; i < array.length; i++) {
        outputFile.println(array[i]);
      }
      outputFile.close();
      JOptionPane.showMessageDialog(this, "List successfully sorted.");
    } else if (action.getSource() == next) {
      // Go to the search options.
      buttonPanel.remove(chooseFile);
      buttonPanel.remove(sort);
      buttonPanel.add(search);
      repaint();
      setVisible(true);
    } else if (action.getSource() == exit) {
      // Exit, obviously.
      dispose();
    } else if (action.getSource() == search) {
      // Call the binarySearch method and display the result.
      String searchValue = JOptionPane.showInputDialog("Enter the value to search for:");
      boolean ignoreCase;
      int result;
      if (JOptionPane.showConfirmDialog(
              this,
              "Case-sensitive search?",
              "Case-sensitive",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE)
          == JOptionPane.YES_OPTION) {
        ignoreCase = false;
      } else {
        ignoreCase = true;
      }
      result = searcher.binarySearch(array, searchValue, ignoreCase) + 1;
      if (result == 0) {
        text.setText("The value, " + searchValue + ", was not found.");
      } else {
        text.setText("The value, " + searchValue + ", was found on line: " + result + ".");
      }
    }
  }