예제 #1
0
  /**
   * A "{" has been read. Read the rest of the size string, the space and then notify the callback
   * with an {@code InputStream}.
   */
  private Object parseLiteral() throws IOException {
    expect('{');
    int size = Integer.parseInt(readStringUntil('}'));
    expect('\r');
    expect('\n');

    if (size == 0) {
      return "";
    }

    if (response.getCallback() != null) {
      FixedLengthInputStream fixed = new FixedLengthInputStream(inputStream, size);

      Object result = null;
      try {
        result = response.getCallback().foundLiteral(response, fixed);
      } catch (IOException e) {
        // Pass IOExceptions through
        throw e;
      } catch (Exception e) {
        // Catch everything else and save it for later.
        exception = e;
      }

      // Check if only some of the literal data was read
      int available = fixed.available();
      if (available > 0 && available != size) {
        // If so, skip the rest
        while (fixed.available() > 0) {
          fixed.skip(fixed.available());
        }
      }

      if (result != null) {
        return result;
      }
    }

    byte[] data = new byte[size];
    int read = 0;
    while (read != size) {
      int count = inputStream.read(data, read, size - read);
      if (count == -1) {
        throw new IOException("parseLiteral(): end of stream reached");
      }
      read += count;
    }

    return new String(data, "US-ASCII");
  }