List of usage examples for io.netty.buffer ByteBuf writeBytes
public abstract ByteBuf writeBytes(ByteBuffer src);
From source file:com.github.subalakr.yasjl.Bench.java
License:Apache License
public void run() throws Exception { for (int i = 0; i < iterations; i++) { ByteBuf inBuf = Unpooled.buffer(); JsonPointer[] jsonPointers = { new JsonPointer("/metrics/resultCount", new JsonPointerCB1() { public void call(ByteBuf buf) { buf.release();/*from w w w .j a va 2 s. c o m*/ } }), new JsonPointer("/metrics/warningCount", new JsonPointerCB1() { public void call(ByteBuf buf) { buf.release(); } }), new JsonPointer("/metrics/errorCount", new JsonPointerCB1() { public void call(ByteBuf buf) { buf.release(); } }), new JsonPointer("/results/-", new JsonPointerCB1() { public void call(ByteBuf buf) { rowsEmitted.getAndIncrement(); buf.release(); } }), new JsonPointer("/errors/-", new JsonPointerCB1() { public void call(ByteBuf buf) { buf.release(); } }), new JsonPointer("/warnings/-", new JsonPointerCB1() { public void call(ByteBuf buf) { buf.release(); } }), }; parser.initialize(inBuf, jsonPointers); inBuf.writeBytes(inJson.getBytes()); long start = System.currentTimeMillis(); parser.parse(); long currentRun = System.currentTimeMillis() - start; totalDuration += currentRun; totalBytesRead += inJsonSz; inBuf.discardReadBytes(); inBuf.release(); } }
From source file:com.google.devtools.build.lib.remote.blobstore.http.HttpDownloadHandlerTest.java
License:Open Source License
private void downloadShouldWork(boolean casDownload, EmbeddedChannel ch) throws IOException { ByteArrayOutputStream out = Mockito.spy(new ByteArrayOutputStream()); DownloadCommand cmd = new DownloadCommand(CACHE_URI, casDownload, "abcdef", out); ChannelPromise writePromise = ch.newPromise(); ch.writeOneOutbound(cmd, writePromise); HttpRequest request = ch.readOutbound(); assertThat(request.method()).isEqualTo(HttpMethod.GET); assertThat(request.headers().get(HttpHeaderNames.HOST)) .isEqualTo(CACHE_URI.getHost() + ":" + CACHE_URI.getPort()); if (casDownload) { assertThat(request.uri()).isEqualTo("/cache-bucket/cas/abcdef"); } else {//from www .jav a 2 s . com assertThat(request.uri()).isEqualTo("/cache-bucket/ac/abcdef"); } assertThat(writePromise.isDone()).isFalse(); HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.headers().set(HttpHeaders.CONTENT_LENGTH, 5); response.headers().set(HttpHeaders.CONNECTION, HttpHeaderValues.KEEP_ALIVE); ch.writeInbound(response); ByteBuf content = Unpooled.buffer(); content.writeBytes(new byte[] { 1, 2, 3, 4, 5 }); ch.writeInbound(new DefaultLastHttpContent(content)); assertThat(writePromise.isDone()).isTrue(); assertThat(out.toByteArray()).isEqualTo(new byte[] { 1, 2, 3, 4, 5 }); verify(out, never()).close(); assertThat(ch.isActive()).isTrue(); }
From source file:com.guowl.websocket.stream.client.StreamClientRunner.java
License:Apache License
public void run() throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try {// ww w. j av a 2 s. c om // Connect with V13 (RFC 6455 aka HyBi-17). You can change it to V08 // or V00. // If you change it to V00, ping is not supported and remember to // change // HttpResponseDecoder to WebSocketHttpResponseDecoder in the // pipeline. final StreamClientHandler handler = new StreamClientHandler(WebSocketClientHandshakerFactory .newHandshaker(uri, WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); final String protocol = uri.getScheme(); int defaultPort; ChannelInitializer<SocketChannel> initializer; // Normal WebSocket if ("ws".equals(protocol)) { initializer = new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast("http-codec", new HttpClientCodec()) .addLast("aggregator", new HttpObjectAggregator(8192)) .addLast("ws-handler", handler); } }; defaultPort = 80; // Secure WebSocket } else { throw new IllegalArgumentException("Unsupported protocol: " + protocol); } Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(initializer); int port = uri.getPort(); // If no port was specified, we'll try the default port: if (uri.getPort() == -1) { port = defaultPort; } Channel ch = b.connect(uri.getHost(), port).sync().channel(); handler.handshakeFuture().sync(); ByteBuf dataBuf = ch.alloc().buffer(); dataBuf.writeBytes("start".getBytes()); ch.writeAndFlush(new BinaryWebSocketFrame(false, 0, dataBuf)); ch.writeAndFlush(new ContinuationWebSocketFrame(true, 0, "end")); Thread.sleep(1000 * 60 * 60); } finally { group.shutdownGracefully(); } }
From source file:com.hazelcast.simulator.protocol.core.SimulatorMessageCodec.java
License:Open Source License
public static void encodeByteBuf(SimulatorMessage msg, ByteBuf buffer) { byte[] data = msg.getOperationData().getBytes(UTF_8); buffer.writeInt(HEADER_SIZE + data.length); buffer.writeInt(MAGIC_BYTES);/* ww w .j av a2 s . c om*/ SimulatorAddressCodec.encodeByteBuf(msg.getDestination(), buffer); SimulatorAddressCodec.encodeByteBuf(msg.getSource(), buffer); buffer.writeLong(msg.getMessageId()); buffer.writeInt(msg.getOperationType().toInt()); buffer.writeBytes(data); }
From source file:com.heelenyc.im.coder.MessageEncoder.java
License:Apache License
@Override protected void encode(ChannelHandlerContext ctx, Message msg, ByteBuf sendBuf) throws Exception { if (msg == null || msg.getHeader() == null) throw new Exception("The encode message is null"); sendBuf.writeInt((msg.getHeader().getCrcCode())); sendBuf.writeInt((msg.getHeader().getLength())); // ? sendBuf.writeLong((msg.getHeader().getSessionID())); sendBuf.writeByte((msg.getHeader().getType())); sendBuf.writeByte((msg.getHeader().getPriority())); sendBuf.writeInt((msg.getHeader().getAttachment().size())); String key = null;//from w w w . j ava 2s. c o m byte[] keyArray = null; Object value = null; for (Map.Entry<String, Object> param : msg.getHeader().getAttachment().entrySet()) { // write key key = param.getKey(); keyArray = key.getBytes(Constans.ATTACHMENT_KEY_CHARACTSET); sendBuf.writeInt(keyArray.length); sendBuf.writeBytes(keyArray); // write value value = param.getValue(); encoder.encode(value, sendBuf); } key = null; keyArray = null; value = null; if (msg.getBody() != null) { encoder.encode(msg.getBody(), sendBuf); } else sendBuf.writeInt(0); int totalSize = sendBuf.readableBytes() - Constans.MESSAGE_LENGTH_FIELD_OFFSET - Constans.MESSAGE_LENGTH_FIELD_LENGTH; // fix head length field msg.getHeader().setLength(totalSize); // ? sendBuf.setInt(Constans.MESSAGE_LENGTH_FIELD_OFFSET, totalSize); logger.debug("encode :" + msg); }
From source file:com.heliosapm.ohcrs.impls.oracle.OracleDriverCodec.java
License:Apache License
/** * {@inheritDoc}/*w ww. j a v a 2 s. c o m*/ * @see com.heliosapm.ohcrs.core.DriverCodec#write(java.lang.Object, com.heliosapm.ohcrs.core.DBType, io.netty.buffer.ByteBuf) */ @Override public int write(final Datum t, final DBType d, final ByteBuf b) throws SQLException { if (prefix(t, d, b)) { final byte[] bytes = t.getBytes(); b.writeInt(bytes.length); if (t instanceof oracle.sql.CHAR) { b.writeInt(((oracle.sql.CHAR) t).oracleId()); } b.writeBytes(bytes); } return b.readerIndex(); }
From source file:com.heliosapm.streams.metrichub.HubManager.java
License:Apache License
protected ByteBuf updateJsonRequest(final List<TSMeta> tsMetas, final ByteBuf header) { try {/*from w w w .j a v a 2s . c o m*/ final ByteBuf request = BufferManager.getInstance().buffer(header.readableBytes() + 1024); request.writeBytes(header); header.resetReaderIndex(); request.writerIndex(request.writerIndex() - REQUEST_CLOSER.length()); for (TSMeta ts : tsMetas) { request.writeCharSequence(new StringBuilder("\"").append(ts.getTSUID()).append("\","), UTF8); } request.writerIndex(request.writerIndex() - 1); request.writeCharSequence(REQUEST_CLOSER, UTF8); return request; } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.heliosapm.streams.metrics.aggregation.StreamedMetricAggregation.java
License:Apache License
/** * Returns this aggregation as a byte array * @return a byte array/*from ww w. ja v a 2 s. c om*/ */ public byte[] toByteArray() { final ByteBuf b = BufferManager.getInstance().buffer(size == -1 ? 128 : size); try { b.writeByte(sticky ? 1 : 0); b.writeByte(doubleType ? 1 : 0); b.writeLong(createTime); b.writeLong(period); b.writeByte(periodUnit.ordinal()); values.position(0); b.writeBytes(values); b.writeByte(tags.size()); BufferManager.writeUTF(metricName, b); for (Map.Entry<String, String> entry : tags.entrySet()) { BufferManager.writeUTF(entry.getKey(), b); BufferManager.writeUTF(entry.getValue(), b); } return ByteBufUtil.getBytes(b); } finally { try { b.release(); } catch (Exception x) { /* No Op */} } }
From source file:com.heliosapm.streams.tracing.DefaultTracerImpl.java
License:Apache License
/** * {@inheritDoc}//from w w w. j a va2 s.c o m * @see com.heliosapm.streams.tracing.ITracer#flush() */ @Override public ITracer flush() { if (bufferedEvents > 0) { final ElapsedTime et = SystemClock.startClock(); outBuffer.setInt(COMPRESS_OFFSET, 0); outBuffer.setInt(COUNT_OFFSET, bufferedEvents); final ByteBuf bufferCopy = bufferFactory.buffer(outBuffer.readableBytes()); // bufferCopy.writeByte(0); // bufferCopy.writeInt(bufferedEvents); bufferCopy.writeBytes(outBuffer); outBuffer.resetReaderIndex(); outBuffer.writerIndex(START_DATA_OFFSET); final int finalCount = bufferedEvents; flushPool.execute(new Runnable() { @Override public void run() { writer.onMetrics(bufferCopy); flushOutEvents.add(finalCount); // log.info(et.printAvg("Metrics flushed", finalCount)); } }); bufferedEvents = 0; } return this; }
From source file:com.hop.hhxx.example.http2.helloworld.multiplex.server.HelloWorldHttp2Handler.java
License:Apache License
/** * If receive a frame with end-of-stream set, send a pre-canned response. *///from www . j av a2s . c o m public void onHeadersRead(ChannelHandlerContext ctx, Http2HeadersFrame headers) throws Exception { if (headers.isEndStream()) { ByteBuf content = ctx.alloc().buffer(); content.writeBytes(RESPONSE_BYTES); ByteBufUtil.writeAscii(content, " - via HTTP/2"); sendResponse(ctx, content); } }