Example #1
0
 /**
  * A getter for the high scores list. Reads it directly from file and throws an error if the file
  * is not found (!working on this!).
  *
  * @return Object[][] where [i][0] is the rank (String), [i][1] is the name (String) and [i][2] is
  *     the score (Integer).
  */
 public static Object[][] getHighScore() {
   if (!new File("HighScores.dat").exists()) {
     // This object matrix actually stores the information of the high scores list
     Object[][] highScores = new Object[10][3];
     // We fill the high scores list with blank entries:  #.    " "    0
     for (int i = 0; i < highScores.length; i++) {
       highScores[i][0] = (i + 1) + ".";
       highScores[i][1] = " ";
       highScores[i][2] = 0;
     }
     // This actually writes and makes the high scores file
     try {
       ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
       o.writeObject(highScores);
       o.close();
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
   try {
     // Read and return the read object matrix
     ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
     Object[][] highScores = (Object[][]) o.readObject();
     o.close();
     return highScores;
   } catch (IOException | ClassNotFoundException e) {
     e.printStackTrace();
   }
   return null;
 }
Example #2
0
  public boolean loadDocument(String fileName) {
    try {
      File file = new File(fileName);
      ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
      SavedDocument doc = (SavedDocument) in.readObject();

      document =
          new EditorDocument(
              doc.getTitle(), doc.getDescription(),
              doc.getText(), doc.getStartTime());
      paragraphs = new Paragraphs(document, doc.getParagraphsVector());
      clients = doc.getClients();
      Iterator i = clients.iterator();
      while (i.hasNext()) {
        EditorClient c = (EditorClient) i.next();
        c.setPresent(false);

        if (c.getIdNumber() > nextClientId) nextClientId = c.getIdNumber();
      }
      nextClientId++;

      lockManager = new LockManager(clients, document, paragraphs);
      highlights =
          new Highlights(lockManager, document, doc.getHighlightTypes(), doc.getHighlights());

      return true;
    } catch (Exception e) {
      System.out.println("EditorServer: loadDocument. error");
      e.printStackTrace();
      return false;
    }
  } // endof const WITH audio profile maker
Example #3
0
  /**
   * Checks if the score is high enough to get to the high scores list, adds the name and score and
   * organizes the list. If HighScores.dat is not found, the method generates a blank one.
   *
   * @param name The nickname of the person getting to the list.
   * @param score The score gained.
   */
  public static void addHighScore(String name, int score) {

    // If we don't yet have a high scores table, we create a blank (and let the user know about it)
    if (!new File("HighScores.dat").exists()) {
      // This object matrix actually stores the information of the high scores list
      Object[][] highScores = new Object[10][3];
      // We fill the high scores list with blank entries:  #.    " "    0
      for (int i = 0; i < highScores.length; i++) {
        highScores[i][0] = (i + 1) + ".";
        highScores[i][1] = " ";
        highScores[i][2] = 0;
      }
      // This actually writes and makes the high scores file
      try {
        ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        o.writeObject(highScores);
        o.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    // We read the file to check if we have a new high score, and then rewrite the highscore
    // This is done even if we didn't previously have a high scores list
    try {
      ObjectInputStream o = new ObjectInputStream(new FileInputStream("HighScores.dat"));
      // The object matrix does the same as the previous one.
      // Here we just take what we read from the HighScores.dat to the Object[][] HighScores.
      Object[][] highScores = (Object[][]) o.readObject();
      // Then we start searching for an entry for which the score is smaller than the achieved score
      for (int i = 0; i < highScores.length; i++) {
        if ((Integer) highScores[i][2] < score) {
          // Once found we start to move entries, which are below the score we had, downwards.
          // I.e. 10. becomes whatever 9. was. 9. becomes what 8. was etc...
          for (int j = 9; j > i; j--) {
            highScores[j][0] = (j + 1) + ".";
            highScores[j][1] = highScores[j - 1][1];
            highScores[j][2] = highScores[j - 1][2];
          }
          // Then we write the score and the name we just got to the correct place
          highScores[i][0] = (i + 1) + ".";
          highScores[i][1] = name;
          highScores[i][2] = score;
          // And break the loop.
          /*Maybe this could be avoided somehow? I haven't been able to come up with an easy way yet.*/
          break;
        }
      }
      try {
        // And finally we overwrite the HighScores.dat with our highScores object matrix
        ObjectOutputStream n = new ObjectOutputStream(new FileOutputStream("HighScores.dat"));
        n.writeObject(highScores);
        n.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    } catch (ClassNotFoundException | IOException e) {
      e.printStackTrace();
    }
  }
Example #4
0
 // reads the configuration (breakpoints, window sizes and positions...) for the current index
 private void restoreConfig() {
   Breakpoints.reset();
   Properties.reset();
   try {
     ObjectInputStream in = new ObjectInputStream(new FileInputStream(idxName + ".config"));
     Breakpoints.restore(in);
     Properties.restore(in);
     in.close();
   } catch (IOException exc) {
     // something went wrong - there probably was no .config file
     // ignore it
   }
 }
Example #5
0
  public void loadSerializedData() {
    // fixme        Race x = loadXML();
    // return;
    // lastRace.getName();
    //        RaceRun run;
    try {
      //          lastRace.loadSerializedData();
      String fileName = lastRace.getName();
      FileInputStream fileIn = new FileInputStream(fileName + ".ser"); // "RaceRun.ser");
      try {
        ObjectInputStream in = new ObjectInputStream(fileIn);
        deSerialize(in);

        in.close();
        fileIn.close();

        tagHeuerConnected = new Boolean(false); // / make sure it exists - transient object
        microgateConnected = new Boolean(false); // / make sure it exists - transient object

      } catch (InvalidClassException ice) {
        log.info("Invalid Class from deserialization " + ice.classname);
      } catch (EOFException eof) {
        log.info("EOF on Serialized data");
      } catch (IOException i) {
        i.printStackTrace();
        // } catch (ClassNotFoundException cnf) {
        //    cnf.printStackTrace();
      } catch (Exception e) {
        e.printStackTrace();
      }
    } catch (FileNotFoundException fnf) {
      // Empty block OK - ignore this exception
    }

    // load required transient members
    Log raceRunLog = Log.getInstance();
    for (RaceRun r : activeRuns) {
      r.setLog(raceRunLog);
    }
    for (RaceRun r : completedRuns) {
      r.setLog(raceRunLog);
    }
    if (pendingRerun != null) {
      pendingRerun.setLog(raceRunLog);
    }

    //     updateResults();   //todo OK Here ???        NO - didn't set

  }
 private Object loadObject(String fName) {
   Object obj = null;
   try {
     FileInputStream fis = new FileInputStream(fName);
     ObjectInputStream oin = new ObjectInputStream(fis);
     obj = oin.readObject();
   } catch (IOException ex) {
     JOptionPane.showMessageDialog(this, "Problemos skaitant Objektus");
     return null;
   } catch (ClassNotFoundException ex) {
     JOptionPane.showMessageDialog(this, "Nerasta objekto klasė");
     return null;
   }
   return obj;
 }
  public static void main(String[] args) {

    MyCustomizableGUI custGUI = new MyCustomizableGUI();
    UserPreferences savedPrefs;

    try (FileInputStream fileIn = new FileInputStream("preferences.ser");
        ObjectInputStream objectIn = new ObjectInputStream(fileIn); ) {

      savedPrefs = (UserPreferences) objectIn.readObject();

      if (savedPrefs.getColor().contains("Red")) {
        custGUI.textField.setForeground(Color.red);
        custGUI.color.setSelectedItem("Red");
      } else if (savedPrefs.getColor().contains("Green")) {
        custGUI.textField.setForeground(Color.green);
        custGUI.color.setSelectedItem("Green");
      } else if (savedPrefs.getColor().contains("Blue")) {
        custGUI.textField.setForeground(Color.blue);
        custGUI.color.setSelectedItem("Blue");
      } else if (savedPrefs.getColor().contains("Cyan")) {
        custGUI.textField.setForeground(Color.cyan);
        custGUI.color.setSelectedItem("Cyan");
      } else if (savedPrefs.getColor().contains("Magenta")) {
        custGUI.textField.setForeground(Color.magenta);
        custGUI.color.setSelectedItem("Magenta");
      } else if (savedPrefs.getColor().contains("Yellow")) {
        custGUI.textField.setForeground(Color.yellow);
        custGUI.color.setSelectedItem("Yellow");
      } else if (savedPrefs.getColor().contains("Black")) {
        custGUI.textField.setForeground(Color.black);
        custGUI.color.setSelectedItem("Black");
      }

      custGUI.setFont(savedPrefs.getFont(), savedPrefs.getFontSize());
      custGUI.font.setSelectedItem(savedPrefs.getFont());
      custGUI.fontSize.setSelectedItem("" + savedPrefs.getFontSize());

    } catch (FileNotFoundException noFile) {
      // load default font and color
      custGUI.setFont("Arial", 25);
      custGUI.textField.setForeground(Color.black);

    } catch (ClassNotFoundException noPrefs) {
      noPrefs.printStackTrace();
    } catch (IOException e) {
      System.out.println("I/O Error: " + e.getMessage());
    }
  }
 /** Stop talking to the server */
 public void stop() {
   if (socket != null) {
     // Close all the streams and socket
     if (out != null) {
       try {
         out.close();
       } catch (IOException ioe) {
       }
       out = null;
     }
     if (in != null) {
       try {
         in.close();
       } catch (IOException ioe) {
       }
       in = null;
     }
     if (socket != null) {
       try {
         socket.close();
       } catch (IOException ioe) {
       }
       socket = null;
     }
   } else {
     // Already stopped
   }
   // Make sure the right buttons are enabled
   start_button.setEnabled(true);
   stop_button.setEnabled(false);
   setStatus(STATUS_STOPPED);
 }
  private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {

    s.defaultReadObject();

    fSelection = CollectionsFactory.current().createList(); // could use lazy initialization instead
    if (drawing() != null) {
      drawing().addDrawingChangeListener(this);
    }
    fSelectionListeners = CollectionsFactory.current().createList();
  }
 public void windowOpened(WindowEvent e) // read file on start
     {
   FileInputStream in = null;
   ObjectInputStream data = null;
   try {
     in = new FileInputStream(DB);
     data = new ObjectInputStream(in);
     p = (Person) data.readObject();
     while (p != null) {
       persons.add(p); // store Person object in ArrayList collection
       p = (Person) data.readObject(); // read the next record
     }
     data.close();
   } catch (Exception ex) {
     // IOException will always occur on the last read above
   } finally {
     if (persons.size() > 0) displayRecord();
   }
 }
  private void jMenuItemLoadProjectActionPerformed(
      java.awt.event.ActionEvent evt) // GEN-FIRST:event_jMenuItemLoadProjectActionPerformed
      { // GEN-HEADEREND:event_jMenuItemLoadProjectActionPerformed
    JFileChooser jfc = new JFileChooser();
    if (lastPath != null) {
      jfc.setCurrentDirectory(lastPath);
    }
    int fileDialogReturnVal = jfc.showOpenDialog(this);

    if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
      try {
        File inputFile = jfc.getSelectedFile();
        FileInputStream fis = new FileInputStream(inputFile);
        ObjectInputStream ois = new ObjectInputStream(fis);

        this.theProject = (Project) ois.readObject();
        this.currentResults = (LSAResults) ois.readObject();

        lastPath = new File(jfc.getSelectedFile().getPath());
      } catch (IOException e) {
        if (this.theProject == null) {
          log.log(Log.ERROR, "Failed to load project");
        }
        if (this.currentResults == null) {
          log.log(Log.WARNING, "Failed to load results");
        }

        log.log(Log.WARNING, e.getMessage());
      } catch (ClassNotFoundException e) {
        log.log(Log.ERROR, "Class not found error, version mismatch");
      }
    }
    if (this.theProject != null) {
      jMenuItemViewDocuments.setEnabled(true);
      jMenuItemSaveProject.setEnabled(true);
      this.setTitle(theProject.getProjectName());
      log.log(Log.INFO, "Project Loaded");
    }
    if (this.currentResults != null) {
      log.log(Log.INFO, "Results loaded");
    }
  } // GEN-LAST:event_jMenuItemLoadProjectActionPerformed
Example #12
0
 // Close crap after chatting
 private void closeCrap() {
   showMessage("\n Closing connection... \n ");
   ableToType(false);
   try {
     output.close();
     input.close();
     connection.close();
   } catch (IOException ioException) {
     ioException.printStackTrace();
   }
 }
  private void jMenuItemLoadLSAResultsActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItemLoadLSAResultsActionPerformed
    JFileChooser jfc = new JFileChooser();
    int fileDialogReturnVal = jfc.showOpenDialog(this);

    if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
      try {
        File inputFile = jfc.getSelectedFile();
        FileInputStream fis = new FileInputStream(inputFile);
        ObjectInputStream ois = new ObjectInputStream(fis);

        this.currentResults = (LSAResults) ois.readObject();
      } catch (IOException e) {
        log.log(Log.ERROR, "Failed to load LSA results\n" + e.getMessage());
      } catch (ClassNotFoundException e) {
        log.log(Log.ERROR, "Class not found : Error loading LSA results due to version mismatch");
      }

      System.out.println(currentResults == null);
    }
  } // GEN-LAST:event_jMenuItemLoadLSAResultsActionPerformed
Example #14
0
  private void deSerialize(ObjectInputStream in) throws DuplicateBibException {
    Object o;
    try {
      while ((o = in.readObject()) != null) {
        Race raceFromSerialized = (Race) o;

        this.date = raceFromSerialized.date;
        this.name = raceFromSerialized.name;
        this.location = raceFromSerialized.location;
        setNbrGates(raceFromSerialized.nbrGates); // this.nbrGates = race.nbrGates;// = 25;
        this.upstreamGates = raceFromSerialized.upstreamGates;
        this.judgingSections = raceFromSerialized.judgingSections;
        for (JudgingSection s : judgingSections) {
          // must assign all transients, otherwise they are null and cause problsm
          s.setClientDeviceAttached(new Boolean(false));
        }

        // Race Status
        this.pendingRerun = raceFromSerialized.pendingRerun;
        this.activeRuns = raceFromSerialized.activeRuns;
        this.completedRuns = raceFromSerialized.completedRuns;

        this.startList = raceFromSerialized.startList;
        this.runsStartedOrCompletedCnt = raceFromSerialized.runsStartedOrCompletedCnt;
        this.currentRunIteration =
            raceFromSerialized.currentRunIteration; // are we on 1st runs, or 2nd runs ?
        this.racers = raceFromSerialized.racers;
        this.tagHeuerEnabled =
            raceFromSerialized.tagHeuerEnabled; // todo REMOVE ->tagHeuerEmulation =
        // raceFromSerialized.tagHeuerEmulation;
        this.microgateEnabled = raceFromSerialized.microgateEnabled;
        this.microgateEnabled = raceFromSerialized.timyEnabled;

        this.icfPenalties = raceFromSerialized.icfPenalties;
      }

    } catch (InvalidClassException ice) {
      clearRace();
      System.out.println("All data cleared, incompatible race object version information");
    } catch (EOFException io) {
      // io.printStackTrace();

    } catch (IOException io) {
      io.printStackTrace();
    } catch (ClassNotFoundException cnfe) {
      cnfe.printStackTrace();
    }
    String duplicates = lookForDuplicateBibsInTheSameClass();
    if (duplicates != null) {
      log.error(duplicates);
      throw new DuplicateBibException();
    }
  }
 private ConnectionData getConnectionData(Socket clientSocket, ObjectInputStream input) {
   ConnectionData res;
   try {
     Object o = input.readObject();
     res = (ConnectionData) o;
     return res;
   } catch (IOException | ClassNotFoundException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   return null;
 }
Example #16
0
 public void disconnect() {
   int cmdID = commID++;
   this.connected = false;
   try {
     out.println(cmdID + ";logout");
     out.flush();
     in.close();
     out.close();
     socket.close();
   } catch (IOException ex) {
     System.err.println("Server stop failed.");
   }
 }
Example #17
0
 public void run() {
   String texto = "";
   while (repetir) {
     try {
       Empleados e = (Empleados) inObjeto.readObject();
       textarea1.setText("");
       textarea1.setForeground(Color.blue);
       if (e == null) {
         textarea1.setForeground(Color.red);
         PintaMensaje("<<EL EMPLEADO NO EXISTE>>");
       } else {
         texto =
             "Empleado: "
                 + e.getEmpNo()
                 + "\n   "
                 + "Oficio: "
                 + e.getOficio()
                 + "\tApellido: "
                 + e.getApellido()
                 + "\n    "
                 + "Comisión: "
                 + e.getComision()
                 + "\tDirección: "
                 + e.getDir()
                 + "\n    "
                 + "Alta: "
                 + e.getFechaAlt()
                 + "\tSalario: "
                 + e.getSalario()
                 + "\n    "
                 + "Departamento: "
                 + e.getDepartamentos().getDnombre();
         textarea1.append(texto);
       }
     } catch (SocketException s) {
       repetir = false;
     } catch (IOException e) {
       e.printStackTrace();
       repetir = false;
     } catch (ClassNotFoundException e) {
       e.printStackTrace();
       repetir = false;
     }
   }
   try {
     socket.close();
     System.exit(0);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Example #18
0
 private void deSerializeXML(ObjectInputStream in) {
   Object o;
   try {
     while ((o = in.readObject()) != null) {
       System.out.println(o);
     }
   } catch (IOException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   } catch (ClassNotFoundException e) {
     e.printStackTrace(); // To change body of catch statement use File | Settings | File
     // Templates.
   }
 }
Example #19
0
 // Fun chatting
 private void whileChatting() throws IOException {
   String message = " You are now connected! ";
   sendMessage(message);
   ableToType(true);
   do {
     // have conversation
     try {
       message = (String) input.readObject();
       showMessage("\n" + message);
     } catch (ClassNotFoundException classNotFoundException) {
       showMessage("\n idk wtf that user sent! \n");
     }
   } while (!message.equals("LEEPING: END"));
 }
Example #20
0
 /**
  * This methods loads the current state of MOCO from a serialized file
  *
  * @param loadFrom The name of the serialized file
  * @return The new state of MOCO
  */
 public Object openObject(String loadFrom) {
   File selected = new File(loadFrom);
   try {
     ObjectInputStream oi =
         new ObjectInputStream(new BufferedInputStream(new FileInputStream(selected)));
     Object obj = oi.readObject();
     oi.close();
     if (!(obj instanceof MOCCOState)) {
       throw new Exception("Object not of type MOCCOState");
     }
     return obj;
   } catch (Exception ex) {
     if (this.mainFrame != null) {
       JOptionPane.showMessageDialog(
           this.mainFrame,
           "Couldn't read object: " + selected.getName() + "\n" + ex.getMessage(),
           "Open object file",
           JOptionPane.ERROR_MESSAGE);
     } else {
       System.out.println("Couldn't read object: " + selected.getName() + "\n" + ex.getMessage());
     }
   }
   return null;
 }
Example #21
0
  /** Performs the action of saving a session to a file. */
  public void actionPerformed(ActionEvent e) {

    // Get the frontmost SessionWrapper.
    SessionEditorIndirectRef sessionEditorRef =
        DesktopController.getInstance().getFrontmostSessionEditor();
    SessionEditor sessionEditor = (SessionEditor) sessionEditorRef;
    SessionEditorWorkbench workbench = sessionEditor.getSessionWorkbench();
    SessionWrapper sessionWrapper = workbench.getSessionWrapper();
    TetradMetadata metadata = new TetradMetadata();

    // Select the file to save this to.
    File file =
        EditorUtils.getSaveFile(
            sessionEditor.getName(),
            "tet",
            JOptionUtils.centeringComp(),
            true,
            "Save Session As...");

    if (file == null) {
      this.saved = false;
      return;
    }

    if ((DesktopController.getInstance().existsSessionByName(file.getName())
        && !(sessionWrapper.getName().equals(file.getName())))) {
      this.saved = false;
      JOptionPane.showMessageDialog(
          JOptionUtils.centeringComp(),
          "Another session by that name is currently open. Please "
              + "\nclose that session first.");
      return;
    }

    sessionWrapper.setName(file.getName());
    sessionEditor.setName(file.getName());

    // Save it.
    try {
      FileOutputStream out = new FileOutputStream(file);
      ObjectOutputStream objOut = new ObjectOutputStream(out);
      objOut.writeObject(metadata);
      objOut.writeObject(sessionWrapper);
      out.close();

      FileInputStream in = new FileInputStream(file);
      ObjectInputStream objIn = new ObjectInputStream(in);
      objIn.readObject();

      sessionWrapper.setSessionChanged(false);
      sessionWrapper.setNewSession(false);
      this.saved = true;
    } catch (Exception e2) {
      this.saved = false;
      e2.printStackTrace();
      JOptionPane.showMessageDialog(
          JOptionUtils.centeringComp(), "An error occurred while attempting to save the session.");
    }

    DesktopController.getInstance().putMetadata(sessionWrapper, metadata);
    sessionEditor.firePropertyChange("name", null, file.getName());
  }
Example #22
0
  /**
   * Creates a new configuration method
   *
   * @param backMenu Menu instance used to control its music
   */
  public Config(Menu backMenu) {

    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
      try (ObjectInputStream entradaObjs =
          new ObjectInputStream(new FileInputStream("Saves" + File.separator + "config.dat"))) {
        configSave = (float[]) entradaObjs.readObject();
      }
    } catch (ClassNotFoundException
        | IOException
        | InstantiationException
        | IllegalAccessException
        | UnsupportedLookAndFeelException e) {
      System.out.println(e.getMessage());
    }

    this.setSize(800, 300);
    this.add(fondo = new Fondo("fondoConfig.png"));
    this.setUndecorated(true);
    this.setLocationRelativeTo(null);
    this.setDefaultCloseOperation(EXIT_ON_CLOSE);
    this.setIconImage(Toolkit.getDefaultToolkit().getImage("Images" + File.separator + "logo.png"));
    this.backMenu = backMenu;

    icon = new ImageIcon("Images/brick.png");

    fondo.setLayout(new BorderLayout());

    returns = CustomButton.createButton("Go Back", this.getGraphicsConfiguration(), 18);
    returns.addActionListener(this);

    musicSlider = new JSlider(JSlider.HORIZONTAL, -30, 0, (int) configSave[0]);
    musicSlider.setOpaque(false);
    musicSlider.setMajorTickSpacing(10);
    musicSlider.setMinorTickSpacing(2);
    musicSlider.setPaintTicks(true);

    volumeSlider = new JSlider(JSlider.HORIZONTAL, -30, 0, (int) configSave[1]);
    volumeSlider.setOpaque(false);
    volumeSlider.setMajorTickSpacing(10);
    volumeSlider.setMinorTickSpacing(2);
    volumeSlider.setPaintTicks(true);

    fondo.add(returns, BorderLayout.SOUTH);
    fondo.add(musicSlider, BorderLayout.NORTH);
    fondo.add(volumeSlider, BorderLayout.CENTER);

    try {
      this.getContentPane()
          .setCursor(
              Toolkit.getDefaultToolkit()
                  .createCustomCursor(
                      CompatibleImage.toCompatibleImage(
                          ImageIO.read(new File("Images" + File.separator + "cursor.png"))),
                      new Point(0, 0),
                      "cursor"));
    } catch (IOException ex) {
      Logger.getLogger(Menu.class.getName()).log(Level.SEVERE, null, ex);
    }

    this.setVisible(true);
  }
Example #23
0
 private Quiz loadSerializedQuiz(File f) throws Exception {
   ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(f));
   Quiz q = (Quiz) objectInputStream.readObject();
   objectInputStream.close();
   return q;
 }
Example #24
0
  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == butConnect) {
      try {
        boolean ok = serverConnection();
        if (ok) {
          setInitPanel();
        } else {
          System.out.println("Le pseudo existe déjà, choisissez en un autre.");
        }
      } catch (IOException err) {
        System.err.println(
            "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butListParty) {
      try {
        // envoyer requête LIST PARTY
        oos.writeInt(JungleServer.REQ_LISTPARTY);
        oos.flush();

        // recevoir résultat et l'afficher dans textInfoInit
        System.out.println("flush");
        boolean pret = ois.readBoolean();
        System.out.println(pret);
        if (pret) {
          String nomParty = (String) ois.readObject();
          System.out.println("apres read");
          textInfoInit.append(nomParty + " ");
        }

      } catch (ClassNotFoundException err) {
      } catch (IOException err) {
        System.err.println(
            "Problème de connection avec le serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }

    } else if (e.getSource() == butCreateParty) {
      try {
        boolean ok;
        // envoyer requête CREATE PARTY (paramètres : nom partie et nb joueurs nécessaires)
        oos.writeInt(JungleServer.REQ_CREATEPARTY);
        oos.writeObject(textCreate.getText());
        int nbJoueurs = (Integer) spinNbPlayer.getValue();
        oos.writeInt(nbJoueurs);
        oos.flush();
        // recevoir résultat -> ok
        ok = ois.readBoolean();
        System.out.println(ok);
        // si ok == true :
        if (ok) {
          // mettre le panneau party au centre
          setPartyPanel();
          // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie
          textInfoParty.append("Attendre le début de la partie");
          // créer un ThreadClient et lancer son exécution
          ThreadClient threadClient = new ThreadClient(this);
          threadClient.start();
        }
      } catch (IOException err) {
        System.err.println(
            "probleme de connection serveur : " + err.getMessage() + "\n.Aborting...");
        System.exit(1);
      }
    } else if (e.getSource() == butJoinParty) {

      try {
        int idPlayer;
        // envoyer requête JOIN PARTY (paramètres : numero partie)
        oos.writeInt(JungleServer.REQ_JOINPARTY);
        oos.flush();
        System.out.println("requete envoyée");
        int numPartie = Integer.parseInt(textJoin.getText());
        oos.writeInt(numPartie);
        oos.flush();
        System.out.println("numPartie flushé");
        // recevoir résultat -> idPlayer
        idPlayer = ois.readInt();
        System.out.println("idplayer reçu : " + idPlayer);
        // si idPlayer >= 1 :
        if (idPlayer >= 1) {
          // mettre le panneau party au centre
          setPartyPanel();
          // afficher un message dans textInfoParty comme quoi il faut attendre le début de partie
          textInfoParty.append("Attendre la début de la partie");
          // créer un ThreadClient et lancer son exécution
          System.out.println("avant démarrage du thread");
          ThreadClient threadClient = new ThreadClient(this);
          threadClient.start();
          System.out.println("Apres le thread");
        }
      } catch (IOException err) {
        System.err.println("Problème de connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butPlay) {
      try {
        // envoyer requête PLAY (paramètre : contenu de textPlay)
        oos.writeInt(JungleServer.REQ_PLAY);
        oos.writeObject(textPlay.getText());
        oos.flush();
        orderSent = true;
        butPlay.setEnabled(false);
        textPlay.setEnabled(false);

        // mettre orderSent à true
        // bloquer le bouton play et le textfiled associé
      } catch (IOException err) {
        System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    } else if (e.getSource() == butQuit) {
      try {
        oos.close();
        ois.close();
        setConnectionPanel();
        comm = null;
      } catch (IOException err) {
        System.err.println("Problème connection serveur: " + err.getMessage() + "\n.Arrêt...");
        System.exit(1);
      }
    }
  }
 /**
  * Subclassed to update the internal representation of the mask after the default read operation
  * has completed.
  */
 private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
   s.defaultReadObject();
   updateMaskIfNecessary();
 }
 /** Restores a serialized object. */
 private void readObject(ObjectInputStream s) throws ClassNotFoundException, IOException {
   s.defaultReadObject();
   valueDrawer = defaultValueDrawer;
 }
  /**
   * waitForConnection waits for incomming connections. There are two cases. If we receive a
   * JoinNetworkRequest it means that a new peer tries to get into the network. We lock the entire
   * system, and sends a ConnectionData object to the new peer, from which he can connect to every
   * other peer. We add this new peer to our data.
   *
   * <p>If we receive a NewPeerDataRequest, it means that a new peer has received ConnectionData
   * from another peer in the network, and he is now trying to connect to everyone, including me. We
   * then update our data with the new peer.
   */
  private void waitForConnection() {
    while (active) {
      Socket client = waitForConnectionFromClient();
      if (client != null) {
        try {
          ObjectOutputStream output = new ObjectOutputStream(client.getOutputStream());
          ObjectInputStream input = new ObjectInputStream(client.getInputStream());
          Object o = input.readObject();

          if (o instanceof JoinNetworkRequest) {
            JoinNetworkRequest request = (JoinNetworkRequest) o;
            dec.sendObjectToAllPeers(new LockRequest(lc.getTimeStamp()));
            waitForAllToLock();
            setLocked(true);
            Thread.sleep(500);
            int id = getNewId();
            Peer p =
                new Peer(
                    editor,
                    er,
                    id,
                    client,
                    output,
                    input,
                    lc,
                    client.getInetAddress().getHostAddress(),
                    request.getPort());
            ConnectionData cd =
                new ConnectionData(
                    er.getEventHistory(),
                    er.getAcknowledgements(),
                    er.getCarets(),
                    id,
                    area1.getText(),
                    lc.getTimeStamp(),
                    lc.getID(),
                    dec.getPeers(),
                    serverSocket.getLocalPort());
            p.writeObjectToStream(cd);
            dec.addPeer(p);
            Thread t = new Thread(p);
            t.start();
            er.addCaretPos(id, 0);
          } else if (o instanceof NewPeerDataRequest) {
            NewPeerDataRequest request = (NewPeerDataRequest) o;
            Peer newPeer =
                new Peer(
                    editor,
                    er,
                    request.getId(),
                    client,
                    output,
                    input,
                    lc,
                    client.getInetAddress().getHostAddress(),
                    request.getPort());
            dec.addPeer(newPeer);
            er.addCaretPos(request.getId(), request.getCaretPos());
            newPeer.writeObjectToStream(new NewPeerDataAcknowledgement(lc.getTimeStamp()));
            Thread t = new Thread(newPeer);
            t.start();
          }
        } catch (IOException | ClassNotFoundException | InterruptedException e) {
          e.printStackTrace();
        }
      }
    }
  }
Example #28
0
 // Serialization support: probably never be used but the transient
 // things should be set correctly just in case:
 private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
   in.defaultReadObject();
   init();
 }
  public void actionPerformed(ActionEvent e) {
    if (e.getSource() == jbSaveLayer) {
      try {
        FileOutputStream fout = new FileOutputStream(jtfCengMing.getText() + ".wyf");
        ObjectOutputStream oout = new ObjectOutputStream(fout);
        oout.writeObject(itemArray);
        oout.close();
        fout.close();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
    } else if (e.getSource() == jbLoadLayer) {
      try {
        FileInputStream fin = new FileInputStream(jtfCengMing.getText() + ".wyf");
        ObjectInputStream oin = new ObjectInputStream(fin);
        itemArray = (Item[][]) oin.readObject();

        oin.close();
        fin.close();
        this.flush();
      } catch (Exception ea) {
        ea.printStackTrace();
      }
      lvp.repaint();
    } else if (e.getSource() == jbLoadAll) { // 全部铺上当前选中

      for (int row = 0; row < 40; row++) {
        for (int col = 0; col < 60; col++) {
          Item item = ((Item) (jl.getSelectedValue())).clone();
          itemArray[row][col] = item;
          if (item != null) {
            item.setPosition(col, row);
          }
        }
      }

      lvp.repaint();
    } else if (e.getSource() == jbCreate) { // 生成源代码

      try {
        FileOutputStream fout = null;
        DataOutputStream dout = null;
        fout = new FileOutputStream("maps.so");
        dout = new DataOutputStream(fout);
        int totalBlocks = 0;

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              totalBlocks++;
            }
          }
        }
        System.out.println("totalBlocks=" + totalBlocks);

        // 写入不空块的数量
        dout.writeInt(totalBlocks);

        for (int i = 0; i < 40; i++) {
          for (int j = 0; j < 60; j++) {
            Item item = itemArray[i][j];
            if (item != null) {
              int w = item.w; // 元素的图片宽度
              int h = item.h; // 元素的图片高度
              int col = item.col; // 元素的地图列
              int row = item.row; // 元素的地图行
              int pCol = item.pCol; // 元素的占位列
              int pRow = item.pRow; // 元素的占位行
              String leiMing = item.leiMing; // 类名

              int[][] notIn = item.notIn; // 不可通过
              int[][] keYu = item.keYu; // 可遇矩阵

              // 计算图片下标
              int outBitmapInxex = 0;
              if (leiMing.equals("Grass")) {
                outBitmapInxex = 0;
              } else if (leiMing.equals("XiaoHua1")) {
                outBitmapInxex = 1;
              } else if (leiMing.equals("MuZhuang")) {
                outBitmapInxex = 2;
              } else if (leiMing.equals("XiaoHua2")) {
                outBitmapInxex = 3;
              } else if (leiMing.equals("Road")) {
                outBitmapInxex = 4;
              } else if (leiMing.equals("Jing")) {
                outBitmapInxex = 5;
              }

              dout.writeByte(outBitmapInxex); // 记录图片下标
              dout.writeByte(0); // 记录可遇标志 0-不可遇 底层都不可遇
              dout.writeByte(w); // 图片宽度
              dout.writeByte(h); // 图片高度
              dout.writeByte(col); // 总列数
              dout.writeByte(row); // 总行数
              dout.writeByte(pCol); // 占位列
              dout.writeByte(pRow); // 占位行

              int bktgCount = notIn.length; // 不可通过点的数量
              dout.writeByte(bktgCount); // 写入不可通过点的数量

              for (int k = 0; k < bktgCount; k++) {
                dout.writeByte(notIn[k][0]);
                dout.writeByte(notIn[k][1]);
              }
            }
          }
        }

        dout.close();
        fout.close();

      } catch (Exception ea) {
        ea.printStackTrace();
      }
    }
  }
    /** Background thread used to receive data from the server. */
    public void run() {
      Long id;
      Integer message_type;
      String target;
      String soap;
      SOAPMonitorData data;
      int selected;
      int row;
      boolean update_needed;
      while (socket != null) {
        try {
          // Get the data from the server
          message_type = (Integer) in.readObject();
          // Process the data depending on its type
          switch (message_type.intValue()) {
            case SOAPMonitorConstants.SOAP_MONITOR_REQUEST:
              // Get the id, target and soap info
              id = (Long) in.readObject();
              target = (String) in.readObject();
              soap = (String) in.readObject();
              // Add new request data to the table
              data = new SOAPMonitorData(id, target, soap);
              model.addData(data);
              // If "most recent" selected then update
              // the details area if needed
              selected = table.getSelectedRow();
              if ((selected == 0) && model.filterMatch(data)) {
                valueChanged(null);
              }
              break;
            case SOAPMonitorConstants.SOAP_MONITOR_RESPONSE:
              // Get the id and soap info
              id = (Long) in.readObject();
              soap = (String) in.readObject();
              data = model.findData(id);
              if (data != null) {
                update_needed = false;
                // Get the selected row
                selected = table.getSelectedRow();
                // If "most recent", then always
                // update details area
                if (selected == 0) {
                  update_needed = true;
                }
                // If the data being updated is
                // selected then update details
                row = model.findRow(data);
                if ((row != -1) && (row == selected)) {
                  update_needed = true;
                }
                // Set the response and update table
                data.setSOAPResponse(soap);
                model.updateData(data);
                // Refresh details area (if needed)
                if (update_needed) {
                  valueChanged(null);
                }
              }
              break;
          }

        } catch (Exception e) {
          // Exceptions are expected here when the
          // server communication has been terminated.
          if (stop_button.isEnabled()) {
            stop();
            setErrorStatus(STATUS_CLOSED);
          }
        }
      }
    }