Reads from the specified <code>channel</code>

@param channel  - the readable channel
@param bb       - the byte buffer to write
@param expected - the number of bytes expected to read
@param message  - the IOException message
@throws IOException
543411
protected void read(ReadableByteChannel channel, ByteBuffer bb, int expected, String message) throws IOException {
        int len = channel.read(bb);
        if (len != expected) {
            throw new IOException(message);
        }
    }
97359
public void writeTo(WritableByteChannel channel) throws IOException {
        for (ByteBuffer buffer : toDirectByteBuffers()) {
            channel.write(buffer);
        }
    }
1030927
@Override
    protected int readBytesWireFormat ( byte[] buffer, int bufferIndex ) throws SMBProtocolDecodingException {
        int start = bufferIndex;
        int structureSize = SMBUtil.readInt2(buffer, bufferIndex);
        if ( structureSize != 17 ) {
            throw new SMBProtocolDecodingException("Expected structureSize = 17");
        }
        bufferIndex += 4;

        this.count = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;
        this.remaining = SMBUtil.readInt4(buffer, bufferIndex);
        bufferIndex += 4;
        bufferIndex += 4; // WriteChannelInfoOffset/WriteChannelInfoLength
        return bufferIndex - start;
    }
191948
protected void onStreamBytesRead(RTMPConnection conn, Channel channel, Header source, BytesRead streamBytesRead) {
        conn.receivedBytesRead(streamBytesRead.getBytesRead());
    }
1362335
public static void closeConnection( Channel channel ) throws IOException {

		if( channel != null ) {
			if( channel.isOpen())
				channel.close();

			if( channel.getConnection().isOpen())
				channel.getConnection().close();
		}
	}
36536
@Process(actionType = InitJberet.class)
    public void init(final Channel channel) {
        ResourceAddress rootAddress = ROOT_ADDRESS.resolve(statementContext);
        Operation readRoot = new Operation.Builder(READ_RESOURCE_OPERATION, rootAddress).build();
        Operation inMemoryRepository = new Operation.Builder(READ_CHILDREN_RESOURCES_OPERATION, rootAddress)
                .param(CHILD_TYPE, "in-memory-job-repository")
                .build();
        Operation jdbcRepository = new Operation.Builder(READ_CHILDREN_RESOURCES_OPERATION, rootAddress)
                .param(CHILD_TYPE, "jdbc-job-repository")
                .build();
        Operation threadFactory = new Operation.Builder(READ_CHILDREN_RESOURCES_OPERATION, rootAddress)
                .param(CHILD_TYPE, "thread-factory")
                .build();
        Operation threadPool = new Operation.Builder(READ_CHILDREN_RESOURCES_OPERATION, rootAddress)
                .param(CHILD_TYPE, "thread-pool")
                .build();
        Composite composite = new Composite(readRoot, inMemoryRepository, jdbcRepository, threadFactory, threadPool);
        dispatcher.execute(new DMRAction(composite), new AsyncCallback<DMRResponse>() {
            @Override
            public void onFailure(final Throwable caught) {
                channel.nack(caught);
            }

            @Override
            public void onSuccess(final DMRResponse response) {
                ModelNode result = response.get();
                if (result.isFailure()) {
                    channel.nack(result.getFailureDescription());
                } else {
                    ModelNode payload = result.get(RESULT);
                    ModelNode step = payload.get("step-1");
                    if (step.get(RESULT).isDefined()) {
                        defaults = step.get(RESULT);
                    }
                    step = payload.get("step-2");
                    if (step.get(RESULT).isDefined()) {
                        inMemoryRepositories.clear();
                        inMemoryRepositories.addAll(step.get(RESULT).asPropertyList());
                    }
                    step = payload.get("step-3");
                    if (step.get(RESULT).isDefined()) {
                        jdbcRepositories.clear();
                        jdbcRepositories.addAll(step.get(RESULT).asPropertyList());
                    }
                    step = payload.get("step-4");
                    if (step.get(RESULT).isDefined()) {
                        threadFactories.clear();
                        threadFactories.addAll(step.get(RESULT).asPropertyList());
                    }
                    step = payload.get("step-5");
                    if (step.get(RESULT).isDefined()) {
                        threadPools.clear();
                        threadPools.addAll(step.get(RESULT).asPropertyList());
                    }
                    channel.ack();
                }
            }
        });
    }
265012
@Override
    public final void channelRead(final ChannelHandlerContext ctx, final Object msg) {
        try {
            JNRPERequest req = (JNRPERequest) msg;

            ReturnValue ret = commandInvoker.invoke(req.getCommand(), req.getArguments());

            JNRPEResponse res = new JNRPEResponse();
            res.setResult(ret.getStatus().intValue(), ret.getMessage());

            ChannelFuture channelFuture = ctx.writeAndFlush(res);
            channelFuture.addListener(ChannelFutureListener.CLOSE);
        } catch ( RuntimeException re ) {
            re.printStackTrace();
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
531477
@Override
  public void writePayload(InputStream message) {
    verifyNotClosed();
    messagesBuffered++;
    currentMessageSeqNo++;
    currentMessageWireSize = 0;
    statsTraceCtx.outboundMessage(currentMessageSeqNo);
    boolean compressed = messageCompression && compressor != Codec.Identity.NONE;
    int written = -1;
    int messageLength = -2;
    try {
      messageLength = getKnownLength(message);
      if (messageLength != 0 && compressed) {
        written = writeCompressed(message, messageLength);
      } else {
        written = writeUncompressed(message, messageLength);
      }
    } catch (IOException e) {
      // This should not be possible, since sink#deliverFrame doesn't throw.
      throw Status.INTERNAL
          .withDescription("Failed to frame message")
          .withCause(e)
          .asRuntimeException();
    } catch (RuntimeException e) {
      throw Status.INTERNAL
          .withDescription("Failed to frame message")
          .withCause(e)
          .asRuntimeException();
    }

    if (messageLength != -1 && written != messageLength) {
      String err = String.format("Message length inaccurate %s != %s", written, messageLength);
      throw Status.INTERNAL.withDescription(err).asRuntimeException();
    }
    statsTraceCtx.outboundUncompressedSize(written);
    statsTraceCtx.outboundWireSize(currentMessageWireSize);
    statsTraceCtx.outboundMessageSent(currentMessageSeqNo, currentMessageWireSize, written);
  }
1088437
public void setChannel(PrivateChannel channel) {
        if (this.channel != channel) {
            if (this.channel != null) {
                ((Cleanupable) this.channel).cleanup();
            }
            this.channel = channel;
        }
    }
1046747
@Override
	public Promise subscribe(String channel) {
		if (client != null) {
			try {
				String postfix = '.' + nodeID;
				String queueName;
				if (channel.endsWith(postfix)) {

					// Create queue
					queueName = channel;
					this.channel.queueDeclareNoWait(queueName, true, exclusive, true, queueProperties);

				} else {

					// Create queue and exchange
					queueName = channel + '.' + nodeID;
					this.channel.queueDeclareNoWait(queueName, true, exclusive, true, queueProperties);
					this.channel.exchangeDeclareNoWait(channel, exchangeType, true, false, internal,
							exchangeProperties);
					this.channel.queueBind(queueName, channel, "");
				}
				this.channel.basicConsume(queueName, true, new Consumer() {

					// --- MESSAGE RECEIVED ---

					@Override
					public final void handleDelivery(String consumerTag, Envelope envelope,
							AMQP.BasicProperties properties, byte[] body) throws IOException {

						// We are running in the shared executor's pool,
						// do not create new task.
						processReceivedMessage(channel, body);
					}

					// --- CONNECTION LOST ---

					@Override
					public final void handleShutdownSignal(String consumerTag, ShutdownSignalException sig) {
						synchronized (factory) {
							if (client != null) {
								logger.info("AMQP pub-sub connection aborted.");
								if (started.get()) {
									reconnect();
								}
							}
						}
					}

					// --- UNUSED METHODS ---

					@Override
					public final void handleConsumeOk(String consumerTag) {
						if (debugHeartbeats) {
							logger.info("ConsumeOk packet received (consumerTag: " + consumerTag + ").");
						}
					}

					@Override
					public final void handleCancelOk(String consumerTag) {
						if (debugHeartbeats) {
							logger.info("CancelOk packet received (consumerTag: " + consumerTag + ").");
						}
					}

					@Override
					public final void handleCancel(String consumerTag) throws IOException {
						if (debugHeartbeats) {
							logger.info("Cancel packet received (consumerTag: " + consumerTag + ").");
						}
					}

					@Override
					public final void handleRecoverOk(String consumerTag) {
						if (debugHeartbeats) {
							logger.info("RecoverOk packet received (consumerTag: " + consumerTag + ").");
						}
					}

				});

			} catch (Exception cause) {
				return Promise.reject(cause);
			}
		}
		return Promise.resolve();
	}
1244640
@Override
	public int append(ReadableByteChannel channel) throws IOException {
		assert invariant(true);

		int totalRead = 0;

		try {

			boolean done;

			// precondition: the channel has data

			do {
				ByteBuffer dest = writableBuf();

				int space = dest.remaining();
				assert space > 0;

				int read = channel.read(dest);
				if (read >= 0) {
					totalRead += read;
				} else {
					// end of stream (e.g. the other end closed the connection)
					removeLastBufferIfEmpty();
					sizeChanged();

					assert invariant(true);
					return -1;
				}

				// if buffer wasn't filled -> no data is available in channel
				done = read < space;
			} while (!done);

		} finally {
			removeLastBufferIfEmpty();
			sizeChanged();
			assert invariant(true);
		}

		return totalRead;
	}
124297
@Override
    public byte[] readBuffer(final ChannelBuffer buffer) {
        int len = getLength();
        byte[] matched = new byte[len];
        buffer.readBytes(matched);
        return matched;
    }
1028780
public void addByte(int b)
    throws IOException
  {
    int nextHead = (_byteHead + 1) % _byteBuffer.length;

    while (nextHead == _byteTail) {
      int ch = readChar();

      if (ch < 0) {
        break;
      }

      outputChar(ch);
    }

    _byteBuffer[_byteHead] = (byte) b;
    _byteHead = nextHead;
  }
947730
public static void readFrom(InputStream is, int needed, ByteBuffer buffer) throws IOException {
        ByteBuffer tmp = allocate(8192);

        while (needed > 0 && buffer.hasRemaining()) {
            int l = is.read(tmp.array(), 0, 8192);
            if (l < 0)
                break;
            tmp.position(0);
            tmp.limit(l);
            buffer.put(tmp);
        }
    }
265004
static int fillBufferWithDelimitedMessageFrom(InputStream in,
            boolean drainRemainingBytesIfTooLarge,
            LinkedBuffer lb) throws IOException
    {
        final byte[] buf = lb.buffer;
        int offset = lb.start, len = buf.length - offset, read = in.read(buf, offset, len);

        if (read < 1)
            throw new EOFException("fillBufferWithDelimitedMessageFrom");

        int last = offset + read, size = buf[offset++];
        if (0 != (size & 0x80))
        {
            size = size & 0x7f;

            for (int shift = 7;; shift += 7)
            {
                if (offset == last)
                {
                    // read too few bytes
                    read = in.read(buf, last, len - (last - lb.start));
                    if (read < 1)
                        throw new EOFException("fillBufferWithDelimitedMessageFrom");

                    last += read;
                }

                byte b = buf[offset++];
                size |= (b & 0x7f) << shift;

                if (0 == (b & 0x80))
                    break;

                if (shift == 28)
                {
                    // discard the remaining bytes (5)
                    for (int i = 0;;)
                    {
                        if (offset == last)
                        {
                            // read more
                            read = in.read(buf, last, len - (last - lb.start));
                            if (read < 1)
                                throw new EOFException("fillBufferWithDelimitedMessageFrom");

                            last += read;
                        }

                        if (buf[offset++] >= 0)
                            break;

                        if (5 == ++i)
                        {
                            // we've already consumed 10 bytes
                            throw ProtobufException.malformedVarint();
                        }
                    }

                }
            }
        }

        if (size == 0)
        {
            if (offset != last)
                throw ProtobufException.misreportedSize();

            return size;
        }

        if (size < 0)
            throw ProtobufException.negativeSize();

        final int partial = last - offset;
        if (partial < size)
        {
            // need to read more
            final int delimSize = offset - lb.start;
            if ((size + delimSize) > len)
            {
                // too large.

                if (!drainRemainingBytesIfTooLarge)
                    return size;

                // drain the remaining bytes
                for (int remaining = size - partial; remaining > 0;)
                {
                    read = in.read(buf, lb.start, Math.min(remaining, len));
                    if (read < 1)
                        throw new EOFException("fillBufferWithDelimitedMessageFrom");

                    remaining -= read;
                }

                return size;
            }

            // read the remaining bytes
            fillBufferFrom(in, buf, last, size - partial);
        }

        // set the read offset (start of message)
        lb.offset = offset;

        return size;
    }
696082
@Override
  public int read(byte []buf, int offset, int length) throws IOException
  {
    try {
      if (_channel == null) {
        return -1;
      }
      
      int remaining = _readBuffer.remaining();
      
      if (remaining > 0) {
        _readBuffer.get(buf, offset, remaining);
      
        return remaining;
      }
      
      _readBuffer.clear();
      
      int channelRead = _channel.read(_readBuffer);
      _readBuffer.flip();
      
      if (channelRead < 0)
        return -1;
      
      _readBuffer.get(buf, offset, channelRead);
      
      return channelRead;
    } catch (InterruptedIOException e) {
      if (_throwReadInterrupts)
        throw e;
      
      log.log(Level.FINEST, e.toString(), e);
    } catch (IOException e) {
      if (_throwReadInterrupts)
        throw e;

      log.log(Level.FINER, e.toString(), e);
      // server/0611
      /*
      try {
        close();
      } catch (IOException e1) {
      }
      */
    }

    return -1;
  }
28401
@Override
    public void handleMessage(final Message message) throws Fault {
        final InputStream is = message.getContent(InputStream.class);
        if (WireTapHelper.isMessageContentToBeLogged(message, logMessageContent, logMessageContentOverride)) {
            if (null == is) {
                Reader reader = message.getContent(Reader.class);
                if (null != reader) {
                    String encoding = (String) message.get(Message.ENCODING);
                    if (encoding == null) {
                        encoding = "UTF-8";
                    }
                    try {
                        final CachedOutputStream cos = new CachedOutputStream();
                        final Writer writer = new OutputStreamWriter(cos, encoding);
                        IOUtils.copy(reader, writer, 1024);
                        reader.reset();
                        writer.flush();
                        message.setContent(InputStream.class, cos.getInputStream());
                        message.setContent(Reader.class, null);
                        message.setContent(CachedOutputStream.class, cos);
                        closeCachedOutputStream(message, cos);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    } finally {
                        try {
                            reader.reset();
                        } catch (IOException e) {
                        }
                    }
                }
            } else {
                try {
                    final CachedOutputStream cos = new CachedOutputStream();
                    // TODO: We should try to make this streaming
                    //WireTapInputStream wtis = new WireTapInputStream(is, cos);
                    //message.setContent(InputStream.class, wtis);
                    IOUtils.copyAndCloseInput(is, cos);
                    message.setContent(InputStream.class, cos.getInputStream());
                    message.setContent(CachedOutputStream.class, cos);
                    closeCachedOutputStream(message, cos);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }else {
            try {
                final CachedOutputStream cos = new CachedOutputStream();
                cos.write(WireTapHelper.CONTENT_LOGGING_IS_DISABLED.getBytes(Charset.forName("UTF-8")));
                message.setContent(CachedOutputStream.class, cos);
                message.setContent(InputStream.class, is);
                closeCachedOutputStream(message, cos);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }