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

The following are Jave code examples for showing how to use buffer() of the org.jboss.netty.buffer.ChannelBuffers class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: flume-release-1.7.0   File: TestSyslogUtils.java   Source Code and License Vote up 6 votes
/**
 * 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 2
Project: flume-release-1.7.0   File: TestSyslogUtils.java   Source Code and License Vote up 6 votes
/**
 * Test bad event format 2: The first char is not <
 */
@Test
public void testExtractBadEvent2() {
  String badData1 = "hi guys! <10> 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 3
Project: athena   File: BgpUpdate.java   Source Code and License Vote up 6 votes
/**
 * Prepares BGP UPDATE Notification data payload.
 *
 * @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
 * @return the buffer with the data payload for the BGP UPDATE Notification
 */
private static ChannelBuffer prepareBgpUpdateNotificationDataPayload(
                                    int attrTypeCode,
                                    int attrLen,
                                    int attrFlags,
                                    ChannelBuffer message) {
    // Compute the attribute length field octets
    boolean extendedLengthBit = ((0x10 & attrFlags) != 0);
    int attrLenOctets = 1;
    if (extendedLengthBit) {
        attrLenOctets = 2;
    }
    ChannelBuffer data =
        ChannelBuffers.buffer(attrLen + attrLenOctets + 1);
    data.writeByte(attrTypeCode);
    if (extendedLengthBit) {
        data.writeShort(attrLen);
    } else {
        data.writeByte(attrLen);
    }
    data.writeBytes(message, attrLen);
    return data;
}
 
Example 4
Project: flume-release-1.7.0   File: TestSyslogUtils.java   Source Code and License Vote up 6 votes
/**
 * Test bad event format 4: Priority too long
 */
@Test
public void testExtractBadEvent4() {
  String badData1 = "<123123123123123123123123123123> 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 5
Project: flume-release-1.7.0   File: TestSyslogUtils.java   Source Code and License Vote up 6 votes
/**
 * Good event
 */
@Test
public void testExtractGoodEvent() {
  String priority = "<10>";
  String goodData1 = "Good good good data\n";
  SyslogUtils util = new SyslogUtils(false);
  ChannelBuffer buff = ChannelBuffers.buffer(100);
  buff.writeBytes((priority + goodData1).getBytes());
  Event e = util.extractEvent(buff);
  if (e == null) {
    throw new NullPointerException("Event is null");
  }
  Map<String, String> headers = e.getHeaders();
  Assert.assertEquals("1", headers.get(SyslogUtils.SYSLOG_FACILITY));
  Assert.assertEquals("2", headers.get(SyslogUtils.SYSLOG_SEVERITY));
  Assert.assertEquals(null, headers.get(SyslogUtils.EVENT_STATUS));
  Assert.assertEquals(priority + goodData1.trim(),
                      new String(e.getBody()).trim());
}
 
Example 6
Project: athena   File: TestBgpPeerChannelHandler.java   Source Code and License Vote up 6 votes
/**
 * Encodes a collection of IPv4 network prefixes in a packed format.
 * <p>
 * The IPv4 prefixes are encoded in the form:
 * <Length, Prefix> where Length is the length in bits of the IPv4 prefix,
 * and Prefix is the IPv4 prefix (padded with trailing bits to the end
 * of an octet).
 *
 * @param prefixes the prefixes to encode
 * @return the buffer with the encoded prefixes
 */
private ChannelBuffer encodePackedPrefixes(Collection<Ip4Prefix> prefixes) {
    ChannelBuffer message =
        ChannelBuffers.buffer(BgpConstants.BGP_MESSAGE_MAX_LENGTH);

    // Write each of the prefixes
    for (Ip4Prefix prefix : prefixes) {
        int prefixBitlen = prefix.prefixLength();
        int prefixBytelen = (prefixBitlen + 7) / 8;         // Round-up
        message.writeByte(prefixBitlen);

        Ip4Address address = prefix.address();
        long value = address.toInt() & 0xffffffffL;
        for (int i = 0; i < Ip4Address.BYTE_LENGTH; i++) {
            if (prefixBytelen-- == 0) {
                break;
            }
            long nextByte =
                (value >> ((Ip4Address.BYTE_LENGTH - i - 1) * 8)) & 0xff;
            message.writeByte((int) nextByte);
        }
    }

    return message;
}
 
Example 7
Project: athena   File: BgpOpen.java   Source Code and License Vote up 6 votes
/**
 * Prepares BGP OPEN message.
 *
 * @param localInfo the BGP Session local information to use
 * @return the message to transmit (BGP header included)
 */
static ChannelBuffer prepareBgpOpen(BgpSessionInfo localInfo) {
    ChannelBuffer message =
        ChannelBuffers.buffer(BgpConstants.BGP_MESSAGE_MAX_LENGTH);

    //
    // Prepare the OPEN message payload
    //
    message.writeByte(localInfo.bgpVersion());
    message.writeShort((int) localInfo.asNumber());
    message.writeShort((int) localInfo.holdtime());
    message.writeInt(localInfo.bgpId().toInt());

    // Prepare the optional BGP Capabilities
    ChannelBuffer capabilitiesMessage =
        prepareBgpOpenCapabilities(localInfo);
    message.writeByte(capabilitiesMessage.readableBytes());
    message.writeBytes(capabilitiesMessage);

    return BgpMessage.prepareBgpMessage(BgpConstants.BGP_TYPE_OPEN,
                                        message);
}
 
Example 8
Project: traccar-service   File: MeiligaoProtocolDecoder.java   Source Code and License Vote up 6 votes
private static void sendResponse(
        Channel channel, SocketAddress remoteAddress, ChannelBuffer id, int type, ChannelBuffer msg) {

    if (channel != null) {
        ChannelBuffer buf = ChannelBuffers.buffer(
                2 + 2 + id.readableBytes() + 2 + msg.readableBytes() + 2 + 2);

        buf.writeByte('@');
        buf.writeByte('@');
        buf.writeShort(buf.capacity());
        buf.writeBytes(id);
        buf.writeShort(type);
        buf.writeBytes(msg);
        buf.writeShort(Checksum.crc16(Checksum.CRC16_CCITT_FALSE, buf.toByteBuffer()));
        buf.writeByte('\r');
        buf.writeByte('\n');

        channel.write(buf, remoteAddress);
    }
}
 
Example 9
Project: traccar-service   File: NoranProtocolEncoder.java   Source Code and License Vote up 6 votes
private ChannelBuffer encodeContent(String content) {

        ChannelBuffer buf = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, 12 + 56);

        buf.writeBytes(
                ChannelBuffers.copiedBuffer(ByteOrder.LITTLE_ENDIAN, "\r\n*KW", StandardCharsets.US_ASCII));
        buf.writeByte(0);
        buf.writeShort(buf.capacity());
        buf.writeShort(NoranProtocolDecoder.MSG_CONTROL);
        buf.writeInt(0); // gis ip
        buf.writeShort(0); // gis port
        buf.writeBytes(content.getBytes(StandardCharsets.US_ASCII));
        buf.writerIndex(buf.writerIndex() + 50 - content.length());
        buf.writeBytes(
                ChannelBuffers.copiedBuffer(ByteOrder.LITTLE_ENDIAN, "\r\n", StandardCharsets.US_ASCII));

        return buf;
    }
 
Example 10
Project: athena   File: BgpNotification.java   Source Code and License Vote up 6 votes
/**
 * Prepares BGP NOTIFICATION message.
 *
 * @param errorCode the BGP NOTIFICATION Error Code
 * @param errorSubcode the BGP NOTIFICATION Error Subcode if applicable,
 * otherwise BgpConstants.Notifications.ERROR_SUBCODE_UNSPECIFIC
 * @param data the BGP NOTIFICATION Data if applicable, otherwise null
 * @return the message to transmit (BGP header included)
 */
static ChannelBuffer prepareBgpNotification(int errorCode,
                                            int errorSubcode,
                                            ChannelBuffer data) {
    ChannelBuffer message =
        ChannelBuffers.buffer(BgpConstants.BGP_MESSAGE_MAX_LENGTH);

    //
    // Prepare the NOTIFICATION message payload
    //
    message.writeByte(errorCode);
    message.writeByte(errorSubcode);
    if (data != null) {
        message.writeBytes(data);
    }
    return BgpMessage.prepareBgpMessage(BgpConstants.BGP_TYPE_NOTIFICATION,
                                        message);
}
 
Example 11
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License Vote up 6 votes
@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 12
Project: flume-release-1.7.0   File: TestSyslogUtils.java   Source Code and License Vote up 5 votes
public static void checkHeader(String keepFields, String msg1, String stamp1, String format1,
                               String host1, String data1) throws ParseException {
  SyslogUtils util;
  if (keepFields == null || keepFields.isEmpty()) {
    util = new SyslogUtils(SyslogUtils.DEFAULT_SIZE, new HashSet<String>(), false);
  } else {
    util = new SyslogUtils(SyslogUtils.DEFAULT_SIZE,
                           SyslogUtils.chooseFieldsToKeep(keepFields),
                           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, Locale.ENGLISH);
    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 13
Project: flume-release-1.7.0   File: TestSyslogUtils.java   Source Code and License Vote up 5 votes
@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 14
Project: athena   File: OspfMessageEncoder.java   Source Code and License Vote up 5 votes
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {

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

    return channelBuffer;
}
 
Example 15
Project: athena   File: BgpKeepalive.java   Source Code and License Vote up 5 votes
/**
 * 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 16
Project: traccar-service   File: MxtFrameDecoder.java   Source Code and License Vote up 5 votes
@Override
protected Object decode(
        ChannelHandlerContext ctx,
        Channel channel,
        ChannelBuffer buf) throws Exception {

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

    int index = buf.indexOf(buf.readerIndex() + 1, buf.writerIndex(), (byte) 0x04);
    if (index != -1) {
        ChannelBuffer result = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, index + 1 - buf.readerIndex());

        while (buf.readerIndex() <= index) {
            int b = buf.readUnsignedByte();
            if (b == 0x10) {
                result.writeByte(buf.readUnsignedByte() - 0x20);
            } else {
                result.writeByte(b);
            }
        }

        return result;
    }

    return null;
}
 
Example 17
Project: athena   File: BgpNotification.java   Source Code and License Vote up 5 votes
/**
 * Prepares BGP NOTIFICATION message: Bad Message Length.
 *
 * @param length the erroneous Length field
 * @return the message to transmit (BGP header included)
 */
static ChannelBuffer prepareBgpNotificationBadMessageLength(int length) {
    int errorCode = BgpConstants.Notifications.MessageHeaderError.ERROR_CODE;
    int errorSubcode = BgpConstants.Notifications.MessageHeaderError.BAD_MESSAGE_LENGTH;
    ChannelBuffer data = ChannelBuffers.buffer(2);
    data.writeShort(length);

    return prepareBgpNotification(errorCode, errorSubcode, data);
}
 
Example 18
Project: traccar-service   File: HuabaoFrameDecoder.java   Source Code and License Vote up 5 votes
@Override
protected Object decode(
        ChannelHandlerContext ctx, Channel channel, ChannelBuffer buf) throws Exception {

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

    int index = buf.indexOf(buf.readerIndex() + 1, buf.writerIndex(), (byte) 0x7e);
    if (index != -1) {
        ChannelBuffer result = ChannelBuffers.buffer(index + 1 - buf.readerIndex());

        while (buf.readerIndex() <= index) {
            int b = buf.readUnsignedByte();
            if (b == 0x7d) {
                int ext = buf.readUnsignedByte();
                if (ext == 0x01) {
                    result.writeByte(0x7d);
                } else if (ext == 0x02) {
                    result.writeByte(0x7e);
                }
            } else {
                result.writeByte(b);
            }
        }

        return result;
    }

    return null;
}
 
Example 19
Project: hadoop   File: TestDelegationTokenRemoteFetcher.java   Source Code and License Vote up 5 votes
@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 20
Project: traccar-service   File: Gt06ProtocolDecoder.java   Source Code and License Vote up 4 votes
private Object decodeBasic(Channel channel, SocketAddress remoteAddress, ChannelBuffer buf) throws Exception {

        int length = buf.readUnsignedByte();
        int dataLength = length - 5;
        int type = buf.readUnsignedByte();

        DeviceSession deviceSession = null;
        if (type != MSG_LOGIN) {
            deviceSession = getDeviceSession(channel, remoteAddress);
            if (deviceSession == null) {
                return null;
            }
        }

        if (type == MSG_LOGIN) {

            String imei = ChannelBuffers.hexDump(buf.readBytes(8)).substring(1);
            buf.readUnsignedShort(); // type

            if (dataLength > 10) {
                int extensionBits = buf.readUnsignedShort();
                int hours = (extensionBits >> 4) / 100;
                int minutes = (extensionBits >> 4) % 100;
                int offset = (hours * 60 + minutes) * 60;
                if ((extensionBits & 0x8) != 0) {
                    offset = -offset;
                }
                if (!forceTimeZone) {
                    timeZone.setRawOffset(offset * 1000);
                }
            }

            if (getDeviceSession(channel, remoteAddress, imei) != null) {
                sendResponse(channel, false, type);
            }

        } else if (type == MSG_X1_GPS) {

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

            buf.readUnsignedInt(); // data and alarm

            decodeGps(position, buf, false);

            buf.readUnsignedShort(); // terminal info

            position.set(Position.KEY_ODOMETER, buf.readUnsignedInt());

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

            return position;

        } else if (type == MSG_X1_PHOTO_INFO) {

            buf.skipBytes(6); // time
            buf.readUnsignedByte(); // fix status
            buf.readUnsignedInt(); // latitude
            buf.readUnsignedInt(); // longitude
            buf.readUnsignedByte(); // camera id
            buf.readUnsignedByte(); // photo source
            buf.readUnsignedByte(); // picture format

            ChannelBuffer photo = ChannelBuffers.buffer(buf.readInt());
            int pictureId = buf.readInt();
            photos.put(pictureId, photo);
            sendPhotoRequest(channel, pictureId);

        } else {

            return decodeBasicOther(channel, buf, deviceSession, type, dataLength);

        }

        return null;
    }