/* this method now throws exception if we don't get full read
353399
protected int readSock(final OtpTransport s, final byte[] b)
            throws IOException {
        int got = 0;
        final int len = b.length;
        int i;

        synchronized (this) {
            if (s == null) {
                throw new IOException("expected " + len
                        + " bytes, socket was closed");
            }
        }

        while (got < len) {
            i = s.getInputStream().read(b, got, len - got);

            if (i < 0) {
                throw new IOException("expected " + len
                        + " bytes, got EOF after " + got + " bytes");
            } else if (i == 0 && len != 0) {
                /*
                 * This is a corner case. According to
                 * http://java.sun.com/j2se/1.4.2/docs/api/ class InputStream
                 * is.read(,,l) can only return 0 if l==0. In other words it
                 * should not happen, but apparently did.
                 */
                throw new IOException("Remote connection closed");
            } else {
                got += i;
            }
        }
        return got;
    }
707302
public function read() {
		
		$id = $this->getId();
		$path = $this->getPath($id);
		if (!is_readable($path)) {
			throw new Exception("Expected path $path is not readable");
		}

		return file_get_contents($path);
	}
1113174
private void checkForThreadErrors() throws IOException {
    if(error == true && childException != null) {
      error = false;
      IOException temp = childException;
      childException = null;
      throw temp;
    }
  }
1034323
@SuppressWarnings("unchecked")
	private void initInputReaders() throws Exception {
		int numGates = 0;
		//  ---------------- create the input readers ---------------------
		// in case where a logical input unions multiple physical inputs, create a union reader
		final int groupSize = this.config.getGroupSize(0);
		numGates += groupSize;
		if (groupSize == 1) {
			// non-union case
			inputReader = new MutableRecordReader<DeserializationDelegate<IT>>(
					getEnvironment().getInputGate(0),
					getEnvironment().getTaskManagerInfo().getTmpDirectories());
		} else if (groupSize > 1){
			// union case
			inputReader = new MutableRecordReader<IOReadableWritable>(
					new UnionInputGate(getEnvironment().getAllInputGates()),
					getEnvironment().getTaskManagerInfo().getTmpDirectories());
		} else {
			throw new Exception("Illegal input group size in task configuration: " + groupSize);
		}
		
		this.inputTypeSerializerFactory = this.config.getInputSerializer(0, getUserCodeClassLoader());
		@SuppressWarnings({ "rawtypes" })
		final MutableObjectIterator<?> iter = new ReaderIterator(inputReader, this.inputTypeSerializerFactory.getSerializer());
		this.reader = (MutableObjectIterator<IT>)iter;

		// final sanity check
		if (numGates != this.config.getNumInputs()) {
			throw new Exception("Illegal configuration: Number of input gates and group sizes are not consistent.");
		}
	}
105508
public void read() throws IOException {
    readFileId();
    in.resetCRC();

    long startcode = in.readStartCode();

    while (true) {
      // Start parsing main and stream information
      header = new MainHeaderPacket();

      if (!Startcode.MAIN.equalsCode(startcode)) {
        throw new IOException(String.format("expected main header found: 0x%X", startcode));
      }

      header.read(in, startcode);
      startcode = readReservedHeaders();

      streams.clear();
      for (int i = 0; i < header.streamCount; i++) {
        if (!Startcode.STREAM.equalsCode(startcode)) {
          throw new IOException(String.format("expected stream header found: 0x%X", startcode));
        }

        StreamHeaderPacket streamHeader = new StreamHeaderPacket();
        streamHeader.read(in, startcode);

        Stream stream = new Stream(header, streamHeader);
        streams.add(stream);
        listener.stream(stream);

        startcode = readReservedHeaders();
      }

      while (Startcode.INFO.equalsCode(startcode)) {
        new Packet().read(in, startcode); // Discard for the moment
        startcode = readReservedHeaders();
      }

      if (Startcode.INDEX.equalsCode(startcode)) {
        new Packet().read(in, startcode); // Discard for the moment
        startcode = in.readStartCode();
      }

      // Now main frame parsing loop
      while (!Startcode.MAIN.equalsCode(startcode)) {

        if (Startcode.SYNCPOINT.equalsCode(startcode)) {
          new Packet().read(in, startcode); // Discard for the moment
          startcode = in.readStartCode();
        }

        if (Startcode.isPossibleStartcode(startcode)) {
          throw new IOException("expected framecode, found " + Startcode.toString(startcode));
        }

        Frame f = new Frame();
        f.read(this, in, (int) startcode);

        listener.frame(f);

        try {
          startcode = readReservedHeaders();
        } catch (java.io.EOFException e) {
          return;
        }
      }
    }
  }
993511
@Override
    public int read()
        throws IOException
    {
        synchronized ( lock )
        {
            ensureOpen();
            if ( next >= length )
                return -1;
            return seq.charAt( next++ );
        }
    }
902561
private void parseContent() throws Exception {
        char c;

        while (true) {
            // consume characters (or ignorable whitspace) until delimiter
            parseCharData();

            // Handle delimiters
            c = readCh();
            switch (c) {
                case '&': // Found "&"
                    c = readCh();
                    if (c == '#') {
                        parseCharRef();
                    } else {
                        unread(c);
                        parseEntityRef(true);
                    }
                    isDirtyCurrentElement = true;
                    break;

                case '<': // Found "<"
                    dataBufferFlush();
                    c = readCh();
                    switch (c) {
                        case '!': // Found "<!"
                            c = readCh();
                            switch (c) {
                                case '-': // Found "<!-"
                                    require('-');
                                    isDirtyCurrentElement = false;
                                    parseComment();
                                    break;
                                case '[': // Found "<!["
                                    isDirtyCurrentElement = false;
                                    require("CDATA[");
                                    handler.startCDATA();
                                    inCDATA = true;
                                    parseCDSect();
                                    inCDATA = false;
                                    handler.endCDATA();
                                    break;
                                default:
                                    fatal("expected comment or CDATA section",
                                            c, null);
                                    break;
                            }
                            break;

                        case '?': // Found "<?"
                            isDirtyCurrentElement = false;
                            parsePI();
                            break;

                        case '/': // Found "</"
                            isDirtyCurrentElement = false;
                            parseETag();
                            return;

                        default: // Found "<" followed by something else
                            isDirtyCurrentElement = false;
                            unread(c);
                            parseElement(false);
                            break;
                    }
            }
        }
    }
670436
public int read() throws IOException {
		if (leftover != null && leftover.remaining() > 0) {
			int b = leftover.get();
			if (leftover.remaining() == 0) {
				leftover = null;
			}
			return b;
		}
		return input.read();
	}
986008
@Override
  public synchronized int read() throws IOException {
    long startTime = System.nanoTime();

    // TODO(user): Wrap this in a while-loop if we ever introduce a non-blocking mode for the
    // underlying channel.
    int numRead = channel.read(ByteBuffer.wrap(singleReadBuf));
    if (numRead == -1) {
      return -1;
    }
    if (numRead != 1) {
      throw new IOException(
          String.format(
              "Somehow read %d bytes using single-byte buffer for path %s ending in position %d!",
              numRead, gcsPath, channel.position()));
    }
    byte b = singleReadBuf[0];

    totalBytesRead++;
    statistics.incrementBytesRead(1);
    long duration = System.nanoTime() - startTime;
    ghfs.increment(GoogleHadoopFileSystemBase.Counter.READ1);
    ghfs.increment(GoogleHadoopFileSystemBase.Counter.READ1_TIME, duration);
    return (b & 0xff);
  }
348780
public final long readTTFULong() throws IOException {
        long ret = readTTFUByte();
        ret = (ret << 8) + readTTFUByte();
        ret = (ret << 8) + readTTFUByte();
        ret = (ret << 8) + readTTFUByte();

        return ret;
    }
155092
@Override
    public final int next() throws XMLStreamException
    {
        /* 24-Sep-2006, TSa: We may have deferred an exception that occurred
         *   during parsing of the previous event. If so, now it needs to
         *   be thrown.
         */
        if (mPendingException != null) {
            XMLStreamException strEx = mPendingException;
            mPendingException = null;
            throw strEx;
        }

        /* Note: can not yet accurately record the location, since the
         * previous event might not yet be completely finished...
         */
        if (mParseState == STATE_TREE) {
            int type = nextFromTree();
            mCurrToken = type;
            if (mTokenState < mStTextThreshold) { // incomplete?
                /* Can remain incomplete if lazy parsing is enabled,
                 * and this is not a validatable text segment; otherwise
                 * must finish
                 */
                if (!mCfgLazyParsing ||
                    (mValidateText && (type == CHARACTERS || type == CDATA))) {
                    finishToken(false);
                }
            }

            /* Special cases -- sometimes (when coalescing text, or
             * when specifically configured to do so), CDATA and SPACE are
             * to be reported as CHARACTERS, although we still will
             * internally keep track of the real type.
             */
            if (type == CDATA) {
                if (mValidateText) {
                    mElementStack.validateText(mTextBuffer, false);
                }
                if (mCfgCoalesceText || mCfgReportTextAsChars) {
                    return CHARACTERS;
                }
                /*
                  } else if (type == SPACE) {
                  //if (mValidateText) { throw new IllegalStateException("Internal error: trying to validate SPACE event"); }
                  */
                mCurrTextLength += mTextBuffer.size();
                verifyLimit("Text size", mConfig.getMaxTextLength(), mCurrTextLength);
            } else if (type == CHARACTERS) {
                if (mValidateText) {
                    /* We may be able to determine that there will be
                     * no more text coming for this element: but only
                     * seeing the end tag marker ("</") is certain
                     * (PIs and comments won't do, nor CDATA; start
                     * element possibly... but that indicates mixed
                     * content that's generally non-validatable)
                         */
                    if ((mInputPtr+1) < mInputEnd
                        && mInputBuffer[mInputPtr] == '<'
                        && mInputBuffer[mInputPtr+1] == '/') {
                        // yup, it's all there is
                        mElementStack.validateText(mTextBuffer, true);
                    } else {
                        mElementStack.validateText(mTextBuffer, false);
                    }
                }
                mCurrTextLength += mTextBuffer.size();
                verifyLimit("Text size", mConfig.getMaxTextLength(), mCurrTextLength);
            } else if (type == START_ELEMENT || type == END_ELEMENT) {
                this.mCurrTextLength = 0;
            }
            return type;
        }

        if (mParseState == STATE_PROLOG) {
            nextFromProlog(true);
        } else if (mParseState == STATE_EPILOG) {
            if (nextFromProlog(false)) {
                // We'll return END_DOCUMENT, need to mark it 'as consumed'
                mSecondaryToken = 0;
                
            }
        } else if (mParseState == STATE_MULTIDOC_HACK) {
            mCurrToken = nextFromMultiDocState();
        } else { // == STATE_CLOSED
            if (mSecondaryToken == END_DOCUMENT) { // marker
                mSecondaryToken = 0; // mark end doc as consumed
                return END_DOCUMENT;
            }
            throw new java.util.NoSuchElementException();
        }
        return mCurrToken;
    }
841040
@Override
    public int read() throws IOException {
        final int c = super.read();
        if (c >= 0)
            dataLength++;
        checkLength(c == -1);
        return c;
    }
1065450
private void processCompleteData() throws ProtocolException {
        WsByteBufferPoolManager bufManager = HttpDispatcher.getBufferManager();
        WsByteBuffer buf = bufManager.allocate(getByteCount(dataPayload));
        for (byte[] bytes : dataPayload) {
            buf.put(bytes);
        }
        buf.flip();
        if (expectedContentLength != -1 && buf.limit() != expectedContentLength) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "processCompleteData release buffer and throw ProtocolException");
            }
            buf.release();
            ProtocolException pe = new ProtocolException("content-length header did not match the expected amount of data received");
            pe.setConnectionError(false); // stream error
            throw pe;
        }
        moveDataIntoReadBufferArray(buf);
    }
170348
@Override
	public boolean handleIncomingData()
	{
		lastRecvActivity = System.currentTimeMillis();
		
		while (inputBuffer.remaining() > 0)
		{		
			if (packetInputBuffer.size() == 0)
			{
				if (inputBuffer.remaining() >= 4) // packet_size = sizeof(int) = 4
				{
					int packetSize = inputBuffer.getInt();
					
					// Security check
					int actualMaxPacketSize = Integer.MAX_VALUE;
					if (maxPacketSize != -1)
						actualMaxPacketSize = trustedConnection ? maxPacketSize : 1024;
					
					if (packetSize > actualMaxPacketSize)
					{
						log.error("#"+id+" packet is too large : "+packetSize+" (maxPacketSize="+actualMaxPacketSize+"), dropping client.");
						return false;
					}
					
					packetInputBuffer.setSize(packetSize);
				}
				else
					return true; // Not enough data to proceed ...
			}
			else
			{
				// Append to current packet
				int readAmount = Math.min(inputBuffer.remaining(), packetInputBuffer.size() - currentInputOffset);
				packetInputBuffer.getFrom(inputBuffer, currentInputOffset, readAmount);
				currentInputOffset += readAmount;
				
				// Packet is complete ?
				if (currentInputOffset == packetInputBuffer.size())
				{
					AbstractPacket packet = unserializePacket(packetInputBuffer);
					if (packet == null)
						return false; // Invalid packet
					packetInputBuffer.clear();
					currentInputOffset = 0;
					
					if (traceEnabled)
	                    log.trace("#"+id+" Received "+packet);
					
					if (listener != null)
						trustedConnection = listener.packetReceived(packet);
				}
			}
		}
		
		return true;
	}
451952
@Override
    public boolean readFrom(ByteBuffer src) {
        boolean complete = doActualRead(src);
        while (!complete && readyToReadData && chunked && src.hasRemaining()) {
            complete = doActualRead(src);
        }
        if (complete) {
            if (data != null) {
                data.flip();
            }
        }
        return complete;
    }
1218457
@Override
  public int read() throws IOException {
    try {
      beforeRead(1);
      int c = in.read();
      afterRead(c != -1 ? 1 : -1);
      return c;
    } catch (IOException e) {
      handleIOException(e);
      return -1;
    }
  }
1215082
@Override
    public int read() throws IOException {
        // initalize the lookahead
        if (lookaheadChar == UNDEFINED) {
            lookaheadChar = super.read();
        }
        lastChar = lookaheadChar;
        if (super.ready()) {
            lookaheadChar = super.read();
        } else {
            lookaheadChar = UNDEFINED;
        }
        if (lastChar == '\n') {
            lineCounter++;
        }
        return lastChar;
    }