⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 httpio.java

📁 java实现的P2P多agent中间件
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
    if(line==null) throw new IOException();
    StringTokenizer st = new StringTokenizer(line);
    try {

      if(!(st.nextToken()).equalsIgnoreCase(POST_STR) ) { 
        if(logger.isLoggable(Logger.WARNING))
        	logger.log(Logger.WARNING,"Malformed POST");

        type.append(CLOSE);
        return ERROR;
      }
      st.nextToken(); // Consumme a token
      if(!(st.nextToken().toUpperCase().startsWith("HTTP/1."))) { 
        if(logger.isLoggable(Logger.WARNING))
        	logger.log(Logger.WARNING,"Malformed HTTP/1.1 ");
        type.append(CLOSE);
        return ERROR;
      }
    }
    catch(NoSuchElementException nsee) {
      if(logger.isLoggable(Logger.WARNING))
      	logger.log(Logger.WARNING,"Malformed start line !: "+line);
      type.append(CLOSE);
      return ERROR;
    }
    //Process rest of header
    while (!BLK.equals(line=readLineFromInputStream(input))) {
      String lowerCaseLine = line.toLowerCase();
      if (lowerCaseLine.startsWith(HOST_STR.toLowerCase())) {
        host = processLine(line); //De momento solo controlamos que este
      }
      /* // NL do not test MIME version for interoperability with other MTP 
         if (line.toLowerCase().startsWith(MIME.toLowerCase())) {		  
         foundMime = true;
         }
      */
      if (lowerCaseLine.startsWith(CONN_STR.toLowerCase())) {
        typeConnection= processLine(line);
      }
      if (lowerCaseLine.startsWith(CONTENT_STR.toLowerCase())) {	
        //Process the left part

        if (!(processLine(line).toLowerCase().startsWith(MM_STR))) {
          if(logger.isLoggable(Logger.WARNING))
          	logger.log(Logger.WARNING,"MULTIPART/MIXED");

          type.append(CLOSE);
          return ERROR;
        }
        //Process the right part
        int pos = line.indexOf(BND_STR);
        if (pos == -1) {
          // Boundary on next line
          line=readLineFromInputStream(input);
          if ((pos = line.indexOf(BND_STR)) == -1) {
            // Bounday not found
            if(logger.isLoggable(Logger.WARNING))
            	logger.log(Logger.WARNING,"MIME boundary not found");
            type.append(CLOSE);
            return ERROR;
          }
        }
        line = line.substring(pos+BND_STR.length());
        pos = line.indexOf("\"")+1;
        boundary = DL_STR+line.substring(pos,line.indexOf("\"",pos));
        foundBoundary = true;
      }
    }//end while
    //if( !foundBoundary || !foundMime) {
    if(!foundBoundary) {
      if(logger.isLoggable(Logger.WARNING))
      	logger.log(Logger.WARNING,"Mime header error");
      type.append(CLOSE);
      return ERROR;
    }
    if (typeConnection == null) {
      type.append(KA); //Default Connection
    }	
    else {
      type.append(typeConnection); //Connection of request
    }
    //jump to first  "--Boundary" 
    while(BLK.equals(line=readLineFromInputStream(input))); // skip empty lines
    do {
      if (line.startsWith(boundary)) { 
        break;
      }
    }
    while(!BLK.equals(line=readLineFromInputStream(input)));
    while(BLK.equals(line=readLineFromInputStream(input))); // skip empty lines
    // Skip content-type
    do {    
      if(line.toLowerCase().startsWith(CONTENT_STR.toLowerCase())) { 
        break;
      }
    }
    while(!BLK.equals(line=readLineFromInputStream(input)));
    //Capture the XML part
    //Capture the message envelope
    while(!boundary.equals(line=readLineFromInputStream(input))) {
      if (! line.equals(BLK)) {
        xml.append(line); 
      }
    }
    //Capture the ACL part
    //JMP to ACLMessage
    while(BLK.equals(line=readLineFromInputStream(input))); // skip empty lines
    // Skip content-type
    do {    
      if(line.toLowerCase().startsWith(CONTENT_STR.toLowerCase())) { 
        break;
      }
    }
    while(!BLK.equals(line=readLineFromInputStream(input)));
    //Create last boundary for capture the ACLMessage
    ByteArrayOutputStream boundaryPattern = new ByteArrayOutputStream(boundary.length()+6);
    boundaryPattern.write(CRLF);
    boundaryPattern.write(boundary.getBytes("ISO-8859-1"));
    boundaryPattern.write(DL);
    //Capture the acl part.
    int character = -1;
    while(((character = input.read()) == CR ) || (character == LF)) {};  // Dirty hack: Skip leading blank lines.
    if (character >= 0) {
      acl.write(character);
      readBytesUpTo(input,acl,boundaryPattern.toByteArray());
    }
    return OK;
    /*
      }
      catch(NullPointerException npe) {
      // readLine returns null <--> EOF
      System.out.println("null pointer in readAll");
      //npe.printStackTrace();
      type.append(CLOSE);
      return ERROR;
      }
    */
  }
  
    
  /** 
   * Capture and return the code of response message, this message is received from client 
   */  
  public static int getResponseCode(InputStream input, StringBuffer type) 
    throws IOException {
    int responseCode = -1;
    try {
      String line = null; 
      //Capture and process the response message
      while (!(line=readLineFromInputStream(input)).startsWith(HTTP1));
      //capture the response code	     
      responseCode= Integer.parseInt(processLine(line));
      //Read all message
      while(((line=readLineFromInputStream(input))!=null)&&(!line.equals(BLK))) {
        if (line.toLowerCase().startsWith(CONN_STR.toLowerCase())) {
          type.append(processLine(line));
        }
        else if (line.toLowerCase().startsWith(PROXY_STR.toLowerCase())) {
          type.append(processLine(line));
        }
      }
      if (type.length() == 0) {
        type.append(KA); //Default Connection type  
      }
      return responseCode;
    }
    catch(Exception e) {
      // Connection has been closed before we receive confirmation.
      // We do cannot know if message has been received
      type.append(CLOSE);
      return responseCode; // NOT OK
    }
  }
  
   
  /** 
   * return the next information of search in the line
   */
  private static String processLine(String line) 
    throws IOException {  
    StringTokenizer st = new StringTokenizer(line);
    try {
      st.nextToken(); // Consumme first token
      return st.nextToken();
    }
    catch(NoSuchElementException nsee) {
      throw new IOException("Malformed line !: "+line);
    }
  }

  /**
   * Reads byte sequence from specified input stream into specified output stream up to specified
   * byte sequence pattern is occurred. The output byte sequence does not contains any bytes matched
   * with pattern. If the specified pattern was not found until the input stream reaches at end, output
   * all byte sequence up to end of input stream and returns false.
   *
   * @param input specified input stream.
   * @param output specified output stream.
   * @param pattern specified pattern byte seqence.
   * @return Whether the specified pattern was found or not.
   * @throws IOException  If an I/O error occurs.
   * @throws IllegalArgumentException If pattern is null or pattern is empty.
   * @author mminagawa
   */
  private static boolean readBytesUpTo(InputStream input, OutputStream output, byte[] pattern) throws IOException {
    if ((pattern == null) || (pattern.length == 0)) {
      throw new IllegalArgumentException("Specified pattern is null or empty.");
    }
    int patternIndex = 0;
    boolean matched = false;
    boolean atEnd = false;
    while ((!matched) && (!atEnd)) {
      int readByte = input.read();
      if (readByte < 0) {
        atEnd = true;
        if (patternIndex != 0) {
          output.write(pattern,0,patternIndex);
          patternIndex = 0;
        }
      } else {
        if (readByte == pattern[patternIndex]) {
          patternIndex++;
          if (patternIndex >= pattern.length) {
            matched = true;
          }
        } else {
          if (patternIndex != 0) {
			output.write(pattern,0,patternIndex);
			patternIndex = 0;
          }
          output.write(readByte);
        }
      }
    }
    return matched;
  }

  /**
   * Read a line of text from specified input stream.  A line is considered to be
   * terminated by a carriage return ('\r') followed immediately by a linefeed ('\n').
   *
   * @param input specified input stream to read from.
   * @return A String containing the contents of the line, not including any line-termination
   *          characters, or null if the end of the stream has been reached.
   * @throws IOException  If an I/O error occurs.
   * @author mminagawa
   */
  private static String readLineFromInputStream(InputStream input) throws IOException {
    StringBuffer buffer = new StringBuffer(256);
    int characterByte;
    boolean justBeforeCR = false;
    boolean terminated = false;
    boolean entered = false;
    while ((!terminated) && ((characterByte = input.read()) >= 0)) {
      entered = true;
      switch (characterByte) {
      case CR :
        if (justBeforeCR) {
          buffer.append((char)CR);
        } else {
          justBeforeCR = true;
        }
        break;
      case LF :
        if (justBeforeCR) {
          terminated = true;
        } else {
          buffer.append((char)LF);
        }
		justBeforeCR = false;
        break;
      default :
        if (justBeforeCR) { buffer.append((char)CR); }
        buffer.append((char)characterByte);
        justBeforeCR = false;
      }
    }
    if (!entered) { return null; }
    if ((!terminated) && (justBeforeCR)) {
      buffer.append((char)CR);
    }
    return buffer.toString();
  }

  /**
   * Write characters contained specified string to specified output stream.<br />
   * These characters must be 7-bit character, and stored only low-byte of each code.
   *
   * @param output specified output stream.
   * @param string specified string to output.
   * @throws IOException  If an I/O error occurs.
   * @author mminagawa
   */
  private static void writeLowBytes(OutputStream output, String string) throws IOException {
    for (int i = 0 ; i < string.length() ; i++ ) {
      output.write(string.charAt(i));
    }
  }

} // End of HTTPIO class 


⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -