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

The following examples show how to use org.jboss.netty.buffer.ChannelBuffer#resetReaderIndex() . 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: PcepErrorMsgVer1.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Parse error-obj-list.
 *
 * @param llErrObjList error object list output
 * @param cb channel buffer input
 * @throws PcepParseException if mandatory fields are missing
 * @return error object header
 */
public PcepObjectHeader parseErrorObjectList(List<PcepErrorObject> llErrObjList, ChannelBuffer cb)
        throws PcepParseException {
    PcepObjectHeader tempObjHeader = null;

    while (0 < cb.readableBytes()) {
        cb.markReaderIndex();
        tempObjHeader = PcepObjectHeader.read(cb);
        cb.resetReaderIndex();
        if (tempObjHeader.getObjClass() == PcepErrorObjectVer1.ERROR_OBJ_CLASS) {
            llErrObjList.add(PcepErrorObjectVer1.read(cb));
        } else {
            break;
        }
    }
    return tempObjHeader;
}
 
Example 2
Source File: OFBigSwitchVendorActionFactory.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@Override
public OFActionVendor readFrom(ChannelBuffer data) {
    data.markReaderIndex();
    OFActionBigSwitchVendor demux = new OFActionBigSwitchVendorDemux();
    demux.readFrom(data);
    data.resetReaderIndex();

    switch(demux.getSubtype()) {
        case OFActionMirror.BSN_ACTION_MIRROR:
            OFActionMirror mirrorAction = new OFActionMirror((short) 0);
            mirrorAction.readFrom(data);
            return mirrorAction;
        case OFActionTunnelDstIP.SET_TUNNEL_DST_SUBTYPE:
            OFActionTunnelDstIP tunnelAction = new OFActionTunnelDstIP();
            tunnelAction.readFrom(data);
            return tunnelAction;
        default:
            logger.error("Unknown BSN vendor action subtype: "+demux.getSubtype());
            return null;
    }
}
 
Example 3
Source File: OFNiciraVendorActionFactory.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: HexDump.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Dump the buffer content in hex format.
 *
 * @param buff buffer content to dump in hex format
 */
public static void dump(ChannelBuffer buff) {
    buff.markReaderIndex();
    try {
        do {
            StringBuilder sb = new StringBuilder();
            for (int k = 0; (k < 16) && (buff.readableBytes() != 0); ++k) {
                if (0 == k % 4) {
                    sb.append(" "); // blank after 4 bytes
                }
                sb.append(String.format("%02X ", buff.readByte()));
            }
            log.debug(sb.toString());
        } while (buff.readableBytes() != 0);
    } catch (Exception e) {
        log.error("[HexDump] Invalid buffer: " + e.toString());
    }
    buff.resetReaderIndex();
}
 
Example 5
Source File: PcepErrorInfoVer1.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void read(ChannelBuffer cb) throws PcepParseException {
    PcepObjectHeader tempObjHeader;

    while (0 < cb.readableBytes()) {
        cb.markReaderIndex();
        tempObjHeader = PcepObjectHeader.read(cb);
        cb.resetReaderIndex();
        byte yObjClass = tempObjHeader.getObjClass();
        if ((yObjClass != PcepRPObjectVer1.RP_OBJ_CLASS) && (yObjClass != PcepLSObjectVer1.LS_OBJ_CLASS)
                && (yObjClass != PcepErrorObjectVer1.ERROR_OBJ_CLASS)) {
            throw new PcepParseException("Unknown Object is present in PCEP-ERROR. Object Class: " + yObjClass);
        }

        this.errList.add(PcepErrorVer1.read(cb));
    }
}
 
Example 6
Source File: PcepErrorVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Reads the byte stream of PcepError from channel buffer.
 *
 * @param cb of type channel buffer
 * @return PcepError error part of PCEP-ERROR
 * @throws PcepParseException if mandatory fields are missing
 */
public static PcepErrorVer1 read(ChannelBuffer cb) throws PcepParseException {
    if (cb.readableBytes() < OBJECT_HEADER_LENGTH) {
        throw new PcepParseException("Unknown Object");
    }

    PcepErrorVer1 pcepError = new PcepErrorVer1();
    // check whether any PCEP Error Info is present
    cb.markReaderIndex();
    PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();
    byte yObjClass = tempObjHeader.getObjClass();

    //If RPlist present then store it.RPList and LSList are optional
    if (yObjClass == PcepRPObjectVer1.RP_OBJ_CLASS) {
        log.debug("RP_LIST");
        pcepError.parseRPList(cb);
        yObjClass = checkNextObject(cb);
    } else if (yObjClass == PcepLSObjectVer1.LS_OBJ_CLASS) {
        log.debug("LS_LIST");
        pcepError.parseLSList(cb);
        yObjClass = checkNextObject(cb);
    }

    if (yObjClass == PcepErrorObjectVer1.ERROR_OBJ_CLASS) {
        log.debug("PCEP-ERROR obj list");
        pcepError.parseErrObjList(cb);
        yObjClass = checkNextObject(cb);
    }

    return pcepError;
}
 
Example 7
Source File: PcepErrorVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Parse LS List from the channel buffer.
 *
 * @param cb of type channel buffer
 * @throws PcepParseException if mandatory fields are missing
 */
public void parseLSList(ChannelBuffer cb) throws PcepParseException {
    byte yObjClass;
    byte yObjType;

    lsObjList = new LinkedList<>();

    // caller should verify for LS object
    if (cb.readableBytes() < OBJECT_HEADER_LENGTH) {
        log.debug("Unable to find LS Object");
        return;
    }

    cb.markReaderIndex();
    PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();
    yObjClass = tempObjHeader.getObjClass();
    yObjType = tempObjHeader.getObjType();
    PcepLSObject lsObj;
    while ((yObjClass == PcepLSObjectVer1.LS_OBJ_CLASS) && ((yObjType == PcepLSObjectVer1.LS_OBJ_TYPE_NODE_VALUE)
            || (yObjType == PcepLSObjectVer1.LS_OBJ_TYPE_LINK_VALUE))) {
        lsObj = PcepLSObjectVer1.read(cb);
        lsObjList.add(lsObj);

        if (cb.readableBytes() > OBJECT_HEADER_LENGTH) {
            cb.markReaderIndex();
            tempObjHeader = PcepObjectHeader.read(cb);
            cb.resetReaderIndex();
            yObjClass = tempObjHeader.getObjClass();
            yObjType = tempObjHeader.getObjType();
        } else {
            break;
        }
    }
}
 
Example 8
Source File: PcepErrorVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Parse RP List from the channel buffer.
 *
 * @param cb of type channel buffer
 * @throws PcepParseException if mandatory fields are missing
 */
public void parseRPList(ChannelBuffer cb) throws PcepParseException {
    byte yObjClass;
    byte yObjType;

    rpObjList = new LinkedList<>();

    // caller should verify for RP object
    if (cb.readableBytes() < OBJECT_HEADER_LENGTH) {
        log.debug("Unable to find RP Object");
        return;
    }

    cb.markReaderIndex();
    PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();
    yObjClass = tempObjHeader.getObjClass();
    yObjType = tempObjHeader.getObjType();
    PcepRPObject rpObj;
    while ((yObjClass == PcepRPObjectVer1.RP_OBJ_CLASS) && (yObjType == PcepRPObjectVer1.RP_OBJ_TYPE)) {
        rpObj = PcepRPObjectVer1.read(cb);
        rpObjList.add(rpObj);

        if (cb.readableBytes() > OBJECT_HEADER_LENGTH) {
            cb.markReaderIndex();
            tempObjHeader = PcepObjectHeader.read(cb);
            cb.resetReaderIndex();
            yObjClass = tempObjHeader.getObjClass();
            yObjType = tempObjHeader.getObjType();
        } else {
            break;
        }
    }
}
 
Example 9
Source File: PcepAttributeVer1.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether there is a more object or not.
 *
 * @param cb of type channel buffer
 * @return instance of object header
 */
private static byte checkNextObject(ChannelBuffer cb) {
    if (cb.readableBytes() < OBJECT_HEADER_LENGTH) {
        return 0;
    }
    cb.markReaderIndex();
    PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();
    return tempObjHeader.getObjClass();
}
 
Example 10
Source File: MessagePackStreamDecoder.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer source) throws Exception {
    // TODO #MN will modify the body with MessagePackBufferUnpacker.
    ByteBuffer buffer = source.toByteBuffer();
    if (!buffer.hasRemaining()) {
        return null;
    }
    source.markReaderIndex();

    byte[] bytes = buffer.array(); // FIXME buffer must has array
    int offset = buffer.arrayOffset() + buffer.position();
    int length = buffer.arrayOffset() + buffer.limit();
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes, offset,
            length);
    int startAvailable = stream.available();
    try{
        Unpacker unpacker = msgpack.createUnpacker(stream);
        Value v = unpacker.readValue();
        source.skipBytes(startAvailable - stream.available());
        return v;
    }catch( EOFException e ){
        // not enough buffers.
        // So retry reading
        source.resetReaderIndex();
        return null;
    }
}
 
Example 11
Source File: PcepMessageDecoder.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
        ChannelBuffer buffer) throws Exception {
    log.debug("Message received.");
    if (!channel.isConnected()) {
        log.info("Channel is not connected.");
        // In testing, I see decode being called AFTER decode last.
        // This check avoids that from reading corrupted frames
        return null;
    }

    HexDump.pcepHexDump(buffer);

    // Buffer can contain multiple messages, also may contain out of bound message.
    // Read the message one by one from buffer and parse it. If it encountered out of bound message,
    // then mark the reader index and again take the next chunk of messages from the channel
    // and parse again from the marked reader index.
    PcepMessageReader<PcepMessage> reader = PcepFactories.getGenericReader();
    List<PcepMessage> msgList = (List<PcepMessage>) ctx.getAttachment();

    if (msgList == null) {
        msgList = new LinkedList<>();
    }

    try {
        while (buffer.readableBytes() > 0) {
            buffer.markReaderIndex();
            PcepMessage message = reader.readFrom(buffer);
            msgList.add(message);
        }
        ctx.setAttachment(null);
        return msgList;
    } catch (PcepOutOfBoundMessageException e) {
        log.debug("PCEP message decode error");
        buffer.resetReaderIndex();
        buffer.discardReadBytes();
        ctx.setAttachment(msgList);
    }
    return null;
}
 
Example 12
Source File: BytesUtil.java    From pinlater with 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 13
Source File: RPCRecordDecoder.java    From nfs-client-java with Apache License 2.0 5 votes vote down vote up
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {
    // Wait until the length prefix is available.
    if (channelBuffer.readableBytes() < 4) {
        // If null is returned, it means there is not enough data yet.
        // FrameDecoder will call again when there is a sufficient amount of data available.
        return null;
    }

    //marking the current reading position
    channelBuffer.markReaderIndex();

    //get the fragment size and wait until the entire fragment is available.
    long fragSize = channelBuffer.readUnsignedInt();
    boolean lastFragment = RecordMarkingUtil.isLastFragment(fragSize);
    fragSize = RecordMarkingUtil.maskFragmentSize(fragSize);
    if (channelBuffer.readableBytes() < fragSize) {
        channelBuffer.resetReaderIndex();
        return null;
    }

    //seek to the beginning of the next fragment
    channelBuffer.skipBytes((int) fragSize);

    _recordLength += 4 + (int) fragSize;

    //check the last fragment
    if (!lastFragment) {
        //not the last fragment, the data is put in an internally maintained cumulative buffer
        return null;
    }

    byte[] rpcResponse = new byte[_recordLength];
    channelBuffer.readerIndex(channelBuffer.readerIndex() - _recordLength);
    channelBuffer.readBytes(rpcResponse, 0, _recordLength);

    _recordLength = 0;
    return rpcResponse;
}
 
Example 14
Source File: RpcUtil.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel,
    ChannelBuffer buf) {

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

  buf.markReaderIndex();

  byte[] fragmentHeader = new byte[4];
  buf.readBytes(fragmentHeader);
  int length = XDR.fragmentSize(fragmentHeader);
  boolean isLast = XDR.isLastFragment(fragmentHeader);

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

  ChannelBuffer newFragment = buf.readSlice(length);
  if (currentFrame == null) {
    currentFrame = newFragment;
  } else {
    currentFrame = ChannelBuffers.wrappedBuffer(currentFrame, newFragment);
  }

  if (isLast) {
    ChannelBuffer completeFrame = currentFrame;
    currentFrame = null;
    return completeFrame;
  } else {
    return null;
  }
}
 
Example 15
Source File: PcepStateReportVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Reads all the Objects for PCEP Message Path.
 *
 * @param bb of type channel buffer
 * @return PCEP Message path
 * @throws PcepParseException when fails to read pcep message path
 */
@Override
public PcepMsgPath read(ChannelBuffer bb) throws PcepParseException {

    PcepEroObject eroObj;
    PcepAttribute attrList;
    PcepRroObject rroObj = null;
    PcepBandwidthObject bandwidth = null;

    eroObj = PcepEroObjectVer1.read(bb);
    attrList = PcepAttributeVer1.read(bb);

    boolean bBreakWhile = false;
    while (0 < bb.readableBytes()) {

        if (bb.readableBytes() < OBJECT_HEADER_LENGTH) {
            break;
        }
        bb.markReaderIndex();
        PcepObjectHeader tempObjHeader = PcepObjectHeader.read(bb);
        bb.resetReaderIndex();
        byte yObjClass = tempObjHeader.getObjClass();

        switch (yObjClass) {
        case PcepRroObjectVer1.RRO_OBJ_CLASS:
            rroObj = PcepRroObjectVer1.read(bb);
            break;
        case PcepInterLayerObjectVer1.INTER_LAYER_OBJ_CLASS:
            bb.skipBytes(tempObjHeader.getObjLen());
            break;
        case PcepBandwidthObjectVer1.BANDWIDTH_OBJ_CLASS:
            bandwidth = PcepBandwidthObjectVer1.read(bb);
            break;
        default:
            //Otherthan above objects handle those objects in caller.
            bBreakWhile = true;
            break;
        }
        if (bBreakWhile) {
            break;
        }
    }
    return new PcepMsgPath(eroObj, attrList, rroObj, bandwidth);
}
 
Example 16
Source File: PcepLabelUpdateVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Reads PcepLabels from the byte stream received from channel buffer.
 *
 * @param cb of type channel buffer.
 * @return PcepLabelUpdate object.
 * @throws PcepParseException when fails to read from channel buffer
 */
public static PcepLabelUpdate read(ChannelBuffer cb) throws PcepParseException {

    PcepLabelUpdateVer1 pceLabelUpdate = new PcepLabelUpdateVer1();

    PcepSrpObject srpObject;
    PcepObjectHeader tempObjHeader;

    //read SRP mandatory Object
    srpObject = PcepSrpObjectVer1.read(cb);

    //checking next object
    cb.markReaderIndex();

    tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();

    if (tempObjHeader.getObjClass() == PcepLspObjectVer1.LSP_OBJ_CLASS) {

        //now it is belong to <pce-label-download>
        PcepLabelDownload labelDownload = new PcepLabelDownload();

        //set SRP
        labelDownload.setSrpObject(srpObject);

        //read and set LSP
        labelDownload.setLspObject(PcepLspObjectVer1.read(cb));

        //<label-list>
        LinkedList<PcepLabelObject> llLabelList = new LinkedList<>();
        PcepLabelObject labelObject;

        while (0 < cb.readableBytes()) {

            cb.markReaderIndex();
            tempObjHeader = PcepObjectHeader.read(cb);
            cb.resetReaderIndex();

            if (tempObjHeader.getObjClass() != PcepLabelObjectVer1.LABEL_OBJ_CLASS) {
                break;
            }
            labelObject = PcepLabelObjectVer1.read(cb);
            llLabelList.add(labelObject);
        }
        labelDownload.setLabelList(llLabelList);
        pceLabelUpdate.setLabelDownload(labelDownload);
    } else if (tempObjHeader.getObjClass() == PcepLabelObjectVer1.LABEL_OBJ_CLASS) {
        //belong to <pce-label-map>
        PcepLabelMap labelMap = new PcepLabelMap();

        //set SRP Object
        labelMap.setSrpObject(srpObject);

        //read and set Label Object
        labelMap.setLabelObject(PcepLabelObjectVer1.read(cb));

        cb.markReaderIndex();
        tempObjHeader = PcepObjectHeader.read(cb);
        cb.resetReaderIndex();

        PcepFecObject fecObject = null;
        switch (tempObjHeader.getObjType()) {
        case PcepFecObjectIPv4Ver1.FEC_OBJ_TYPE:
            fecObject = PcepFecObjectIPv4Ver1.read(cb);
            break;
        case PcepFecObjectIPv6Ver1.FEC_OBJ_TYPE:
            fecObject = PcepFecObjectIPv6Ver1.read(cb);
            break;
        case PcepFecObjectIPv4AdjacencyVer1.FEC_OBJ_TYPE:
            fecObject = PcepFecObjectIPv4AdjacencyVer1.read(cb);
            break;
        case PcepFecObjectIPv6AdjacencyVer1.FEC_OBJ_TYPE:
            fecObject = PcepFecObjectIPv6AdjacencyVer1.read(cb);
            break;
        case PcepFecObjectIPv4UnnumberedAdjacencyVer1.FEC_OBJ_TYPE:
            fecObject = PcepFecObjectIPv4UnnumberedAdjacencyVer1.read(cb);
            break;
        default:
            throw new PcepParseException("Unkown FEC object type " + tempObjHeader.getObjType());
        }
        labelMap.setFecObject(fecObject);
        pceLabelUpdate.setLabelMap(labelMap);
    } else {
        throw new PcepParseException(
                "Either <pce-label-download> or <pce-label-map> should be present. Received Class: "
                        + tempObjHeader.getObjClass());
    }
    return pceLabelUpdate;
}
 
Example 17
Source File: PcepAttributeVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Reads lspa , bandwidth , Metriclist and Iro objects and sets the objects.
 *
 * @param cb of type channel buffer
 * @return instance of Pcep Attribute
 * @throws PcepParseException while parsing Pcep Attributes from channel buffer
 */

public static PcepAttribute read(ChannelBuffer cb) throws PcepParseException {
    if (cb.readableBytes() < OBJECT_HEADER_LENGTH) {
        return null;
    }
    //check whether any pcep attribute is present
    cb.markReaderIndex();
    PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);
    cb.resetReaderIndex();
    byte yObjClass = tempObjHeader.getObjClass();

    if (PcepLspaObjectVer1.LSPA_OBJ_CLASS != yObjClass && PcepBandwidthObjectVer1.BANDWIDTH_OBJ_CLASS != yObjClass
            && PcepMetricObjectVer1.METRIC_OBJ_CLASS != yObjClass && PcepIroObjectVer1.IRO_OBJ_CLASS != yObjClass) {
        //No PCEP attribute is present
        return null;
    }

    PcepAttributeVer1 pcepAttribute = new PcepAttributeVer1();

    //If LSPA present then store it.LSPA is optional
    if (yObjClass == PcepLspaObjectVer1.LSPA_OBJ_CLASS) {
        pcepAttribute.setLspaObject(PcepLspaObjectVer1.read(cb));
        yObjClass = checkNextObject(cb);
    }

    //If BANDWIDTH present then store it.BANDWIDTH is optional
    if (yObjClass == PcepBandwidthObjectVer1.BANDWIDTH_OBJ_CLASS) {
        pcepAttribute.setBandwidthObject(PcepBandwidthObjectVer1.read(cb));
        yObjClass = checkNextObject(cb);
    }

    //If Metric list present then store it.MetricList is optional
    if (yObjClass == PcepMetricObjectVer1.METRIC_OBJ_CLASS) {
        pcepAttribute.parseMetricList(cb);
        yObjClass = checkNextObject(cb);
    }

    //If IRO present then store it.IRO is optional
    if (yObjClass == PcepIroObjectVer1.IRO_OBJ_CLASS) {
        pcepAttribute.setIroObject(PcepIroObjectVer1.read(cb));
    }

    PcepLspaObject lspaObject = pcepAttribute.getLspaObject();
    PcepBandwidthObject bandwidthObject = pcepAttribute.getBandwidthObject();
    LinkedList<PcepMetricObject> metriclist = pcepAttribute.llMetricList;
    PcepIroObject iroObject = pcepAttribute.getIroObject();

    return new PcepAttributeVer1(lspaObject, bandwidthObject, metriclist, iroObject);
}
 
Example 18
Source File: MemcachedBinaryCommandDecoder.java    From fqueue with Apache License 2.0 4 votes vote down vote up
protected Object decode(ChannelHandlerContext channelHandlerContext, Channel channel, ChannelBuffer channelBuffer) throws Exception {

        // need at least 24 bytes, to get header
        if (channelBuffer.readableBytes() < 24) return null;

        // get the header
        channelBuffer.markReaderIndex();
        ChannelBuffer headerBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24);
        channelBuffer.readBytes(headerBuffer);

        short magic = headerBuffer.readUnsignedByte();

        // magic should be 0x80
        if (magic != 0x80) {
            headerBuffer.resetReaderIndex();

            throw new MalformedCommandException("binary request payload is invalid, magic byte incorrect");
        }

        short opcode = headerBuffer.readUnsignedByte();
        short keyLength = headerBuffer.readShort();
        short extraLength = headerBuffer.readUnsignedByte();
        short dataType = headerBuffer.readUnsignedByte();   // unused
        short reserved = headerBuffer.readShort(); // unused
        int totalBodyLength = headerBuffer.readInt();
        int opaque = headerBuffer.readInt();
        long cas = headerBuffer.readLong();

        // we want the whole of totalBodyLength; otherwise, keep waiting.
        if (channelBuffer.readableBytes() < totalBodyLength) {
            channelBuffer.resetReaderIndex();
            return null;
        }

        // This assumes correct order in the enum. If that ever changes, we will have to scan for 'code' field.
        BinaryCommand bcmd = BinaryCommand.values()[opcode];

        Command cmdType = bcmd.correspondingCommand;
        CommandMessage cmdMessage = CommandMessage.command(cmdType);
        cmdMessage.noreply = bcmd.noreply;
        cmdMessage.cas_key = cas;
        cmdMessage.opaque = opaque;
        cmdMessage.addKeyToResponse = bcmd.addKeyToResponse;

        // get extras. could be empty.
        ChannelBuffer extrasBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, extraLength);
        channelBuffer.readBytes(extrasBuffer);

        // get the key if any
        if (keyLength != 0) {
            ChannelBuffer keyBuffer = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, keyLength);
            channelBuffer.readBytes(keyBuffer);

            ArrayList<String> keys = new ArrayList<String>();
            String key = keyBuffer.toString(USASCII);
            keys.add(key); // TODO this or UTF-8? ISO-8859-1?

            cmdMessage.keys = keys;


            if (cmdType == Command.ADD ||
                    cmdType == Command.SET ||
                    cmdType == Command.REPLACE ||
                    cmdType == Command.APPEND ||
                    cmdType == Command.PREPEND)
            {
                // TODO these are backwards from the spec, but seem to be what spymemcached demands -- which has the mistake?!
                short expire = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0);
                short flags = (short) (extrasBuffer.capacity() != 0 ? extrasBuffer.readUnsignedShort() : 0);

                // the remainder of the message -- that is, totalLength - (keyLength + extraLength) should be the payload
                int size = totalBodyLength - keyLength - extraLength;

                cmdMessage.element = new LocalCacheElement(key, flags, expire != 0 && expire < CacheElement.THIRTY_DAYS ? LocalCacheElement.Now() + expire : expire, 0L);
                cmdMessage.element.setData(new byte[size]);
                channelBuffer.readBytes(cmdMessage.element.getData(), 0, size);
            } else if (cmdType == Command.INCR || cmdType == Command.DECR) {
                long initialValue = extrasBuffer.readUnsignedInt();
                long amount = extrasBuffer.readUnsignedInt();
                long expiration = extrasBuffer.readUnsignedInt();

                cmdMessage.incrAmount = (int) amount;
                cmdMessage.incrDefault = (int) initialValue;
                cmdMessage.incrExpiry = (int) expiration;
            }
        }

        return cmdMessage;
    }
 
Example 19
Source File: PcepReportMsgVer1.java    From onos with Apache License 2.0 4 votes vote down vote up
public void parseStateReportList(ChannelBuffer cb) throws PcepParseException {

            /*
                                <state-report-list>
            Where:
                    <state-report-list>     ::= <state-report>[<state-report-list>]
                    <state-report>          ::=  [<SRP>]
                                                  <LSP>
                                                  <path>
            Where:
                    <path>                  ::= <ERO><attribute-list>[<RRO>]
            Where:
                    <attribute-list> is defined in [RFC5440] and extended by PCEP extensions.

             */

            while (0 < cb.readableBytes()) {

                PcepStateReport pcestateReq = new PcepStateReportVer1();

                /*
                 * SRP is optional
                 * Check whether SRP Object is available, if yes store it.
                 * First read common object header and check the Object Class whether it is SRP or LSP
                 * If it is LSP then store only LSP. So, SRP is optional. then read path and store.
                 * If it is SRP then store SRP and then read LSP, path and store them.
                 */

                //mark the reader index to reset
                cb.markReaderIndex();
                PcepObjectHeader tempObjHeader = PcepObjectHeader.read(cb);

                byte yObjectClass = tempObjHeader.getObjClass();
                byte yObjectType = tempObjHeader.getObjType();

                //reset reader index
                cb.resetReaderIndex();
                //If SRP present then store it.
                if ((PcepSrpObjectVer1.SRP_OBJ_CLASS == yObjectClass)
                        && (PcepSrpObjectVer1.SRP_OBJ_TYPE == yObjectType)) {
                    PcepSrpObject srpObj;
                    srpObj = PcepSrpObjectVer1.read(cb);
                    pcestateReq.setSrpObject(srpObj);
                }

                //store LSP object
                PcepLspObject lspObj;
                lspObj = PcepLspObjectVer1.read(cb);
                pcestateReq.setLspObject(lspObj);

                if (cb.readableBytes() > 0) {

                    //mark the reader index to reset
                    cb.markReaderIndex();
                    tempObjHeader = PcepObjectHeader.read(cb);

                    yObjectClass = tempObjHeader.getObjClass();
                    yObjectType = tempObjHeader.getObjType();

                    //reset reader index
                    cb.resetReaderIndex();

                    if ((PcepEroObjectVer1.ERO_OBJ_CLASS == yObjectClass)
                            && (PcepEroObjectVer1.ERO_OBJ_TYPE == yObjectType)) {
                        // store path
                        PcepStateReport.PcepMsgPath msgPath = new PcepStateReportVer1().new PcepMsgPath().read(cb);
                        pcestateReq.setMsgPath(msgPath);
                    }
                }

                llStateReportList.add(pcestateReq);
            }
        }
 
Example 20
Source File: BgpPathAttributes.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Reads from channelBuffer and parses BGP path attributes.
 *
 * @param cb channelBuffer
 * @return object of BgpPathAttributes
 * @throws BgpParseException while parsing BGP path attributes
 */
public static BgpPathAttributes read(ChannelBuffer cb)
        throws BgpParseException {

    BgpValueType pathAttribute = null;
    List<BgpValueType> pathAttributeList = new LinkedList<>();
    boolean isOrigin = false;
    boolean isAsPath = false;
    boolean isNextHop = false;
    boolean isMpReach = false;
    boolean isMpUnReach = false;
    while (cb.readableBytes() > 0) {
        cb.markReaderIndex();
        byte flags = cb.readByte();
        byte typeCode = cb.readByte();
        cb.resetReaderIndex();
        switch (typeCode) {
        case Origin.ORIGIN_TYPE:
            pathAttribute = Origin.read(cb);
            isOrigin = ((Origin) pathAttribute).isOriginSet();
            break;
        case AsPath.ASPATH_TYPE:
            pathAttribute = AsPath.read(cb);
            isAsPath = ((AsPath) pathAttribute).isaspathSet();
            break;
        case As4Path.AS4PATH_TYPE:
            pathAttribute = As4Path.read(cb);
            break;
        case NextHop.NEXTHOP_TYPE:
            pathAttribute = NextHop.read(cb);
            isNextHop = ((NextHop) pathAttribute).isNextHopSet();
            break;
        case Med.MED_TYPE:
            pathAttribute = Med.read(cb);
            break;
        case LocalPref.LOCAL_PREF_TYPE:
            pathAttribute = LocalPref.read(cb);
            break;
        case MpReachNlri.MPREACHNLRI_TYPE:
            pathAttribute = MpReachNlri.read(cb);
            isMpReach = ((MpReachNlri) pathAttribute).isMpReachNlriSet();
            break;
        case MpUnReachNlri.MPUNREACHNLRI_TYPE:
            pathAttribute = MpUnReachNlri.read(cb);
            isMpUnReach = ((MpUnReachNlri) pathAttribute)
                    .isMpUnReachNlriSet();
            break;
        case LINK_STATE_ATTRIBUTE_TYPE:
            pathAttribute = LinkStateAttributes.read(cb);
            break;
        case EXTENDED_COMMUNITY_TYPE:
            pathAttribute = BgpExtendedCommunity.read(cb);
            break;
        case WideCommunity.TYPE:
            pathAttribute = WideCommunity.read(cb);
            break;
        default:
            log.debug("Skip bytes for unsupported attribute types");
            UnSupportedAttribute.read(cb);
        }
        pathAttributeList.add(pathAttribute);
    }

    checkMandatoryAttr(isOrigin, isAsPath, isNextHop, isMpReach, isMpUnReach);
    //TODO:if mp_reach or mp_unreach not present ignore the packet
    return new BgpPathAttributes(pathAttributeList);
}