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

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/impl/.

Source file: DefaultSmppSession.java

  23 
vote

/** 
 * Asynchronously sends a PDU and does not wait for a response PDU. This method will wait for the PDU to be written to the underlying channel.
 * @param pdu The PDU to send (can be either a response or request)
 * @throws RecoverablePduEncodingException
 * @throws UnrecoverablePduEncodingException
 * @throws SmppChannelException
 * @throws InterruptedException
 */
@Override public void sendResponsePdu(PduResponse pdu) throws RecoverablePduException, UnrecoverablePduException, SmppChannelException, InterruptedException {
  if (!pdu.hasSequenceNumberAssigned()) {
    pdu.setSequenceNumber(this.sequenceNumber.next());
  }
  ChannelBuffer buffer=transcoder.encode(pdu);
  if (configuration.getLoggingOptions().isLogPduEnabled()) {
    logger.info("send PDU: {}",pdu);
  }
  ChannelFuture channelFuture=this.channel.write(buffer).await();
  if (!channelFuture.isSuccess()) {
    throw new SmppChannelException(channelFuture.getCause().getMessage(),channelFuture.getCause());
  }
}
 

Example 2

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/http/.

Source file: SubmissionHandler.java

  22 
vote

private void writeResponse(HttpResponseStatus status,MessageEvent e,String namespace,String entity){
  HttpResponse response=new DefaultHttpResponse(HTTP_1_1,status);
  response.addHeader(CONTENT_TYPE,"plain/text");
  if (entity != null) {
    ChannelBuffer buf=ChannelBuffers.wrappedBuffer(entity.getBytes(CharsetUtil.UTF_8));
    response.setContent(buf);
    response.setHeader(CONTENT_LENGTH,response.getContent().readableBytes());
  }
  ChannelFuture future=e.getChannel().write(response);
  future.addListener(ChannelFutureListener.CLOSE);
  updateResponseMetrics(namespace,response.getStatus().getCode());
}
 

Example 3

From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/channel/.

Source file: SmppSessionLogger.java

  22 
vote

/** 
 * Logs the specified event to the  {@link InternalLogger} returned by{@link #getLogger()}. If hex dump has been enabled for this handler, the hex dump of the  {@link ChannelBuffer} in a {@link MessageEvent} willbe logged together.
 */
protected void log(Direction direction,ChannelEvent evt){
  if (evt instanceof MessageEvent) {
    MessageEvent me=(MessageEvent)evt;
    if ((me.getMessage() instanceof ChannelBuffer) && this.options.isLogBytesEnabled()) {
      ChannelBuffer buffer=(ChannelBuffer)me.getMessage();
      if (direction == Direction.UP) {
        logger.info("read bytes: [{}]",hexDump(buffer));
      }
 else       if (direction == Direction.DOWN) {
        logger.info("write bytes: [{}]",hexDump(buffer));
      }
    }
  }
}
 

Example 4

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: MessageCodec.java

  22 
vote

@Override protected Object encode(final ChannelHandlerContext ctx,final Channel channel,final Object msg) throws Exception {
  if (msg instanceof Message) {
    final Message m=(Message)msg;
    final ChannelBuffer rv=ChannelBuffers.dynamicBuffer(m.headerSize() + m.estimatedBodySize());
    m.marshall(rv);
    return ChannelBuffers.unmodifiableBuffer(rv);
  }
 else   return msg;
}
 

Example 5

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: SubscriptionMessage.java

  22 
vote

SubscriptionMessage(final ChannelBuffer body){
  super(Type.Subscription);
  this.body=ChannelBuffers.copiedBuffer(body);
  subscribe=this.body.readInt() > 0;
  topics=new String[this.body.readInt()];
  for (int pos=0; pos < topics.length; ++pos) {
    final ChannelBuffer topic=ChannelBuffers.buffer(this.body.readInt());
    this.body.readBytes(topic,topic.capacity());
    topics[pos]=topic.toString(Charsets.UTF_8);
  }
}
 

Example 6

From project Countandra, under directory /src/.

Source file: TestLoad.java

  22 
vote

public void initcassandradb(){
  ClientBootstrap client=new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  client.setPipelineFactory(new ClientPipelineFactory());
  Channel channel;
  HttpRequest request;
  ChannelBuffer buffer;
  channel=client.connect(new InetSocketAddress("127.0.0.1",8080)).awaitUninterruptibly().getChannel();
  request=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,"init");
  buffer=ChannelBuffers.copiedBuffer(" ",Charset.defaultCharset());
  request.addHeader(org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH,buffer.readableBytes());
  request.setContent(buffer);
  channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();
  client.releaseExternalResources();
}
 

Example 7

From project efflux, under directory /src/main/java/com/biasedbit/efflux/packet/.

Source file: ReceptionReport.java

  22 
vote

public static ChannelBuffer encode(ReceptionReport block){
  ChannelBuffer buffer=ChannelBuffers.buffer(24);
  buffer.writeInt((int)block.ssrc);
  buffer.writeByte(block.fractionLost);
  buffer.writeMedium(block.cumulativeNumberOfPacketsLost);
  buffer.writeInt((int)block.extendedHighestSequenceNumberReceived);
  buffer.writeInt((int)block.interArrivalJitter);
  buffer.writeInt((int)block.lastSenderReport);
  buffer.writeInt((int)block.delaySinceLastSenderReport);
  return buffer;
}
 

Example 8

From project efflux, under directory /src/test/java/com/biasedbit/efflux/packet/.

Source file: ByePacketTest.java

  22 
vote

@Test public void testDecode() throws Exception {
  byte[] packetBytes=ByteUtils.convertHexStringToByteArray("81cb0001e6aa996e");
  ChannelBuffer buffer=ChannelBuffers.wrappedBuffer(packetBytes);
  ControlPacket controlPacket=ControlPacket.decode(buffer);
  assertEquals(ControlPacket.Type.BYE,controlPacket.getType());
  ByePacket byePacket=(ByePacket)controlPacket;
  assertNotNull(byePacket.getSsrcList());
  assertEquals(1,byePacket.getSsrcList().size());
  assertEquals(new Long(0xe6aa996eL),byePacket.getSsrcList().get(0));
  assertEquals(null,byePacket.getReasonForLeaving());
  assertEquals(0,buffer.readableBytes());
}
 

Example 9

From project enterprise, under directory /com/src/main/java/org/neo4j/com/.

Source file: Server.java

  22 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent event) throws Exception {
  try {
    ChannelBuffer message=(ChannelBuffer)event.getMessage();
    handleRequest(message,event.getChannel());
  }
 catch (  Throwable e) {
    msgLog.logMessage("Error handling request",e);
    ctx.getChannel().close();
    tryToFinishOffChannel(ctx.getChannel());
    throw Exceptions.launderedException(e);
  }
}
 

Example 10

From project adbcj, under directory /mysql/netty/src/main/java/org/adbcj/mysql/netty/.

Source file: MysqlConnectionManager.java

  21 
vote

public void handleDownstream(ChannelHandlerContext context,ChannelEvent event) throws Exception {
  if (!(event instanceof MessageEvent)) {
    context.sendDownstream(event);
    return;
  }
  MessageEvent e=(MessageEvent)event;
  if (!(e.getMessage() instanceof ClientRequest)) {
    context.sendDownstream(event);
    return;
  }
  ChannelBuffer buffer=ChannelBuffers.buffer(1024);
  ChannelBufferOutputStream out=new ChannelBufferOutputStream(buffer);
  encoder.encode((ClientRequest)e.getMessage(),out);
  Channels.write(context,e.getFuture(),buffer);
}
 

Example 11

From project adbcj, under directory /postgresql/netty/src/main/java/org/adbcj/postgresql/netty/.

Source file: NettyConnectionManager.java

  21 
vote

public void handleDownstream(ChannelHandlerContext context,ChannelEvent event) throws Exception {
  if (!(event instanceof MessageEvent)) {
    context.sendDownstream(event);
    return;
  }
  MessageEvent e=(MessageEvent)event;
  Object message=e.getMessage();
  boolean singleMessage=message instanceof AbstractFrontendMessage;
  boolean multipleMessages=message instanceof AbstractFrontendMessage[];
  if (!singleMessage && !multipleMessages) {
    context.sendDownstream(event);
    return;
  }
  ChannelBuffer buffer=ChannelBuffers.buffer(1024);
  ChannelBufferOutputStream out=new ChannelBufferOutputStream(buffer);
  if (singleMessage) {
    encoder.encode(out,(AbstractFrontendMessage)e.getMessage());
  }
 else {
    encoder.encode(out,(AbstractFrontendMessage[])e.getMessage());
  }
  Channels.write(context,e.getFuture(),buffer);
}
 

Example 12

From project ardverk-dht, under directory /components/http/src/main/java/org/ardverk/dht/http/.

Source file: HttpTransport.java

  21 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,final MessageEvent e) throws IOException {
  HttpRequest httpRequest=(HttpRequest)e.getMessage();
  SocketAddress src=e.getRemoteAddress();
  ChannelBuffer content=httpRequest.getContent();
  ByteArrayInputStream bais=new ByteArrayInputStream(content.array());
  Decoder decoder=codec.createDecoder(src,bais);
  RequestMessage request=(RequestMessage)decoder.read();
  decoder.close();
  ResponseMessage response=HttpTransport.this.handleRequest(request);
  ByteArrayOutputStream baos=new ByteArrayOutputStream();
  Encoder encoder=codec.createEncoder(baos);
  encoder.write(response);
  encoder.close();
  byte[] encoded=baos.toByteArray();
  HttpResponse httpResponse=new DefaultHttpResponse(HttpVersion.HTTP_1_1,HttpResponseStatus.OK);
  httpResponse.setContent(ChannelBuffers.copiedBuffer(encoded));
  httpResponse.setHeader(HttpHeaders.Names.CONTENT_LENGTH,encoded.length);
  httpResponse.setHeader(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
  Channel channel=e.getChannel();
  ChannelFuture future=channel.write(httpResponse);
  future.addListener(ChannelFutureListener.CLOSE);
  future.addListener(new MessageListener(request,response));
}
 

Example 13

From project ardverk-dht, under directory /components/http/src/main/java/org/ardverk/dht/http/.

Source file: HttpTransport.java

  21 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws IOException {
  try {
    HttpResponse httpResponse=(HttpResponse)e.getMessage();
    SocketAddress src=e.getRemoteAddress();
    ChannelBuffer content=httpResponse.getContent();
    ByteArrayInputStream bais=new ByteArrayInputStream(content.array());
    Decoder decoder=codec.createDecoder(src,bais);
    ResponseMessage response=(ResponseMessage)decoder.read();
    decoder.close();
    HttpTransport.this.handleResponse(response);
  }
  finally {
    HttpUtils.close(e);
  }
}
 

Example 14

From project arquillian-extension-warp, under directory /impl/src/main/java/org/jboss/arquillian/warp/impl/client/execution/.

Source file: DefaultResponseDeenrichmentService.java

  21 
vote

@Override public void deenrichResponse(HttpResponse response){
  try {
    final ChannelBuffer content=response.getContent();
    long originalLength=HttpHeaders.getContentLength(response);
    int payloadLength=Integer.valueOf(getHeader(response));
    String responseEnrichment=content.toString(0,payloadLength,Charset.defaultCharset());
    content.readerIndex(payloadLength);
    content.discardReadBytes();
    ResponsePayload payload=SerializationUtils.deserializeFromBase64(responseEnrichment);
    HttpHeaders.setContentLength(response,originalLength - payloadLength);
    HttpResponseStatus status=HttpResponseStatus.valueOf(payload.getStatus());
    response.setStatus(status);
    AssertionHolder.addResponse(new ResponseEnrichment(payload));
  }
 catch (  Exception originalException) {
    ResponsePayload exceptionPayload=new ResponsePayload();
    ClientWarpExecutionException explainingException=new ClientWarpExecutionException("deenriching response failed: " + originalException.getMessage(),originalException);
    exceptionPayload.setTestResult(new TestResult(Status.FAILED,explainingException));
    AssertionHolder.addResponse(new ResponseEnrichment(exceptionPayload));
  }
}
 

Example 15

From project bagheera, under directory /src/main/java/com/mozilla/bagheera/http/json/.

Source file: JsonFilter.java

  21 
vote

@Override public void messageReceived(ChannelHandlerContext ctx,MessageEvent e) throws Exception {
  Object msg=e.getMessage();
  if (msg instanceof HttpRequest) {
    HttpRequest request=(HttpRequest)e.getMessage();
    ChannelBuffer content=request.getContent();
    if (content.readable()) {
      if (!validator.isValidJson(content.toString(CharsetUtil.UTF_8))) {
        throw new InvalidJsonException("Invalid JSON");
      }
    }
    Channels.fireMessageReceived(ctx,request,e.getRemoteAddress());
  }
 else {
    ctx.sendUpstream(e);
  }
}
 

Example 16

From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/websocket/.

Source file: WebSocket00FrameDecoder.java

  21 
vote

private WebSocketFrame decodeTextFrame(byte type,ChannelBuffer buffer) throws TooLongFrameException {
  int ridx=buffer.readerIndex();
  int rbytes=actualReadableBytes();
  int delimPos=buffer.indexOf(ridx,ridx + rbytes,(byte)0xFF);
  if (delimPos == -1) {
    if (rbytes > maxFrameSize) {
      throw new TooLongFrameException();
    }
 else {
      return null;
    }
  }
  int frameSize=delimPos - ridx;
  if (frameSize > maxFrameSize) {
    throw new TooLongFrameException();
  }
  ChannelBuffer binaryData=buffer.readBytes(frameSize);
  buffer.skipBytes(1);
  int ffDelimPos=binaryData.indexOf(binaryData.readerIndex(),binaryData.writerIndex(),(byte)0xFF);
  if (ffDelimPos >= 0) {
    throw new IllegalArgumentException("a text frame should not contain 0xFF.");
  }
  return new TextWebSocketFrame(binaryData);
}
 

Example 17

From project chililog-server, under directory /src/main/java/org/chililog/server/workbench/.

Source file: ApiRequestHandler.java

  21 
vote

/** 
 * Write response for when there is an exception
 * @param e Message event
 * @param ex Exception that was thrown
 */
private void writeResponse(ChannelHandlerContext ctx,MessageEvent e,Exception ex) throws Exception {
  boolean keepAlive=isKeepAlive(_request);
  HttpResponse response=new DefaultHttpResponse(HTTP_1_1,HttpResponseStatus.INTERNAL_SERVER_ERROR);
  setDateHeader(response);
  response.setHeader(CONTENT_TYPE,Worker.JSON_CONTENT_TYPE);
  ErrorAO errorAO=new ErrorAO(ex);
  ChannelBuffer buffer=ChannelBuffers.dynamicBuffer(4096);
  ChannelBufferOutputStream os=new ChannelBufferOutputStream(buffer);
  PrintStream ps=new PrintStream(os,true,Worker.JSON_CHARSET);
  JsonTranslator.getInstance().toJson(errorAO,ps);
  ps.close();
  os.close();
  response.setContent(buffer);
  if (_logger.isDebugEnabled()) {
    logHttpResponse(response,response.getContent().array());
  }
  if (keepAlive) {
    response.setHeader(CONTENT_LENGTH,response.getContent().readableBytes());
  }
  ChannelFuture future=e.getChannel().write(response);
  if (!keepAlive) {
    future.addListener(ChannelFutureListener.CLOSE);
  }
}
 

Example 18

From project Countandra, under directory /src/org/countandra/unittests/.

Source file: CountandraTestUtils.java

  21 
vote

public static void insertData(String content){
  Channel channel=null;
  HttpRequest request;
  ChannelBuffer buffer;
  try {
    channel=client.connect(new InetSocketAddress("localhost",httpPort)).awaitUninterruptibly().getChannel();
    request=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,"insert");
    buffer=ChannelBuffers.copiedBuffer(content,Charset.defaultCharset());
    request.addHeader(org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH,buffer.readableBytes());
    request.setContent(buffer);
    channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();
  }
 catch (  Exception e) {
    System.err.println("Error: " + e.getMessage());
  }
  channel.getCloseFuture().awaitUninterruptibly();
}
 

Example 19

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/shuffle/.

Source file: RequestEncoder.java

  21 
vote

@Override protected Object encode(ChannelHandlerContext ctx,Channel channel,Object msg) throws Exception {
  if (!(msg instanceof Event)) {
    return msg;
  }
  Event message=(Event)msg;
  ChannelBuffer buf=ChannelBuffers.dynamicBuffer();
  buf.writeByte(1);
  buf.writeByte(REQ);
  buf.writeByte(0);
  int crcIndex=buf.writerIndex();
  buf.writerIndex(buf.writerIndex() + 4 + 4);
  buf.writeLong(message.offset());
  ChannelBufferOutputStream cbos=new ChannelBufferOutputStream(buf);
  CheckedOutputStream eventChk=new CheckedOutputStream(cbos,new PureJavaCrc32());
  serializer.open(eventChk);
  serializer.serialize(message.key());
  serializer.serialize(message.value());
  serializer.close();
  int end=buf.writerIndex();
  int len=end - (crcIndex + 4 + 4);
  buf.writerIndex(crcIndex);
  buf.writeInt((int)eventChk.getChecksum().getValue());
  buf.writeInt(len);
  buf.writerIndex(end);
  return buf;
}
 

Example 20

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/shuffle/.

Source file: ResponseEncoder.java

  21 
vote

@Override protected Object encode(ChannelHandlerContext ctx,Channel channel,Object msg) throws Exception {
  if (!(msg instanceof Event)) {
    return msg;
  }
  Event message=(Event)msg;
  ChannelBuffer buf=ChannelBuffers.dynamicBuffer();
  buf.writeByte(1);
  buf.writeByte(RESP);
  buf.writeByte(0);
  int crcIndex=buf.writerIndex();
  buf.writerIndex(buf.writerIndex() + 4 + 4);
  buf.writeLong(message.offset());
  ChannelBufferOutputStream cbos=new ChannelBufferOutputStream(buf);
  CheckedOutputStream eventChk=new CheckedOutputStream(cbos,new PureJavaCrc32());
  serializer.open(eventChk);
  serializer.serialize(message.key());
  serializer.serialize(message.value());
  serializer.close();
  int end=buf.writerIndex();
  int len=end - (crcIndex + 4 + 4);
  buf.writerIndex(crcIndex);
  buf.writeInt((int)eventChk.getChecksum().getValue());
  buf.writeInt(len);
  buf.writerIndex(end);
  return buf;
}
 

Example 21

From project enterprise, under directory /com/src/main/java/org/neo4j/com/.

Source file: DechunkingChannelBuffer.java

  21 
vote

protected ChannelBuffer readNext(){
  try {
    ChannelBuffer result=reader.read(timeoutSeconds,TimeUnit.SECONDS);
    if (result == null) {
      throw new ComException("Channel has been closed");
    }
    return result;
  }
 catch (  IOException e) {
    throw new ComException(e);
  }
catch (  InterruptedException e) {
    throw new ComException(e);
  }
}
 

Example 22

From project AirReceiver, under directory /src/main/java/org/phlo/AirReceiver/.

Source file: RaopRtpPacket.java

  19 
vote

/** 
 * Creates an RTP packet from a  {@link ChannelBuffer}, using the sub-class of  {@link RaopRtpPacket} indicated by the packet's{@link #getPayloadType()}
 * @param buffer ChannelBuffer containing the packet
 * @return Instance of one of the sub-classes of {@link RaopRtpPacket}
 * @throws ProtocolException if the packet is invalid.
 */
public static RaopRtpPacket decode(final ChannelBuffer buffer) throws ProtocolException {
  final RtpPacket rtpPacket=new RtpPacket(buffer,Length);
switch (rtpPacket.getPayloadType()) {
case TimingRequest.PayloadType:
    return new TimingRequest(buffer);
case TimingResponse.PayloadType:
  return new TimingResponse(buffer);
case Sync.PayloadType:
return new Sync(buffer);
case RetransmitRequest.PayloadType:
return new RetransmitRequest(buffer);
case AudioRetransmit.PayloadType:
return new AudioRetransmit(buffer);
case AudioTransmit.PayloadType:
return new AudioTransmit(buffer);
default :
throw new ProtocolException("Invalid PayloadType " + rtpPacket.getPayloadType());
}
}
 

Example 23

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/.

Source file: NettyTransportCodec.java

  19 
vote

/** 
 * decode buffer to NettyDataPack
 */
@Override protected Object decode(ChannelHandlerContext ctx,Channel channel,ChannelBuffer buffer) throws Exception {
  if (!packHeaderRead) {
    if (decodePackHeader(ctx,channel,buffer)) {
      packHeaderRead=true;
    }
    return null;
  }
 else {
    if (decodePackBody(ctx,channel,buffer)) {
      packHeaderRead=false;
      return dataPack;
    }
 else {
      return null;
    }
  }
}
 

Example 24

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/.

Source file: NettyTransportCodec.java

  19 
vote

private boolean decodePackHeader(ChannelHandlerContext ctx,Channel channel,ChannelBuffer buffer) throws Exception {
  if (buffer.readableBytes() < 8) {
    return false;
  }
  int serial=buffer.readInt();
  int listSize=buffer.readInt();
  if (listSize * SIZEOF_REF > 0.1 * maxMem) {
    channel.close().await();
    throw new AvroRuntimeException("Excessively large list allocation " + "request detected: " + listSize + " items! Connection closed.");
  }
  this.listSize=listSize;
  dataPack=new NettyDataPack(serial,new ArrayList<ByteBuffer>(listSize));
  return true;
}