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

The following are Jave code examples for showing how to use wrappedBuffer() 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: hadoop   File: TestFrameDecoder.java   Source Code and License Vote up 6 votes
@Override
protected void handleInternal(ChannelHandlerContext ctx, RpcInfo info) {
  // This is just like what's done in RpcProgramMountd#handleInternal and
  // RpcProgramNfs3#handleInternal.
  RpcCall rpcCall = (RpcCall) info.header();
  final int procedure = rpcCall.getProcedure();
  if (procedure != 0) {
    boolean portMonitorSuccess = doPortMonitoring(info.remoteAddress());
    if (!portMonitorSuccess) {
      sendRejectedReply(rpcCall, info.remoteAddress(), ctx);
      return;
    }
  }
  
  resultSize = info.data().readableBytes();
  RpcAcceptedReply reply = RpcAcceptedReply.getAcceptInstance(1234,
      new VerifierNone());
  XDR out = new XDR();
  reply.write(out);
  ChannelBuffer b = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap().buffer());
  RpcResponse rsp = new RpcResponse(b, info.remoteAddress());
  RpcUtil.sendRpcResponse(ctx, rsp);
}
 
Example 2
Project: iTAP-controller   File: ThriftFrameEncoder.java   Source Code and License Vote up 6 votes
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel,
                        Object message) throws Exception {
    if (message instanceof SyncMessage) {
        ChannelBuffer buf = new DynamicChannelBuffer(512);
        ChannelBufferOutputStream os = new ChannelBufferOutputStream(buf);
        TCompactProtocol thriftProtocol =
                new TCompactProtocol(new TIOStreamTransport(os));
        ((SyncMessage) message).write(thriftProtocol);

        ChannelBuffer len = ChannelBuffers.buffer(4);
        len.writeInt(buf.readableBytes());
        return ChannelBuffers.wrappedBuffer(len, buf);
    }
    return message;
}
 
Example 3
Project: hadoop   File: RpcUtil.java   Source Code and License Vote up 6 votes
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {
  ChannelBuffer buf = (ChannelBuffer) e.getMessage();
  ByteBuffer b = buf.toByteBuffer().asReadOnlyBuffer();
  XDR in = new XDR(b, XDR.State.READING);

  RpcInfo info = null;
  try {
    RpcCall callHeader = RpcCall.read(in);
    ChannelBuffer dataBuffer = ChannelBuffers.wrappedBuffer(in.buffer()
        .slice());
    info = new RpcInfo(callHeader, dataBuffer, ctx, e.getChannel(),
        e.getRemoteAddress());
  } catch (Exception exc) {
    LOG.info("Malformed RPC request from " + e.getRemoteAddress());
  }

  if (info != null) {
    Channels.fireMessageReceived(ctx, info);
  }
}
 
Example 4
Project: traccar-service   File: TramigoFrameDecoder.java   Source Code and License Vote up 6 votes
@Override
protected Object decode(
        ChannelHandlerContext ctx,
        Channel channel,
        ChannelBuffer buf) throws Exception {

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

    // Swap byte order for legacy protocol
    if (buf.getUnsignedByte(buf.readerIndex()) == 0x80) {
        int length = buf.readableBytes();
        byte[] bytes = new byte[length];
        buf.getBytes(buf.readerIndex(), bytes);

        ChannelBuffer result = (ChannelBuffer) super.decode(
                ctx, channel, ChannelBuffers.wrappedBuffer(ByteOrder.LITTLE_ENDIAN, bytes));
        if (result != null) {
            buf.skipBytes(result.readableBytes());
        }
        return result;
    }

    return super.decode(ctx, channel, buf);
}
 
Example 5
Project: hadoop   File: RpcProgram.java   Source Code and License Vote up 6 votes
private void sendAcceptedReply(RpcCall call, SocketAddress remoteAddress,
    AcceptState acceptState, ChannelHandlerContext ctx) {
  RpcAcceptedReply reply = RpcAcceptedReply.getInstance(call.getXid(),
      acceptState, Verifier.VERIFIER_NONE);

  XDR out = new XDR();
  reply.write(out);
  if (acceptState == AcceptState.PROG_MISMATCH) {
    out.writeInt(lowProgVersion);
    out.writeInt(highProgVersion);
  }
  ChannelBuffer b = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap()
      .buffer());
  RpcResponse rsp = new RpcResponse(b, remoteAddress);
  RpcUtil.sendRpcResponse(ctx, rsp);
}
 
Example 6
Project: voyage   File: RpcResponseEncode.java   Source Code and License Vote up 5 votes
@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 7
Project: EatDubbo   File: NettyCodecAdapter.java   Source Code and License Vote up 5 votes
@Override
protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception {
    com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer =
        com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024);
    NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
    try {
    	codec.encode(channel, buffer, msg);
    } finally {
        NettyChannel.removeChannelIfDisconnected(ch);
    }
    return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
}
 
Example 8
Project: hadoop   File: RpcProgramPortmap.java   Source Code and License Vote up 5 votes
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
    throws Exception {

  RpcInfo info = (RpcInfo) e.getMessage();
  RpcCall rpcCall = (RpcCall) info.header();
  final int portmapProc = rpcCall.getProcedure();
  int xid = rpcCall.getXid();
  XDR in = new XDR(info.data().toByteBuffer().asReadOnlyBuffer(),
      XDR.State.READING);
  XDR out = new XDR();

  if (portmapProc == PMAPPROC_NULL) {
    out = nullOp(xid, in, out);
  } else if (portmapProc == PMAPPROC_SET) {
    out = set(xid, in, out);
  } else if (portmapProc == PMAPPROC_UNSET) {
    out = unset(xid, in, out);
  } else if (portmapProc == PMAPPROC_DUMP) {
    out = dump(xid, in, out);
  } else if (portmapProc == PMAPPROC_GETPORT) {
    out = getport(xid, in, out);
  } else if (portmapProc == PMAPPROC_GETVERSADDR) {
    out = getport(xid, in, out);
  } else {
    LOG.info("PortmapHandler unknown rpc procedure=" + portmapProc);
    RpcAcceptedReply reply = RpcAcceptedReply.getInstance(xid,
        RpcAcceptedReply.AcceptState.PROC_UNAVAIL, new VerifierNone());
    reply.write(out);
  }

  ChannelBuffer buf = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap()
      .buffer());
  RpcResponse rsp = new RpcResponse(buf, info.remoteAddress());
  RpcUtil.sendRpcResponse(ctx, rsp);
}
 
Example 9
Project: traccar-service   File: CharacterDelimiterFrameDecoder.java   Source Code and License Vote up 5 votes
private static ChannelBuffer createDelimiter(String delimiter) {
    byte[] buf = new byte[delimiter.length()];
    for (int i = 0; i < delimiter.length(); i++) {
        buf[i] = (byte) delimiter.charAt(i);
    }
    return ChannelBuffers.wrappedBuffer(buf);
}
 
Example 10
Project: Elasticsearch   File: ESHttpResponseEncoder.java   Source Code and License Vote up 5 votes
@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 11
Project: Elasticsearch   File: NettyTransport.java   Source Code and License Vote up 5 votes
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 12
Project: astrobee_android   File: MainActivity.java   Source Code and License Vote up 5 votes
@SuppressWarnings("unused")
protected final void onNewData(final ByteBuffer data) {
    if (!mExposureSet) {
        mUiHandler.post(new Runnable() {
            @Override
            public void run() {
                if (mExposureSet)
                    return;
                setExposure();
                mExposureSet = true;
            }
        });
    }

    if (mPublisher == null)
        return;
    if (!mPublisher.hasSubscribers())
        return;

    data.order(ByteOrder.nativeOrder());
    data.rewind();

    if (mChannelBuffer == null) {
        mChannelBuffer = ChannelBuffers.wrappedBuffer(data);
    }

    mChannelBuffer.setIndex(0, mChannelBuffer.capacity());

    mCloud.getHeader().setStamp(mConnectedNode.getCurrentTime());
    mCloud.getHeader().setSeq(mSeqNum.incrementAndGet());
    mCloud.setData(mChannelBuffer);

    mPublisher.publish(mCloud);
}
 
Example 13
Project: dubbox-hystrix   File: NettyCodecAdapter.java   Source Code and License Vote up 5 votes
@Override
protected Object encode(ChannelHandlerContext ctx, Channel ch, Object msg) throws Exception {
    com.alibaba.dubbo.remoting.buffer.ChannelBuffer buffer =
        com.alibaba.dubbo.remoting.buffer.ChannelBuffers.dynamicBuffer(1024);
    NettyChannel channel = NettyChannel.getOrAddChannel(ch, url, handler);
    try {
    	codec.encode(channel, buffer, msg);
    } finally {
        NettyChannel.removeChannelIfDisconnected(ch);
    }
    return ChannelBuffers.wrappedBuffer(buffer.toByteBuffer());
}
 
Example 14
Project: hadoop   File: RpcProgram.java   Source Code and License Vote up 5 votes
protected static void sendRejectedReply(RpcCall call,
    SocketAddress remoteAddress, ChannelHandlerContext ctx) {
  XDR out = new XDR();
  RpcDeniedReply reply = new RpcDeniedReply(call.getXid(),
      RpcReply.ReplyState.MSG_DENIED,
      RpcDeniedReply.RejectState.AUTH_ERROR, new VerifierNone());
  reply.write(out);
  ChannelBuffer buf = ChannelBuffers.wrappedBuffer(out.asReadOnlyWrap()
      .buffer());
  RpcResponse rsp = new RpcResponse(buf, remoteAddress);
  RpcUtil.sendRpcResponse(ctx, rsp);
}
 
Example 15
Project: EatDubbo   File: NettyBackedChannelBufferFactory.java   Source Code and License Vote up 4 votes
public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
    return new NettyBackedChannelBuffer(ChannelBuffers.wrappedBuffer(nioBuffer));
}
 
Example 16
Project: dubbo2   File: NettyBackedChannelBufferFactory.java   Source Code and License Vote up 4 votes
@Override
public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
    return new NettyBackedChannelBuffer(ChannelBuffers.wrappedBuffer(nioBuffer));
}
 
Example 17
Project: traccar-service   File: CharacterDelimiterFrameDecoder.java   Source Code and License Vote up 4 votes
private static ChannelBuffer createDelimiter(char delimiter) {
    byte[] buf = {(byte) delimiter};
    return ChannelBuffers.wrappedBuffer(buf);
}
 
Example 18
Project: traccar-service   File: ProtocolTest.java   Source Code and License Vote up 4 votes
protected ChannelBuffer binary(ByteOrder endianness, String... data) {
    return ChannelBuffers.wrappedBuffer(
            endianness, DatatypeConverter.parseHexBinary(concatenateStrings(data)));
}
 
Example 19
Project: dubbocloud   File: NettyBackedChannelBufferFactory.java   Source Code and License Vote up 4 votes
@Override
public ChannelBuffer getBuffer(ByteBuffer nioBuffer) {
    return new NettyBackedChannelBuffer(ChannelBuffers.wrappedBuffer(nioBuffer));
}
 
Example 20
Project: Elasticsearch   File: PagedBytesReference.java   Source Code and License Vote up 4 votes
@Override
public ChannelBuffer toChannelBuffer() {
    // nothing to do
    if (length == 0) {
        return ChannelBuffers.EMPTY_BUFFER;
    }

    ChannelBuffer[] buffers;
    ChannelBuffer currentBuffer = null;
    BytesRef ref = new BytesRef();
    int pos = 0;

    // are we a slice?
    if (offset != 0) {
        // remaining size of page fragment at offset
        int fragmentSize = Math.min(length, PAGE_SIZE - (offset % PAGE_SIZE));
        bytearray.get(offset, fragmentSize, ref);
        currentBuffer = ChannelBuffers.wrappedBuffer(ref.bytes, ref.offset, fragmentSize);
        pos += fragmentSize;
    }

    // no need to create a composite buffer for a single page
    if (pos == length && currentBuffer != null) {
        return currentBuffer;
    }

    // a slice > pagesize will likely require extra buffers for initial/trailing fragments
    int numBuffers = countRequiredBuffers((currentBuffer != null ? 1 : 0), length - pos);

    buffers = new ChannelBuffer[numBuffers];
    int bufferSlot = 0;

    if (currentBuffer != null) {
        buffers[bufferSlot] = currentBuffer;
        bufferSlot++;
    }

    // handle remainder of pages + trailing fragment
    while (pos < length) {
        int remaining = length - pos;
        int bulkSize = (remaining > PAGE_SIZE) ? PAGE_SIZE : remaining;
        bytearray.get(offset + pos, bulkSize, ref);
        currentBuffer = ChannelBuffers.wrappedBuffer(ref.bytes, ref.offset, bulkSize);
        buffers[bufferSlot] = currentBuffer;
        bufferSlot++;
        pos += bulkSize;
    }

    // this would indicate that our numBuffer calculation is off by one.
    assert (numBuffers == bufferSlot);

    return ChannelBuffers.wrappedBuffer(NettyUtils.DEFAULT_GATHERING, buffers);
}