Java Code Examples for org.jboss.netty.buffer.ChannelBuffer

The following examples show how to use org.jboss.netty.buffer.ChannelBuffer. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: hadoop   Source File: RpcProgram.java    License: Apache License 2.0 6 votes vote down vote up
private void sendAcceptedReply(RpcCall call, SocketAddress remoteAddress,
    AcceptState acceptState, ChannelHandlerContext ctx) {
  RpcAcceptedReply reply = RpcAcceptedReply.getInstance(call.getXid(),
      acceptState, Verifier.VERIFIER_NONE);

  XDR out = new XDR();
  reply.write(out);
  if (acceptState == AcceptState.PROG_MISMATCH) {
    out.writeInt(lowProgVersion);
    out.writeInt(highProgVersion);
  }
  ChannelBuffer b = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap()
      .buffer());
  RpcResponse rsp = new RpcResponse(b, remoteAddress);
  RpcUtil.sendRpcResponse(ctx, rsp);
}
 
Example 2
@Override
public OFActionVendor readFrom(ChannelBuffer data) {
    data.markReaderIndex();
    OFActionNiciraVendorDemux demux = new OFActionNiciraVendorDemux();
    demux.readFrom(data);
    data.resetReaderIndex();

    switch(demux.getSubtype()) {
        case OFActionNiciraTtlDecrement.TTL_DECREMENT_SUBTYPE:
            OFActionNiciraTtlDecrement ttlAction = new OFActionNiciraTtlDecrement();
            ttlAction.readFrom(data);
            return ttlAction;
        default:
            logger.error("Unknown Nicira vendor action subtype: "+demux.getSubtype());
            return null;
    }
}
 
Example 3
Source Project: onos   Source File: BgpUpdateMsgTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * In this test case, Marker is set as 0 in input and expecting
 * an exception.
 */
@Test(expected = BgpParseException.class)
public void bgpUpdateMessageTest02() throws BgpParseException {
    byte[] updateMsg = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
            0x00, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
            (byte) 0xff, (byte) 0xff, 0x00, 0x17, 0x02, 0x00, 0x00, 0x00, 0x00};

    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(updateMsg);

    BgpMessageReader<BgpMessage> reader = BgpFactories.getGenericReader();
    BgpMessage message;
    BgpHeader bgpHeader = new BgpHeader();
    message = reader.readFrom(buffer, bgpHeader);

    assertThat(message, instanceOf(BgpUpdateMsg.class));
}
 
Example 4
Source Project: onos   Source File: PceccCapabilityTlv.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public int write(ChannelBuffer c) {
    int iLenStartIndex = c.writerIndex();
    int temp = 0;
    c.writeShort(TYPE);
    c.writeShort(LENGTH);
    if (isRawValueSet) {
        c.writeInt(rawValue);
    } else {
        if (sBit) {
            temp = temp | SBIT_CHECK;
        }
        c.writeInt(temp);
    }
    return c.writerIndex() - iLenStartIndex;
}
 
Example 5
Source Project: ikasoa   Source File: TNettyTransport.java    License: MIT License 6 votes vote down vote up
public TNettyTransport(Channel channel, ChannelBuffer inputBuffer, TNettyTransportType tNettyTransportType) {
	this.channel = channel;
	this.inputBuffer = inputBuffer;
	this.tNettyTransportType = tNettyTransportType;
	this.outputBuffer = ChannelBuffers.dynamicBuffer(DEFAULT_OUTPUT_BUFFER_SIZE);
	this.initialReaderIndex = inputBuffer.readerIndex();
	if (!inputBuffer.hasArray()) {
		buffer = null;
		bufferPosition = 0;
		initialBufferPosition = bufferEnd = -1;
	} else {
		buffer = inputBuffer.array();
		initialBufferPosition = bufferPosition = inputBuffer.arrayOffset() + inputBuffer.readerIndex();
		bufferEnd = bufferPosition + inputBuffer.readableBytes();
		inputBuffer.readerIndex(inputBuffer.readerIndex() + inputBuffer.readableBytes());
	}
}
 
Example 6
Source Project: mt-flume   Source File: SyslogUDPSource.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent mEvent) {
  try {
    syslogUtils.setEventSize(maxsize);
    Event e = syslogUtils.extractEvent((ChannelBuffer)mEvent.getMessage());
    if (e == null) {
      return;
    }
    getChannelProcessor().processEvent(e);
    counterGroup.incrementAndGet("events.success");
  } catch (ChannelException ex) {
    counterGroup.incrementAndGet("events.dropped");
    logger.error("Error writting to channel", ex);
    return;
  }
}
 
Example 7
Source Project: onos   Source File: BgpUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the appropriate actions after detecting BGP UPDATE
 * Attribute Length Error: send NOTIFICATION and close the channel.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param attrTypeCode the attribute type code
 * @param attrLen the attribute length (in octets)
 * @param attrFlags the attribute flags
 * @param message the message with the data
 */
private static void actionsBgpUpdateAttributeLengthError(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int attrTypeCode,
                            int attrLen,
                            int attrFlags,
                            ChannelBuffer message) {
    log.debug("BGP RX UPDATE Error from {}: Attribute Length Error",
              bgpSession.remoteInfo().address());

    //
    // ERROR: Attribute Length Error
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.UpdateMessageError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.UpdateMessageError.ATTRIBUTE_LENGTH_ERROR;
    ChannelBuffer data =
        prepareBgpUpdateNotificationDataPayload(attrTypeCode, attrLen,
                                                attrFlags, message);
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               data);
    ctx.getChannel().write(txMessage);
    bgpSession.closeSession(ctx);
}
 
Example 8
Source Project: simple-netty-source   Source File: ChannelBuffers.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new Java heap buffer with the specified {@code endianness}
 * and {@code capacity}.  The new buffer's {@code readerIndex} and
 * {@code writerIndex} are {@code 0}.
 */
public static ChannelBuffer buffer(ByteOrder endianness, int capacity) {
    if (endianness == BIG_ENDIAN) {
        if (capacity == 0) {
            return EMPTY_BUFFER;
        }
        return new BigEndianHeapChannelBuffer(capacity);
    } else if (endianness == LITTLE_ENDIAN) {
        if (capacity == 0) {
            return EMPTY_BUFFER;
        }
        return new LittleEndianHeapChannelBuffer(capacity);
    } else {
        throw new NullPointerException("endianness");
    }
}
 
Example 9
Source Project: usergrid   Source File: MongoMessageFrame.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf ) throws Exception {

    if ( buf.readableBytes() < 4 ) {
        return null;
    }

    // logger.info("Mongo message decoding...");

    int length = buf.getInt( buf.readerIndex() );

    if ( length < 0 ) {
        return null;
    }

    if ( buf.readableBytes() < length ) {
        return null;
    }

    ChannelBuffer frame = buf.readSlice( length );
    return frame;
}
 
Example 10
Source Project: onos   Source File: BgpUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Parses BGP UPDATE Attribute Type MULTI_EXIT_DISC.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param attrTypeCode the attribute type code
 * @param attrLen the attribute length (in octets)
 * @param attrFlags the attribute flags
 * @param message the message to parse
 * @return the parsed MULTI_EXIT_DISC value
 * @throws BgpMessage.BgpParseException
 */
private static long parseAttributeTypeMultiExitDisc(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int attrTypeCode,
                            int attrLen,
                            int attrFlags,
                            ChannelBuffer message)
    throws BgpMessage.BgpParseException {

    // Check the Attribute Length
    if (attrLen != BgpConstants.Update.MultiExitDisc.LENGTH) {
        // ERROR: Attribute Length Error
        actionsBgpUpdateAttributeLengthError(
            bgpSession, ctx, attrTypeCode, attrLen, attrFlags, message);
        String errorMsg = "Attribute Length Error";
        throw new BgpMessage.BgpParseException(errorMsg);
    }

    long multiExitDisc = message.readUnsignedInt();
    return multiExitDisc;
}
 
Example 11
Source Project: onos   Source File: BgpLinkAttrMaxLinkBandwidth.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads the BGP link attributes of Maximum link bandwidth.
 *
 * @param cb Channel buffer
 * @param type type of this tlv
 * @return object of type BgpLinkAttrMaxLinkBandwidth
 * @throws BgpParseException while parsing BgpLinkAttrMaxLinkBandwidth
 */
public static BgpLinkAttrMaxLinkBandwidth read(ChannelBuffer cb, short type)
        throws BgpParseException {
    float maxBandwidth;
    short lsAttrLength = cb.readShort();

    if ((lsAttrLength != MAX_BANDWIDTH_LEN)
            || (cb.readableBytes() < lsAttrLength)) {
        Validation.validateLen(BgpErrorType.UPDATE_MESSAGE_ERROR,
                               BgpErrorType.ATTRIBUTE_LENGTH_ERROR,
                               lsAttrLength);
    }

    maxBandwidth = ieeeToFloatRead(cb.readInt()) * NO_OF_BITS;

    return BgpLinkAttrMaxLinkBandwidth.of(maxBandwidth, type);
}
 
Example 12
Source Project: onos   Source File: BgpFsPortNum.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Reads the channel buffer and returns object.
 *
 * @param cb channelBuffer
 * @return object of flow spec port number
 * @throws BgpParseException while parsing BgpFsPortNum
 */
public static BgpFsPortNum read(ChannelBuffer cb) throws BgpParseException {
    List<BgpFsOperatorValue> operatorValue = new LinkedList<>();
    byte option;
    short port;

    do {
        option = (byte) cb.readByte();
        int len = (option & Constants.BGP_FLOW_SPEC_LEN_MASK) >> 4;
        if ((1 << len) == 1) {
            port = cb.readByte();
            operatorValue.add(new BgpFsOperatorValue(option, new byte[] {(byte) port}));
        } else {
            port = cb.readShort();
            operatorValue.add(new BgpFsOperatorValue(option, new byte[] {(byte) (port >> 8), (byte) port}));
        }


    } while ((option & Constants.BGP_FLOW_SPEC_END_OF_LIST_MASK) == 0);

    return new BgpFsPortNum(operatorValue);
}
 
Example 13
@Override
public void writeTo(ChannelBuffer data) {
    data.writeShort(this.portNumber);
    data.writeShort((short) 0); // pad
    data.writeInt(0); // pad
    data.writeLong(this.receivePackets);
    data.writeLong(this.transmitPackets);
    data.writeLong(this.receiveBytes);
    data.writeLong(this.transmitBytes);
    data.writeLong(this.receiveDropped);
    data.writeLong(this.transmitDropped);
    data.writeLong(this.receiveErrors);
    data.writeLong(this.transmitErrors);
    data.writeLong(this.receiveFrameErrors);
    data.writeLong(this.receiveOverrunErrors);
    data.writeLong(this.receiveCRCErrors);
    data.writeLong(this.collisions);
}
 
Example 14
Source Project: usergrid   Source File: OpInsert.java    License: 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 15
Source Project: pinpoint   Source File: ControlMessageEncoder.java    License: Apache License 2.0 5 votes vote down vote up
public byte[] encode(Map<String, Object> value) throws ProtocolException {
    ChannelBuffer cb = ChannelBuffers.dynamicBuffer(100);
    encode(value, cb);

    int writeIndex = cb.writerIndex();
    byte[] result = new byte[writeIndex];

    cb.readBytes(result);

    return result;
}
 
Example 16
Source Project: flink   Source File: NetworkFailureHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext context, MessageEvent event) throws Exception {
	if (blocked.get()) {
		return;
	}
	ChannelBuffer msg = (ChannelBuffer) event.getMessage();
	sourceChannel.write(msg);
}
 
Example 17
Source Project: onos   Source File: LspEntry.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Sets the LSP entry values for  LSP entry from byte buffer.
 *
 * @param channelBuffer channel Buffer instance
 */
public void readFrom(ChannelBuffer channelBuffer) {
    this.setRemainingTime(channelBuffer.readUnsignedShort());
    byte[] tempByteArray = new byte[IsisUtil.ID_PLUS_TWO_BYTE];
    channelBuffer.readBytes(tempByteArray, 0, IsisUtil.ID_PLUS_TWO_BYTE);
    this.setLspId(IsisUtil.systemIdPlus(tempByteArray));
    this.setLspSequenceNumber(channelBuffer.readInt());
    this.setLspChecksum(channelBuffer.readUnsignedShort());
}
 
Example 18
Source Project: onos   Source File: SharedRiskLinkGroupSubTlv.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int write(ChannelBuffer c) {
    int iLenStartIndex = c.writerIndex();
    c.writeShort(TYPE);
    c.writeShort(hLength);
    for (int b : srlgValue) {
        c.writeInt(b);
    }
    return c.writerIndex() - iLenStartIndex;
}
 
Example 19
Source Project: onos   Source File: PcepLspaObjectVer1.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads channel buffer and returns object of PcepLspaObject.
 *
 * @param cb of type channel buffer.
 * @return object of PcepLspaObject
 * @throws PcepParseException while parsing lspa object from channel buffer
 */
public static PcepLspaObject read(ChannelBuffer cb) throws PcepParseException {

    log.debug("LspaObject::read");
    PcepObjectHeader lspaObjHeader;
    int iExcludeAny;
    int iIncludeAny;
    int iIncludeAll;
    byte cSetupPriority;
    byte cHoldPriority;
    boolean bLFlag;
    byte flags;

    // Optional TLV
    LinkedList<PcepValueType> llOptionalTlv;

    lspaObjHeader = PcepObjectHeader.read(cb);

    //take only Lspa Object buffer.
    ChannelBuffer tempCb = cb.readBytes(lspaObjHeader.getObjLen() - OBJECT_HEADER_LENGTH);
    iExcludeAny = tempCb.readInt();
    iIncludeAny = tempCb.readInt();
    iIncludeAll = tempCb.readInt();
    cSetupPriority = tempCb.readByte();
    cHoldPriority = tempCb.readByte();
    flags = tempCb.readByte();
    tempCb.readByte();

    bLFlag = (flags & (byte) LFLAG_SET) == LFLAG_SET;

    llOptionalTlv = parseOptionalTlv(tempCb);

    return new PcepLspaObjectVer1(lspaObjHeader, bLFlag, iExcludeAny, iIncludeAny, iIncludeAll, cSetupPriority,
            cHoldPriority, llOptionalTlv);
}
 
Example 20
/**
 * Creates a new stream which writes data to the specified {@code buffer}.
 */
public ChannelBufferServletOutputStream(ChannelBuffer buffer) {
    if (buffer == null) {
        throw new NullPointerException("buffer");
    }
    this.buffer = buffer;
    startIndex = buffer.writerIndex();
}
 
Example 21
Source Project: onos   Source File: PcepUpdateMsgExtTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test case is for SRP object, LSP object(StatefulLspDbVerTlv), ERO object,LSPA
 * bandwidth object in PcepUpdate message.
 */
@Test
public void pcepUpdateMsgTest11() throws PcepParseException, PcepOutOfBoundMessageException {
    byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x54,
            0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, //SRP object
            0x20, 0x10, 0x00, 0x14, 0x00, 0x00, 0x10, 0x03, //LSP object
            0x00, 0x17, 0x00, 0x08, //StatefulLspDbVerTlv
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
            0x07, 0x10, 0x00, 0x14, 0x01, 0x08, 0x11, 0x01, //ERO Object
            0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
            0x01, 0x01, 0x04, 0x00,
            0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA object
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00,
            0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00}; //Bandwidth object

    byte[] testupdateMsg = {0};
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(updateMsg);

    PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
    PcepMessage message = null;

    message = reader.readFrom(buffer);

    assertThat(message, instanceOf(PcepUpdateMsg.class));
    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    message.writeTo(buf);
    testupdateMsg = buf.array();

    int readLen = buf.writerIndex() - 0;
    testupdateMsg = new byte[readLen];
    buf.readBytes(testupdateMsg, 0, readLen);

    assertThat(testupdateMsg, is(updateMsg));
}
 
Example 22
Source Project: netty-file-parent   Source File: FileClientHandler.java    License: 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 23
Source Project: onos   Source File: PcepUpdateMsgExtTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test case is for SRP object, LSP object(StatefulRsvpErrorSpecTlv), ERO object,LSPA
 * bandwidth object in PcepUpdate message.
 */
@Test
public void pcepUpdateMsgTest10() throws PcepParseException, PcepOutOfBoundMessageException {
    byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x50,
            0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, //SRP object
            0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP object
            0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08, //StatefulLspErrorCodeTlv
            0x07, 0x10, 0x00, 0x14, 0x01, 0x08, 0x11, 0x01, //ERO Object
            0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
            0x01, 0x01, 0x04, 0x00,
            0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPa object
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00,
            0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00 }; //Bandwidth object

    byte[] testupdateMsg = {0};
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(updateMsg);

    PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
    PcepMessage message = null;

    message = reader.readFrom(buffer);

    assertThat(message, instanceOf(PcepUpdateMsg.class));
    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    message.writeTo(buf);
    testupdateMsg = buf.array();

    int readLen = buf.writerIndex() - 0;
    testupdateMsg = new byte[readLen];
    buf.readBytes(testupdateMsg, 0, readLen);

    assertThat(testupdateMsg, is(updateMsg));
}
 
Example 24
Source Project: onos   Source File: BgpUpdate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parses a message that contains encoded IPv4 network prefixes.
 * <p>
 * The IPv4 prefixes are encoded in the form:
 * <Length, Prefix> where Length is the length in bits of the IPv4 prefix,
 * and Prefix is the IPv4 prefix (padded with trailing bits to the end
 * of an octet).
 *
 * @param totalLength the total length of the data to parse
 * @param message the message with data to parse
 * @return a collection of parsed IPv4 network prefixes
 * @throws BgpMessage.BgpParseException
 */
private static Collection<Ip4Prefix> parsePackedIp4Prefixes(
                                            int totalLength,
                                            ChannelBuffer message)
    throws BgpMessage.BgpParseException {
    Collection<Ip4Prefix> result = new ArrayList<>();

    if (totalLength == 0) {
        return result;
    }

    // Parse the data
    byte[] buffer = new byte[Ip4Address.BYTE_LENGTH];
    int dataEnd = message.readerIndex() + totalLength;
    while (message.readerIndex() < dataEnd) {
        int prefixBitlen = message.readUnsignedByte();
        int prefixBytelen = (prefixBitlen + 7) / 8;     // Round-up
        if (message.readerIndex() + prefixBytelen > dataEnd) {
            String errorMsg = "Malformed Network Prefixes";
            throw new BgpMessage.BgpParseException(errorMsg);
        }

        message.readBytes(buffer, 0, prefixBytelen);
        Ip4Prefix prefix = Ip4Prefix.valueOf(Ip4Address.valueOf(buffer),
                                             prefixBitlen);
        result.add(prefix);
    }

    return result;
}
 
Example 25
Source Project: onos   Source File: LabelSubObject.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads the channel buffer and returns object of LabelSubObject.
 *
 * @param c type of channel buffer
 * @return object of LabelSubObject
 */
public static PcepValueType read(ChannelBuffer c) {
    byte flags = c.readByte();
    byte cType = c.readByte();
    int contents = c.readInt();
    return new LabelSubObject(flags, cType, contents);
}
 
Example 26
Source Project: onos   Source File: PcepFecObjectIPv6Ver1.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int write(ChannelBuffer cb) throws PcepParseException {

    int objStartIndex = cb.writerIndex();

    //write common header
    int objLenIndex = fecObjHeader.write(cb);
    cb.writeBytes(nodeID);

    //now write FEC IPv4 Object Length
    cb.setShort(objLenIndex, (short) (cb.writerIndex() - objStartIndex));
    return cb.writerIndex();
}
 
Example 27
Source Project: onos   Source File: PcepInterLayerObjectVer1.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int write(ChannelBuffer cb) throws PcepParseException {

    //write Object header
    int objStartIndex = cb.writerIndex();

    int objLenIndex = interLayerObjHeader.write(cb);

    if (objLenIndex <= 0) {
        throw new PcepParseException(" ObjectLength Index is " + objLenIndex);
    }

    int iTemp = 0;

    if (bIFlag) {
        iTemp = iTemp | (byte) IFLAG_SHIFT_VALUE;
    }
    if (bNFlag) {
        iTemp = iTemp | (byte) NFLAG_SHIFT_VALUE;
    }

    cb.writeInt(iTemp);

    //Update object length now
    int length = cb.writerIndex() - objStartIndex;
    //will be helpful during print().
    interLayerObjHeader.setObjLen((short) length);
    cb.setShort(objLenIndex, (short) length);

    objLenIndex = cb.writerIndex();
    return objLenIndex;
}
 
Example 28
/**
 * Write the vendor data to the channel buffer
 */
public void writeTo(ChannelBuffer data) {
    super.writeTo(data);
    data.writeByte(tableIndex);
    data.writeByte(pad1);
    data.writeByte(pad2);
    data.writeByte(pad3);
    data.writeInt(netMask);
}
 
Example 29
Source Project: pinlater   Source File: BytesUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts UNREAD BYTES to byte array from ChannelBuffer
 * NOTE: this will consume all the readable bytes from channel buffer
 */
public static byte[] toBytesWithoutConsume(ChannelBuffer input) {
  // save old reader's index & reset it
  int oldIndex = input.readerIndex();
  input.resetReaderIndex();
  // read bytes out
  byte[] output = new byte[input.readableBytes()];
  input.readBytes(output);
  // set reader's index back to
  input.readerIndex(oldIndex);
  return output;
}
 
Example 30
Source Project: simple-netty-source   Source File: ChannelBuffers.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * The default implementation of {@link ChannelBuffer#indexOf(int, int, byte)}.
 * This method is useful when implementing a new buffer type.
 */
public static int indexOf(ChannelBuffer buffer, int fromIndex, int toIndex, byte value) {
    if (fromIndex <= toIndex) {
        return firstIndexOf(buffer, fromIndex, toIndex, value);
    } else {
        return lastIndexOf(buffer, fromIndex, toIndex, value);
    }
}
 
Example 31
Source Project: onos   Source File: PcepUpdateMsgTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test case checks for SRP, LSP (SymbolicPathNameTlv, StatefulIPv4LspIdentidiersTlv,
 * SymbolicPathNameTlv), ERO objects in PcUpd message.
 */
@Test
public void pcepUpdateMsgTest4() throws PcepParseException, PcepOutOfBoundMessageException {

    byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x40,
            0x21, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, //SRP object
            0x00, 0x11, 0x00, 0x02,  0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
            0x20, 0x10, 0x00, 0x24, 0x00, 0x00, 0x10, 0x03, //LSP object
            0x00, 0x12, 0x00, 0x10, //StatefulIPv4LspIdentidiersTlv
            (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x00, 0x01, (byte) 0x80, 0x01,
            (byte) 0xb6, 0x02, 0x4e, 0x1f, (byte) 0xb6, 0x02, 0x4e, 0x20,
            0x00, 0x11, 0x00, 0x02,  0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
            0x07, 0x10, 0x00, 0x04 }; //ERO object

    byte[] testupdateMsg = {0};
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(updateMsg);

    PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
    PcepMessage message = null;

    message = reader.readFrom(buffer);

    assertThat(message, instanceOf(PcepUpdateMsg.class));
    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    message.writeTo(buf);
    testupdateMsg = buf.array();

    int readLen = buf.writerIndex() - 0;
    testupdateMsg = new byte[readLen];
    buf.readBytes(testupdateMsg, 0, readLen);

    assertThat(testupdateMsg, is(updateMsg));
}
 
Example 32
Source Project: pinpoint   Source File: ControlMessageEncoder.java    License: Apache License 2.0 5 votes vote down vote up
private void encodeMap(Map<?, ?> map, ChannelBuffer out) throws ProtocolException {
    out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_START);
    for (Object element : map.entrySet()) {
        Map.Entry<?, ?> entry = (Map.Entry<?, ?>) element;
        encode(entry.getKey(), out);
        encode(entry.getValue(), out);
    }
    out.writeByte((byte) ControlMessageProtocolConstant.CONTROL_CHARACTER_MAP_END);
}
 
Example 33
Source Project: onos   Source File: NexthopIPv4addressTlv.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public int write(ChannelBuffer c) {
    int iStartIndex = c.writerIndex();
    c.writeShort(TYPE);
    c.writeShort(VALUE_LENGTH);
    c.writeInt(rawValue);
    return c.writerIndex() - iStartIndex;
}
 
Example 34
Source Project: onos   Source File: PcepUpdateMsgVer1.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public PcepUpdateMsg readFrom(ChannelBuffer cb) throws PcepParseException {

    if (cb.readableBytes() < PACKET_MINIMUM_LENGTH) {
        throw new PcepParseException("Readable bytes is less than update message minimum length");
    }

    llUpdateRequestList = new LinkedList<>();

    // fixed value property version == 1
    byte version = cb.readByte();
    version = (byte) (version >> PcepMessageVer1.SHIFT_FLAG);
    if (version != PACKET_VERSION) {
        throw new PcepParseException("Wrong version. Expected=PcepVersion.PCEP_1(1), got=" + version);
    }
    // fixed value property type == 11
    byte type = cb.readByte();
    if (type != MSG_TYPE.getType()) {
        throw new PcepParseException("Wrong type. Expected=PcepType.UPDATE(11), got=" + type);
    }
    short length = cb.readShort();
    if (length < PACKET_MINIMUM_LENGTH) {
        throw new PcepParseException("Wrong length. Expected to be >= " + PACKET_MINIMUM_LENGTH + ", was: "
                + length);
    }

    log.debug("reading update message of length " + length);

    // parse Update Request list
    if (!parseUpdateRequestList(cb)) {
        throw new PcepParseException("parsing Update Request List Failed.");
    }

    return new PcepUpdateMsgVer1(llUpdateRequestList);
}
 
Example 35
Source Project: onos   Source File: IsisMessageEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

    byte[] byteMsg = (byte[]) msg;
    log.debug("Encoding isisMessage of length {}", byteMsg.length);
    ChannelBuffer channelBuffer = ChannelBuffers.buffer(byteMsg.length);
    channelBuffer.writeBytes(byteMsg);

    return channelBuffer;
}
 
Example 36
Source Project: onos   Source File: PcepUpdateMsgTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test case checks for SRP, LSP (SymbolicPathNameTlv, SymbolicPathNameTlv),
 * ERO (IPv4SubObject, IPv4SubObject), LSPA, Bandwidth, Metric objects in PcUpd message.
 */
@Test
public void pcepUpdateMsgTest34() throws PcepParseException, PcepOutOfBoundMessageException {

    byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x64,
            0x21, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, //SRP object
            0x00, 0x11, 0x00, 0x02,  0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
            0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP object
            0x00, 0x11, 0x00, 0x02,  0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
            0x07, 0x10, 0x00, 0x14, 0x01, 0x08, 0x11, 0x01, //ERO object
            0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
            0x01, 0x01, 0x04, 0x00,
            0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA object
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00,
            0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth object
            0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20 }; //Metric object

    byte[] testupdateMsg = {0};
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(updateMsg);

    PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
    PcepMessage message = null;

    message = reader.readFrom(buffer);

    assertThat(message, instanceOf(PcepUpdateMsg.class));
    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    message.writeTo(buf);
    testupdateMsg = buf.array();

    int readLen = buf.writerIndex() - 0;
    testupdateMsg = new byte[readLen];
    buf.readBytes(testupdateMsg, 0, readLen);

    assertThat(testupdateMsg, is(updateMsg));
}
 
Example 37
Source Project: onos   Source File: RemoteInterfaceIpAddress.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Reads bytes from channel buffer .
 *
 * @param channelBuffer channel buffer instance
 * @throws OspfParseException might throws exception while parsing packet
 */
public void readFrom(ChannelBuffer channelBuffer) throws OspfParseException {
    while (channelBuffer.readableBytes() >= OspfUtil.FOUR_BYTES) {
        try {
            byte[] tempByteArray = new byte[OspfUtil.FOUR_BYTES];
            channelBuffer.readBytes(tempByteArray, 0, OspfUtil.FOUR_BYTES);
            this.addRemoteInterfaceAddress(InetAddress.getByAddress(tempByteArray).getHostName());
        } catch (Exception e) {
            log.debug("Error::RemoteInterfaceIPAddress:: {}", e.getMessage());
            throw new OspfParseException(OspfErrorType.OSPF_MESSAGE_ERROR,
                                         OspfErrorType.BAD_MESSAGE);
        }
    }
}
 
Example 38
Source Project: android-netty   Source File: FrameDecoder.java    License: Apache License 2.0 5 votes vote down vote up
protected ChannelBuffer updateCumulation(ChannelHandlerContext ctx, ChannelBuffer input) {
	ChannelBuffer newCumulation;
	int readableBytes = input.readableBytes();
	if (readableBytes > 0) {
		int inputCapacity = input.capacity();

		// If input.readableBytes() == input.capacity() (i.e. input is
		// full),
		// there's nothing to save from creating a new cumulation buffer
		// even if input.capacity() exceeds the threshold, because the new
		// cumulation
		// buffer will have the same capacity and content with input.
		if (readableBytes < inputCapacity && inputCapacity > copyThreshold) {
			// At least one byte was consumed by callDecode() and
			// input.capacity()
			// exceeded the threshold.
			cumulation = newCumulation = newCumulationBuffer(ctx, input.readableBytes());
			cumulation.writeBytes(input);
		} else {
			// Nothing was consumed by callDecode() or input.capacity() did
			// not
			// exceed the threshold.
			if (input.readerIndex() != 0) {
				cumulation = newCumulation = input.slice();
			} else {
				cumulation = newCumulation = input;
			}
		}
	} else {
		cumulation = newCumulation = null;
	}
	return newCumulation;
}
 
Example 39
Source Project: onos   Source File: BgpUpdateMsgVer4.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeTo(ChannelBuffer channelBuffer) {
    try {
        WRITER.write(channelBuffer, this);
    } catch (BgpParseException e) {
        log.debug("[writeTo] Error: " + e.toString());
    }
}
 
Example 40
Source Project: onos   Source File: DefaultIsisInterfaceTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests processCsnPduMessage() method.
 */
@Test(expected = Exception.class)
public void testProcessCsnPduMessage() throws Exception {
    ChannelBuffer channelBuffer = ChannelBuffers.copiedBuffer(csnpBytes);
    csnp = new Csnp(isisHeader);
    csnp.readFrom(channelBuffer);
    csnp.setSourceMac(macAddress1);
    csnp.setIsisPduType(IsisPduType.L2CSNP.value());
    isisMessage = csnp;
    defaultIsisInterface.processIsisMessage(isisMessage, isisLsdb, channel);
    assertThat(defaultIsisInterface, is(notNullValue()));
}