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

The following are top voted examples for showing how to use org.jboss.netty.buffer.ChannelBuffer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: athena   File: BgpLinkAttrOpaqLnkAttrib.java   View source code 6 votes vote down vote up
/**
 * Reads the BGP link attributes Opaque link attribute.
 *
 * @param cb Channel buffer
 * @return object of type BgpLinkAttrOpaqLnkAttrib
 * @throws BgpParseException while parsing BgpLinkAttrOpaqLnkAttrib
 */
public static BgpLinkAttrOpaqLnkAttrib read(ChannelBuffer cb)
        throws BgpParseException {

    byte[] opaqueLinkAttribute;

    short lsAttrLength = cb.readShort();

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

    opaqueLinkAttribute = new byte[lsAttrLength];
    cb.readBytes(opaqueLinkAttribute);

    return BgpLinkAttrOpaqLnkAttrib.of(opaqueLinkAttribute);
}
 
Example 2
Project: athena   File: BgpMessage.java   View source code 6 votes vote down vote up
/**
 * Prepares BGP message.
 *
 * @param type the BGP message type
 * @param payload the message payload to transmit (BGP header excluded)
 * @return the message to transmit (BGP header included)
 */
static ChannelBuffer prepareBgpMessage(int type, ChannelBuffer payload) {
    ChannelBuffer message =
        ChannelBuffers.buffer(BgpConstants.BGP_HEADER_LENGTH +
                              payload.readableBytes());

    // Write the marker
    for (int i = 0; i < BgpConstants.BGP_HEADER_MARKER_LENGTH; i++) {
        message.writeByte(0xff);
    }

    // Write the rest of the BGP header
    message.writeShort(BgpConstants.BGP_HEADER_LENGTH +
                       payload.readableBytes());
    message.writeByte(type);

    // Write the payload
    message.writeBytes(payload);
    return message;
}
 
Example 3
Project: athena   File: BgpLinkAttrTeDefaultMetric.java   View source code 6 votes vote down vote up
/**
 * Reads the BGP link attributes of TE default metric.
 *
 * @param cb Channel buffer
 * @return object of type BgpLinkAttrTeDefaultMetric
 * @throws BgpParseException while parsing BgpLinkAttrTeDefaultMetric
 */
public static BgpLinkAttrTeDefaultMetric read(ChannelBuffer cb)
        throws BgpParseException {
    int linkTeMetric;

    short lsAttrLength = cb.readShort();

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

    linkTeMetric = cb.readInt();

    return new BgpLinkAttrTeDefaultMetric(linkTeMetric);
}
 
Example 4
Project: athena   File: BgpFsPacketLength.java   View source code 6 votes vote down vote up
/**
 * Reads the channel buffer and returns object.
 *
 * @param cb channelBuffer
 * @return object of flow spec packet length
 * @throws BgpParseException while parsing BgpFsPacketLength
 */
public static BgpFsPacketLength read(ChannelBuffer cb) throws BgpParseException {
    List<BgpFsOperatorValue> operatorValue = new LinkedList<>();
    byte option;
    short packetLen;

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

    return new BgpFsPacketLength(operatorValue);
}
 
Example 5
Project: athena   File: BgpSession.java   View source code 6 votes vote down vote up
@Override
public void run(Timeout timeout) throws Exception {
    if (timeout.isCancelled()) {
        return;
    }
    if (!ctx.getChannel().isOpen()) {
        return;
    }

    log.debug("BGP Session Timeout: peer {}", remoteInfo.address());
    //
    // ERROR: Invalid Optional Parameter Length field: Unspecific
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.HoldTimerExpired.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.ERROR_SUBCODE_UNSPECIFIC;
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               null);
    ctx.getChannel().write(txMessage);
    closeChannel(ctx);
}
 
Example 6
Project: athena   File: BgpUpdateMsgTest.java   View source code 6 votes vote down vote up
/**
 * In this test case, Mandatory attributes are not given in input and expecting
 * an exception.
 */
@Test(expected = BgpParseException.class)
public void bgpUpdateMessageTest23() throws BgpParseException {
    byte[] updateMsg = new byte[] {(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
            (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff,
            (byte) 0xff, (byte) 0xff, 0x00, 0x29, 0x02, 0x00, 0x00, //withdrawn len
            0x00, 0x12, //path attribute len
            0x0e, 0x01, 0x01, 0x00, //origin
            0x40, 0x02, 0x04, 0x02, 0x01, (byte) 0xfd, (byte) 0xe9, //as_path
            (byte) 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00}; //med

    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 7
Project: traccar-service   File: TeltonikaProtocolDecoder.java   View source code 6 votes vote down vote up
private DeviceSession parseIdentification(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) {

        int length = buf.readUnsignedShort();
        String imei = buf.toString(buf.readerIndex(), length, StandardCharsets.US_ASCII);
        DeviceSession deviceSession = getDeviceSession(channel, remoteAddress, imei);

        if (channel != null) {
            ChannelBuffer response = ChannelBuffers.directBuffer(1);
            if (deviceSession != null) {
                response.writeByte(1);
            } else {
                response.writeByte(0);
            }
            channel.write(response);
        }
        return deviceSession;
    }
 
Example 8
Project: athena   File: BgpAttrNodeName.java   View source code 6 votes vote down vote up
/**
 * Reads the LS attribute node name.
 *
 * @param cb ChannelBuffer
 * @return object of BgpAttrNodeName
 * @throws BgpParseException while parsing BgpAttrNodeName
 */
public static BgpAttrNodeName read(ChannelBuffer cb)
        throws BgpParseException {
    byte[] nodeName;

    short lsAttrLength = cb.readShort();

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

    nodeName = new byte[lsAttrLength];
    cb.readBytes(nodeName);
    return BgpAttrNodeName.of(nodeName);
}
 
Example 9
Project: athena   File: PcepKeepaliveMsgVer1.java   View source code 6 votes vote down vote up
@Override
public void write(ChannelBuffer cb, PcepKeepaliveMsgVer1 message) {
    int startIndex = cb.writerIndex();
    // first 3 bits set to version
    cb.writeByte((byte) (PACKET_VERSION << PcepMessageVer1.SHIFT_FLAG));
    // message type
    cb.writeByte(MSG_TYPE.getType());
    // length is length of variable message, will be updated at the end
    // Store the position of message
    // length in buffer
    int msgLenIndex = cb.writerIndex();
    cb.writeShort((short) 0);
    // update message length field
    int length = cb.writerIndex() - startIndex;
    cb.setShort(msgLenIndex, (short) length);
}
 
Example 10
Project: traccar-service   File: CellocatorProtocolDecoder.java   View source code 6 votes vote down vote up
private void sendReply(Channel channel, SocketAddress remoteAddress, long deviceId, byte packetNumber) {
    ChannelBuffer reply = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 28);
    reply.writeByte('M');
    reply.writeByte('C');
    reply.writeByte('G');
    reply.writeByte('P');
    reply.writeByte(MSG_SERVER_ACKNOWLEDGE);
    reply.writeInt((int) deviceId);
    reply.writeByte(commandCount++);
    reply.writeInt(0); // authentication code
    reply.writeByte(0);
    reply.writeByte(packetNumber);
    reply.writeZero(11);

    byte checksum = 0;
    for (int i = 4; i < 27; i++) {
        checksum += reply.getByte(i);
    }
    reply.writeByte(checksum);

    if (channel != null) {
        channel.write(reply, remoteAddress);
    }
}
 
Example 11
Project: athena   File: BgpFsTcpFlags.java   View source code 6 votes vote down vote up
/**
 * Reads the channel buffer and returns object.
 *
 * @param cb channelBuffer
 * @return object of flow spec TCP flags
 * @throws BgpParseException while parsing BgpFsTcpFlags
 */
public static BgpFsTcpFlags read(ChannelBuffer cb) throws BgpParseException {
    List<BgpFsOperatorValue> operatorValue = new LinkedList<>();
    byte option;
    short tcpFlag;

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

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

    return new BgpFsTcpFlags(operatorValue);
}
 
Example 12
Project: traccar-service   File: MediaManager.java   View source code 6 votes vote down vote up
public String writeFile(String uniqueId, ChannelBuffer buf, String extension) {
    int size = buf.readableBytes();
    String name = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()) + "." + extension;
    try (FileOutputStream output = new FileOutputStream(createFile(uniqueId, name));
            FileChannel fileChannel = output.getChannel()) {
        ByteBuffer byteBuffer = buf.toByteBuffer();
        int written = 0;
        while (written < size) {
            written += fileChannel.write(byteBuffer);
        }
        fileChannel.force(false);
        return name;
    } catch (IOException e) {
        Log.warning(e);
    }
    return null;
}
 
Example 13
Project: traccar-service   File: CityeasyProtocolEncoder.java   View source code 6 votes vote down vote up
private ChannelBuffer encodeContent(int type, ChannelBuffer content) {

        ChannelBuffer buf = ChannelBuffers.dynamicBuffer();

        buf.writeByte('S');
        buf.writeByte('S');
        buf.writeShort(2 + 2 + 2 + content.readableBytes() + 4 + 2 + 2);
        buf.writeShort(type);
        buf.writeBytes(content);
        buf.writeInt(0x0B);
        buf.writeShort(Checksum.crc16(Checksum.CRC16_KERMIT, buf.toByteBuffer()));
        buf.writeByte('\r');
        buf.writeByte('\n');

        return buf;
    }
 
Example 14
Project: traccar-service   File: AdmProtocolDecoder.java   View source code 6 votes vote down vote up
private Position parseCommandResponse(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) {
    DeviceSession deviceSession = getDeviceSession(channel, remoteAddress);
    if (deviceSession == null) {
        return null;
    }

    Position position = new Position();
    position.setProtocol(getProtocolName());
    position.setDeviceId(deviceSession.getDeviceId());

    getLastLocation(position, null);

    int responseTextLength = buf.bytesBefore((byte) 0);
    if (responseTextLength < 0) {
        responseTextLength = CMD_RESPONSE_SIZE - 3;
    }
    position.set(Position.KEY_RESULT, buf.readBytes(responseTextLength).toString(StandardCharsets.UTF_8));

    return position;
}
 
Example 15
Project: athena   File: IPReachabilityInformationTlv.java   View source code 6 votes vote down vote up
/**
 * Reads the channel buffer and returns object of IPReachabilityInformationTlv.
 *
 * @param cb ChannelBuffer
 * @param length of value field
 * @return object of IPReachabilityInformationTlv
 */
public static IPReachabilityInformationTlv read(ChannelBuffer cb, short length) {
    byte preficLen = cb.readByte();
    byte[] prefix;
    if (preficLen == 0) {
        prefix = new byte[] {0};
    } else {
        int len = preficLen / ONE_BYTE_LEN;
        int reminder = preficLen % ONE_BYTE_LEN;
        if (reminder > 0) {
            len = len + 1;
        }
        prefix = new byte[len];
        cb.readBytes(prefix, 0, len);
    }
    return IPReachabilityInformationTlv.of(preficLen, prefix, length);
}
 
Example 16
Project: athena   File: PcepLabelObjectVer1.java   View source code 6 votes vote down vote up
/**
 * Returns the writer index.
 *
 * @param cb of channel buffer.
 * @return writer index
 */
protected int packOptionalTlv(ChannelBuffer cb) {

    ListIterator<PcepValueType> listIterator = optionalTlv.listIterator();

    while (listIterator.hasNext()) {
        PcepValueType tlv = listIterator.next();

        if (tlv == null) {
            log.debug("tlv is null from OptionalTlv list");
            continue;
        }
        tlv.write(cb);
    }
    return cb.writerIndex();
}
 
Example 17
Project: traccar-service   File: BcdUtil.java   View source code 6 votes vote down vote up
public static double readCoordinate(ChannelBuffer buf) {
    int b1 = buf.readUnsignedByte();
    int b2 = buf.readUnsignedByte();
    int b3 = buf.readUnsignedByte();
    int b4 = buf.readUnsignedByte();

    double value = (b2 & 0xf) * 10 + (b3 >> 4);
    value += (((b3 & 0xf) * 10 + (b4 >> 4)) * 10 + (b4 & 0xf)) / 1000.0;
    value /= 60;
    value += ((b1 >> 4 & 0x7) * 10 + (b1 & 0xf)) * 10 + (b2 >> 4);

    if ((b1 & 0x80) != 0) {
        value = -value;
    }

    return value;
}
 
Example 18
Project: traccar-service   File: Gt06ProtocolDecoder.java   View source code 6 votes vote down vote up
private boolean decodeLbs(Position position, ChannelBuffer buf, boolean hasLength) {

        int length = 0;
        if (hasLength) {
            length = buf.readUnsignedByte();
            if (length == 0) {
                return false;
            }
        }

        position.setNetwork(new Network(CellTower.from(
                buf.readUnsignedShort(), buf.readUnsignedByte(), buf.readUnsignedShort(), buf.readUnsignedMedium())));

        if (length > 0) {
            buf.skipBytes(length - (hasLength ? 9 : 8));
        }

        return true;
    }
 
Example 19
Project: traccar-service   File: CastelProtocolDecoder.java   View source code 5 votes vote down vote up
private void decodeObd(Position position, ChannelBuffer buf, boolean groups) {

        int count = buf.readUnsignedByte();

        int[] pids = new int[count];
        for (int i = 0; i < count; i++) {
            pids[i] = buf.readUnsignedShort() & 0xff;
        }

        if (groups) {
            buf.readUnsignedByte(); // group count
            buf.readUnsignedByte(); // group size
        }

        for (int i = 0; i < count; i++) {
            int value;
            switch (PID_LENGTH_MAP.get(pids[i])) {
                case 1:
                    value = buf.readUnsignedByte();
                    break;
                case 2:
                    value = buf.readUnsignedShort();
                    break;
                case 4:
                    value = buf.readInt();
                    break;
                default:
                    value = 0;
                    break;
            }
            position.add(ObdDecoder.decodeData(pids[i], value, false));
        }
    }
 
Example 20
Project: athena   File: PcepRroObjectVer1.java   View source code 5 votes vote down vote up
@Override
public int write(ChannelBuffer cb) throws PcepParseException {
    //write Object header
    int objStartIndex = cb.writerIndex();

    int objLenIndex = rroObjHeader.write(cb);

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

    ListIterator<PcepValueType> listIterator = llSubObjects.listIterator();

    while (listIterator.hasNext()) {
        listIterator.next().write(cb);
    }

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

    //As per RFC the length of object should be multiples of 4
    int pad = length % 4;

    if (0 != pad) {
        pad = 4 - pad;
        for (int i = 0; i < pad; i++) {
            cb.writeByte((byte) 0);
        }
        length = length + pad;
    }
    objLenIndex = cb.writerIndex();
    return objLenIndex;
}
 
Example 21
Project: dubbo2   File: NettyCodecAdapter.java   View source code 5 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception {
    com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer =
        com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024);
    NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
    try {
    	codec.encode(channel, buffer, msg);
    } finally {
        NettyChannel.removeChannelIfDisconnected(ch);
    }
    return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
}
 
Example 22
Project: traccar-service   File: UlbotechProtocolDecoder.java   View source code 5 votes vote down vote up
@Override
protected Object decode(
        Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ChannelBuffer buf = (ChannelBuffer) msg;

    if (buf.getUnsignedByte(buf.readerIndex()) == 0xF8) {

        if (channel != null) {
            ChannelBuffer response = ChannelBuffers.dynamicBuffer();
            response.writeByte(0xF8);
            response.writeByte(DATA_GPS);
            response.writeByte(0xFE);
            response.writeShort(buf.getShort(response.writerIndex() - 1 - 2));
            response.writeShort(Checksum.crc16(Checksum.CRC16_XMODEM, response.toByteBuffer(1, 4)));
            response.writeByte(0xF8);
            channel.write(response);
        }

        return decodeBinary(channel, remoteAddress, buf);
    } else {

        if (channel != null) {
            channel.write(ChannelBuffers.copiedBuffer(String.format("*TS01,ACK:%04X#",
                    Checksum.crc16(Checksum.CRC16_XMODEM, buf.toByteBuffer(1, buf.writerIndex() - 2))),
                    StandardCharsets.US_ASCII));
        }

        return decodeText(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII));
    }
}
 
Example 23
Project: athena   File: AutonomousSystemTlv.java   View source code 5 votes vote down vote up
@Override
public int write(ChannelBuffer c) {
    int iLenStartIndex = c.writerIndex();
    c.writeShort(TYPE);
    c.writeShort(LENGTH);
    c.writeInt(asNum);
    return c.writerIndex() - iLenStartIndex;
}
 
Example 24
Project: athena   File: IPv4SubObject.java   View source code 5 votes vote down vote up
@Override
public int write(ChannelBuffer c) {
    int iLenStartIndex = c.writerIndex();
    byte bValue = LBIT;
    bValue = (byte) (bValue << SHIFT_LBIT_POSITION);
    bValue = (byte) (bValue | TYPE);
    c.writeByte(bValue);
    c.writeByte(OBJ_LENGTH);
    c.writeInt(ipAddress);
    c.writeByte(prefixLen);
    c.writeByte(resvd);

    return c.writerIndex() - iLenStartIndex;
}
 
Example 25
Project: athena   File: PcepUpdateMsgExtTest.java   View source code 5 votes vote down vote up
/**
 * This test case is for SRP object(SymbolicPathNameTlv), LSP object(SymbolicPathNameTlv), ERO object,
 * Bandwidth , metric object in PcepUpdate message.
 */
@Test
public void pcepUpdateMsgTest25() throws PcepParseException, PcepOutOfBoundMessageException {
    byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x50,
            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,
            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 26
Project: athena   File: BgpUpdate.java   View source code 5 votes vote down vote up
/**
 * Applies the appropriate actions after detecting BGP UPDATE
 * Invalid ORIGIN Attribute 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
 * @param origin the ORIGIN attribute value
 */
private static void actionsBgpUpdateInvalidOriginAttribute(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int attrTypeCode,
                            int attrLen,
                            int attrFlags,
                            ChannelBuffer message,
                            short origin) {
    log.debug("BGP RX UPDATE Error from {}: Invalid ORIGIN Attribute",
              bgpSession.remoteInfo().address());

    //
    // ERROR: Invalid ORIGIN Attribute
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.UpdateMessageError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.UpdateMessageError.INVALID_ORIGIN_ATTRIBUTE;
    ChannelBuffer data =
        prepareBgpUpdateNotificationDataPayload(attrTypeCode, attrLen,
                                                attrFlags, message);
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               data);
    ctx.getChannel().write(txMessage);
    bgpSession.closeSession(ctx);
}
 
Example 27
Project: athena   File: PcepInitiateMsgExtTest.java   View source code 5 votes vote down vote up
/**
 * This test case checks for SRP, LSP (SymbolicPathNameTlv, SymbolicPathNameTlv), END-POINTS, ERO, LSPA,
 * BANDWIDTH, METRIC OBJECT objects in PcInitiate message.
 */
@Test
public void initiateMessageTest27() throws PcepParseException, PcepOutOfBoundMessageException {

    // SRP, LSP (SymbolicPathNameTlv, SymbolicPathNameTlv), END-POINTS, ERO, LSPA, BANDWIDTH, METRIC OBJECT.
    //
    byte[] initiateCreationMsg = new byte[]{0x20, 0x0C, 0x00, (byte) 0x60,
            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
            0x04, 0x12, 0x00, 0x0C, 0x01, 0x01, 0x01, 0x01, 0x02, 0x02, 0x02, 0x02, //Endpoints Object
            0x07, 0x10, 0x00, 0x04, //ERO object
            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, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01}; //Metric object

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

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

    message = reader.readFrom(buffer);

    assertThat(message, instanceOf(PcepInitiateMsg.class));
    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();

    message.writeTo(buf);

    testInitiateCreationMsg = buf.array();

    int iReadLen = buf.writerIndex();
    testInitiateCreationMsg = new byte[iReadLen];
    buf.readBytes(testInitiateCreationMsg, 0, iReadLen);

    assertThat(testInitiateCreationMsg, is(initiateCreationMsg));
}
 
Example 28
Project: hadoop   File: RegistrationClient.java   View source code 5 votes vote down vote up
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
  ChannelBuffer buf = (ChannelBuffer) e.getMessage(); // Read reply
  if (!validMessageLength(buf.readableBytes())) {
    e.getChannel().close();
    return;
  }

  // handling fragment header for TCP, 4 bytes.
  byte[] fragmentHeader = Arrays.copyOfRange(buf.array(), 0, 4);
  int fragmentSize = XDR.fragmentSize(fragmentHeader);
  boolean isLast = XDR.isLastFragment(fragmentHeader);
  assert (fragmentSize == 28 && isLast == true);

  XDR xdr = new XDR();
  xdr.writeFixedOpaque(Arrays.copyOfRange(buf.array(), 4,
      buf.readableBytes()));

  RpcReply reply = RpcReply.read(xdr);
  if (reply.getState() == RpcReply.ReplyState.MSG_ACCEPTED) {
    RpcAcceptedReply acceptedReply = (RpcAcceptedReply) reply;
    handle(acceptedReply, xdr);
  } else {
    RpcDeniedReply deniedReply = (RpcDeniedReply) reply;
    handle(deniedReply);
  }
  e.getChannel().close(); // shutdown now that request is complete
}
 
Example 29
Project: athena   File: BgpNotificationMsgTest.java   View source code 5 votes vote down vote up
/**
 * Notification message with error code, error subcode and data.
 *
 * @throws BgpParseException while decoding and encoding notification message
 */
@Test
public void bgpNotificationMessageTest1() throws BgpParseException {
    byte[] notificationMsg = new byte[] {(byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff, 0x00,
                                         0x17, 0x03, 0x02, 0x02,
                                         (byte) 0xfe, (byte) 0xb0};

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

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

    message = reader.readFrom(buffer, bgpHeader);
    assertThat(message, instanceOf(BgpNotificationMsg.class));

    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    message.writeTo(buf);
    testNotificationMsg = buf.array();

    int iReadLen = buf.writerIndex() - 0;
    testNotificationMsg = new byte[iReadLen];
    buf.readBytes(testNotificationMsg, 0, iReadLen);
    assertThat(testNotificationMsg, is(notificationMsg));
}
 
Example 30
Project: athena   File: PcepLSReportMsgVer1.java   View source code 5 votes vote down vote up
/**
 * Parse ls-report-list.
 *
 * @param cb input Channel Buffer
 * @throws PcepParseException when fails to parse LS-Report list.
 */
public void parseLSReportList(ChannelBuffer cb) throws PcepParseException {
    // <ls-report-list> ::= <LS>[<ls-report-list>]

    while (0 < cb.readableBytes()) {
        //store LS objects
        if (!lsReportList.add(PcepLSObjectVer1.read(cb))) {
            throw new PcepParseException("Failed to add LS object to LS-Report list");
        }
    }
}
 
Example 31
Project: athena   File: PcepRsvpObjectHeader.java   View source code 5 votes vote down vote up
/**
 * Reads the PcepRsvpObjectHeader.
 *
 * @param cb input channel buffer
 * @return PcepRsvpObjectHeader
 */
public static PcepRsvpObjectHeader read(ChannelBuffer cb) {
    log.debug("read ");
    byte objClassNum;
    byte objClassType;
    short objLen;
    objLen = cb.readShort();
    objClassNum = cb.readByte();
    objClassType = cb.readByte();

    return new PcepRsvpObjectHeader(objClassNum, objClassType, objLen);
}
 
Example 32
Project: athena   File: PcepUpdateMsgTest.java   View source code 5 votes vote down vote up
/**
 * This test case checks for SRP, LSP (StatefulIPv4LspIdentidiersTlv, SymbolicPathNameTlv,
 * StatefulLspErrorCodeTlv), ERO (IPv4SubObject, IPv4SubObject) objects in PcUpd message.
 */
@Test
public void pcepUpdateMsgTest9() throws PcepParseException, PcepOutOfBoundMessageException {

    byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x58,
            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, 0x2c, 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
            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 };

    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 33
Project: traccar-service   File: ApelProtocolDecoder.java   View source code 5 votes vote down vote up
private void sendSimpleMessage(Channel channel, short type) {
    ChannelBuffer request = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, 8);
    request.writeShort(type);
    request.writeShort(0);
    request.writeInt(Checksum.crc32(request.toByteBuffer(0, 4)));
    channel.write(request);
}
 
Example 34
Project: athena   File: BgpFsIcmpType.java   View source code 5 votes vote down vote up
/**
 * Reads the channel buffer and returns object.
 *
 * @param cb channelBuffer
 * @return object of flow spec ICMP type
 * @throws BgpParseException while parsing BgpFsIcmpType
 */
public static BgpFsIcmpType read(ChannelBuffer cb) throws BgpParseException {
    List<BgpFsOperatorValue> operatorValue = new LinkedList<>();
    byte option;
    byte icmpType;

    do {
        option = (byte) cb.readByte();
        icmpType = cb.readByte();
        operatorValue.add(new BgpFsOperatorValue(option, new byte[] {(byte) icmpType}));
    } while ((option & Constants.BGP_FLOW_SPEC_END_OF_LIST_MASK) == 0);

    return new BgpFsIcmpType(operatorValue);
}
 
Example 35
Project: athena   File: PcepMsgPathVer1.java   View source code 5 votes vote down vote up
@Override
public int write(ChannelBuffer cb) throws PcepParseException {
    int iLenStartIndex = cb.writerIndex();

    //write Object header
    if (this.isEroObjectSet) {
        this.eroObj.write(cb);
    }
    if (this.isAttributeListSet) {
        attrList.write(cb);
    }

    return cb.writerIndex() - iLenStartIndex;
}
 
Example 36
Project: athena   File: BgpNotificationMsgTest.java   View source code 5 votes vote down vote up
/**
 * Notification message with wrong message length.
 *
 * @throws BgpParseException while decoding and encoding notification message
 */
@Test(expected = BgpParseException.class)
public void bgpNotificationMessageTest5() throws BgpParseException {
    byte[] notificationMsg = new byte[] {(byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff,
                                         (byte) 0xff, (byte) 0xff, 0x00,
                                         0x14, 0x03, 0x02, 0x02};

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

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

    message = reader.readFrom(buffer, bgpHeader);
    assertThat(message, instanceOf(BgpNotificationMsg.class));

    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    message.writeTo(buf);
    testNotificationMsg = buf.array();

    int iReadLen = buf.writerIndex() - 0;
    testNotificationMsg = new byte[iReadLen];
    buf.readBytes(testNotificationMsg, 0, iReadLen);
    assertThat(testNotificationMsg, is(notificationMsg));
}
 
Example 37
Project: athena   File: PcepLspObjectVer1.java   View source code 5 votes vote down vote up
/**
 * returns writer index.
 *
 * @param cb of type channel buffer
 * @return length of bytes written to channel buffer
 */
protected int packOptionalTlv(ChannelBuffer cb) {

    ListIterator<PcepValueType> listIterator = llOptionalTlv.listIterator();
    int startIndex = cb.writerIndex();

    while (listIterator.hasNext()) {
        PcepValueType tlv = listIterator.next();

        if (tlv == null) {
            log.debug("tlv is null from OptionalTlv list");
            continue;
        }

        tlv.write(cb);

        // need to take care of padding
        int pad = tlv.getLength() % 4;

        if (0 != pad) {
            pad = 4 - pad;
            for (int i = 0; i < pad; ++i) {
                cb.writeByte((byte) 0);
            }
        }
    }

    return cb.writerIndex() - startIndex;
}
 
Example 38
Project: traccar-service   File: EnforaProtocolEncoder.java   View source code 5 votes vote down vote up
private ChannelBuffer encodeContent(String content) {

        ChannelBuffer buf = ChannelBuffers.dynamicBuffer();

        buf.writeShort(content.length() + 6);
        buf.writeShort(0); // index
        buf.writeByte(0x04); // command type
        buf.writeByte(0); // optional header
        buf.writeBytes(content.getBytes(StandardCharsets.US_ASCII));

        return buf;
    }
 
Example 39
Project: traccar-service   File: UlbotechProtocolDecoder.java   View source code 5 votes vote down vote up
private void decodeDriverBehavior(Position position, ChannelBuffer buf) {

        int value = buf.readUnsignedByte();

        if (BitUtil.check(value, 0)) {
            position.set("rapidAcceleration", true);
        }
        if (BitUtil.check(value, 1)) {
            position.set("roughBraking", true);
        }
        if (BitUtil.check(value, 2)) {
            position.set("harshCourse", true);
        }
        if (BitUtil.check(value, 3)) {
            position.set("noWarmUp", true);
        }
        if (BitUtil.check(value, 4)) {
            position.set("longIdle", true);
        }
        if (BitUtil.check(value, 5)) {
            position.set("fatigueDriving", true);
        }
        if (BitUtil.check(value, 6)) {
            position.set("roughTerrain", true);
        }
        if (BitUtil.check(value, 7)) {
            position.set("highRpm", true);
        }
    }
 
Example 40
Project: athena   File: LspEntry.java   View source code 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());
}