List of usage examples for io.netty.buffer ByteBuf array
public abstract byte[] array();
From source file:cn.wantedonline.puppy.httpserver.component.HttpRequest.java
License:Apache License
public String getContentString() { ByteBuf content = content(); if (content.hasArray()) { return new String(content.array(), charset4ContentDecoder); }// w w w .j av a 2s . co m return ""; }
From source file:com.addthis.hydra.store.db.DBKey.java
License:Apache License
@Override public byte[] deltaEncode(@Nonnull IPageDB.Key baseKey) { long offset = id - baseKey.id(); ByteBuf buffer = Unpooled.buffer(); Varint.writeSignedVarLong(offset, buffer); if (key != null) { buffer.writeBytes(key.toBytes()); }//from w w w .ja v a2 s . c o m return Arrays.copyOf(buffer.array(), buffer.readableBytes()); }
From source file:com.athena.dolly.websocket.server.test.WebSocketServerHandler.java
License:Apache License
private void handleWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); try {/*from w w w . j a v a 2s. c o m*/ fos.flush(); fos.close(); fos = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return; } if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { // Send the uppercase string back. String fileName = ((TextWebSocketFrame) frame).text(); logger.debug(String.format("Received file name is [%s]", fileName)); destFile = new File(fileName + ".received"); try { fos = new FileOutputStream(destFile); } catch (FileNotFoundException e) { e.printStackTrace(); } ctx.channel().write(new TextWebSocketFrame(fileName.toUpperCase())); } if (frame instanceof BinaryWebSocketFrame) { byte[] buffer = null; ByteBuf rawMessage = ((BinaryWebSocketFrame) frame).content(); //logger.debug(">>>> BinaryWebSocketFrame Found, " + rawMessage); // check if this ByteBuf is DIRECT (no backing byte[]) if (rawMessage.hasArray() == false) { int size = rawMessage.readableBytes(); buffer = new byte[size]; rawMessage.readBytes(buffer); try { fos.write(buffer); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { buffer = rawMessage.array(); } logger.debug(">>>> Read Byte Array: " + buffer.length); return; } }
From source file:com.beeswax.hexbid.parser.BidProtobufParser.java
License:Apache License
/** * Parse serialized protocol buffer Bytebuf to protobuf object.</br> * Preferencing implementation of {@link ProtobufDecoder} * /*from w ww . ja va 2s. c o m*/ * @param bytebuf * @return protocol buffer message * @throws InvalidProtocolBufferException */ public static <T extends Message.Builder> Message parseProtoBytebuf(ByteBuf bytebuf, T messageBuilder) throws InvalidProtocolBufferException { final byte[] array; final int offset; final int length = bytebuf.readableBytes(); if (bytebuf.hasArray()) { array = bytebuf.array(); offset = bytebuf.arrayOffset() + bytebuf.readerIndex(); } else { array = new byte[length]; bytebuf.getBytes(bytebuf.readerIndex(), array, 0, length); offset = 0; } return messageBuilder.mergeFrom(array, offset, length).buildPartial(); }
From source file:com.chat.common.netty.handler.decode.ProtobufDecoder.java
License:Apache License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { final byte[] array; final int offset; final int length = msg.readableBytes(); if (msg.hasArray()) { array = msg.array(); offset = msg.arrayOffset() + msg.readerIndex(); } else {//w w w . j a va 2 s . c om array = new byte[length]; msg.getBytes(msg.readerIndex(), array, 0, length); offset = 0; } if (extensionRegistry == null) { if (HAS_PARSER) { out.add(prototype.getParserForType().parseFrom(array, offset, length)); } else { out.add(prototype.newBuilderForType().mergeFrom(array, offset, length).build()); } } else { if (HAS_PARSER) { out.add(prototype.getParserForType().parseFrom(array, offset, length, extensionRegistry)); } else { out.add(prototype.newBuilderForType().mergeFrom(array, offset, length, extensionRegistry).build()); } } }
From source file:com.codebullets.external.party.simulator.connections.websocket.inbound.NettyWebSocketServerHandler.java
License:Apache License
private void handleWebSocketFrame(final ChannelHandlerContext ctx, final WebSocketFrame frame) { // Check for closing frame if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); } else if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); } else if (frame instanceof TextWebSocketFrame) { String request = ((TextWebSocketFrame) frame).text(); LOG.debug("{} received {}", ctx.channel(), request); connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), request)); } else if (frame instanceof BinaryWebSocketFrame) { ByteBuf buffer = Unpooled.buffer(frame.content().capacity()); buffer.writeBytes(frame.content()); byte[] data = buffer.array(); LOG.debug("{} received {} bytes of data.", ctx.channel(), data.length); connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), data)); } else {/* www . j a v a 2 s . c o m*/ throw new UnsupportedOperationException( String.format("%s frame types not supported", frame.getClass().getName())); } }
From source file:com.codebullets.external.party.simulator.connections.websocket.outbound.NettyWebSocketClientHandler.java
License:Apache License
@Override public void messageReceived(final ChannelHandlerContext ctx, final Object msg) throws Exception { Channel ch = ctx.channel();// w ww . j a va 2s .c o m if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ch, (FullHttpResponse) msg); LOG.info("WebSocket client {} connected.", connectionName); connectionMonitor.connectionEstablished(getContext(ctx)); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new Exception("Unexpected FullHttpResponse (getStatus=" + response.getStatus() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } WebSocketFrame frame = (WebSocketFrame) msg; if (frame instanceof TextWebSocketFrame) { TextWebSocketFrame textFrame = (TextWebSocketFrame) frame; LOG.debug("WebSocket client {} received message: " + textFrame.text(), connectionName); connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), textFrame.text())); } else if (frame instanceof BinaryWebSocketFrame) { ByteBuf buffer = Unpooled.buffer(frame.content().capacity()); buffer.writeBytes(frame.content()); byte[] data = buffer.array(); LOG.debug("WebSocket client {} received buffer with length " + data.length, connectionName); connectionMonitor.messageReceived(MessageReceivedEvent.create(getContext(ctx), buffer)); } else if (frame instanceof PingWebSocketFrame) { LOG.trace("WebSocket client {} received ping.", connectionName); ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); } else if (frame instanceof CloseWebSocketFrame) { LOG.debug("WebSocket client {} received closing frame.", connectionName); ch.close(); } }
From source file:com.datastax.driver.core.CBUtil.java
License:Apache License
public static byte[] readRawBytes(ByteBuf cb) { if (cb.hasArray() && cb.readableBytes() == cb.array().length) { // Move the readerIndex just so we consistently consume the input cb.readerIndex(cb.writerIndex()); return cb.array(); }/*www . ja v a2 s . c om*/ // Otherwise, just read the bytes in a new array byte[] bytes = new byte[cb.readableBytes()]; cb.readBytes(bytes); return bytes; }
From source file:com.datastax.driver.core.LZ4Compressor.java
License:Apache License
private ByteBuf compressHeap(ByteBuf input) throws IOException { int maxCompressedLength = compressor.maxCompressedLength(input.readableBytes()); // Not a direct buffer so use byte arrays... int inOffset = input.arrayOffset() + input.readerIndex(); byte[] in = input.array(); int len = input.readableBytes(); // Increase reader index. input.readerIndex(input.writerIndex()); // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so // can eliminate the overhead of allocate a new byte[]. ByteBuf output = input.alloc().heapBuffer(INTEGER_BYTES + maxCompressedLength); try {/*from w ww . j a v a 2 s .c o m*/ output.writeInt(len); // calculate the correct offset. int offset = output.arrayOffset() + output.writerIndex(); byte[] out = output.array(); int written = compressor.compress(in, inOffset, len, out, offset); // Set the writer index so the amount of written bytes is reflected output.writerIndex(output.writerIndex() + written); } catch (Exception e) { // release output buffer so we not leak and rethrow exception. output.release(); throw new IOException(e); } return output; }
From source file:com.datastax.driver.core.LZ4Compressor.java
License:Apache License
private ByteBuf decompressHeap(ByteBuf input) throws IOException { // Not a direct buffer so use byte arrays... byte[] in = input.array(); int len = input.readableBytes(); int uncompressedLength = input.readInt(); int inOffset = input.arrayOffset() + input.readerIndex(); // Increase reader index. input.readerIndex(input.writerIndex()); // Allocate a heap buffer from the ByteBufAllocator as we may use a PooledByteBufAllocator and so // can eliminate the overhead of allocate a new byte[]. ByteBuf output = input.alloc().heapBuffer(uncompressedLength); try {//from w w w .ja va2s . co m int offset = output.arrayOffset() + output.writerIndex(); byte out[] = output.array(); int read = decompressor.decompress(in, inOffset, out, offset, uncompressedLength); if (read != len - INTEGER_BYTES) throw new IOException("Compressed lengths mismatch"); // Set the writer index so the amount of written bytes is reflected output.writerIndex(output.writerIndex() + uncompressedLength); } catch (Exception e) { // release output buffer so we not leak and rethrow exception. output.release(); throw new IOException(e); } return output; }