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

The following examples show how to use org.jboss.netty.buffer.ChannelBuffers. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: jstorm   Source File: TaskMessage.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * create a buffer containing the encoding of this batch
 */
@Override
public ChannelBuffer buffer() throws Exception {
    int payloadLen = 0;
    if (_message != null)
        payloadLen = _message.length;

    int totalLen = 8 + payloadLen;
    ChannelBufferOutputStream bout = new ChannelBufferOutputStream(ChannelBuffers.directBuffer(totalLen));
    bout.writeShort(_type);

    if (_task > Short.MAX_VALUE)
        throw new RuntimeException("Task ID should not exceed " + Short.MAX_VALUE);

    bout.writeShort((short) _task);
    bout.writeInt(payloadLen);
    if (payloadLen > 0)
        bout.write(_message);

    bout.close();
    return bout.buffer();
}
 
Example 2
Source Project: fqueue   Source File: MemcachedBinaryResponseEncoder.java    License: Apache License 2.0 6 votes vote down vote up
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 3
Source Project: hadoop   Source File: TestDelegationTokenRemoteFetcher.java    License: Apache License 2.0 6 votes vote down vote up
@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 4
private void testAll(OFActionTunnelDstIP tip) {
    assertEquals(OFActionType.VENDOR, tip.getType());
    assertEquals(2, tip.getSubtype());
    assertEquals(16, tip.getLength());
    assertEquals(0x005c16c7, tip.getVendor());

    tip.setTunnelDstIP(24);
    assertEquals(24, tip.getTunnelDstIP());
    
    // Test wire format
    int ip = IPv4.toIPv4Address("17.33.49.65");
    tip.setTunnelDstIP(ip);
    ChannelBuffer buf = ChannelBuffers.buffer(32);
    tip.writeTo(buf);
    ChannelBuffer buf2 = buf.copy();
    assertEquals(16, buf.readableBytes());
    byte fromBuffer[] = new byte[16]; 
    buf.readBytes(fromBuffer);
    assertArrayEquals(expectedWireFormat1, fromBuffer);
    
    OFActionTunnelDstIP act2 = new OFActionTunnelDstIP();
    act2.readFrom(buf2);
    assertEquals(tip, act2);
    
    
}
 
Example 5
Source Project: onos   Source File: IsisMessageReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests readFromBuffer() method.
 */
@Test
public void testReadFromBuffer() throws Exception {
    channelBuffer = ChannelBuffers.copiedBuffer(helloP2P);
    message = reader.readFromBuffer(channelBuffer);
    assertThat(message, is(instanceOf(P2PHelloPdu.class)));

    channelBuffer = ChannelBuffers.copiedBuffer(helloL1L2);
    message = reader.readFromBuffer(channelBuffer);
    assertThat(message, is(instanceOf(L1L2HelloPdu.class)));

    byte[] tlv1 = Bytes.concat(l1Lsp, (IsisUtil.getPaddingTlvs(l1Lsp.length)));
    channelBuffer = ChannelBuffers.copiedBuffer(tlv1);
    message = reader.readFromBuffer(channelBuffer);
    assertThat(message, is(instanceOf(LsPdu.class)));

    tlv1 = Bytes.concat(csnp, (IsisUtil.getPaddingTlvs(csnp.length)));
    channelBuffer = ChannelBuffers.copiedBuffer(tlv1);
    message = reader.readFromBuffer(channelBuffer);
    assertThat(message, is(instanceOf(Csnp.class)));

    tlv1 = Bytes.concat(psnp, (IsisUtil.getPaddingTlvs(psnp.length)));
    channelBuffer = ChannelBuffers.copiedBuffer(tlv1);
    message = reader.readFromBuffer(channelBuffer);
    assertThat(message, is(instanceOf(Psnp.class)));
}
 
Example 6
public void testCreateAndParse() throws MessageParseException {
    BasicFactory factory = BasicFactory.getInstance();
    OFMessage m = factory.getMessage(OFType.HELLO);
    m.setVersion((byte) 1);
    m.setType(OFType.ECHO_REQUEST);
    m.setLength(U16.t(8));
    m.setXid(0xdeadbeef);
    ChannelBuffer bb = ChannelBuffers.dynamicBuffer();
    ChannelBuffer bb2 = ChannelBuffers.dynamicBuffer();
    m.writeTo(bb);
    bb2.writeBytes(bb, bb.readableBytes()-1);
    TestCase.assertNull(factory.parseMessage(bb2));
    bb2.writeByte(bb.readByte());
    List<OFMessage> message = factory.parseMessage(bb2);
    TestCase.assertNotNull(message);
    TestCase.assertEquals(message.size(), 1);
    TestCase.assertTrue(message.get(0).getType() == OFType.ECHO_REQUEST);
}
 
Example 7
Source Project: onos   Source File: OpaqueLsa9Test.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests readFrom() method.
 */
@Test
public void testReadFrom() throws Exception {
    opqueHeader = new OpaqueLsaHeader();
    opqueHeader.setLsType(1);
    opqueHeader.setLsPacketLen(48);
    opqueHeader.setLsCheckSum(10);
    opqueHeader.setAge(4);
    opqueHeader.setOpaqueId(9);
    opqueHeader.setOpaqueType(9);
    opqueHeader.setLsSequenceNo(250);
    opqueHeader.setAdvertisingRouter(Ip4Address.valueOf("100.226.165.165"));
    opqueHeader.setOptions(2);
    opaqueLsa9 = new OpaqueLsa9(opqueHeader);
    channelBuffer = ChannelBuffers.copiedBuffer(packet);
    opaqueLsa9.readFrom(channelBuffer);
    assertThat(opaqueLsa9, is(notNullValue()));
}
 
Example 8
Source Project: mt-flume   Source 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 9
Source Project: hadoop-arch-book   Source File: EventClient.java    License: Apache License 2.0 6 votes vote down vote up
public Action submitUserEvent(UserEvent userEvent) throws Exception {
  Channel channel = channelStateEvent.getChannel();

  if (channel.isWritable()) {
    String json = userEvent.getJSONObject().toString();
    ChannelBuffer m = ChannelBuffers.wrappedBuffer(Bytes.toBytes(json));

    LOG.info("EventClient:sending " + json);

    channel.write(m);
  } else {
    throw new RuntimeException("Channel is not writable");
  }

  synchronized (this) {
    long startTime = System.currentTimeMillis();
    LOG.info("-- EventClient:Waiting for response " + startTime);
    this.wait();
    LOG.info("-- EventClient:Got response " + (System.currentTimeMillis() - startTime));
  }

  LOG.info("EventClient:action " + action.alert);
  return action;
}
 
Example 10
Source Project: onos   Source File: BgpUpdateMsgTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * In this test case, Invalid message type is given as input and expecting
 * an exception.
 */
@Test(expected = BgpParseException.class)
public void bgpUpdateMessageTest04() 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, 0x17, 0x06, 0x00, 0x00, 0x00, 0x00};

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

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

    assertThat(message, instanceOf(BgpUpdateMsg.class));
}
 
Example 11
Source Project: onos   Source File: PcepInitiateMsgTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test case checks for SRP, LSP (StatefulIPv4LspIdentidiersTlv, StatefulRsvpErrorSpecTlv)
 * objects in PcInitiate message.
 */
@Test
public void initiateMessageTest10() throws PcepParseException, PcepOutOfBoundMessageException {

    /* SRP, LSP (StatefulIPv4LspIdentidiersTlv, StatefulRsvpErrorSpecTlv).
     */
    byte[] initiateDeletionMsg = new byte[]{0x20, 0x0C, 0x00, 0x44,
            0x21, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x03, //SRP object
            0x00, 0x11, 0x00, 0x02, 0x54, 0x31, 0x00, 0x00, //SymbolicPathTlv
            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, 0x04, 0x54, 0x31, 0x32, 0x33, //SymbolicPathNameTlv
            0x00, 0x14, 0x00, 0x04, 0x00, 0x00, 0x00, 0x08 //StatefulLspErrorCodeTlv
    };

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

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


    message = reader.readFrom(buffer);

    assertThat(message, instanceOf(PcepInitiateMsg.class));

    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();

    message.writeTo(buf);

    testInitiateDeletionMsg = buf.array();

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

    assertThat(testInitiateDeletionMsg, is(initiateDeletionMsg));
}
 
Example 12
Source Project: onos   Source File: RouterTlvTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests readFrom() method.
 */
@Test
public void testReadFrom() throws Exception {
    header = new TlvHeader();
    header.setTlvType(1);
    header.setTlvLength(4);
    rtlv = new RouterTlv(header);
    channelBuffer = ChannelBuffers.copiedBuffer(packet);
    rtlv.readFrom(channelBuffer);
    assertThat(rtlv, is(notNullValue()));
    assertThat(rtlv, instanceOf(RouterTlv.class));
}
 
Example 13
Source Project: pinpoint   Source File: StreamPongPacket.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());
    header.writeInt(requestId);

    return header;
}
 
Example 14
Source Project: onos   Source File: IsisNeighborTlvTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests asBytes() getter method.
 */
@Test
public void testAsBytes() throws Exception {
    channelBuffer = ChannelBuffers.copiedBuffer(tlv);
    isisNeighborTlv.readFrom(channelBuffer);
    result = isisNeighborTlv.asBytes();
    assertThat(result, is(notNullValue()));
}
 
Example 15
Source Project: restcommander   Source File: PlayHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected static void writeResponse(ChannelHandlerContext ctx, Response response, HttpResponse nettyResponse, HttpRequest nettyRequest) {
    if (Logger.isTraceEnabled()) {
        Logger.trace("writeResponse: begin");
    }

    byte[] content = null;

    final boolean keepAlive = isKeepAlive(nettyRequest);
    if (nettyRequest.getMethod().equals(HttpMethod.HEAD)) {
        content = new byte[0];
    } else {
        content = response.out.toByteArray();
    }

    ChannelBuffer buf = ChannelBuffers.copiedBuffer(content);
    nettyResponse.setContent(buf);

    if (Logger.isTraceEnabled()) {
        Logger.trace("writeResponse: content length [" + response.out.size() + "]");
    }

    setContentLength(nettyResponse, response.out.size());

    ChannelFuture f = ctx.getChannel().write(nettyResponse);

    // Decide whether to close the connection or not.
    if (!keepAlive) {
        // Close the connection when the whole content is written out.
        f.addListener(ChannelFutureListener.CLOSE);
    }
    if (Logger.isTraceEnabled()) {
        Logger.trace("writeResponse: end");
    }
}
 
Example 16
Source Project: onos   Source File: PcepUpdateMsgExtTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test case is for SRP object(SymbolicPathNameTlv), LSP object(SymbolicPathNameTlv), ERO object,
 * bandwidth object Metric object in PcepUpdate message.
 */
@Test
public void pcepUpdateMsgTest7() throws PcepParseException, PcepOutOfBoundMessageException {
    byte[] updateMsg = new byte[] {0x20, 0x0b, 0x00, (byte) 0x64,
            0x21, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, //SRP object
            0x00, 0x11, 0x00, 0x02,  0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
            0x20, 0x10, 0x00, 0x10, 0x00, 0x00, 0x10, 0x03, //LSP object
            0x00, 0x11, 0x00, 0x02,  0x54, 0x31, 0x00, 0x00, //SymbolicPathNameTlv
            0x07, 0x10, 0x00, 0x14, 0x01, 0x08, 0x11, 0x01, //ERO Object
            0x01, 0x01, 0x04, 0x00, 0x01, 0x08, 0x11, 0x01,
            0x01, 0x01, 0x04, 0x00,
            0x09, 0x10, 0x00, 0x14, 0x00, 0x00, 0x00, 0x00, //LSPA object
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x07, 0x00, 0x00,
            0x05, 0x20, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, //Bandwidth object
            0x06, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x00, 0x20 }; //Metric object

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

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

    message = reader.readFrom(buffer);

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

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

    assertThat(testupdateMsg, is(updateMsg));
}
 
Example 17
Source Project: onos   Source File: LspEntriesTlvTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests asBytes()  method.
 */
@Test
public void testAsBytes() throws Exception {
    channelBuffer = ChannelBuffers.copiedBuffer(entry);
    lspEntriesTlv.readFrom(channelBuffer);
    lspEntriesTlv.asBytes();
}
 
Example 18
Source Project: onos   Source File: BgpFlowSpecNlri.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Update buffer with non-identical flow types.
 *
 * @param cb channel buffer
 * @param bgpFlowSpecNlri flow specification
 */
public static void updateBufferNonIdenticalFlowTypes(ChannelBuffer cb, BgpFlowSpecNlri bgpFlowSpecNlri) {
    ChannelBuffer flowSpecTmpBuff = ChannelBuffers.dynamicBuffer();
    List<BgpValueType> flowSpec = bgpFlowSpecNlri.flowSpecComponents();
    ListIterator<BgpValueType> listIterator = flowSpec.listIterator();
    int tmpBuffStartIndx = flowSpecTmpBuff.writerIndex();

    flowSpec = bgpFlowSpecNlri.flowSpecComponents();
    listIterator = flowSpec.listIterator();

    while (listIterator.hasNext()) {
        BgpValueType tlv = listIterator.next();
        writeFlowType(tlv, flowSpecTmpBuff);
    }

    /* RFC 5575: section 4,  If the NLRI length value is smaller than 240 (0xf0 hex), the length
                             field can be encoded as a single octet.  Otherwise, it is encoded as
                             an extended-length 2-octet values */
    int len = flowSpecTmpBuff.writerIndex() - tmpBuffStartIndx;
    if (len >= FLOW_SPEC_LEN) {
        cb.writeShort(len);
    } else {
        cb.writeByte(len);
    }
    //Copy from bynamic buffer to channel buffer
    cb.writeBytes(flowSpecTmpBuff);
}
 
Example 19
Source Project: Android-Airplay-Server   Source File: RaopAudioHandler.java    License: MIT License 5 votes vote down vote up
/**
 * Handle GET_PARAMETER request. Currently only {@code volume} is supported
 */
public synchronized void getParameterReceived(final ChannelHandlerContext ctx, final HttpRequest req) throws ProtocolException {
	final StringBuilder body = new StringBuilder();

	if (audioOutputQueue != null) {
		/* Report output gain */
		body.append("volume: ");
		body.append(audioOutputQueue.getRequestedVolume());
		body.append("\r\n");
	}

	final HttpResponse response = new DefaultHttpResponse(RtspVersions.RTSP_1_0,  RtspResponseStatuses.OK);
	response.setContent(ChannelBuffers.wrappedBuffer(body.toString().getBytes(Charset.forName("ASCII"))));
	ctx.getChannel().write(response);
}
 
Example 20
Source Project: voyage   Source File: RpcResponseEncode.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent e)
		throws Exception {
	RpcResponse response = (RpcResponse) e.getMessage();
	ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
	//先写入标示的魔数
	baos.write(Constants.MAGIC_BYTES);
	MySerializerFactory.getInstance(Constants.DEFAULT_RPC_CODE_MODE).encodeResponse(baos, response);
	ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(baos.toByteArray());
	Channels.write(ctx, e.getFuture(), buffer);
}
 
Example 21
Source Project: onos   Source File: HostNameTlvTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests asBytes() method.
 */
@Test
public void testAsBytes() throws Exception {
    channelBuffer = ChannelBuffers.copiedBuffer(tlv);
    hostNameTlv.readFrom(channelBuffer);
    result1 = hostNameTlv.asBytes();
    assertThat(result1, is(notNullValue()));
}
 
Example 22
Source Project: onos   Source File: TrafficEngineeringMetricTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests readFrom() method.
 */
@Test
public void testReadFrom() throws Exception {
    header = new TlvHeader();
    header.setTlvLength(4);
    header.setTlvType(5);
    channelBuffer = ChannelBuffers.copiedBuffer(packet);
    trafficEngineeringMetric = new TrafficEngineeringMetric(header);
    trafficEngineeringMetric.readFrom(channelBuffer);
    assertThat(trafficEngineeringMetric, is(notNullValue()));
}
 
Example 23
Source Project: onos   Source File: BgpUpdateMsgTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * In this test case, Invalid SAFI is given as input and expecting
 * an exception.
 */
@Test(expected = BgpParseException.class)
public void bgpUpdateMessageTest15() 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, 0x60, 0x02, 0x00, 0x00, //withdrawn len
            0x00, 0x49, //path attribute len
            (byte) 0xff, 0x01, 0x01, 0x00, //origin
            0x40, 0x02, 0x04, 0x02, 0x01, (byte) 0xfd, (byte) 0xe9, //as_path
            (byte) 0x80, 0x04, 0x04, 0x00, 0x00, 0x00, 0x00, //med
            (byte) 0x80, 0x0e, 0x34, 0x40, 0x04, 0x49, //mpreach with safi = 71
            0x04, 0x04, 0x00, 0x00, 0x01, //nexthop
            0x00, //reserved
            0x00, 0x01, 0x00,
            0x27, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x1a, 0x02, 0x00,
            0x00, 0x04, 0x00, 0x00, 0x08, (byte) 0xae, 0x02, 0x01, 0x00, 0x04, 0x02, 0x02, 0x02, 0x02, 0x02, 0x03,
            0x00, 0x06, 0x19, 0x00, (byte) 0x95, 0x01, (byte) 0x90, 0x58}; //node nlri};

    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 24
Source Project: Elasticsearch   Source File: ESHttpResponseEncoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    Object retVal = super.encode(ctx, channel, msg);
    if (retVal instanceof CompositeChannelBuffer) {
        CompositeChannelBuffer ccb = (CompositeChannelBuffer) retVal;
        if (ccb.useGathering() != NettyUtils.DEFAULT_GATHERING) {
            List<ChannelBuffer> decompose = ccb.decompose(ccb.readerIndex(), ccb.readableBytes());
            return ChannelBuffers.wrappedBuffer(NettyUtils.DEFAULT_GATHERING,
                    decompose.toArray(new ChannelBuffer[decompose.size()]));
        }
    }
    return retVal;
}
 
Example 25
Source Project: Elasticsearch   Source File: NettyTransport.java    License: Apache License 2.0 5 votes vote down vote up
protected void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    if (!lifecycle.started()) {
        // ignore
        return;
    }
    if (isCloseConnectionException(e.getCause())) {
        logger.trace("close connection exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
        // close the channel, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (isConnectException(e.getCause())) {
        logger.trace("connect exception caught on transport layer [{}]", e.getCause(), ctx.getChannel());
        // close the channel as safe measure, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (e.getCause() instanceof CancelledKeyException) {
        logger.trace("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
        // close the channel as safe measure, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (e.getCause() instanceof SizeHeaderFrameDecoder.HttpOnTransportException) {
        // in case we are able to return data, serialize the exception content and sent it back to the client
        if (ctx.getChannel().isOpen()) {
            ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(e.getCause().getMessage().getBytes(Charsets.UTF_8));
            ChannelFuture channelFuture = ctx.getChannel().write(buffer);
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    future.getChannel().close();
                }
            });
        }
    } else {
        logger.warn("exception caught on transport layer [{}], closing connection", e.getCause(), ctx.getChannel());
        // close the channel, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    }
}
 
Example 26
Source Project: onos   Source File: IsReachabilityTlvTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests asBytes() method.
 */
@Test
public void testAsBytes() throws Exception {
    channelBuffer = ChannelBuffers.copiedBuffer(tlv);
    isReachabilityTlv.readFrom(channelBuffer);
    result = isReachabilityTlv.asBytes();
    assertThat(result, is(notNullValue()));
}
 
Example 27
public void testWriteRead() throws Exception {
    OFPortMod msg = (OFPortMod) messageFactory
            .getMessage(OFType.PORT_MOD);
    msg.setHardwareAddress(new byte[6]);
    msg.portNumber = 1;
    ChannelBuffer bb = ChannelBuffers.dynamicBuffer();
    bb.clear();
    msg.writeTo(bb);
    msg.readFrom(bb);
    TestCase.assertEquals(OFType.PORT_MOD, msg.getType());
    TestCase.assertEquals(1, msg.getPortNumber());
}
 
Example 28
Source Project: onos   Source File: AdministrativeGroupTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests readFrom() method.
 */
@Test
public void testReadFrom() throws Exception {
    tlvHeader = new TlvHeader();
    tlvHeader.setTlvType(9);
    tlvHeader.setTlvLength(4);
    administrativeGroup = new AdministrativeGroup(tlvHeader);
    channelBuffer = ChannelBuffers.copiedBuffer(packet);
    administrativeGroup.readFrom(channelBuffer);
    assertThat(administrativeGroup.administrativeGroup(), is(notNullValue()));
}
 
Example 29
Source Project: onos   Source File: PcepReportMsgTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * This test case checks for SRP Object, LSP Object(StatefulIPv4LspIdentidiersTlv,SymbolicPathNameTlv
 * StatefulLspErrorCodeTlv) ERO Object, IRO object
 * in PcRpt message.
 */
@Test
public void reportMessageTest5() throws PcepParseException, PcepOutOfBoundMessageException {

    byte[] reportMsg = new byte[]{0x20, 0x0a, 0x00, (byte) 0x50,
            0x21, 0x10, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, //SRP Object
            0x20, 0x10, 0x00, 0x2c, 0x00, 0x00, 0x10, 0x03, //LSP Object //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, //ERO Object
            0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x1f, 0x04, 0x00,
            0x01, 0x08, (byte) 0xb6, 0x02, 0x4e, 0x20, 0x04, 0x00};

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

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

    message = reader.readFrom(buffer);

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

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

    assertThat(testReportMsg, is(reportMsg));
}
 
Example 30
Source Project: onos   Source File: OspfInterfaceChannelHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Utility for test method.
 */
private DdPacket createDdPacket() throws OspfParseException {
    byte[] ddPacket = {2, 2, 0, 32, -64, -88, -86, 8, 0, 0, 0, 1, -96, 82,
            0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, -36, 2, 7, 65, 119, -87, 126};
    DdPacket ddPacket1 = new DdPacket();
    ChannelBuffer buf = ChannelBuffers.buffer(ddPacket.length);
    buf.writeBytes(ddPacket);
    ddPacket1.readFrom(buf);
    return ddPacket1;
}