/** Создаёт новый файл для хранения долговременной информации */
 public static void createNewData() throws IOException {
   if (ApplicationProperties.BUY_FILE.createNewFile()) {
     ObjectOutputStream os =
         new ObjectOutputStream(new FileOutputStream(ApplicationProperties.BUY_FILE));
     os.writeObject(new ApplicationService());
   }
 }
  private void doSave() {
    ObjectOutputStream objectStream = getObjectOutputStream();

    if (objectStream != null) {
      try {
        System.out.println("Saving " + selectedChildrenPaths.size() + " Selected Generations...");

        for (int i = 0; i < selectedChildrenPaths.size(); i++) {
          // Get the userObject at the supplied path
          Object selectedPath =
              ((TreePath) selectedChildrenPaths.elementAt(i)).getLastPathComponent();
          DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) selectedPath;

          objectStream.writeObject(selectedNode.getUserObject());
        }

        objectStream.close();
        System.out.println("Save completed successfully.");
      } catch (IOException e) {
        System.err.println(e);
      }
    } else {
      System.out.println("Save Selected Files has been aborted!");
    }
  }
 public void windowClosing(WindowEvent e) // write file on finish
     {
   FileOutputStream out = null;
   ObjectOutputStream data = null;
   try {
     // open file for output
     out = new FileOutputStream(DB);
     data = new ObjectOutputStream(out);
     // write Person objects to file using iterator class
     Iterator<Person> itr = persons.iterator();
     while (itr.hasNext()) {
       data.writeObject((Person) itr.next());
     }
     data.flush();
     data.close();
   } catch (Exception ex) {
     JOptionPane.showMessageDialog(
         objUpdate.this,
         "Error processing output file" + "\n" + ex.toString(),
         "Output Error",
         JOptionPane.ERROR_MESSAGE);
   } finally {
     System.exit(0);
   }
 }
Exemplo n.º 4
0
 // Utility methods
 // Send message to client
 private void sendMessage(String message) {
   try {
     output.writeObject("KELVIN: " + message);
     output.flush();
     showMessage("\nKELVIN: " + message);
   } catch (IOException ioException) {
     chatWindow.append("\n ERROR: CANNOT SEND MESSAGE! \n");
   }
 }
 /** Записыввает данные в файл долговременной информации */
 public static void writeData() {
   try {
     ObjectOutputStream bin =
         new ObjectOutputStream(new FileOutputStream(ApplicationProperties.BUY_FILE));
     bin.writeObject(getInstance());
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
Exemplo n.º 6
0
 // saves the current configuration (breakpoints, window sizes and positions...)
 private void saveConfig() {
   try {
     ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(idxName + ".config"));
     Breakpoints.save(out);
     Properties.save(out);
     out.close();
   } catch (IOException exc) {
     consoleFrame.echoInfo("Could not save settings: " + exc);
   }
 }
 /**
  * sends a message to the server, and to the other clients
  *
  * @param message: message to be sent
  */
 public void sendMessage(String message) {
   try {
     System.out.println("Sending a message..." + message);
     toChatServer.writeObject(new String(message));
     toChatServer.flush();
   } catch (IOException e) {
     System.out.println("IOException in sendMessage");
     System.err.println(e);
     System.exit(1);
   }
 }
 private void saveObject(Object obj, String fName) {
   try {
     FileOutputStream fos = new FileOutputStream(fName);
     ObjectOutputStream oos = new ObjectOutputStream(fos);
     oos.writeObject(obj);
     oos.flush();
     oos.close();
     fos.close();
   } catch (IOException ex) {
     JOptionPane.showMessageDialog(this, "Problemos saugojant Objektus");
   }
 }
Exemplo n.º 9
0
  public static byte[] object2ByteArray(Object obj) throws java.io.IOException {
    /*
     * http://www.javafaq.nu/java-article236.html
     * http://stackoverflow.com/questions/2836646/java-serializable-object-to-byte-array
     */

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(bos);
    oos.writeObject(obj);
    oos.flush();
    oos.close();
    bos.close();
    byte[] data = bos.toByteArray();
    return data;
  }
Exemplo n.º 10
0
 public synchronized void sendClientData(String name, ObjectOutputStream out) throws IOException {
   for (ClientData cd : clientList)
     if (cd.getName().equals(name)) {
       out.writeObject(cd);
       return;
     }
 }
 /** 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);
 }
 /** Start talking to the server */
 public void start() {
   String codehost = getCodeBase().getHost();
   if (socket == null) {
     try {
       // Open the socket to the server
       socket = new Socket(codehost, port);
       // Create output stream
       out = new ObjectOutputStream(socket.getOutputStream());
       out.flush();
       // Create input stream and start background
       // thread to read data from the server
       in = new ObjectInputStream(socket.getInputStream());
       new Thread(this).start();
     } catch (Exception e) {
       // Exceptions here are unexpected, but we can't
       // really do anything (so just write it to stdout
       // in case someone cares and then ignore it)
       System.out.println("Exception! " + e.toString());
       e.printStackTrace();
       setErrorStatus(STATUS_NOCONNECT);
       socket = null;
     }
   } else {
     // Already started
   }
   if (socket != null) {
     // Make sure the right buttons are enabled
     start_button.setEnabled(false);
     stop_button.setEnabled(true);
     setStatus(STATUS_ACTIVE);
   }
 }
Exemplo n.º 13
0
  public static void main(String[] args) {
    try {

      DecimalFormatSymbols dfs = new DecimalFormatSymbols();
      System.out.println(
          "Default currency symbol in the default locale : " + dfs.getCurrencySymbol());
      dfs.setCurrencySymbol("*SpecialCurrencySymbol*");
      System.out.println("The special currency symbol is set : " + dfs.getCurrencySymbol());
      FileOutputStream ostream = new FileOutputStream("DecimalFormatSymbols.142");
      ObjectOutputStream p = new ObjectOutputStream(ostream);
      p.writeObject(dfs);
      ostream.close();
      System.out.println("DecimalFormatSymbols saved ok.");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 14
0
  // {{{ savePrintSpec() method
  private static void savePrintSpec() {
    String settings = jEdit.getSettingsDirectory();
    if (settings == null) return;

    String printSpecPath = MiscUtilities.constructPath(settings, "printspec");
    File filePrintSpec = new File(printSpecPath);

    try {
      FileOutputStream fileOut = new FileOutputStream(filePrintSpec);
      ObjectOutputStream obOut = new ObjectOutputStream(fileOut);
      obOut.writeObject(format);
      // for backwards compatibility, the color variable is stored also as a property
      Chromaticity cc = (Chromaticity) format.get(Chromaticity.class);
      if (cc != null)
        jEdit.setBooleanProperty("print.color", cc.getValue() == Chromaticity.COLOR.getValue());
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 15
0
 /**
  * This method saves the current MOCOData into a serialized file
  *
  * @param saveAs The name of the outputfile
  */
 public void saveObject(String saveAs) {
   File sFile = new File(saveAs);
   try {
     ObjectOutputStream oo =
         new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(sFile)));
     oo.writeObject(this.state);
     oo.close();
   } catch (Exception ex) {
     if (this.mainFrame != null) {
       JOptionPane.showMessageDialog(
           this.mainFrame,
           "Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage(),
           "Save object",
           JOptionPane.ERROR_MESSAGE);
     } else {
       System.out.println("Couldn't write to file: " + sFile.getName() + "\n" + ex.getMessage());
     }
   }
 }
  private void jMenuItemSaveLSAResultsActionPerformed(
      java.awt.event.ActionEvent evt) { // GEN-FIRST:event_jMenuItemSaveLSAResultsActionPerformed
    if (this.currentResults != null) {
      JFileChooser jfc = new JFileChooser();
      int fileDialogReturnVal = jfc.showSaveDialog(this);

      if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
        try {
          File outputFile = jfc.getSelectedFile();
          FileOutputStream fos = new FileOutputStream(outputFile);
          ObjectOutputStream oos = new ObjectOutputStream(fos);

          oos.writeObject(this.currentResults);
        } catch (IOException e) {
          System.out.println("IOexception");
          System.out.println(e.getMessage());
        }
      }
    }
  } // GEN-LAST:event_jMenuItemSaveLSAResultsActionPerformed
Exemplo n.º 17
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 doSaveAll() {
    ObjectOutputStream objectStream = getObjectOutputStream();

    if (objectStream != null) {
      try {
        System.out.println("Saving All " + generations.getLeafCount() + " Generations...");

        for (Enumeration e = generations.depthFirstEnumeration(); e.hasMoreElements(); ) {
          DefaultMutableTreeNode tmpNode = (DefaultMutableTreeNode) e.nextElement();

          if (tmpNode.isLeaf()) objectStream.writeObject(tmpNode.getUserObject());
        }

        objectStream.close();
        System.out.println("Save completed successfully.");
      } catch (IOException e) {
        System.err.println(e);
      }
    } else {
      System.out.println("Save All Files has been aborted!");
    }
  }
  private void jMenuItemSaveProjectActionPerformed(
      java.awt.event.ActionEvent evt) // GEN-FIRST:event_jMenuItemSaveProjectActionPerformed
      { // GEN-HEADEREND:event_jMenuItemSaveProjectActionPerformed
    if (this.theProject != null) {
      JFileChooser jfc = new JFileChooser();
      int fileDialogReturnVal = jfc.showSaveDialog(this);

      if (fileDialogReturnVal == JFileChooser.APPROVE_OPTION) {
        try {
          File outputFile = jfc.getSelectedFile();
          FileOutputStream fos = new FileOutputStream(outputFile);
          ObjectOutputStream oos = new ObjectOutputStream(fos);

          oos.writeObject(this.theProject);
          if (this.currentResults != null) {
            oos.writeObject(this.currentResults);
          }
        } catch (IOException e) {
          log.log(Log.ERROR, "Failed to save file\n" + e.getMessage());
        }
      }
    }
  } // GEN-LAST:event_jMenuItemSaveProjectActionPerformed
Exemplo n.º 20
0
  /**
   * Methode de connection avec le serveur
   *
   * @return
   * @throws IOException
   */
  public boolean serverConnection() throws IOException {

    boolean ok = false;
    // créer la connexion au serveur, ainsi que les flux uniquement si elle n'est pas active
    if (comm == null) {
      try {
        // Récupération de l'adresse du serveur
        comm = new Socket(textServerIP.getText(), 12345);

        oos = new ObjectOutputStream(comm.getOutputStream());
        ois = new ObjectInputStream(comm.getInputStream());

        // envoyer le pseudo du joueur
        oos.writeObject(textPseudo.getText());
        oos.flush();
        // lire un booléen -> ok
        ok = true;
      } catch (IOException e) {
        System.out.println("problème de connexion au serveur : (JungleIG)" + e.getMessage());
        System.exit(1);
      }
    }
    return ok;
  }
Exemplo n.º 21
0
 private void save() {
   try {
     ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("save.dat"));
     out.writeObject(snake);
     out.writeObject(apple);
     out.writeObject(snakeMoveDelay);
     out.writeObject(delay);
     out.writeObject(appleCount);
     out.writeObject(stepsCount);
     out.writeObject(mlSeconds);
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
  /**
   * run will be exicuted when the thread is called, and will connect to the server and start
   * communicating with it.
   */
  public void run() {
    WaitForConnection wfc = new WaitForConnection("Waiting For Connection");
    m_OldWindow.setEnabled(false);
    try {
      m_Socket = new Socket(m_IP, m_Port);

      // System.out.println("Connecting to ChatService...");
      m_ChatSocket = new Socket(m_IP, m_Port);
      // System.out.println("\nConnected to ChatService...");

      wfc.updateMessage("Waiting For Other Players");

      // System.out.println("Getting OutputStream Stream From server...");
      toServer = new ObjectOutputStream(m_Socket.getOutputStream());
      toChatServer = new ObjectOutputStream(m_ChatSocket.getOutputStream());
      toChatServer.flush();

      // System.out.println("Getting Input Stream From server...");
      fromServer = new ObjectInputStream(m_Socket.getInputStream());
      fromChatServer = new ObjectInputStream(m_ChatSocket.getInputStream());

      m_ChatService = new ChatService();
      m_ChatServiceThread = new Thread(m_ChatService);
      m_ChatServiceThread.start();

      m_MultiPlayerMenu.startGame();
      wfc.dispose();
      m_OldWindow.dispose();
    } catch (java.net.ConnectException e) {
      wfc.dispose();
      MenuWindow menu = new MenuWindow(new JFrame(""));
      JOptionPane.showMessageDialog(menu.getMainFrame(), "Error Connection refused");
      m_OldWindow.setEnabled(true);
    } catch (IOException ex) {
      System.err.print(ex);
    }
  }
Exemplo n.º 23
0
  public void mouseClicked(MouseEvent e) {
    /*can = false;
    boolean f = true;
    for (int i = 0; i < 8; i++)
    {
    	for (int j = 0; j < 8; j++)
    	if (cell[i][j] == e.getSource())
    	{
    		int judege = Clicked(cell[i][j]);
    		f = false;
    		break;
    	}
    	if (!f) break;
    }*/

    boolean flage = CheckAll();
    if (flage) {
      can = false;
      if (kind.equals("" + turn)) {
        ChessBoard cel = (ChessBoard) (e.getSource());
        int judge = Clicked(cel);
        if (judge == 1) {
          try {
            System.out.println("发送前:" + cell[3][5].taken);
            out66.writeObject("落子" + turn);
            out66.flush();
            out66.writeObject(stateList.get(stateList.size() - 1));
            out66.flush();
            out66.writeObject(takenList.get(takenList.size() - 1));
            out66.flush();
          } catch (IOException e1) {
            e1.printStackTrace();
          }
        }
      } else {
        JOptionPane.showMessageDialog(null, "请确定您的身份,您此时不能落子");
      }
    } else CheckAtTheEnd();
  }
Exemplo n.º 24
0
 private void writeObject(ObjectOutputStream aOutputStream) throws Exception {
   transmitting = true;
   aOutputStream.defaultWriteObject();
   transmitting = false;
 }
Exemplo n.º 25
0
  public static boolean save() {
    if (registry.isSaving) {
      return false;
    }

    boolean status = true;

    registry.isSaving = true;

    resolutions.add("800x600");
    resolutions.add("1024x768");
    resolutions.add("1152x864");
    resolutions.add("1280x720");
    resolutions.add("1280x768");
    resolutions.add("1280x800");
    resolutions.add("1280x960");
    resolutions.add("1280x1024");
    resolutions.add("1360x768");
    resolutions.add("1366x768");
    resolutions.add("1440x900");
    resolutions.add("1600x900");
    resolutions.add("1600x1024");
    resolutions.add("1680x1050");
    resolutions.add("1920x1080");
    resolutions.add("1920x1200");
    // resolutions.add("Full Screen");

    // try to save the settings file
    try {
      FileOutputStream settingsFile = new FileOutputStream("SettingsTemp.dat");
      ObjectOutputStream settings = new ObjectOutputStream(settingsFile);

      settings.writeObject(new Integer(1)); // settings file version
      settings.writeObject(new Integer(resolution));
      if (volumeMusic == 0) {
        settings.writeObject(new Integer(-1));
      } else {
        settings.writeObject(new Integer(volumeMusic));
      }
      if (volumeFX == 0) {
        settings.writeObject(new Integer(-1));
      } else {
        settings.writeObject(new Integer(volumeFX));
      }
      settings.writeObject(new Integer(buttonMoveRight));
      settings.writeObject(new Integer(buttonMoveLeft));
      settings.writeObject(new Integer(buttonJump));
      settings.writeObject(new Integer(buttonAction));
      settings.writeObject(new Integer(buttonRobot));
      settings.writeObject(new Integer(buttonInventory));
      settings.writeObject(new Integer(buttonPause));

      settings.close();

      moveFile("SettingsTemp.dat", "Settings.dat");
      EIError.debugMsg("Saved Settings", EIError.ErrorLevel.Notice);
    } catch (Exception e) {
      status = false;
      EIError.debugMsg("Couldn't save settings " + e.getMessage(), EIError.ErrorLevel.Error);
    }

    // try to save the players
    for (int i = 1; i <= NUMBER_OF_PLAYER_SLOTS; i++) {
      try {
        if (player == i - 1) {
          FileOutputStream playerFile = new FileOutputStream("PlayerTemp.dat");
          ObjectOutputStream playerInfo = new ObjectOutputStream(playerFile);

          playerInfo.writeObject(new Integer(2)); // settings file version
          playerInfo.writeObject(players.get(i - 1));
          if (registry.getGameController().multiplayerMode != GameController.MultiplayerMode.CLIENT
              && player == i - 1) {
            blockManagers.set(i - 1, registry.getBlockManager());
            placeableManagers.set(i - 1, registry.getPlaceableManager());
            monsterManagers.set(i - 1, registry.getMonsterManager());
          }
          playerInfo.writeObject(blockManagers.get(i - 1));
          playerInfo.writeObject(placeableManagers.get(i - 1));
          playerInfo.writeObject(monsterManagers.get(i - 1));

          playerInfo.close();

          moveFile("PlayerTemp.dat", "Player" + i + ".dat");
          EIError.debugMsg("Saved Player " + i, EIError.ErrorLevel.Notice);
        }
      } catch (Exception e) {
        status = false;
        EIError.debugMsg(
            "Couldn't save Player " + i + " " + e.getMessage(), EIError.ErrorLevel.Error);
      }
    }

    registry.isSaving = false;

    return status;
  }
Exemplo n.º 26
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);
      }
    }
  }
Exemplo n.º 27
0
        public void actionPerformed(ActionEvent e) {
          saveOld();
          area1.setText("");
          resetArea2();
          try {
            clientSocket = new Socket(ipaddress.getText(), Integer.parseInt(portNumber.getText()));
            Random r = new Random();
            serverport = 10000 + r.nextInt(8999); // random port :D

            serverSocket = new ServerSocket(serverport);
            active = true;
            editor.setTitleToListen();

            connected = true;

            ObjectOutputStream output = new ObjectOutputStream(clientSocket.getOutputStream());
            ObjectInputStream input = new ObjectInputStream(clientSocket.getInputStream());
            output.writeObject(new JoinNetworkRequest(serverport));

            ConnectionData data = getConnectionData(clientSocket, input);

            lc = new LamportClock(data.getId());
            lc.setMaxTime(data.getTs());
            dec = new DocumentEventCapturer(lc, editor);
            er = new EventReplayer(editor, dec, lc);
            ert = new Thread(er);
            ert.start();

            Peer peer =
                new Peer(
                    editor,
                    er,
                    data.getHostId(),
                    clientSocket,
                    output,
                    input,
                    lc,
                    clientSocket.getInetAddress().getHostAddress(),
                    data.getPort());
            dec.addPeer(peer);
            Thread thread = new Thread(peer);
            thread.start();

            er.setAcknowledgements(data.getAcknowledgements());
            er.setEventHistory(data.getEventHistory());
            er.setCarets(data.getCarets());

            er.addCaretPos(lc.getID(), 0);

            for (PeerWrapper p : data.getPeers()) {
              Socket socket;
              try {
                socket = connectToPeer(p.getIP(), p.getPort());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                outputStream.writeObject(
                    new NewPeerDataRequest(lc.getID(), serverSocket.getLocalPort(), 0));
                Peer newPeer =
                    new Peer(
                        editor,
                        er,
                        p.getId(),
                        socket,
                        outputStream,
                        inputStream,
                        lc,
                        p.getIP(),
                        p.getPort());
                dec.addPeer(newPeer);
                Thread t = new Thread(newPeer);
                t.start();
              } catch (IOException ex) {
                continue;
              }
            }

            Thread t1 =
                new Thread(
                    new Runnable() {

                      @Override
                      public void run() {
                        waitForConnection();
                      }
                    });
            t1.start();
            area1.setText(data.getTextField());
            area1.setCaretPosition(0);
            setDocumentFilter(dec);

            dec.sendObjectToAllPeers(new UnlockRequest(lc.getTimeStamp()));

            changed = false;
            Connect.setEnabled(false);
            Disconnect.setEnabled(true);
            Listen.setEnabled(false);
            Save.setEnabled(false);
            SaveAs.setEnabled(false);
          } catch (NumberFormatException | IOException e1) {
            setTitle("Unable to connect");
          }
        }
Exemplo n.º 28
0
  // create a new profile: read the script and possibly execute the queries,
  // save the stats (if 'import' == true, we assume the profile already exists
  // and don't run the queries)
  public void createWkld(String name, String scriptFile, boolean runQueries) {
    System.gc();
    Workload wkld = new Workload(name);

    if (showCmdsItem.getState()) {
      consoleFrame.echoCmd((!runQueries ? "importprof " : "newwkld ") + name + " " + scriptFile);
    }

    // construct the Workload object from the script;
    // first, check if the file exists
    try {
      FileReader reader = new FileReader(scriptFile);
      reader.close();
    } catch (FileNotFoundException e) {
      System.out.println("couldn't open " + scriptFile);
      return;
    } catch (IOException e) {
      System.out.println("couldn't close " + scriptFile);
    }

    // now, check if it contains only queries
    int scriptId = 0;
    try {
      scriptId = Libgist.openScript(scriptFile);
    } catch (LibgistException e) {
      System.out.println("couldn't open (C) " + scriptFile);
      return;
    }
    char[] arg1 = new char[64 * 1024];
    StringBuffer arg1Buf = new StringBuffer();
    char[] arg2 = new char[64 * 1024];
    StringBuffer arg2Buf = new StringBuffer();
    // for (;;) {
    // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
    // if (cmd == Libgist.EOF) break;
    // if (cmd != Libgist.FETCH) {
    // there should only be queries
    // System.out.println("Script file contains non-SELECT command");
    // return;
    // }
    // }

    if (runQueries) {
      // turn profiling on and execute queries
      // Libgist.setProfilingEnabled(true);
      Libgist.disableBps(true); // we don't want to stop at breakpoints

      // rescan queries
      try {
        scriptId = Libgist.openScript(scriptFile);
      } catch (LibgistException e) {
        System.out.println("couldn't open (C) " + scriptFile);
        return;
      }
      int cnt = 1;
      // for (;;) {
      // int cmd = Libgist.getCommand(scriptId, arg1, arg2);
      // if (cmd == Libgist.EOF) break;
      // arg1Buf.setLength(0);
      // arg1Buf.append(arg1, 0, strlen(arg1));
      // arg2Buf.setLength(0);
      // arg2Buf.append(arg2, 0, strlen(arg2));
      // OpThread.execCmd(LibgistCommand.FETCH, arg1Buf.toString(),
      // arg2Buf.toString(), false);
      // System.out.print(cnt + " ");
      // System.out.println(cnt + ": execute " + arg2Buf.toString() + " "
      // + arg1Buf.toString());
      // cnt++;
      // }
      System.out.println();

      Libgist.disableBps(false);
      // compute optimal clustering and some more statistics
      // Libgist.computeMetrics(wkld.filename);
    }

    // save profile
    try {
      // we're saving Java and C++ data in separate files (filename and filename.prof)
      // the profile object only contains the filename, the queries will be
      // read in from the file when the profile is opened (faster that way)
      ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(wkld.filename));
      out.writeObject(wkld);
      out.close();
      System.out.println("copy query file");
      Runtime.getRuntime().exec("cp " + scriptFile + " " + wkld.filename + ".queries");
      System.out.println("saving tree and profile");
      Libgist.saveToFile(wkld.filename + ".idx");
      if (runQueries) {
        // Libgist.saveProfile(wkld.filename + ".prof");
      }
    } catch (Exception e) {
      System.out.println("Error saving profile: " + e);
      return;
    }

    if (runQueries) {
      // turn profiling off (after the metrics were computed and
      // the profile saved)
      // Libgist.setProfilingEnabled(false);
    }
  }
  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();
      }
    }
  }
Exemplo n.º 30
0
 @Override
 public void actionPerformed(ActionEvent e) {
   if (e.getActionCommand().equals("下棋")) {
     audience.setEnabled(false);
     fighter.setEnabled(false);
     begin.setEnabled(true);
     //			JOptionPane.showMessageDialog(null, "下棋");
     System.out.println("下棋");
     try {
       System.out.println("客户端发送下棋指令");
       out66.writeObject("对手");
       out66.flush();
       out66.writeObject(new char[0][0]);
       out66.flush();
       out66.writeObject(new boolean[0][0]);
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
   if (e.getActionCommand().equals("观看")) {
     submit.setEnabled(false);
     regret.setEnabled(false);
     audience.setEnabled(false);
     fighter.setEnabled(false);
     //			JOptionPane.showMessageDialog(null, "观看");
     System.out.println("观看");
     try {
       out66.writeObject("观众");
       out66.flush();
       out66.writeObject(stateList.get(stateList.size() - 1));
       out66.flush();
       out66.writeObject(takenList.get(takenList.size() - 1));
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
   /*if (e.getActionCommand().equals("人机对弈"))
   {
   	audience.setEnabled(false);
   	fighter.setEnabled(false);
   	AIPlayer.setEnabled(false);
   	begin.setEnabled(true);
   	JOptionPane.showMessageDialog(null, "人机对弈");
   }*/
   if (e.getActionCommand().equals("发送")) {
     //			JOptionPane.showMessageDialog(null, "发送");
     System.out.println("发送");
     String str = myRole + ": " + " " + jt1.getText() + "\n";
     try {
       out99.writeObject(" " + str);
       out99.flush();
       out99.writeObject(new char[8][8]);
       out99.flush();
       out99.writeObject(new boolean[8][8]);
       out99.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     jt2.append(str);
     jt1.setText("");
   }
   if (e.getActionCommand().equals("取消")) {
     //			JOptionPane.showMessageDialog(null, "取消");
     System.out.println("取消");
     jt1.setText("");
   }
   if (e.getActionCommand().equals("悔棋")) {
     //			JOptionPane.showMessageDialog(null, "悔棋");
     System.out.println("悔棋");
     try {
       out66.writeObject("请求悔棋");
       out66.flush();
       out66.writeObject(new char[8][8]);
       out66.flush();
       out66.writeObject(new boolean[8][8]);
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     // RegretChess();
     // ShowChessNumber();
   }
   if (e.getActionCommand().equals("退出")) {
     int quit =
         JOptionPane.showConfirmDialog(null, "您确定要强制退出吗?", "请确认您的选择", JOptionPane.YES_NO_OPTION);
     if (quit == JOptionPane.YES_OPTION) {
       JOptionPane.showMessageDialog(null, "已强制退出");
       System.exit(0);
     } else return;
   }
   if (e.getActionCommand().equals("开始")) {
     begin.setEnabled(false);
     System.out.println("客户端发送开始指令");
     //			JOptionPane.showMessageDialog(null, "开始");
     try {
       out66.writeObject("请求开始");
       out66.flush();
       out66.writeObject(stateList.get(stateList.size() - 1));
       out66.flush();
       out66.writeObject(takenList.get(takenList.size() - 1));
       out66.flush();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
     Begin();
     if (kind == "黑") {
       for (int i = 0; i < 8; i++)
         for (int j = 0; j < 8; j++)
           if (cell[i][j].taken == false) {
             CheckPlace(cell[i][j]);
             if (canPut) {
               cell[i][j].ChangeBackground();
               canPut = false;
             }
           }
     }
   }
   if (e.getActionCommand().equals("存盘")) {
     //			JOptionPane.showMessageDialog(null, "存盘");
     System.out.println("存盘");
     try {
       System.out.println();
       out.writeObject(stateList);
       out.flush();
       out.close();
     } catch (IOException e1) {
       e1.printStackTrace();
     }
   }
 }