/* This method will not return until len bytes have been read
or the stream has been closed.
321215
public synchronized int read( byte[] b, int off, int len ) throws IOException {
        if( len == 0 ) {
            return 0;
        }
        tot = 0;

        while( true ) {
            while( bip > 0 ) {
                n = in.read( b, off, Math.min( len, bip ));
                if( n == -1 ) {
                    return tot > 0 ? tot : -1;
                }
                tot += n;
                off += n;
                len -= n;
                bip -= n;
                if( len == 0 ) {
                    return tot;
                }
            }

            switch( SessionServicePacket.readPacketType( in, header, 0 )) {
                case SessionServicePacket.SESSION_KEEP_ALIVE:
                    break;
                case SessionServicePacket.SESSION_MESSAGE:
                    bip = SessionServicePacket.readLength( header, 0 );
                    break;
                case -1:
                    if( tot > 0 ) {
                        return tot;
                    }
                    return -1;
            }
        }
    }
1134955
public int readTimeout(byte []buf, int offset, int length, long timeout)
    throws IOException
  {
    if (_s == null || _is == null)
      return -1;

    int oldTimeout = _s.getSoTimeout();

    try {
      _s.setSoTimeout((int) timeout);

      int readLength = read(buf, offset, length);

      return readLength;
    } finally {
      _s.setSoTimeout(oldTimeout);
    }
  }
342506
def read_until(stream, delimiter, max_bytes=16):
    

    buf = bytearray()
    delim_len = len(delimiter)

    while len(buf) < max_bytes:
        c = stream.read(1)

        if not c:
            break

        buf += c
        if buf[-delim_len:] == delimiter:
            return bytes(buf[:-delim_len])
652946
@Override
	public int read(char[] cbuf, int off, int len) throws IOException {
		try {
			if (closed) {
				throw new IOException("Attempt to read from a closed stream"); //$NON-NLS-1$
			}
			if (eof) {
				return -1;
			}
			if (curr == null) {
				curr = getNextInputReader();
				if (curr == null) {
					eof = true;
					return -1;
				}
			}
			int size, bytesRead = 0, bytesToRead = len;
			while (!eof && bytesRead < bytesToRead) {
				size = curr
						.read(cbuf, off + bytesRead, bytesToRead - bytesRead);
				if (size == -1) {
					curr.close();
					curr = getNextInputReader();
					if (curr == null) {
						eof = true;
					}
				} else {
					bytesRead += size;
				}
			}
			return bytesRead;
		} catch (IOException e) {
			throw e;
		} catch (Exception e) {
			throw new IOException(e);
		}
	}
102036
@Override
  public synchronized int read(byte buf[], int off, int len) throws IOException {
    dfsClient.checkOpen();
    if (closed) {
      dfsClient.incReadExpCntToStats();

      throw new IOException("Stream closed");
    }
    DFSClient.dfsInputStreamfailures.set(0);
    long start = System.currentTimeMillis();
    
    if (pos < getFileLength() || (pos == getFileLength() && len == 0)) {
      int retries = 2;
      while (retries > 0) {
        try {
          // If position equals or is larger than the end position of the
          // block, we try to seek to the next block, unless:
          // 1. user tries to read 0 bytes (usually by available() call), AND
          // 2. there is at least a known block for the file (blockEnd != -1), AND
          // 3. pos is the end of the file, AND
          // 4. the end of the block is the end of the file
          //    (the current block is the known last block of the file)
          // For this case, we want to stay in the current block, as in the case
          // that it is the last block (which is almost always true given
          // len == 0), the current block is the under-construction block whose size
          // you want to update.
          //
          if (len == 0) { // called by available()
            if (blockEnd == -1 // No current block selected
                || pos == getFileLength()) { // at the end of the file
              currentNode = blockSeekTo(pos, false);
              if (currentNode == null) {
                // In this case, user wants to know available information of
                // the file, but the file doesn't have any block created yet (it
                // is a 0 size file). Simply 0 should be returned.
                return 0;
              }
            } else {
              throw new IOException(
                  "Try to read 0 bytes while current position is not the end of the file");
            }
          } else if (pos > blockEnd
              || (this.isCurrentBlockUnderConstruction && blockReader != null
                  && blockReader.eos && blockReader.available() == 0)) {
            currentNode = blockSeekTo(pos, true);
          }
          
          int realLen = (int) Math.min((long) len, (blockEnd - pos + 1L));
          int result = readBuffer(buf, off, realLen);

          if (result >= 0) {
            pos += result;
          } else if (len != 0){
            // got a EOS from reader though we expect more data on it.
            throw new IOException("Unexpected EOS from the reader");
          }
          if (dfsClient.stats != null && result != -1) {
            dfsClient.stats.incrementBytesRead(result);
          }
          long timeval = System.currentTimeMillis() - start;
          dfsClient.metrics.incReadTime(timeval);
          dfsClient.metrics.incReadSize(result);
          dfsClient.metrics.incReadOps();
          return (result >= 0) ? result : 0;
        } catch (InterruptedIOException iie) {
          throw iie;
        } catch (ChecksumException ce) {
          dfsClient.incReadExpCntToStats();

          throw ce;
        } catch (IOException e) {
          dfsClient.incReadExpCntToStats();

          if (retries == 1) {
            DFSClient.LOG.warn("DFS Read: " + StringUtils.stringifyException(e));
          }
          blockEnd = -1;
          if (currentNode != null) { addToDeadNodes(currentNode); }
          if (--retries == 0) {
            if (len != 0) {
              throw e;
            } else {
              // When called by available(). No need to fail the query. In that case
              // available() value might not be updated, but it's OK.
              return 0;
            }
          }
        }
      }
    }
    return -1;
  }
1055961
@Override
  public int read(byte[] b, int off, int len) throws IOException {
    if (b == null) {
      throw new NullPointerException();
    } else if (off < 0 || len < 0 || len > b.length - off) {
      throw new IndexOutOfBoundsException();
    } else if (len == 0) {
      return 0;
    }
    if (endOfInput && !bbuf.hasRemaining()) {
      return -1;
    }

    int totalRead = 0;
    while (len > 0 && !endOfInput) {
      if (bbuf.hasRemaining()) {
        int remaining = Math.min(len, bbuf.remaining());
        bbuf.get(b, off, remaining);
        totalRead += remaining;
        off += remaining;
        len -= remaining;
        if (len == 0) {
          return totalRead;
        }
      }
      advance();
    }
    if (endOfInput && !bbuf.hasRemaining() && totalRead == 0) {
      return -1;
    }
    return totalRead;
  }
868372
public static void readAndCloseStream(InputStream is) {
		final byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
		try {
			while (is.read(bytes, 0, DEFAULT_BUFFER_SIZE) != -1);
		} catch (IOException ignored) {
		} finally {
			closeSilently(is);
		}
	}
1242077
@Override
  public synchronized int available() throws IOException {
    if (closed) {
      throw new IOException("Stream closed");
    }
    long length = getFileLength() - pos;
    
    if (!isUnderConstruction() || length > 0) {
      return (int) length;
    }
    
    long timeNow = System.currentTimeMillis();
    if (timeShowNoAvailableByte != NOT_WAITING_FOR_MORE_BYTES
        && timeNow - timeShowNoAvailableByte > timeoutGetAvailFromDatanode) {
      if (DFSClient.LOG.isDebugEnabled()) {
        DFSClient.LOG
            .debug("To calculate available(), refetch metedata for file " + src);
      }
      // To avoid the minor case that:
      // (1) we stick to a datanode with a replica with older generation stamp
      // (2) after reopening the stream because of failure the file length is
      // (temporarily) smaller than current pos
      // after available value stays to be zero for a while, we re-fetch all the
      // metadata from the name node.
      //
      // The default value of timeoutGetAvailFromDatanode is set to be
      // relatively long to minimize namenode traffic in the case that
      // the the file is kept open with no new data for a long time. This
      // time out is the time bound of update delay of available in corner
      // cases.
      openInfo();
      // Force not to reuse the current block reader
      blockEnd = -1;
      // Reset the refetch metadata timer
      timeShowNoAvailableByte = NOT_WAITING_FOR_MORE_BYTES;
    }

    // In the case that file length shrinks after connection failure,
    // this call might always return -1 without updating the length.
    // In this case, we also reply on get available time out mechanism to
    // eventually make sure the stream is reopened and the client can read
    // data from it.
    read(DFSClient.emptyByteArray, 0, 0);
    
    long availableBytes = getFileLength() - pos;

    if (availableBytes > 0) {
      timeShowNoAvailableByte = NOT_WAITING_FOR_MORE_BYTES;
    } else if (timeShowNoAvailableByte == NOT_WAITING_FOR_MORE_BYTES) {
      timeShowNoAvailableByte = timeNow;
    }

    // Since the client might reopen the file because of exceptions
    // and refetch file length from another data node and gets a file
    // length that is smaller than current position. In this case, instead
    // of returning a negative value, return 0.
    return Math.max(0,
        (int) (Math.min(availableBytes, (long) Integer.MAX_VALUE)));
  }
670017
@Override
    public Buffer readBytes(final int length) throws IndexOutOfBoundsException, IOException {
        if (!checkReadableBytesSafe(length)) {
            final int availableBytes = getReadableBytes();
            final int read = internalReadBytes(length);
            if (read == -1) {
                // end-of-file
                return null;
            } else if (read + availableBytes < length) {
                // do something else?
                throw new IndexOutOfBoundsException("Not enough bytes left in the stream. Wanted " + length
                        + " but only read " + read);
            }
        }

        // perhaps we should create a composite buffer instead of this
        // copying???
        int index = 0;
        final byte[] buf = new byte[length];
        while (index < length) {
            final int spaceLeft = getAvailableLocalReadingSpace();
            final int readAtMost = Math.min(length - index, spaceLeft);
            final int localIndex = getLocalReaderIndex();

            System.arraycopy(this.buffer, localIndex, buf, index, readAtMost);
            this.readerIndex += readAtMost;
            index += readAtMost;
        }
        return Buffers.wrap(buf);

    }
537169
@Override
    public int read() throws IOException {
        abortIfNeeded();
        int result;
        // If there are no more available bytes, mark that we are at the end of the stream.
        if (this.virtualAvailable <= 0) {
            result = -1;
        } else {
            // Otherwise, read a byte.
            result = this.decryptedContents.read();
        }

        // If we have not reached the end of the stream, decrement the number of available bytes.
        if (result != -1) {
            this.virtualAvailable--;
        } else {
            // If we are at the end of the stream, close it.
            this.virtualAvailable = 0;
            close();
        }

        return result;
    }
221919
@Override
    public int read(byte[] output) throws IOException {
        
        //Return -1 here because if we are closed or finished, we're at the end of the stream
        if(isClosed || isFinished()){
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Nothing to read, stream is closed : " + isClosed + ", or finished : " + isFinished());
            return -1;
        }
        
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, "read" , "SRTInputStream31.read(byte[])");
        }
        if(output == null){
            if (TraceComponent.isAnyTracingEnabled() && tc.isErrorEnabled())
                Tr.error(tc, "read.write.bytearray.null");
            throw new NullPointerException(Tr.formatMessage(tc, "read.write.bytearray.null"));
        }
        
        int returnSize = 0;
        
        if(this.request.isAsyncStarted() && (this.getReadListener()!= null)){
            synchronized(this){
                
                //Check if isReady had returned false. If it did then an IllegalArgumentException will be thrown if a listener is set
                isReadyFalseCheck();
                returnSize = super.read(output);
            }
        }else{
            returnSize = super.read(output);
        }
        
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, "read" , "SRTInputStream31.read(byte[]) : " + returnSize);
        }
        
        return returnSize;
    }
537443
private static void streamResource(ServiceRequestContext ctx, HttpResponseWriter res,
                                       ReadableByteChannel in, long remainingBytes) {

        final int chunkSize = (int) Math.min(8192, remainingBytes);
        final ByteBuf buf = ctx.alloc().buffer(chunkSize);
        final int readBytes;
        boolean success = false;
        try {
            readBytes = read(in, buf);
            if (readBytes < 0) {
                // Should not reach here because we only read up to the end of the stream.
                // If reached, it may mean the stream has been truncated.
                throw new EOFException();
            }
            success = true;
        } catch (Exception e) {
            close(res, in, e);
            return;
        } finally {
            if (!success) {
                buf.release();
            }
        }

        final long nextRemainingBytes = remainingBytes - readBytes;
        final boolean endOfStream = nextRemainingBytes == 0;
        if (readBytes > 0) {
            if (!res.tryWrite(new ByteBufHttpData(buf, endOfStream))) {
                close(in);
                return;
            }
        } else {
            buf.release();
        }

        if (endOfStream) {
            close(res, in);
            return;
        }

        res.onDemand(() -> {
            try {
                ctx.blockingTaskExecutor().execute(() -> streamResource(ctx, res, in, nextRemainingBytes));
            } catch (Exception e) {
                close(res, in, e);
            }
        });
    }
1007705
byte[] readAndClose(InputStream input) throws IOException {
        byte[] buffer = new byte[512];
        ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.length);
        int read;
        try {
            read = input.read(buffer); //assignment separate from loop invariant check for code coverage checks
            while (read != -1) {
                out.write(buffer, 0, read);
                read = input.read(buffer);
            }
        } finally {
            Objects.nullSafeClose(input);
        }
        return out.toByteArray();
    }
902201
public int read(byte []buffer, int offset, int length, long timeout)
    throws IOException
  {
    if (length == 0) {
      throw new IllegalArgumentException();
    }

    long requestExpireTime = _requestExpireTime;

    if (requestExpireTime > 0 && requestExpireTime < CurrentTime.currentTime()) {
      close();
      throw new ClientDisconnectException(L.l("{0}: request-timeout read",
                                              addressRemote()));
    }

    int result = 0;

    synchronized (_readLock) {
      long now = CurrentTime.getCurrentTimeActual();

      long expires;

      // gap is because getCurrentTimeActual() isn't exact
      long gap = 20;

      if (timeout >= 0)
        expires = timeout + now - gap;
      else
        expires = _socketTimeout + now - gap;

      do {
        result = readNative(_socketFd, buffer, offset, length, timeout);

        now = CurrentTime.getCurrentTimeActual();

        timeout = expires - now;
      } while (result == JniStream.TIMEOUT_EXN && timeout > 0);
    }

    return result;
  }
899169
public synchronized int read(byte[] externalBuf, int off, int len) throws IOException {

    if (len == 0) {
      return 0;
    }

    int totalReads = 0;
    while (true) {

      //read
      if (end - pos <= 0) {
        if (len - totalReads >= buf.length) {
          //buffer length is less than asked byte and buffer is empty
          // => filling directly into external buffer
          int reads = super.read(externalBuf, off + totalReads, len - totalReads);
          if (reads <= 0) {
            return (totalReads == 0) ? -1 : totalReads;
          }
          return totalReads + reads;

        } else {

          //filling internal buffer
          fillBuffer(len - totalReads);
          if (end <= 0) {
            return (totalReads == 0) ? -1 : totalReads;
          }
        }
      }

      //copy internal value to buffer.
      int copyLength = Math.min(len - totalReads, end - pos);
      System.arraycopy(buf, pos, externalBuf, off + totalReads, copyLength);
      pos += copyLength;
      totalReads += copyLength;

      if (totalReads >= len || super.available() <= 0) {
        return totalReads;
      }
    }
  }
739293
private long getChunkSize() throws IOException {
        final int st = this.state;
        switch (st) {
        case CHUNK_CRLF:
            this.buffer.clear();
            final int bytesRead1 = this.in.readLine(this.buffer);
            if (bytesRead1 == -1) {
                throw new MalformedChunkCodingException(
                    "CRLF expected at end of chunk");
            }
            if (!this.buffer.isEmpty()) {
                throw new MalformedChunkCodingException(
                    "Unexpected content at the end of chunk");
            }
            state = CHUNK_LEN;
            //$FALL-THROUGH$
        case CHUNK_LEN:
            this.buffer.clear();
            final int bytesRead2 = this.in.readLine(this.buffer);
            if (bytesRead2 == -1) {
                throw new ConnectionClosedException("Premature end of chunk coded message body: " +
                        "closing chunk expected");
            }
            int separator = this.buffer.indexOf(';');
            if (separator < 0) {
                separator = this.buffer.length();
            }
            final String s = this.buffer.substringTrimmed(0, separator);
            try {
                return Long.parseLong(s, 16);
            } catch (final NumberFormatException e) {
                throw new MalformedChunkCodingException("Bad chunk header: " + s);
            }
        default:
            throw new IllegalStateException("Inconsistent codec state");
        }
    }
965069
public byte[] readToBytes() {
        try {
            try (InputStream in = body()) {
                return InputStreams.readAll(in);
            }
        } catch (IOException e) {
            throw new RequestsException(e);
        } finally {
            close();
        }
    }