Java Code Examples for org.jboss.netty.buffer.ChannelBuffer#readable()

The following examples show how to use org.jboss.netty.buffer.ChannelBuffer#readable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SyslogTcpSource.java    From mt-flume with Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent mEvent) {
  ChannelBuffer buff = (ChannelBuffer) mEvent.getMessage();
  while (buff.readable()) {
    Event e = syslogUtils.extractEvent(buff);
    if (e == null) {
      logger.debug("Parsed partial event, event will be generated when " +
          "rest of the event is received.");
      continue;
    }
    try {
      getChannelProcessor().processEvent(e);
      counterGroup.incrementAndGet("events.success");
    } catch (ChannelException ex) {
      counterGroup.incrementAndGet("events.dropped");
      logger.error("Error writting to channel, event dropped", ex);
    }
  }

}
 
Example 2
Source File: FrameDecoder.java    From android-netty with Apache License 2.0 6 votes vote down vote up
private void callDecode(ChannelHandlerContext context, Channel channel, ChannelBuffer cumulation, SocketAddress remoteAddress) throws Exception {

		while (cumulation.readable()) {
			int oldReaderIndex = cumulation.readerIndex();
			Object frame = decode(context, channel, cumulation);
			if (frame == null) {
				if (oldReaderIndex == cumulation.readerIndex()) {
					// Seems like more data is required.
					// Let us wait for the next notification.
					break;
				} else {
					// Previous data has been discarded.
					// Probably it is reading on.
					continue;
				}
			}
			if (oldReaderIndex == cumulation.readerIndex()) {
				throw new IllegalStateException("decode() method must read at least one byte " + "if it returned a frame (caused by: " + getClass() + ')');
			}

			unfoldAndFireMessageReceived(context, remoteAddress, frame);
		}
	}
 
Example 3
Source File: BgpFactories.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public BgpMessage readFrom(ChannelBuffer bb, BgpHeader bgpHeader)
        throws BgpParseException {
    BgpFactory factory;

    if (!bb.readable()) {
        log.error("Empty message received");
        throw new BgpParseException("Empty message received");
    }
    // TODO: Currently only BGP version 4 is supported
    factory = org.onosproject.bgpio.protocol.ver4.BgpFactoryVer4.INSTANCE;
    return factory.getReader().readFrom(bb, bgpHeader);
}
 
Example 4
Source File: OpInsert.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void decode( ChannelBuffer buffer ) throws IOException {
    super.decode( buffer );

    flags = buffer.readInt();
    fullCollectionName = readCString( buffer );

    while ( buffer.readable() ) {
        documents.add( BSONUtils.decoder().readObject( new ChannelBufferInputStream( buffer ) ) );
    }
}
 
Example 5
Source File: OpReply.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void decode( ChannelBuffer buffer ) throws IOException {
    super.decode( buffer );

    responseFlags = buffer.readInt();
    cursorID = buffer.readLong();
    startingFrom = buffer.readInt();
    numberReturned = buffer.readInt();

    while ( buffer.readable() ) {
        documents.add( BSONUtils.decoder().readObject( new ChannelBufferInputStream( buffer ) ) );
    }
}
 
Example 6
Source File: OpQuery.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void decode( ChannelBuffer buffer ) throws IOException {
    super.decode( buffer );
    flags = buffer.readInt();
    fullCollectionName = readCString( buffer );
    numberToSkip = buffer.readInt();
    numberToReturn = buffer.readInt();
    query = BSONUtils.decoder().readObject( new ChannelBufferInputStream( buffer ) );
    if ( buffer.readable() ) {
        returnFieldSelector = BSONUtils.decoder().readObject( new ChannelBufferInputStream( buffer ) );
        logger.info( "found fieldSeclector: {}", returnFieldSelector );
    }
}
 
Example 7
Source File: OpKillCursors.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Override
public void decode( ChannelBuffer buffer ) throws IOException {
    super.decode( buffer );

    buffer.readInt();
    numberOfCursorIDs = buffer.readInt();
    while ( buffer.readable() ) {
        cursorIDs.add( buffer.readLong() );
    }
}
 
Example 8
Source File: HttpProxyHandler.java    From zuul-netty with Apache License 2.0 5 votes vote down vote up
private static String dumpBuffer(ChannelBuffer buffer) {
    StringBuffer output = new StringBuffer();
    while (buffer.readable()) {
        try {
            output.append(new String(new byte[]{buffer.readByte()}, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
    return output.toString();
}
 
Example 9
Source File: FrameDecoder.java    From android-netty with Apache License 2.0 5 votes vote down vote up
/**
 * Gets called on
 * {@link #channelDisconnected(ChannelHandlerContext, ChannelStateEvent)}
 * and {@link #channelClosed(ChannelHandlerContext, ChannelStateEvent)}
 */
protected void cleanup(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
	try {
		ChannelBuffer cumulation = this.cumulation;
		if (cumulation == null) {
			return;
		}

		this.cumulation = null;

		if (cumulation.readable()) {
			// Make sure all frames are read before notifying a closed
			// channel.
			callDecode(ctx, ctx.getChannel(), cumulation, null);
		}

		// Call decodeLast() finally. Please note that decodeLast() is
		// called even if there's nothing more to read from the buffer to
		// notify a user that the connection was closed explicitly.
		Object partialFrame = decodeLast(ctx, ctx.getChannel(), cumulation);
		if (partialFrame != null) {
			unfoldAndFireMessageReceived(ctx, null, partialFrame);
		}
	} finally {
		ctx.sendUpstream(e);
	}
}
 
Example 10
Source File: FrameDecoder.java    From android-netty with Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

	Object m = e.getMessage();
	if (!(m instanceof ChannelBuffer)) {
		ctx.sendUpstream(e);
		return;
	}

	ChannelBuffer input = (ChannelBuffer) m;
	if (!input.readable()) {
		return;
	}

	if (cumulation == null) {
		try {
			// the cumulation buffer is not created yet so just pass the
			// input to callDecode(...) method
			callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
		} finally {
			updateCumulation(ctx, input);
		}
	} else {
		input = appendToCumulation(input);
		try {
			callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
		} finally {
			updateCumulation(ctx, input);
		}
	}
}
 
Example 11
Source File: FileClientHandler.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	if (!this.readingChunks) {
		HttpResponse response = (HttpResponse) e.getMessage();
		LOGGER.info("STATUS: " + response.getStatus());
		if ((response.getStatus().getCode() == 200)
				&& (response.isChunked())) {
			this.readingChunks = true;
		} else {
			ChannelBuffer content = response.getContent();
			if (content.readable())
				this.responseContent.append(content
						.toString(CharsetUtil.UTF_8));
		}
	} else {
		HttpChunk chunk = (HttpChunk) e.getMessage();
		if (chunk.isLast()) {
			this.readingChunks = false;
			this.responseContent.append(chunk.getContent().toString(
					CharsetUtil.UTF_8));

			String json = this.responseContent.toString();
			this.result = ((Result) JSONUtil.parseObject(json,Result.class));
		} else {
			this.responseContent.append(chunk.getContent().toString(
					CharsetUtil.UTF_8));
		}
	}
}
 
Example 12
Source File: PcepFactories.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public PcepMessage readFrom(ChannelBuffer bb) throws PcepParseException, PcepOutOfBoundMessageException {

    if (!bb.readable()) {
        throw new PcepParseException("Empty message received");
    }

    /*
     * 0                   1                   2                   3
     * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
     * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     * | Ver |  Flags  |                                               |
     * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
     *
     * Currently Version 1 is supported
     * Currently no flags are used, it is all ignored
     */

    byte packetVersion = bb.getByte(bb.readerIndex());
    packetVersion = (byte) (packetVersion >> SHIFT_FLAG);
    PcepFactory factory;

    switch (packetVersion) {

    case 1:
        factory = org.onosproject.pcepio.protocol.ver1.PcepFactoryVer1.INSTANCE;
        break;
    default:
        throw new PcepParseException("Unknown Packet version: " + packetVersion);
    }
    return factory.getReader().readFrom(bb);
}
 
Example 13
Source File: ChannelBuffers.java    From simple-netty-source with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new buffer whose content is a copy of the specified
 * {@code buffer}'s readable bytes.  The new buffer's {@code readerIndex}
 * and {@code writerIndex} are {@code 0} and {@code buffer.readableBytes}
 * respectively.
 */
public static ChannelBuffer copiedBuffer(ChannelBuffer buffer) {
    if (buffer.readable()) {
        return buffer.copy();
    } else {
        return EMPTY_BUFFER;
    }
}
 
Example 14
Source File: ChannelBuffers.java    From simple-netty-source with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new buffer which wraps the specified buffer's readable bytes.
 * A modification on the specified buffer's content will be visible to the
 * returned buffer.
 */
public static ChannelBuffer wrappedBuffer(ChannelBuffer buffer) {
    if (buffer.readable()) {
        return buffer.slice();
    } else {
        return EMPTY_BUFFER;
    }
}
 
Example 15
Source File: SyslogUtils.java    From mt-flume with Apache License 2.0 4 votes vote down vote up
public Event extractEvent(ChannelBuffer in){

    /* for protocol debugging
    ByteBuffer bb = in.toByteBuffer();
    int remaining = bb.remaining();
    byte[] buf = new byte[remaining];
    bb.get(buf);
    HexDump.dump(buf, 0, System.out, 0);
    */

    byte b = 0;
    Event e = null;
    boolean doneReading = false;

    try {
      while (!doneReading && in.readable()) {
        b = in.readByte();
        switch (m) {
        case START:
          if (b == '<') {
            m = Mode.PRIO;
          } else if(b == '\n'){
          //If the character is \n, it was because the last event was exactly
          //as long  as the maximum size allowed and
          //the only remaining character was the delimiter - '\n', or
          //multiple delimiters were sent in a row.
          //Just ignore it, and move forward, don't change the mode.
          //This is a no-op, just ignore it.
            logger.debug("Delimiter found while in START mode, ignoring..");

          } else {
            isBadEvent = true;
            baos.write(b);
            //Bad event, just dump everything as if it is data.
            m = Mode.DATA;
          }
          break;
        case PRIO:
          if (b == '>') {
            m = Mode.DATA;
          } else {
            char ch = (char) b;
            prio.append(ch);
            if (!Character.isDigit(ch)) {
              isBadEvent = true;
              //Append the priority to baos:
              String badPrio = "<"+ prio;
              baos.write(badPrio.getBytes());
              //If we hit a bad priority, just write as if everything is data.
              m = Mode.DATA;
            }
          }
          break;
        case DATA:
          // TCP syslog entries are separated by '\n'
          if (b == '\n') {
            e = buildEvent();
            doneReading = true;
          } else {
            baos.write(b);
          }
          if(baos.size() == this.maxSize && !doneReading){
            isIncompleteEvent = true;
            e = buildEvent();
            doneReading = true;
          }
          break;
        }

      }

      // UDP doesn't send a newline, so just use what we received
      if (e == null && isUdp) {
        doneReading = true;
        e = buildEvent();
      }
    //} catch (IndexOutOfBoundsException eF) {
    //    e = buildEvent(prio, baos);
    } catch (IOException e1) {
      //no op
    } finally {
      // no-op
    }

    return e;
  }
 
Example 16
Source File: ChannelBuffers.java    From simple-netty-source with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new composite buffer which wraps the readable bytes of the
 * specified buffers without copying them.  A modification on the content
 * of the specified buffers will be visible to the returned buffer.
 * If gathering is {@code true} then gathering writes will be used when ever
 * possible.
 *
 * @throws IllegalArgumentException
 *         if the specified buffers' endianness are different from each
 *         other
 */
public static ChannelBuffer wrappedBuffer(boolean gathering, ChannelBuffer... buffers) {
    switch (buffers.length) {
    case 0:
        break;
    case 1:
        if (buffers[0].readable()) {
            return wrappedBuffer(buffers[0]);
        }
        break;
    default:
        ByteOrder order = null;
        final List<ChannelBuffer> components = new ArrayList<ChannelBuffer>(buffers.length);
        for (ChannelBuffer c: buffers) {
            if (c == null) {
                break;
            }
            if (c.readable()) {
                if (order != null) {
                    if (!order.equals(c.order())) {
                        throw new IllegalArgumentException(
                                "inconsistent byte order");
                    }
                } else {
                    order = c.order();
                }
                if (c instanceof CompositeChannelBuffer) {
                    // Expand nested composition.
                    components.addAll(
                            ((CompositeChannelBuffer) c).decompose(
                                    c.readerIndex(), c.readableBytes()));
                } else {
                    // An ordinary buffer (non-composite)
                    components.add(c.slice());
                }
            }
        }
        return compositeBuffer(order, components, gathering);
    }
    return EMPTY_BUFFER;
}
 
Example 17
Source File: Fetcher.java    From incubator-tajo with Apache License 2.0 4 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {
  messageReceiveCount++;
  try {
    if (!readingChunks) {
      HttpResponse response = (HttpResponse) e.getMessage();

      StringBuilder sb = new StringBuilder();
      if (LOG.isDebugEnabled()) {
        sb.append("STATUS: ").append(response.getStatus())
            .append(", VERSION: ").append(response.getProtocolVersion())
            .append(", HEADER: ");
      }
      if (!response.getHeaderNames().isEmpty()) {
        for (String name : response.getHeaderNames()) {
          for (String value : response.getHeaders(name)) {
            if (LOG.isDebugEnabled()) {
              sb.append(name).append(" = ").append(value);
            }
            if (this.length == -1 && name.equals("Content-Length")) {
              this.length = Long.valueOf(value);
            }
          }
        }
      }
      if (LOG.isDebugEnabled()) {
        LOG.debug(sb.toString());
      }

      if (response.getStatus() == HttpResponseStatus.NO_CONTENT) {
        LOG.info("There are no data corresponding to the request");
        return;
      }

      this.raf = new RandomAccessFile(file, "rw");
      this.fc = raf.getChannel();

      if (response.isChunked()) {
        readingChunks = true;
      } else {
        ChannelBuffer content = response.getContent();
        if (content.readable()) {
          fc.write(content.toByteBuffer());
        }
      }
    } else {
      HttpChunk chunk = (HttpChunk) e.getMessage();
      if (chunk.isLast()) {
        readingChunks = false;
        long fileLength = file.length();
        if (fileLength == length) {
          LOG.info("Data fetch is done (total received bytes: " + fileLength
              + ")");
        } else {
          LOG.info("Data fetch is done, but cannot get all data "
              + "(received/total: " + fileLength + "/" + length + ")");
        }
      } else {
        fc.write(chunk.getContent().toByteBuffer());
      }
    }
  } finally {
    if(raf != null) {
      fileLen = file.length();
    }

    if(fileLen >= length){
      IOUtils.cleanup(LOG, fc, raf);

    }
  }
}