コード例 #1
0
ファイル: LiteLoader.java プロジェクト: Nanonid/liteloader
  /**
   * Reads a base class overrride from a resource file
   *
   * @param binaryClassName
   * @param fileName
   */
  private void registerBaseClassOverride(String binaryClassName, String fileName) {
    try {
      Method mDefineClass =
          ClassLoader.class.getDeclaredMethod(
              "defineClass", String.class, byte[].class, int.class, int.class);
      mDefineClass.setAccessible(true);

      InputStream resourceInputStream =
          LiteLoader.class.getResourceAsStream("/classes/" + fileName + ".bin");

      if (resourceInputStream != null) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        for (int readBytes = resourceInputStream.read();
            readBytes >= 0;
            readBytes = resourceInputStream.read()) {
          outputStream.write(readBytes);
        }

        byte[] data = outputStream.toByteArray();

        outputStream.close();
        resourceInputStream.close();

        logger.info("Defining class override for " + binaryClassName);
        mDefineClass.invoke(
            Minecraft.class.getClassLoader(), binaryClassName, data, 0, data.length);
      } else {
        logger.info("Error defining class override for " + binaryClassName + ", file not found");
      }
    } catch (Throwable th) {
      logger.log(Level.WARNING, "Error defining class override for " + binaryClassName, th);
    }
  }
コード例 #2
0
ファイル: ZipScanner.java プロジェクト: GEFFROY/Quercus
  private static int readInt(InputStream is) throws IOException {
    int value;

    value =
        ((is.read() & 0xff)
            + ((is.read() & 0xff) << 8)
            + ((is.read() & 0xff) << 16)
            + ((is.read() & 0xff) << 24));

    return value;
  }
コード例 #3
0
ファイル: OCSSWRuntimeConfig.java プロジェクト: mg1989/seadas
  private void loadConfiguration() throws RuntimeConfigException {
    trace(String.format("Loading configuration from [%s]", configFilePath));
    try {
      InputStream stream = new FileInputStream(configFilePath);
      // InputStream stream1 = new FileInputStream("config/ocsswws.config");
      try {
        Properties fileProperties = new Properties();
        fileProperties.load(stream);
        // @todo check tests - code was not backward compatible with Java 5
        // so i changed it - but this is not the only place of uncompatibilty
        // add default properties so that they override file properties
        // Set<String> propertyNames = fileProperties.stringPropertyNames();
        //                for (String propertyName : propertyNames) {
        //                    String propertyValue = fileProperties.getProperty(propertyName);
        //                    if (!isPropertySet(propertyName)) {
        //                        setProperty(propertyName, propertyValue);
        //                        trace(String.format("Configuration property [%s] added",
        // propertyName));
        //                    } else {
        //                        trace(String.format("Configuration property [%s] ignored",
        // propertyName));
        //                    }
        //                }

        Enumeration<?> enumeration = fileProperties.propertyNames();
        while (enumeration.hasMoreElements()) {
          final Object key = enumeration.nextElement();
          if (key instanceof String) {
            final Object value = fileProperties.get(key);
            if (value instanceof String) {
              final String keyString = (String) key;
              String propertyValue = fileProperties.getProperty(keyString);
              if (!isPropertySet(keyString)) {
                setProperty(keyString, propertyValue);
                trace(String.format("Configuration property [%s] added", keyString));
              } else {
                trace(String.format("Configuration property [%s] ignored", keyString));
              }
            }
          }
        }
      } finally {
        stream.close();
      }
    } catch (IOException e) {
      throw new RuntimeConfigException(
          String.format("Failed to load configuration [%s]", configFilePath), e);
    }
  }
コード例 #4
0
ファイル: LibRt.java プロジェクト: yamila87/rt_src
 public static int pipe_stream(InputStream is, OutputStream os, boolean wantsKeepOpen)
     throws IOException { // U: copia de un stream al otro
   int cnt = 0;
   int n;
   byte[] buffer = new byte[BUFF_SZ];
   while ((n = is.read(buffer)) > -1) {
     cnt += n;
     os.write(buffer, 0, n);
   }
   if (!wantsKeepOpen) {
     is.close();
     os.close();
   }
   return cnt;
 }
コード例 #5
0
    @Override
    public void run() {
      byte[] buf = new byte[100];
      try {
        int len;
        while ((len = in.read(buf)) > 0) {
          String output = new String(buf, 0, len);
          Thread t = Thread.currentThread();
          System.out.println(
              "thread " + t.getName() + " " + t.getId() + ", read " + len + " bytes: " + output);
        }

      } catch (IOException e) {
        logger.log(Level.SEVERE, "Failed to read", e);

      } finally {
        try {
          in.close();
        } catch (IOException e) {
          logger.log(Level.SEVERE, "Failed to close", e);
        }
      }
    }
コード例 #6
0
ファイル: ZipScanner.java プロジェクト: GEFFROY/Quercus
  public void close() {
    InputStream is = _is;
    _is = null;

    InputStream fileIs = _fileIs;
    _fileIs = null;

    if (is != null) {
      try {
        is.close();
      } catch (Exception e) {
        throw new IllegalStateException(e);
      }
    }

    if (fileIs != null) {
      try {
        fileIs.close();
      } catch (Exception e) {
        throw new IllegalStateException(e);
      }
    }
  }
コード例 #7
0
ファイル: TypeList.java プロジェクト: Oger-Lord/JPenguin
 public static TypeList load(String gamePath, String dataName) {
   System.out.println("load:" + dataName);
   InputStream is = null;
   Savable sav = null;
   try {
     File file =
         new File(
             System.getProperty("user.dir")
                 + File.separator
                 + gamePath
                 + File.separator
                 + dataName);
     if (!file.exists()) {
       return null;
     }
     is = new BufferedInputStream(new FileInputStream(file));
     // is = new GZIPInputStream(new BufferedInputStream(new FileInputStream(file)));
     XMLImporter imp = XMLImporter.getInstance();
     // if (manager != null) {
     //     imp.setAssetManager(manager);
     // }
     sav = imp.load(is);
   } catch (IOException ex) {
     Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
     ex.printStackTrace();
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (IOException ex) {
         Logger.getLogger(Type.class.getName()).log(Level.SEVERE, "Error loading data: {0}", ex);
         ex.printStackTrace();
       }
     }
   }
   return (TypeList) sav;
 }
コード例 #8
0
ファイル: LibRt.java プロジェクト: yamila87/rt_src
 public static String get_stream(InputStream is, String encoding) throws IOException {
   if (encoding == null) {
     encoding = CfgEncodingDflt;
   }
   byte[] buffer = new byte[BUFF_SZ];
   StringBuilder out = new StringBuilder();
   logm("DBG", 9, "STREAM GET", is + "");
   for (; ; ) {
     int rsz = is.read(buffer, 0, buffer.length);
     logm("DBG", 9, "STREAM GET READ", rsz);
     if (rsz < 0) break;
     out.append(new String(buffer, 0, rsz, encoding));
   }
   String s = out.toString();
   logm("DBG", 9, "STREAM GET RESULT", s);
   return s;
 }
コード例 #9
0
  /**
   * @param in input stream to be used (e.g. System.in)
   * @param prompt The prompt to display to the user.
   * @return The password as entered by the user.
   */
  public static final char[] getPassword(InputStream in, String prompt) throws IOException {
    MaskingThread maskingthread = new MaskingThread(prompt);
    Thread thread = new Thread(maskingthread);
    thread.start();

    char[] lineBuffer;
    char[] buf;
    int i;

    buf = lineBuffer = new char[128];

    int room = buf.length;
    int offset = 0;
    int c;

    loop:
    while (true) {
      c = in.read();
      switch (c) {
        case -1:
        case '\n':
          break loop;

        case '\r':
          int c2 = in.read();
          if ((c2 != '\n') && (c2 != -1)) {
            if (!(in instanceof PushbackInputStream)) {
              in = new PushbackInputStream(in);
            }
            ((PushbackInputStream) in).unread(c2);
          } else {
            break loop;
          }
        default:
          if (--room < 0) {
            buf = new char[offset + 128];
            room = buf.length - offset - 1;
            System.arraycopy(lineBuffer, 0, buf, 0, offset);
            Arrays.fill(lineBuffer, ' ');
            lineBuffer = buf;
          }
          buf[offset++] = (char) c;
          break;
      }
    }
    maskingthread.stopMasking();
    System.out.print("\010");
    // Code to clear doskey on win nt/2000 - Alt+F7
    String os = System.getProperty("os.name");
    if (os != null && os.toLowerCase().startsWith("windows")) {
      try {
        java.awt.Robot robot = new java.awt.Robot();
        robot.keyPress(java.awt.event.KeyEvent.VK_ALT);
        robot.keyPress(java.awt.event.KeyEvent.VK_F7);
        robot.keyRelease(java.awt.event.KeyEvent.VK_F7);
        robot.keyRelease(java.awt.event.KeyEvent.VK_ALT);
      } catch (Exception ignore) {
        logger.warning("Could not clears command history: " + ignore);
      }
    }

    if (offset == 0) {
      return null;
    }
    char[] ret = new char[offset];
    System.arraycopy(buf, 0, ret, 0, offset);
    Arrays.fill(buf, ' ');
    return ret;
  }
コード例 #10
0
  @Override
  public void run() {
    try {
      socketInput =
          new BufferedReader(
              new InputStreamReader(
                  connectionSocket.getInputStream())); // get the inputstream from other peer
      pieceReader =
          connectionSocket
              .getInputStream(); // return an input stream for reading bytes from this socket.
      socketOutput =
          new DataOutputStream(
              connectionSocket.getOutputStream()); // get the outputstream to others
      // return an output stream for writing bytes to this socket.
    } catch (IOException ex) {
      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
    }

    // TCP handshake
    if (OtherPeerID != -1) {
      try {
        socketOutput.writeBytes(handshakeMsg);
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }

      try {
        while (socketInput.ready() == false) {}

      } catch (Exception e) {
      }
      try {
        checkHandShakeMsg = socketInput.readLine() + "";
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
      checkHandShakeHeader = checkHandShakeMsg.substring(0, 18);
      OtherPeerID = Integer.parseInt(checkHandShakeMsg.substring(28, 32));

    } else // ackhandshake
    {

      try {
        while (socketInput.ready() == false) {}

      } catch (Exception e) {
      }

      try {
        checkHandShakeMsg = socketInput.readLine() + "";
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
      checkHandShakeHeader = checkHandShakeMsg.substring(0, 18);
      OtherPeerID = Integer.parseInt(checkHandShakeMsg.substring(28, 32));

      if (checkHandShakeHeader.equals(handshakeheader)) {

        try { // if it is the right neighbour, write log that peer1 is connected from peer2
          peerProcess.logfile.write(LogWriter.logmsg(1, peerProcess.myPeerID, OtherPeerID));
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }

        try {

          socketOutput.writeBytes(handshakeMsg);
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }

    // start transferring
    try {
      while (quited == false
          && (peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainAll() == false
              || peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).obtainAll() == false)) {

        try {
          socketOutput.writeBytes(peerNotExitMsg);
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " sent not quit message to peer "
                  + OtherPeerID
                  + ".");
        } catch (Exception e) {
        }
        try {
          while (socketInput.ready() == false) {
            //
          }
        } catch (Exception e) {
        }
        try {
          MsgFromOtherPeer = socketInput.readLine() + "";
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        // get the corresponding message length, message type and message payload
        RecvdMsg = MsgFromOtherPeer.split("#");
        msgLen = Integer.parseInt(RecvdMsg[0]);
        msgType = Integer.parseInt(RecvdMsg[1]);
        msgPayload = RecvdMsg[2];
        if (msgType == 8) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received quit message from peer "
                  + OtherPeerID
                  + ".");
          quited = true;
          break;
        } else if (msgType != 9) {
          System.out.println(
              "Received message type " + msgType + ", expecting quit/not quit message.");
        } else {
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received not quit message from peer "
                  + OtherPeerID
                  + ".");
        }

        // bitField exchange
        try {
          mybitfield =
              peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainBitField();
          haveMsg = mybitfield.length() + "#" + 4 + "#" + mybitfield + "\n";
          socketOutput.writeBytes(haveMsg);
          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " sent bitfield message to peer "
                  + OtherPeerID
                  + ".");
        } catch (Exception e) {
        }
        try {
          while (socketInput.ready() == false) {}

        } catch (Exception e) {
        }
        try {
          MsgFromOtherPeer = socketInput.readLine() + "";
        } catch (IOException ex) {
          Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
        }
        RecvdMsg = MsgFromOtherPeer.split("#");
        msgLen = Integer.parseInt(RecvdMsg[0]);
        msgType = Integer.parseInt(RecvdMsg[1]);
        msgPayload = RecvdMsg[2];
        if (msgType == 4) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received bitField message from peer "
                  + OtherPeerID
                  + ".");
          peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
        } else if (msgType == 8) {

          System.out.println(
              "Peer "
                  + peerProcess.myPeerID
                  + " received quit message from peer "
                  + OtherPeerID
                  + ".");
          quited = true;
          break;
        } else {
          System.out.println(" received message type " + msgType + ", expecting bitField message.");
        }

        if (peerProcess.choked[OtherPeerID % 1000 - 1] == false) {
          try {

            socketOutput.writeBytes(unchokedMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          mybitfield =
              peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).obtainBitField();
          haveMsg = mybitfield.length() + "#" + 4 + "#" + mybitfield + "\n";
          try {

            socketOutput.writeBytes(haveMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }

          try {
            while (socketInput.ready() == false) {}

          } catch (Exception e) {
          }
          try {
            MsgFromOtherPeer = socketInput.readLine();
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          RecvdMsg = MsgFromOtherPeer.split("#");
          msgLen = Integer.parseInt(RecvdMsg[0]);
          msgType = Integer.parseInt(RecvdMsg[1]);
          msgPayload = RecvdMsg[2];
          if (msgType == 1) {
            try {
              peerProcess.logfile.write(LogWriter.logmsg(3, peerProcess.myPeerID, OtherPeerID));
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
              while (socketInput.ready() == false) {}
            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine();
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 4) {
              peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
              interestedPieceID =
                  peerProcess
                      .Peers
                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                      .obtainInterestedPiece(OtherPeerID);
              try {
                if (interestedPieceID != -1)
                  peerProcess.logfile.write(
                      LogWriter.logmsg(5, peerProcess.myPeerID, OtherPeerID, interestedPieceID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
              if (interestedPieceID == -1) {
                try {
                  socketOutput.writeBytes(1 + "#" + 3 + "#" + "-1\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}
                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 2) {
                  try {
                    peerProcess.logfile.write(
                        LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
                  piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
                  try {
                    socketOutput.writeBytes(piecemsg);

                    while (socketInput.ready() == false) {}

                    try {
                      MsgFromOtherPeer = socketInput.readLine();
                    } catch (Exception e) {
                    }
                    RecvdMsg = MsgFromOtherPeer.split("#");
                    msgLen = Integer.parseInt(RecvdMsg[0]);
                    msgType = Integer.parseInt(RecvdMsg[1]);
                    msgPayload = RecvdMsg[2];
                    if (msgType == 10) {

                      socketOutput.write(piececontent);

                      while (socketInput.ready() == false) {}

                      try {
                        MsgFromOtherPeer = socketInput.readLine();
                      } catch (Exception e) {
                      }
                      RecvdMsg = MsgFromOtherPeer.split("#");
                      msgLen = Integer.parseInt(RecvdMsg[0]);
                      msgType = Integer.parseInt(RecvdMsg[1]);
                      msgPayload = RecvdMsg[2];
                      if (msgType != 10) {
                        System.out.println(
                            "received message type "
                                + msgType
                                + ", expecting channel clear message.");
                      }
                      continue;
                    } else {
                      System.out.println(
                          "received message type "
                              + msgType
                              + ", expecting channel clear message.");
                    }
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                } else if (msgType == 3) {
                  try {

                    peerProcess.logfile.write(
                        LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                }
              } else {
                try {
                  socketOutput.writeBytes(1 + "#" + 2 + "#" + interestedPieceID + "\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}
                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 2) {
                  byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
                  piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
                  try {
                    try {
                      peerProcess.logfile.write(
                          LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
                    } catch (IOException ex) {
                      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    socketOutput.writeBytes(piecemsg);

                    while (socketInput.ready() == false) {}
                    try {
                      MsgFromOtherPeer = socketInput.readLine();
                    } catch (Exception e) {
                    }
                    RecvdMsg = MsgFromOtherPeer.split("#");
                    msgLen = Integer.parseInt(RecvdMsg[0]);
                    int indexFromOther = msgLen;
                    msgType = Integer.parseInt(RecvdMsg[1]);
                    msgPayload = RecvdMsg[2];
                    int loadsize = Integer.parseInt(msgPayload);
                    byte[] mspiececon = new byte[loadsize];
                    if (msgType == 7) {
                      if (peerProcess.myPeerID < OtherPeerID) {

                        socketOutput.writeBytes(channelClearMsg);

                        while (pieceReader.available() <= 0) {}

                        int totallen = 0;
                        byte[] c = new byte[1];
                        while (totallen < loadsize) {
                          try {
                            pieceReader.read(c);
                          } catch (Exception e) {
                          }
                          mspiececon[totallen] = c[0];
                          totallen++;
                        }
                        socketOutput.write(piececontent);
                        try {

                          peerProcess.writebackPiece(indexFromOther, mspiececon);
                          peerProcess.logfile.write(
                              LogWriter.logmsg(
                                  8,
                                  peerProcess.myPeerID,
                                  OtherPeerID,
                                  interestedPieceID,
                                  peerProcess
                                      .Peers
                                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                                      .hasHowManyPieces()));

                          if (peerProcess
                                  .Peers
                                  .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                                  .obtainAll()
                              == true) {
                            try {
                              peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                            } catch (Exception e) {
                            }
                          }
                        } catch (IOException ex) {
                          Logger.getLogger(SocketThread.class.getName())
                              .log(Level.SEVERE, null, ex);
                        }

                        while (socketInput.ready() == false) {}

                        try {
                          MsgFromOtherPeer = socketInput.readLine();
                        } catch (Exception e) {
                        }
                        RecvdMsg = MsgFromOtherPeer.split("#");
                        msgLen = Integer.parseInt(RecvdMsg[0]);
                        msgType = Integer.parseInt(RecvdMsg[1]);
                        msgPayload = RecvdMsg[2];
                        if (msgType != 10) {
                          System.out.println(
                              "Expecting channel clear message, received message type " + msgType);
                        }
                        continue;
                      } else {

                        while (socketInput.ready() == false) {}

                        try {
                          MsgFromOtherPeer = socketInput.readLine();
                        } catch (Exception e) {
                        }
                        RecvdMsg = MsgFromOtherPeer.split("#");
                        msgLen = Integer.parseInt(RecvdMsg[0]);
                        msgType = Integer.parseInt(RecvdMsg[1]);
                        msgPayload = RecvdMsg[2];
                        if (msgType == 10) {

                          socketOutput.write(piececontent);

                          while (pieceReader.available() <= 0) {}

                          int totallen = 0;
                          byte[] c = new byte[1];
                          while (totallen < loadsize) {
                            try {
                              pieceReader.read(c);
                            } catch (Exception e) {
                            }
                            mspiececon[totallen] = c[0];
                            totallen++;
                          }
                          socketOutput.writeBytes(channelClearMsg);
                          try {

                            peerProcess.writebackPiece(indexFromOther, mspiececon);
                            peerProcess.logfile.write(
                                LogWriter.logmsg(
                                    8,
                                    peerProcess.myPeerID,
                                    OtherPeerID,
                                    interestedPieceID,
                                    peerProcess
                                        .Peers
                                        .elementAt(peerProcess.myPeerID % 1000 - 1)
                                        .hasHowManyPieces()));

                            if (peerProcess
                                    .Peers
                                    .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                                    .obtainAll()
                                == true) {
                              try {
                                peerProcess.logfile.write(
                                    LogWriter.logmsg(9, peerProcess.myPeerID));
                              } catch (Exception e) {
                              }
                            }
                          } catch (IOException ex) {
                            Logger.getLogger(SocketThread.class.getName())
                                .log(Level.SEVERE, null, ex);
                          }
                          continue;
                        } else {
                          System.out.println(
                              "Expecting channel clear message, received message type " + msgType);
                        }
                      }
                    } else {
                      System.out.println(
                          "Expecting piecemessage, received message type " + msgType);
                    }

                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                } else if (msgType == 3) {
                  try {

                    peerProcess.logfile.write(
                        LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  try {

                    MsgFromOtherPeer = socketInput.readLine() + "";
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  RecvdMsg = MsgFromOtherPeer.split("#");
                  msgLen = Integer.parseInt(RecvdMsg[0]);
                  int indexFromOther = msgLen;
                  msgType = Integer.parseInt(RecvdMsg[1]);
                  msgPayload = RecvdMsg[2];
                  int loadsize = Integer.parseInt(msgPayload);
                  byte[] mspiececon = new byte[loadsize];
                  if (msgType == 7) {
                    socketOutput.writeBytes(channelClearMsg);

                    while (pieceReader.available() <= 0) {}
                    int totallen = 0;
                    byte[] c = new byte[1];
                    while (totallen < loadsize) {
                      try {
                        pieceReader.read(c);
                      } catch (Exception e) {
                      }
                      mspiececon[totallen] = c[0];
                      totallen++;
                    }
                    socketOutput.writeBytes(channelClearMsg);
                    try {

                      peerProcess.writebackPiece(indexFromOther, mspiececon);
                      peerProcess.logfile.write(
                          LogWriter.logmsg(
                              8,
                              peerProcess.myPeerID,
                              OtherPeerID,
                              interestedPieceID,
                              peerProcess
                                  .Peers
                                  .elementAt(peerProcess.myPeerID % 1000 - 1)
                                  .hasHowManyPieces()));

                      if (peerProcess
                              .Peers
                              .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                              .obtainAll()
                          == true) {
                        try {
                          peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                        } catch (Exception e) {
                        }
                      }
                    } catch (IOException ex) {
                      Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                    }
                    continue;
                  } else {
                    System.out.println(
                        "Expecting piece data, received message type" + msgType + ".");
                  }
                }
              }
            }
          } else if (msgType == 0) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(4, peerProcess.myPeerID, OtherPeerID));
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }

            try {
              while (socketInput.ready() == false) {}

            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine();
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 2) {
              byte[] piececontent = peerProcess.obtainPiece(Integer.parseInt(msgPayload));
              piecemsg = msgPayload + "#" + 7 + "#" + piececontent.length + "\n";
              try {
                socketOutput.writeBytes(piecemsg);

                while (socketInput.ready() == false) {}

                try {
                  MsgFromOtherPeer = socketInput.readLine();
                } catch (Exception e) {
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                if (msgType == 10) {

                  socketOutput.write(piececontent);

                  while (socketInput.ready() == false) {}

                  try {
                    MsgFromOtherPeer = socketInput.readLine();
                  } catch (Exception e) {
                  }
                  RecvdMsg = MsgFromOtherPeer.split("#");
                  msgLen = Integer.parseInt(RecvdMsg[0]);
                  msgType = Integer.parseInt(RecvdMsg[1]);
                  msgPayload = RecvdMsg[2];
                  if (msgType != 10) {
                    System.out.println(
                        "Expecting channel clear message, received message type " + msgType);
                  }
                  continue;
                } else {
                  System.out.println(
                      "Expecting channel clear message, received message type " + msgType);
                }
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
              try {
                peerProcess.logfile.write(LogWriter.logmsg(6, peerProcess.myPeerID, OtherPeerID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
            } else if (msgType == 3) {
              try {

                peerProcess.logfile.write(LogWriter.logmsg(7, peerProcess.myPeerID, OtherPeerID));
              } catch (IOException ex) {
                Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
              }
            }
          } else {
            continue;
          }
        } else {
          try {
            socketOutput.writeBytes(chokedMsg);
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }

          try {
            while (socketInput.ready() == false) {}

          } catch (Exception e) {
          }
          try {
            MsgFromOtherPeer = socketInput.readLine() + "";
          } catch (IOException ex) {
            Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
          }
          RecvdMsg = MsgFromOtherPeer.split("#");
          msgLen = Integer.parseInt(RecvdMsg[0]);
          msgType = Integer.parseInt(RecvdMsg[1]);
          msgPayload = RecvdMsg[2];
          if (msgType == 0) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(4, peerProcess.myPeerID, OtherPeerID));
            } catch (Exception e) {
            }

            continue;
          } else if (msgType == 1) {

            try {
              peerProcess.logfile.write(LogWriter.logmsg(3, peerProcess.myPeerID, OtherPeerID));
            } catch (Exception e) {
            }
            try {
              while (socketInput.ready() == false) {}

            } catch (Exception e) {
            }
            try {
              MsgFromOtherPeer = socketInput.readLine() + "";
            } catch (IOException ex) {
              Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
            }
            RecvdMsg = MsgFromOtherPeer.split("#");
            msgLen = Integer.parseInt(RecvdMsg[0]);
            msgType = Integer.parseInt(RecvdMsg[1]);
            msgPayload = RecvdMsg[2];
            if (msgType == 4) {

              peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setTheBitField(msgPayload);
              interestedPieceID =
                  peerProcess
                      .Peers
                      .elementAt(peerProcess.myPeerID % 1000 - 1)
                      .obtainInterestedPiece(OtherPeerID);
              try {

                if (interestedPieceID != -1)
                  peerProcess.logfile.write(
                      LogWriter.logmsg(5, peerProcess.myPeerID, OtherPeerID, interestedPieceID));
              } catch (Exception e) {
              }
              if (interestedPieceID == -1) {
                try {
                  socketOutput.writeBytes(1 + "#" + 3 + "#" + "-1\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
              } else {
                try {
                  socketOutput.writeBytes(1 + "#" + 2 + "#" + interestedPieceID + "\n");
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }

                try {
                  while (socketInput.ready() == false) {}

                } catch (Exception e) {
                }
                try {
                  MsgFromOtherPeer = socketInput.readLine() + "";
                } catch (IOException ex) {
                  Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                }
                RecvdMsg = MsgFromOtherPeer.split("#");
                msgLen = Integer.parseInt(RecvdMsg[0]);
                int indexFromOther = msgLen;
                msgType = Integer.parseInt(RecvdMsg[1]);
                msgPayload = RecvdMsg[2];
                int loadsize = Integer.parseInt(msgPayload);
                byte[] mspiececon = new byte[loadsize];
                if (msgType == 7) {
                  socketOutput.writeBytes(channelClearMsg);

                  while (pieceReader.available() <= 0) {}
                  int totallen = 0;
                  byte[] c = new byte[1];
                  while (totallen < loadsize) {
                    try {
                      pieceReader.read(c);
                    } catch (Exception e) {
                    }
                    mspiececon[totallen] = c[0];
                    totallen++;
                  }
                  socketOutput.writeBytes(channelClearMsg);
                  try {

                    peerProcess.writebackPiece(indexFromOther, mspiececon);
                    peerProcess.logfile.write(
                        LogWriter.logmsg(
                            8,
                            peerProcess.myPeerID,
                            OtherPeerID,
                            interestedPieceID,
                            peerProcess
                                .Peers
                                .elementAt(peerProcess.myPeerID % 1000 - 1)
                                .hasHowManyPieces()));

                    if (peerProcess
                            .Peers
                            .elementAt(peerProcess.myPeerID % peerIDBase - 1)
                            .obtainAll()
                        == true) {
                      try {
                        peerProcess.logfile.write(LogWriter.logmsg(9, peerProcess.myPeerID));
                      } catch (Exception e) {
                      }
                    }
                  } catch (IOException ex) {
                    Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
                  }
                  continue;
                } else {
                  System.out.println("received msg type " + msgType + ", expecting piece data.");
                }
              }

            } else {
              System.out.println("received msg type " + msgType + ", expecting have msg.");
            }
          } else {
            System.out.println("received msg type " + msgType + ", expecting choke/unchoke msg.");
          }
        }
      }
    } catch (Exception ite) {
    }

    if (quited == false) {

      try {
        socketOutput.writeBytes(peerExitMsg);
        System.out.println(
            "Peer " + peerProcess.myPeerID + " sent quit message to peer " + OtherPeerID + ".");
        try {
          Thread.sleep(100);
        } catch (Exception e) {
        }
      } catch (IOException ex) {
        Logger.getLogger(SocketThread.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    System.out.println(
        "The socket between peer"
            + peerProcess.myPeerID
            + "and peer "
            + OtherPeerID
            + " will disconnect now.\n");
    peerProcess.Peers.elementAt(OtherPeerID % 1000 - 1).setHasAllPieces();
    peerProcess.Peers.elementAt(peerProcess.myPeerID % 1000 - 1).setHasAllPieces();
  }