Reads a byte from the comms port

@return Value of the byte

@throws IOException If it cannot read or times out
162482
protected int readByte() throws IOException {
        if (commPort != null && commPort.isOpen()) {
            byte[] buffer = new byte[1];
            int cnt = commPort.readBytes(buffer, 1);
            if (cnt != 1) {
                throw new IOException("Cannot read from serial port");
            }
            else {
                return buffer[0] & 0xff;
            }
        }
        else {
            throw new IOException("Comm port is not valid or not open");
        }
    }
224695
public Object readObject()
        throws IOException
    {
        int tag = read();

        switch (tag) {
            case 'N':
                return null;

            case 'T':
                return Boolean.valueOf(true);

            case 'F':
                return Boolean.valueOf(false);

            case 'I':
                return Integer.valueOf(parseInt());

            case 'L':
                return Long.valueOf(parseLong());

            case 'D':
                return Double.valueOf(parseDouble());

            case 'd':
                return new Date(parseLong());

            case 'x':
            case 'X': {
                _isLastChunk = tag == 'X';
                _chunkLength = (read() << 8) + read();

                return parseXML();
            }

            case 's':
            case 'S': {
                _isLastChunk = tag == 'S';
                _chunkLength = (read() << 8) + read();

                int data;
                _sbuf.setLength(0);

                while ((data = parseChar()) >= 0)
                    _sbuf.append((char) data);

                return _sbuf.toString();
            }

            case 'b':
            case 'B': {
                _isLastChunk = tag == 'B';
                _chunkLength = (read() << 8) + read();

                int data;
                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                while ((data = parseByte()) >= 0)
                    bos.write(data);

                return bos.toByteArray();
            }

            case 'V': {
                String type = readType();
                int length = readLength();

                return _serializerFactory.readList(this, length, type);
            }

            case 'M': {
                String type = readType();

                return _serializerFactory.readMap(this, type);
            }

            case 'R': {
                int ref = parseInt();

                return _refs.get(ref);
            }

            case 'r': {
                String type = readType();
                String url = readString();

                return resolveRemote(type, url);
            }

            default:
                throw error("unknown code for readObject at " + codeName(tag));
        }
    }
634743
public int read() throws IOException {
        int b = in.read();
        if (b != -1) {
            cksum.update(b);
        }
        return b;
    }
766596
public int readByte()
        throws IOException
    {
        if (_chunkLength > 0) {
            _chunkLength--;
            if (_chunkLength == 0 && _isLastChunk)
                _chunkLength = END_OF_DATA;

            return read();
        }
        else if (_chunkLength == END_OF_DATA) {
            _chunkLength = 0;
            return -1;
        }

        int tag = read();

        switch (tag) {
            case 'N':
                return -1;

            case 'B':
            case 'b':
                _isLastChunk = tag == 'B';
                _chunkLength = (read() << 8) + read();

                int value = parseByte();

                // special code so successive read byte won't
                // be read as a single object.
                if (_chunkLength == 0 && _isLastChunk)
                    _chunkLength = END_OF_DATA;

                return value;

            default:
                throw new IOException("expected 'B' at " + (char) tag);
        }
    }
1109143
public byte[] getBytes() throws IOException {
        if (!connection.isOpen())
            connection.open();

        connection.prepare("GET");
        response = connection.readInput();
        return getResponseBytes();
    }
119353
public byte[] getBytes() throws IOException {
        InputStream input = getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        final byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int len;

        try {
            while ((len = input.read(buffer)) != -1) {
                output.write(buffer, 0, len);
            }
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                // ignore
            }
            try {
                input.close();
            } catch (IOException e) {
                // ignore
            }
        }

        return output.toByteArray();
    }
1047705
private byte readByte()
            throws IOException
    {
        if (buffer.size() > position) {
            byte b = buffer.getByte(position);
            position++;
            return b;
        }
        else {
            nextBuffer();
            if (buffer.size() > 0) {
                byte b = buffer.getByte(0);
                position = 1;
                return b;
            }
            return readByte();
        }
    }
861361
public byte readByte() throws IOException {

		// buffer depleted ?
		if (head == tail) {
			head = 0;
			// Refill.
			tail = input.read(buffer, head, bufSize);
			if (tail == -1) {
				// no more data available.
				throw new IOException("No more data is available");
			}
		}

		return buffer[head++];
	}
1278685
private int receivePacket() throws IOException {
    eventStartReceivePacket();
    
    long startTime = System.currentTimeMillis();
    
    // The packet format is documented in DFSOuputStream.Packet.getBuffer().
    //
    int payloadLen = readNextPacket();
    
    if (payloadLen <= 0) {
      return payloadLen;
    }
    
    buf.mark();
    //read the header
    buf.getInt(); // packet length
    int packetVersion;
    if (pktIncludeVersion) {
      packetVersion = buf.getInt();
    } else {
      packetVersion = DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST;
    }
    offsetInBlock = buf.getLong(); // get offset of packet in block
    long seqno = buf.getLong();    // get seqno
    
    byte booleanFieldValue = buf.get();
    boolean lastPacketInBlock = ((booleanFieldValue &
    DataNode.isLastPacketInBlockMask) == 0 ) ?
    false : true;

    boolean forceSync = ((booleanFieldValue & DataNode.forceSyncMask) == 0 ) ?
    false : true;

    int endOfHeader = buf.position();
    buf.reset();
    
    if (LOG.isDebugEnabled()){
      LOG.debug("Receiving one packet for block " + block +
                " of length " + payloadLen +
                " seqno " + seqno +
                " offsetInBlock " + offsetInBlock +
                " lastPacketInBlock " + lastPacketInBlock);
    }
    
    eventEndReceivePacketStartForward();
    
    // First write the packet to the mirror:
    if (mirrorOut != null && !mirrorError) {
      try {
        long mirrorWriteStartTime = System.currentTimeMillis();
        mirrorOut.write(buf.array(), buf.position(), buf.remaining());
        mirrorOut.flush();
        long mirrorWritePacketDuration = System.currentTimeMillis() - mirrorWriteStartTime;
        datanode.myMetrics.mirrorWritePacketLatency.inc(mirrorWritePacketDuration);
        if (mirrorWritePacketDuration > slowPacketThreshold) {
          LOG.info("operationTooSlow : mirrorPacket for block " + block +
              " of length " + payloadLen +
              " seqno " + seqno +
              " offsetInBlock " + offsetInBlock +
              " lastPacketInBlock " + lastPacketInBlock +
              " to mirror : " + mirrorAddr +
              " took : " + mirrorWritePacketDuration);
          datanode.myMetrics.slowMirrorWritePacketNumOps.inc(1);
        }
      } catch (IOException e) {
        handleMirrorOutError(e);
      }
    }

    buf.position(endOfHeader);        
    int len = buf.getInt();
    
    if (len < 0) {
      throw new IOException("Got wrong length during writeBlock(" + block + 
                            ") from " + inAddr + " at offset " + 
                            offsetInBlock + ": " + len); 
    }
    
    eventEndForwardStartEnqueue();

    Packet ackPacket = null;
    if (responder != null) {
      ackPacket = ((PacketResponder) responder.getRunnable()).enqueue(seqno,
          lastPacketInBlock, offsetInBlock + len, profileForCurrentPacket);
    }
    
    eventEndEnqueueStartSetPostion();

    if (len == 0) {
      LOG.debug("Receiving empty packet for block " + block);
    } else {
      setBlockPosition(offsetInBlock);  // adjust file position
      int firstChunkOffset = (int) (offsetInBlock % bytesPerChecksum);

      long expectedBlockCrcOffset = offsetInBlock;
      offsetInBlock += len;
      this.replicaBeingWritten.setBytesReceived(offsetInBlock);
      
      int numChunks = ((firstChunkOffset + len + bytesPerChecksum - 1) / bytesPerChecksum);
      
      if (buf.remaining() != (numChunks * checksumSize + len)) {
        throw new IOException("Data remaining in packet does not match "
            + "sum of checksumLen and dataLen buf.remaining() "
            + buf.remaining() + " numChunks " + numChunks + " len " + len
            + " offsetInBlock " + offsetInBlock);
      }
      int checksumOff = buf.position();
      int dataOff;
      if (packetVersion == DataTransferProtocol.PACKET_VERSION_CHECKSUM_FIRST) {
        int checksumLen = numChunks * checksumSize;
        dataOff = checksumOff + checksumLen;
      } else if (packetVersion == DataTransferProtocol.PACKET_VERSION_CHECKSUM_INLINE) {
        dataOff = checksumOff;
      } else {
        throw new IOException("Packet version " + packetVersion + " not supported.");
      }
      byte pktBuf[] = buf.array();
      
      buf.position(buf.limit()); // move to the end of the data.

      eventEndSetPositionStartVerifyChecksum();

      
      /* skip verifying checksum iff this is not the last one in the 
       * pipeline and clientName is non-null. i.e. Checksum is verified
       * on all the datanodes when the data is being written by a 
       * datanode rather than a client. Whe client is writing the data, 
       * protocol includes acks and only the last datanode needs to verify 
       * checksum.
       */
      if (mirrorOut == null || clientName.length() == 0) {
        verifyChunks(pktBuf, dataOff, len, pktBuf, checksumOff,
           firstChunkOffset, packetVersion);
      }
      
      eventEndVerifyChecksumStartUpdateBlockCrc();
            
      if (datanode.updateBlockCrcWhenWrite) {
        // update Block CRC.
        // It introduces extra costs in critical code path. But compared to the
        // total checksum calculating costs (the previous operation),
        // this costs are negligible. If we want to optimize, we can optimize it
        // together with the previous operation to hide the latency from disk
        // I/O latency.
        int chunkOffset = (int) (expectedBlockCrcOffset % bytesPerChecksum);
        int crcCalculateOffset = checksumOff;
        for (int i = 0; i < numChunks; i++) {
          int bytesInChunk;
          if (i != numChunks - 1) {
            bytesInChunk = bytesPerChecksum - chunkOffset;
          } else {
            bytesInChunk = (len + chunkOffset) % bytesPerChecksum;
            if (bytesInChunk == 0) {
              bytesInChunk = bytesPerChecksum;
            }
          }
          if (packetVersion == DataTransferProtocol.PACKET_VERSION_CHECKSUM_INLINE) {
            // Needs to skip the data chunk for the checksum
            crcCalculateOffset += bytesInChunk;
          }
          replicaBeingWritten.updateBlockCrc(expectedBlockCrcOffset,
              bytesInChunk,
              DataChecksum.getIntFromBytes(pktBuf, crcCalculateOffset));
          crcCalculateOffset += checksum.getChecksumSize();
          expectedBlockCrcOffset += bytesInChunk;
          
          chunkOffset = 0;
        }
      }

      eventEndUpdateBlockCrcStartWritePacket();

      try {
        long writeStartTime = System.currentTimeMillis();

        blockWriter.writePacket(pktBuf, len, dataOff, checksumOff, numChunks,
            packetVersion);

        datanode.myMetrics.bytesWritten.inc(len);
        
        eventEndWritePacketStartFlush();

        // / flush entire packet before sending ack
        this.bufSizeSinceLastSync += len;
        flush(forceSync);

        attemptFadvise(len);
        if (forceSync) {
          this.bufSizeSinceLastSync = 0;
        } else if (this.flushKb > 0
            && this.bufSizeSinceLastSync >= this.flushKb * 1024) {
          long syncStartOffset = offsetInBlock - this.bufSizeSinceLastSync;
          if (syncStartOffset < 0) {
            syncStartOffset = 0;
          }
          long bytesToSync = offsetInBlock - syncStartOffset;
          long startFileRangeSync = System.currentTimeMillis();
          fileRangeSync(bytesToSync, syncFileRange);
          long syncFileRangeDuration = System.currentTimeMillis() - startFileRangeSync;
          datanode.myMetrics.syncFileRangeLatency.inc(syncFileRangeDuration);
          if (syncFileRangeDuration > slowPacketThreshold) {
            LOG.info("operationTooSlow : syncFileRange for block " + block +
                " of length " + payloadLen +
                " seqno " + seqno +
                " offsetInBlock " + offsetInBlock +
                " lastPacketInBlock " + lastPacketInBlock +
                " took : " + syncFileRangeDuration);
          }
          this.bufSizeSinceLastSync = 0;
        }
        this.replicaBeingWritten.setBytesOnDisk(offsetInBlock);

        // Record time taken to write packet
        long writePacketDuration = System.currentTimeMillis() - writeStartTime;
        datanode.myMetrics.writePacketLatency.inc(writePacketDuration);
        if (writePacketDuration > slowPacketThreshold) {
          LOG.info("operationTooSlow : writePacket for block " + block +
              " of length " + payloadLen +
              " seqno " + seqno +
              " offsetInBlock " + offsetInBlock +
              " lastPacketInBlock " + lastPacketInBlock +
              " took : " + writePacketDuration);
          datanode.myMetrics.slowWritePacketNumOps.inc(1);
        }

        eventEndFlush();
      } catch (ClosedByInterruptException cix) {
        LOG.warn(
            "Thread interrupted when flushing bytes to disk. Might cause inconsistent sates",
            cix);
        throw cix;
      } catch (InterruptedIOException iix) {
        LOG.warn(
            "InterruptedIOException when flushing bytes to disk. Might cause inconsistent sates",
            iix);
        throw iix;
      } catch (IOException iex) {
        datanode.checkDiskError(iex);
        throw iex;
      }
    }
    if (ackPacket != null) {
      ackPacket.setPersistent();
    }
    
    if (throttler != null) { // throttle I/O
      throttler.throttle(payloadLen);
    }

    long receiveAndWritePacketDuration = System.currentTimeMillis() - startTime;
    datanode.myMetrics.receiveAndWritePacketLatency.inc(receiveAndWritePacketDuration);
    
    eventEndCurrentPacket();

    return payloadLen;
  }
274064
public int read() throws IOException {
        synchronized (lock) {
            ensureOpen();
            if (pos < buf.length)
                return buf[pos++];
            else
                return super.read();
        }
    }
1122583
int readAsciiByte() throws IOException {
        if (commPort != null && commPort.isOpen()) {
            byte[] buffer = new byte[1];
            int cnt = commPort.readBytes(buffer, 1);
            if (cnt != 1) {
                throw new IOException("Cannot read from serial port");
            }
            else if (buffer[0] == ':') {
                return ModbusASCIITransport.FRAME_START;
            }
            else if (buffer[0] == '\r' || buffer[0] == '\n') {
                return ModbusASCIITransport.FRAME_END;
            }
            else {
                logger.debug("Read From buffer: " + buffer[0] + " (" + String.format("%02X", buffer[0]) + ")");
                byte firstValue = buffer[0];
                cnt = commPort.readBytes(buffer, 1);
                if (cnt != 1) {
                    throw new IOException("Cannot read from serial port");
                }
                else {
                    logger.debug("Read From buffer: " + buffer[0] + " (" + String.format("%02X", buffer[0]) + ")");
                    int combinedValue = (Character.digit(firstValue, 16) << 4) + Character.digit(buffer[0], 16);
                    logger.debug("Returning combined value of: " + String.format("%02X", combinedValue));
                    return combinedValue;
                }
            }
        }
        else {
            throw new IOException("Comm port is not valid or not open");
        }
    }
762387
@Override
	public int read(byte[] b) throws IOException {
		int result = stream.read(b);
		update(result);
		return result;
	}
159175
public byte[] receiveMessages()
    {
        try
        {
            final byte[] data;
            final int size = in.available();
            if (size <= 0)
            {
                data = null;
            }
            else
            {
                data = new byte[size];
                in.readFully(data);
            }
            return data;
        }
        catch (final IOException exception)
        {
            Verbose.exception(exception);
            return new byte[0];
        }
    }
837868
public byte[] getBytes() throws IOException {
        if(cachedData == null){
            if(getReader().available() > 0) {
                cachedData = getReader().read();
            }
            else{
                cachedData = new byte[0];
            }
        }
        return cachedData;
    }
752327
protected String read(SocketChannel sc) throws IOException {
        sc.read(buffer);
        buffer.flip();

        decoder.decode(buffer, charBuffer, true);
        charBuffer.flip();

        String result = charBuffer.toString();

        // Clear out buffers
        buffer.clear();
        charBuffer.clear();
        decoder.reset();

        return result;
    }
109228
@Override
	public int read() throws IOException {
		if (pos >= limit)
			return -1;

		try {
			int c = buf[pos] & 0xff;
			if (c < 0x80) {
				pos++;
			} else if (c < 0xE0) {
				c = (char) ((c & 0x1F) << 6 | buf[pos + 1] & 0x3F);
				pos += 2;
			} else {
				c = (char) ((c & 0x0F) << 12 | (buf[pos + 1] & 0x3F) << 6 | (buf[pos + 2] & 0x3F));
				pos += 3;
			}
			if (pos > limit)
				throw new IOException();
			return c;
		} catch (ArrayIndexOutOfBoundsException e) {
			throw new IOException(e);
		}
	}
170128
public synchronized int read() throws IOException
	{
		if (bytesUntilNextMetadata > 0)
		{
			bytesUntilNextMetadata--;
			return super.read();
		}
		else 
		if (bytesUntilNextMetadata == 0)
		{
			readMetadata();
			bytesUntilNextMetadata = metaint - 1;
			// -1 because we read byte on next line
			return super.read();
		}
		else
		{
			return super.read();
		}
	}