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

The following examples show how to use org.jboss.netty.buffer.ChannelBuffers#buffer() . 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 check out the related API usage on the sidebar.
Example 1
Source Project: mt-flume   File: TestSyslogUtils.java    License: Apache License 2.0 6 votes vote down vote up
public void checkHeader(String msg1, String stamp1, String format1, String host1, String data1) throws ParseException {
  SyslogUtils util = new SyslogUtils(false);
  ChannelBuffer buff = ChannelBuffers.buffer(200);

  buff.writeBytes(msg1.getBytes());
  Event e = util.extractEvent(buff);
  if(e == null){
    throw new NullPointerException("Event is null");
  }
  Map<String, String> headers2 = e.getHeaders();
  if (stamp1 == null) {
    Assert.assertFalse(headers2.containsKey("timestamp"));
  } else {
    SimpleDateFormat formater = new SimpleDateFormat(format1);
    Assert.assertEquals(String.valueOf(formater.parse(stamp1).getTime()), headers2.get("timestamp"));
  }
  if (host1 == null) {
    Assert.assertFalse(headers2.containsKey("host"));
  } else {
    String host2 = headers2.get("host");
    Assert.assertEquals(host2,host1);
  }
  Assert.assertEquals(data1, new String(e.getBody()));
}
 
Example 2
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);

  Credentials creds = new Credentials();
  creds.addToken(new Text(serviceUrl), token);
  DataOutputBuffer out = new DataOutputBuffer();
  creds.write(out);
  int fileLength = out.getData().length;
  ChannelBuffer cbuffer = ChannelBuffers.buffer(fileLength);
  cbuffer.writeBytes(out.getData());
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(fileLength));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 3
Source Project: onos   File: BgpUpdate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Applies the appropriate actions after detecting BGP UPDATE
 * Missing Well-known Attribute Error: send NOTIFICATION and close the
 * channel.
 *
 * @param bgpSession the BGP Session to use
 * @param ctx the Channel Handler Context
 * @param missingAttrTypeCode the missing attribute type code
 */
private static void actionsBgpUpdateMissingWellKnownAttribute(
                            BgpSession bgpSession,
                            ChannelHandlerContext ctx,
                            int missingAttrTypeCode) {
    log.debug("BGP RX UPDATE Error from {}: Missing Well-known Attribute: {}",
              bgpSession.remoteInfo().address(), missingAttrTypeCode);

    //
    // ERROR: Missing Well-known Attribute
    //
    // Send NOTIFICATION and close the connection
    int errorCode = BgpConstants.Notifications.UpdateMessageError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.UpdateMessageError.MISSING_WELL_KNOWN_ATTRIBUTE;
    ChannelBuffer data = ChannelBuffers.buffer(1);
    data.writeByte(missingAttrTypeCode);
    ChannelBuffer txMessage =
        BgpNotification.prepareBgpNotification(errorCode, errorSubcode,
                                               data);
    ctx.getChannel().write(txMessage);
    bgpSession.closeSession(ctx);
}
 
Example 4
public ChannelBuffer constructHeader(MemcachedBinaryCommandDecoder.BinaryCommand bcmd, ChannelBuffer extrasBuffer, ChannelBuffer keyBuffer, ChannelBuffer valueBuffer, short responseCode, int opaqueValue, long casUnique) {
    // take the ResponseMessage and turn it into a binary payload.
    ChannelBuffer header = ChannelBuffers.buffer(ByteOrder.BIG_ENDIAN, 24);
    header.writeByte((byte)0x81);  // magic
    header.writeByte(bcmd.code); // opcode
    short keyLength = (short) (keyBuffer != null ? keyBuffer.capacity() :0);

    header.writeShort(keyLength);
    int extrasLength = extrasBuffer != null ? extrasBuffer.capacity() : 0;
    header.writeByte((byte) extrasLength); // extra length = flags + expiry
    header.writeByte((byte)0); // data type unused
    header.writeShort(responseCode); // status code

    int dataLength = valueBuffer != null ? valueBuffer.capacity() : 0;
    header.writeInt(dataLength + keyLength + extrasLength); // data length
    header.writeInt(opaqueValue); // opaque

    header.writeLong(casUnique);

    return header;
}
 
Example 5
Source Project: mt-flume   File: TestSyslogUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Test bad event format 1: Priority is not numeric
 */
@Test
public void testExtractBadEvent1() {
  String badData1 = "<10F> bad bad data\n";
  SyslogUtils util = new SyslogUtils(false);
  ChannelBuffer buff = ChannelBuffers.buffer(100);
  buff.writeBytes(badData1.getBytes());
  Event e = util.extractEvent(buff);
  if(e == null){
    throw new NullPointerException("Event is null");
  }
  Map<String, String> headers = e.getHeaders();
  Assert.assertEquals("0", headers.get(SyslogUtils.SYSLOG_FACILITY));
  Assert.assertEquals("0", headers.get(SyslogUtils.SYSLOG_SEVERITY));
  Assert.assertEquals(SyslogUtils.SyslogStatus.INVALID.getSyslogStatus(),
      headers.get(SyslogUtils.EVENT_STATUS));
  Assert.assertEquals(badData1.trim(), new String(e.getBody()).trim());

}
 
Example 6
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  byte[] bytes = EXP_DATE.getBytes();
  ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length);
  cbuffer.writeBytes(bytes);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(bytes.length));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 7
Source Project: mt-flume   File: TestSyslogUtils.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBadEventBadEvent(){
  String badData1 = "hi guys! <10F> bad bad data\n";
  SyslogUtils util = new SyslogUtils(false);
  ChannelBuffer buff = ChannelBuffers.buffer(100);
  buff.writeBytes(badData1.getBytes());
  String badData2 = "hi guys! <20> bad bad data\n";
  buff.writeBytes((badData2).getBytes());
  Event e = util.extractEvent(buff);

  if(e == null){
    throw new NullPointerException("Event is null");
  }
  Map<String, String> headers = e.getHeaders();
  Assert.assertEquals("0", headers.get(SyslogUtils.SYSLOG_FACILITY));
  Assert.assertEquals("0", headers.get(SyslogUtils.SYSLOG_SEVERITY));
  Assert.assertEquals(SyslogUtils.SyslogStatus.INVALID.getSyslogStatus(),
      headers.get(SyslogUtils.EVENT_STATUS));
  Assert.assertEquals(badData1.trim(), new String(e.getBody()).trim());

  Event e2 = util.extractEvent(buff);

  if(e2 == null){
    throw new NullPointerException("Event is null");
  }
  Map<String, String> headers2 = e2.getHeaders();
  Assert.assertEquals("0", headers2.get(SyslogUtils.SYSLOG_FACILITY));
  Assert.assertEquals("0", headers2.get(SyslogUtils.SYSLOG_SEVERITY));
  Assert.assertEquals(SyslogUtils.SyslogStatus.INVALID.getSyslogStatus(),
      headers2.get(SyslogUtils.EVENT_STATUS));
  Assert.assertEquals(badData2.trim(), new String(e2.getBody()).trim());
}
 
Example 8
@Override
public void handle(Channel channel, Token<DelegationTokenIdentifier> token,
    String serviceUrl) throws IOException {
  Assert.assertEquals(testToken, token);
  byte[] bytes = EXP_DATE.getBytes();
  ChannelBuffer cbuffer = ChannelBuffers.buffer(bytes.length);
  cbuffer.writeBytes(bytes);
  HttpResponse response = new DefaultHttpResponse(HTTP_1_1, OK);
  response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
      String.valueOf(bytes.length));
  response.setContent(cbuffer);
  channel.write(response).addListener(ChannelFutureListener.CLOSE);
}
 
Example 9
Source Project: pinpoint   File: StreamResponsePacket.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChannelBuffer toBuffer() {
    ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4);
    header.writeShort(getPacketType());
    header.writeInt(getStreamChannelId());

    return PayloadPacket.appendPayload(header, payload);
}
 
Example 10
Source Project: pinpoint   File: TraceSendAckPacket.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChannelBuffer toBuffer() {
    ChannelBuffer header = ChannelBuffers.buffer(2 + 4);
    header.writeShort(PacketType.APPLICATION_TRACE_SEND_ACK);
    header.writeInt(traceId);

    return header;
}
 
Example 11
Source Project: onos   File: BgpKeepalive.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Prepares BGP KEEPALIVE message.
 *
 * @return the message to transmit (BGP header included)
 */
static ChannelBuffer prepareBgpKeepalive() {
    ChannelBuffer message =
        ChannelBuffers.buffer(BgpConstants.BGP_MESSAGE_MAX_LENGTH);

    //
    // Prepare the KEEPALIVE message payload: nothing to do
    //
    return BgpMessage.prepareBgpMessage(BgpConstants.BGP_TYPE_KEEPALIVE,
                                        message);
}
 
Example 12
Source Project: usergrid   File: Message.java    License: Apache License 2.0 5 votes vote down vote up
public ChannelBuffer encode( ChannelBuffer buffer ) {
    if ( buffer == null ) {
        buffer = ChannelBuffers.buffer( ByteOrder.LITTLE_ENDIAN, messageLength );
    }
    buffer.writeInt( messageLength );
    buffer.writeInt( requestID );
    buffer.writeInt( responseTo );
    buffer.writeInt( opCode );
    return buffer;
}
 
Example 13
@Test
public void testAction() {
    ChannelBuffer buf = ChannelBuffers.buffer(32);
    
    OFActionNiciraTtlDecrement act = new OFActionNiciraTtlDecrement();
    
    assertEquals(true, act instanceof OFActionNiciraVendor);
    assertEquals(true, act instanceof OFActionVendor);
    assertEquals(true, act instanceof OFAction);
    
    act.writeTo(buf);
    
    ChannelBuffer buf2 = buf.copy();
    
    assertEquals(16, buf.readableBytes());
    byte fromBuffer[] = new byte[16]; 
    buf.readBytes(fromBuffer);
    assertArrayEquals(expectedWireFormat, fromBuffer);
    
    // Test parsing. TODO: we don't really have the proper parsing
    // infrastructure....
    OFActionNiciraVendor act2 = new OFActionNiciraTtlDecrement();
    act2.readFrom(buf2);
    assertEquals(act, act2);
    assertNotSame(act, act2);
    
    assertEquals(OFActionType.VENDOR, act2.getType());
    assertEquals(16, act2.getLength());
    assertEquals(OFActionNiciraVendor.NICIRA_VENDOR_ID, act2.getVendor());
    assertEquals((short)18, act2.getSubtype());
}
 
Example 14
Source Project: pinpoint   File: ControlHandshakePacket.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ChannelBuffer toBuffer() {

    ChannelBuffer header = ChannelBuffers.buffer(2 + 4 + 4);
    header.writeShort(PacketType.CONTROL_HANDSHAKE);
    header.writeInt(getRequestId());

    return PayloadPacket.appendPayload(header, payload);
}
 
Example 15
Source Project: restcommander   File: PlayHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void upgradeResponseHixie76(HttpRequest req, HttpResponse res) {
    res.setStatus(new HttpResponseStatus(101, "Web Socket Protocol Handshake"));
    res.addHeader(UPGRADE, WEBSOCKET);
    res.addHeader(CONNECTION, UPGRADE);
    res.addHeader(SEC_WEBSOCKET_ORIGIN, req.getHeader(ORIGIN));
    res.addHeader(SEC_WEBSOCKET_LOCATION, getWebSocketLocation(req));
    String protocol = req.getHeader(SEC_WEBSOCKET_PROTOCOL);
    if (protocol != null) {
        res.addHeader(SEC_WEBSOCKET_PROTOCOL, protocol);
    }

    // Calculate the answer of the challenge.
    String key1 = req.getHeader(SEC_WEBSOCKET_KEY1);
    String key2 = req.getHeader(SEC_WEBSOCKET_KEY2);
    int a = (int) (Long.parseLong(key1.replaceAll("[^0-9]", "")) / key1.replaceAll("[^ ]", "").length());
    int b = (int) (Long.parseLong(key2.replaceAll("[^0-9]", "")) / key2.replaceAll("[^ ]", "").length());
    long c = req.getContent().readLong();
    ChannelBuffer input = ChannelBuffers.buffer(16);
    input.writeInt(a);
    input.writeInt(b);
    input.writeLong(c);
    try {
        ChannelBuffer output = ChannelBuffers.wrappedBuffer(
                MessageDigest.getInstance("MD5").digest(input.array()));
        res.setContent(output);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}
 
Example 16
Source Project: feeyo-hlsserver   File: UdpClient.java    License: Apache License 2.0 4 votes vote down vote up
public void write(byte[] payload, InetSocketAddress addr) {
	
	ChannelBuffer channelBuffer = ChannelBuffers.buffer( payload.length );
	channelBuffer.writeBytes( payload );
	channel.write(channelBuffer, addr);
}
 
Example 17
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 18
Source Project: onos   File: TestBgpPeerChannelHandler.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Prepares BGP UPDATE message.
 *
 * @param nextHopRouter the next-hop router address for the routes to add
 * @param localPref the local preference for the routes to use
 * @param multiExitDisc the MED value
 * @param asPath the AS path for the routes to add
 * @param addedRoutes the routes to add
 * @param withdrawnRoutes the routes to withdraw
 * @return the message to transmit (BGP header included)
 */
ChannelBuffer prepareBgpUpdate(Ip4Address nextHopRouter,
                               long localPref,
                               long multiExitDisc,
                               BgpRouteEntry.AsPath asPath,
                               Collection<Ip4Prefix> addedRoutes,
                               Collection<Ip4Prefix> withdrawnRoutes) {
    int attrFlags;
    ChannelBuffer message =
        ChannelBuffers.buffer(BgpConstants.BGP_MESSAGE_MAX_LENGTH);
    ChannelBuffer pathAttributes =
        ChannelBuffers.buffer(BgpConstants.BGP_MESSAGE_MAX_LENGTH);

    // Encode the Withdrawn Routes
    ChannelBuffer encodedPrefixes = encodePackedPrefixes(withdrawnRoutes);
    message.writeShort(encodedPrefixes.readableBytes());
    message.writeBytes(encodedPrefixes);

    // Encode the Path Attributes
    // ORIGIN: IGP
    attrFlags = 0x40;                               // Transitive flag
    pathAttributes.writeByte(attrFlags);
    pathAttributes.writeByte(BgpConstants.Update.Origin.TYPE);
    pathAttributes.writeByte(1);                    // Data length
    pathAttributes.writeByte(BgpConstants.Update.Origin.IGP);

    // AS_PATH: asPath
    attrFlags = 0x40;                               // Transitive flag
    pathAttributes.writeByte(attrFlags);
    pathAttributes.writeByte(BgpConstants.Update.AsPath.TYPE);
    ChannelBuffer encodedAsPath = encodeAsPath(asPath);
    pathAttributes.writeByte(encodedAsPath.readableBytes()); // Data length
    pathAttributes.writeBytes(encodedAsPath);
    // NEXT_HOP: nextHopRouter
    attrFlags = 0x40;                               // Transitive flag
    pathAttributes.writeByte(attrFlags);
    pathAttributes.writeByte(BgpConstants.Update.NextHop.TYPE);
    pathAttributes.writeByte(4);                    // Data length
    pathAttributes.writeInt(nextHopRouter.toInt()); // Next-hop router
    // LOCAL_PREF: localPref
    attrFlags = 0x40;                               // Transitive flag
    pathAttributes.writeByte(attrFlags);
    pathAttributes.writeByte(BgpConstants.Update.LocalPref.TYPE);
    pathAttributes.writeByte(4);                    // Data length
    pathAttributes.writeInt((int) localPref);       // Preference value
    // MULTI_EXIT_DISC: multiExitDisc
    attrFlags = 0x80;                               // Optional
                                                    // Non-Transitive flag
    pathAttributes.writeByte(attrFlags);
    pathAttributes.writeByte(BgpConstants.Update.MultiExitDisc.TYPE);
    pathAttributes.writeByte(4);                    // Data length
    pathAttributes.writeInt((int) multiExitDisc);   // Preference value
    // The NLRI prefixes
    encodedPrefixes = encodePackedPrefixes(addedRoutes);

    // Write the Path Attributes, beginning with its length
    message.writeShort(pathAttributes.readableBytes());
    message.writeBytes(pathAttributes);
    message.writeBytes(encodedPrefixes);

    return BgpMessage.prepareBgpMessage(BgpConstants.BGP_TYPE_UPDATE,
                                        message);
}
 
Example 19
protected void sendPacket(HashSet<String> matchedFilters, IOFSwitch sw, 
        OFMessage msg, FloodlightContext cntx, boolean sync) 
                throws TException {
    Message sendMsg = new Message();
    Packet packet = new Packet();
    ChannelBuffer bb;
    sendMsg.setPacket(packet);

    List<String> sids = new ArrayList<String>(matchedFilters);

    sendMsg.setSessionIDs(sids);
    packet.setMessageType(OFMessageType.findByValue((msg.getType().ordinal())));

    switch (msg.getType()) {
        case PACKET_IN:
            OFPacketIn pktIn = (OFPacketIn)msg;
            packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), 
                                                      pktIn.getInPort()));
            bb = ChannelBuffers.buffer(pktIn.getLength());
            pktIn.writeTo(bb);
            packet.setData(OFMessage.getData(sw, msg, cntx));
            break;
        case PACKET_OUT:
            OFPacketOut pktOut = (OFPacketOut)msg;
            packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), 
                                                      pktOut.getInPort()));
            bb = ChannelBuffers.buffer(pktOut.getLength());
            pktOut.writeTo(bb);
            packet.setData(OFMessage.getData(sw, msg, cntx));
            break;
        case FLOW_MOD:
            OFFlowMod offlowMod = (OFFlowMod)msg;
            packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), 
                                                      offlowMod.
                                                      getOutPort()));
            bb = ChannelBuffers.buffer(offlowMod.getLength());
            offlowMod.writeTo(bb);
            packet.setData(OFMessage.getData(sw, msg, cntx));
            break;
        default:
            packet.setSwPortTuple(new SwitchPortTuple(sw.getId(), 
                                                      (short)0));
            String strData = "Unknown packet";
            packet.setData(strData.getBytes());
            break;
    }

    try {
        if (transport == null || 
            !transport.isOpen() || 
            packetClient == null) {
            if (!connectToPSServer()) {
                // No need to sendPacket if can't make connection to 
                // the server
                return;
            }
        }
        if (sync) {
            log.debug("Send packet sync: {}", packet.toString());
            packetClient.pushMessageSync(sendMsg);
        } else {
            log.debug("Send packet sync: ", packet.toString());
            packetClient.pushMessageAsync(sendMsg);
        }
    } catch (Exception e) {
        log.error("Error while sending packet", e);
        disconnectFromPSServer();
        connectToPSServer();
    }
}
 
Example 20
Source Project: onos   File: BgpOpen.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Prepares the Capabilities for the BGP OPEN message.
 *
 * @param localInfo the BGP Session local information to use
 * @return the buffer with the BGP Capabilities to transmit
 */
private static ChannelBuffer prepareBgpOpenCapabilities(
                                    BgpSessionInfo localInfo) {
    ChannelBuffer message =
        ChannelBuffers.buffer(BgpConstants.BGP_MESSAGE_MAX_LENGTH);

    //
    // Write the Multiprotocol Extensions Capabilities
    //

    // IPv4 unicast
    if (localInfo.ipv4Unicast()) {
        message.writeByte(BgpConstants.Open.Capabilities.TYPE);               // Param type
        message.writeByte(BgpConstants.Open.Capabilities.MIN_LENGTH +
                          BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Param len
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.CODE);    // Capab. code
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Capab. len
        message.writeShort(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.AFI_IPV4);
        message.writeByte(0);               // Reserved field
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.SAFI_UNICAST);
    }
    // IPv4 multicast
    if (localInfo.ipv4Multicast()) {
        message.writeByte(BgpConstants.Open.Capabilities.TYPE);               // Param type
        message.writeByte(BgpConstants.Open.Capabilities.MIN_LENGTH +
                          BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Param len
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.CODE);    // Capab. code
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Capab. len
        message.writeShort(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.AFI_IPV4);
        message.writeByte(0);               // Reserved field
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.SAFI_MULTICAST);
    }
    // IPv6 unicast
    if (localInfo.ipv6Unicast()) {
        message.writeByte(BgpConstants.Open.Capabilities.TYPE);               // Param type
        message.writeByte(BgpConstants.Open.Capabilities.MIN_LENGTH +
                          BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Param len
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.CODE);    // Capab. code
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Capab. len
        message.writeShort(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.AFI_IPV6);
        message.writeByte(0);               // Reserved field
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.SAFI_UNICAST);
    }
    // IPv6 multicast
    if (localInfo.ipv6Multicast()) {
        message.writeByte(BgpConstants.Open.Capabilities.TYPE);               // Param type
        message.writeByte(BgpConstants.Open.Capabilities.MIN_LENGTH +
                          BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Param len
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.CODE);    // Capab. code
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.LENGTH);  // Capab. len
        message.writeShort(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.AFI_IPV6);
        message.writeByte(0);               // Reserved field
        message.writeByte(
                BgpConstants.Open.Capabilities.MultiprotocolExtensions.SAFI_MULTICAST);
    }

    // 4 octet AS path capability
    if (localInfo.as4OctetCapability()) {
        message.writeByte(BgpConstants.Open.Capabilities.TYPE);               // Param type
        message.writeByte(BgpConstants.Open.Capabilities.MIN_LENGTH +
                          BgpConstants.Open.Capabilities.As4Octet.LENGTH);                 // Param len
        message.writeByte(BgpConstants.Open.Capabilities.As4Octet.CODE);                   // Capab. code
        message.writeByte(BgpConstants.Open.Capabilities.As4Octet.LENGTH);                 // Capab. len
        message.writeInt((int) localInfo.as4Number());
    }
    return message;
}