List of usage examples for io.netty.buffer ByteBuf getBytes
public abstract ByteBuf getBytes(int index, ByteBuffer dst);
From source file:com.yeetor.androidcontrol.WSSocketHandler.java
License:Open Source License
private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // ?//from ww w . ja va 2s. c om if (frame instanceof CloseWebSocketFrame) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); return; } // ?ping? if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { if (event != null) { event.onTextMessage(ctx, ((TextWebSocketFrame) frame).text()); } } else if (frame instanceof BinaryWebSocketFrame || frame instanceof ContinuationWebSocketFrame) { if (event != null) { ByteBuf byteBuf = frame.content(); byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); binaryCache = ArrayUtils.addAll(binaryCache, bytes); if (frame.isFinalFragment()) { byte[] b = binaryCache; binaryCache = new byte[0]; event.onBinaryMessage(ctx, b); } } } }
From source file:com.yeetor.server.handler.WSHandler.java
License:Open Source License
private void handlerWebSocketFrame(ChannelHandlerContext ctx, WebSocketFrame frame) { // ?//from w w w . j a va2 s . c om if (frame instanceof CloseWebSocketFrame && handshaker != null) { handshaker.close(ctx.channel(), (CloseWebSocketFrame) frame.retain()); if (eventListener != null) { eventListener.onDisconnect(ctx); } return; } // ?ping? if (frame instanceof PingWebSocketFrame) { ctx.channel().write(new PongWebSocketFrame(frame.content().retain())); return; } if (frame instanceof TextWebSocketFrame) { if (eventListener != null) { eventListener.onTextMessage(ctx, ((TextWebSocketFrame) frame).text()); } } else if (frame instanceof BinaryWebSocketFrame || frame instanceof ContinuationWebSocketFrame) { ByteBuf byteBuf = frame.content(); byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.getBytes(0, bytes); binaryCache = ArrayUtils.addAll(binaryCache, bytes); if (frame.isFinalFragment()) { byte[] b = binaryCache; binaryCache = new byte[0]; if (eventListener != null) { eventListener.onBinaryMessage(ctx, b); } } } }
From source file:dan200.qcraft.shared.QCraftPacket.java
License:Open Source License
@Override public void fromBytes(ByteBuf buffer) { packetType = buffer.readByte();/*from w ww .jav a 2 s. c o m*/ byte nString = buffer.readByte(); byte nInt = buffer.readByte(); int nByte = buffer.readInt(); if (nString == 0) { dataString = null; } else { dataString = new String[nString]; for (int k = 0; k < nString; k++) { if (buffer.readBoolean()) { int len = buffer.readInt(); byte[] b = new byte[len]; buffer.readBytes(b); try { dataString[k] = new String(b, "UTF-8"); } catch (UnsupportedEncodingException e) { dataString[k] = null; } } } } if (nInt == 0) { dataInt = null; } else { dataInt = new int[nInt]; for (int k = 0; k < nInt; k++) { dataInt[k] = buffer.readInt(); } } if (nByte == 0) { dataByte = null; } else { dataByte = new byte[nByte][]; for (int k = 0; k < nByte; k++) { int length = buffer.readInt(); if (length > 0) { dataByte[k] = new byte[length]; buffer.getBytes(buffer.readerIndex(), dataByte[k]); } } } }
From source file:de.dfki.kiara.http.HttpHandler.java
License:Open Source License
@Override protected void channelRead0(final ChannelHandlerContext ctx, Object msg) throws Exception { logger.debug("Handler: {} / Channel: {}", this, ctx.channel()); if (mode == Mode.SERVER) { if (msg instanceof FullHttpRequest) { final FullHttpRequest request = (FullHttpRequest) msg; HttpRequestMessage transportMessage = new HttpRequestMessage(this, request); transportMessage.setPayload(request.content().nioBuffer()); if (logger.isDebugEnabled()) { logger.debug("RECEIVED REQUEST WITH CONTENT {}", Util.bufferToString(transportMessage.getPayload())); }//from w w w .j av a 2 s . c om synchronized (listeners) { if (!listeners.isEmpty()) { for (TransportMessageListener listener : listeners) { listener.onMessage(transportMessage); } } } boolean keepAlive = HttpHeaders.isKeepAlive(request); } } else { // CLIENT if (msg instanceof HttpResponse) { HttpResponse response = (HttpResponse) msg; headers = response.headers(); //if (!response.headers().isEmpty()) { // contentType = response.headers().get("Content-Type"); //} } if (msg instanceof HttpContent) { HttpContent content = (HttpContent) msg; ByteBuf buf = content.content(); if (buf.isReadable()) { if (buf.hasArray()) { bout.write(buf.array(), buf.readerIndex(), buf.readableBytes()); } else { byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(buf.readerIndex(), bytes); bout.write(bytes); } } if (content instanceof LastHttpContent) { //ctx.close(); bout.flush(); HttpResponseMessage response = new HttpResponseMessage(this, headers); response.setPayload(ByteBuffer.wrap(bout.toByteArray(), 0, bout.size())); onResponse(response); bout.reset(); } } } }
From source file:discord4j.voice.PacketTransformer.java
License:Open Source License
@Nullable byte[] nextReceive(ByteBuf packet) { byte[] header = new byte[RTP_HEADER_LENGTH]; packet.getBytes(0, header); int audioOffset = RTP_HEADER_LENGTH + (4 * (byte) (header[0] & 0x0F)); byte[] encrypted = new byte[packet.readableBytes() - audioOffset]; packet.getBytes(audioOffset, encrypted); packet.release();// www . jav a2 s.c o m byte[] decrypted = boxer.open(encrypted, getNonce(header)); if (decrypted == null) { return null; } byte[] newPacket = new byte[RTP_HEADER_LENGTH + decrypted.length]; System.arraycopy(header, 0, newPacket, 0, RTP_HEADER_LENGTH); System.arraycopy(decrypted, 0, newPacket, audioOffset, decrypted.length); return newPacket; }
From source file:divconq.ctp.stream.UngzipStream.java
License:Open Source License
protected void inflate(ByteBuf in) { switch (this.gzipState) { case HEADER_START: if (in.readableBytes() < 10) return; // read magic numbers int magic0 = in.readByte(); int magic1 = in.readByte(); if (magic0 != 31) { OperationContext.get().getTaskRun().kill("Input is not in the GZIP format"); return; }//from w w w .ja va 2 s. c o m this.crc.update(magic0); this.crc.update(magic1); int method = in.readUnsignedByte(); if (method != Deflater.DEFLATED) { OperationContext.get().getTaskRun() .kill("Unsupported compression method " + method + " in the GZIP header"); return; } this.crc.update(method); this.flags = in.readUnsignedByte(); this.crc.update(this.flags); if ((this.flags & FRESERVED) != 0) { OperationContext.get().getTaskRun().kill("Reserved flags are set in the GZIP header"); return; } // mtime (int) this.crc.update(in.readByte()); this.crc.update(in.readByte()); this.crc.update(in.readByte()); this.crc.update(in.readByte()); this.crc.update(in.readUnsignedByte()); // extra flags this.crc.update(in.readUnsignedByte()); // operating system this.gzipState = GzipState.FLG_READ; case FLG_READ: if ((this.flags & FEXTRA) != 0) { if (in.readableBytes() < 2) return; int xlen1 = in.readUnsignedByte(); int xlen2 = in.readUnsignedByte(); this.crc.update(xlen1); this.crc.update(xlen2); this.xlen |= xlen1 << 8 | xlen2; } this.gzipState = GzipState.XLEN_READ; case XLEN_READ: if (this.xlen != -1) { if (in.readableBytes() < xlen) return; byte[] xtra = new byte[xlen]; in.readBytes(xtra); this.crc.update(xtra); } this.gzipState = GzipState.SKIP_FNAME; case SKIP_FNAME: if ((this.flags & FNAME) != 0) { boolean gotend = false; while (in.isReadable()) { int b = in.readUnsignedByte(); this.crc.update(b); if (b == 0x00) { gotend = true; break; } } if (!gotend) return; } this.gzipState = GzipState.SKIP_COMMENT; case SKIP_COMMENT: if ((this.flags & FCOMMENT) != 0) { boolean gotend = false; while (in.isReadable()) { int b = in.readUnsignedByte(); this.crc.update(b); if (b == 0x00) { gotend = true; break; } } if (!gotend) return; } this.gzipState = GzipState.PROCESS_FHCRC; case PROCESS_FHCRC: if ((this.flags & FHCRC) != 0) { if (in.readableBytes() < 4) return; long crcValue = 0; for (int i = 0; i < 4; ++i) crcValue |= (long) in.readUnsignedByte() << i * 8; long readCrc = crc.getValue(); if (crcValue != readCrc) { OperationContext.get().getTaskRun() .kill("CRC value missmatch. Expected: " + crcValue + ", Got: " + readCrc); return; } } this.crc.reset(); this.gzipState = GzipState.PRROCESS_CONTENT; case PRROCESS_CONTENT: int readableBytes = in.readableBytes(); if (readableBytes < 1) return; if (in.hasArray()) { this.inflater.setInput(in.array(), in.arrayOffset() + in.readerIndex(), readableBytes); } else { byte[] array = new byte[readableBytes]; in.getBytes(in.readerIndex(), array); this.inflater.setInput(array); } int maxOutputLength = this.inflater.getRemaining() << 1; ByteBuf decompressed = Hub.instance.getBufferAllocator().heapBuffer(maxOutputLength); boolean readFooter = false; byte[] outArray = decompressed.array(); try { while (!this.inflater.needsInput()) { int writerIndex = decompressed.writerIndex(); int outIndex = decompressed.arrayOffset() + writerIndex; int length = decompressed.writableBytes(); if (length == 0) { // completely filled the buffer allocate a new one and start to fill it this.outlist.add(decompressed); decompressed = Hub.instance.getBufferAllocator().heapBuffer(maxOutputLength); outArray = decompressed.array(); continue; } int outputLength = this.inflater.inflate(outArray, outIndex, length); if (outputLength > 0) { decompressed.writerIndex(writerIndex + outputLength); this.crc.update(outArray, outIndex, outputLength); } else { if (this.inflater.needsDictionary()) { if (this.dictionary == null) { OperationContext.get().getTaskRun().kill( "decompression failure, unable to set dictionary as non was specified"); return; } this.inflater.setDictionary(this.dictionary); } } if (this.inflater.finished()) { readFooter = true; break; } } in.skipBytes(readableBytes - this.inflater.getRemaining()); } catch (DataFormatException x) { OperationContext.get().getTaskRun().kill("decompression failure: " + x); return; } finally { if (decompressed.isReadable()) { this.outlist.add(decompressed); } else { decompressed.release(); } } if (!readFooter) break; this.gzipState = GzipState.PROCESS_FOOTER; case PROCESS_FOOTER: if (in.readableBytes() < 8) return; long crcValue = 0; for (int i = 0; i < 4; ++i) crcValue |= (long) in.readUnsignedByte() << i * 8; long readCrc = this.crc.getValue(); if (crcValue != readCrc) { OperationContext.get().getTaskRun() .kill("CRC value missmatch. Expected: " + crcValue + ", Got: " + readCrc); return; } // read ISIZE and verify int dataLength = 0; for (int i = 0; i < 4; ++i) dataLength |= in.readUnsignedByte() << i * 8; int readLength = this.inflater.getTotalOut(); if (dataLength != readLength) { OperationContext.get().getTaskRun() .kill("Number of bytes mismatch. Expected: " + dataLength + ", Got: " + readLength); return; } this.gzipState = GzipState.DONE; case DONE: break; } }
From source file:dorkbox.network.pipeline.ByteBufInput.java
License:Apache License
private String readAscii() { ByteBuf buffer = byteBuf; int start = buffer.readerIndex() - 1; int b;//from w w w.j ava 2 s . c o m do { b = buffer.readByte(); } while ((b & 0x80) == 0); int i = buffer.readerIndex() - 1; buffer.setByte(i, buffer.getByte(i) & 0x7F); // Mask end of ascii bit. int capp = buffer.readerIndex() - start; byte[] ba = new byte[capp]; buffer.getBytes(start, ba); @SuppressWarnings("deprecation") String value = new String(ba, 0, 0, capp); buffer.setByte(i, buffer.getByte(i) | 0x80); return value; }
From source file:io.advantageous.conekt.dns.impl.netty.decoder.AddressDecoder.java
License:Open Source License
/** * Returns an {@link java.net.InetAddress} containing a decoded address from either an A * or AAAA resource record./*from w ww . j a va 2 s . com*/ * * @param response the {@link DnsResponse} received that contained the resource * record being decoded * @param resource the {@link DnsResource} being decoded */ @Override public InetAddress decode(DnsResponse response, DnsResource resource) { ByteBuf data = resource.content().copy().readerIndex(response.originalIndex()); int size = data.writerIndex() - data.readerIndex(); if (data.readerIndex() != 0 || size != octets) { throw new DecoderException("Invalid content length, or reader index when decoding address [index: " + data.readerIndex() + ", expected length: " + octets + ", actual: " + size + "]."); } byte[] address = new byte[octets]; data.getBytes(data.readerIndex(), address); try { return InetAddress.getByAddress(address); } catch (UnknownHostException e) { throw new DecoderException("Could not convert address " + data.toString(data.readerIndex(), size, CharsetUtil.UTF_8) + " to InetAddress."); } }
From source file:io.airlift.drift.transport.netty.codec.TestThriftFramedDecoder.java
License:Apache License
private static void assertContentEquals(ByteBuf buffer, byte[] expectedContent) { assertEquals(buffer.readableBytes(), expectedContent.length); byte[] actual = new byte[buffer.readableBytes()]; buffer.getBytes(buffer.readerIndex(), actual); assertEquals(actual, expectedContent); }
From source file:io.crate.protocols.postgres.types.BasePGTypeTest.java
License:Apache License
void assertBytesWritten(Object value, byte[] expectedBytes, int expectedLength) { ByteBuf buffer = Unpooled.buffer(); try {/*from w ww.j a v a 2 s.c o m*/ int bytesWritten = pgType.writeAsBinary(buffer, value); assertThat(bytesWritten, is(expectedLength)); byte[] bytes = new byte[expectedLength]; buffer.getBytes(0, bytes); assertThat(bytes, is(expectedBytes)); } finally { buffer.release(); } }