List of usage examples for io.netty.buffer ByteBuf retain
@Override public abstract ByteBuf retain();
From source file:com.yahoo.pulsar.common.compression.CommandsTest.java
License:Apache License
@Test public void testChecksumSendCommand() throws Exception { // test checksum in send command String producerName = "prod-name"; int sequenceId = 0; ByteBuf data = Unpooled.buffer(1024); MessageMetadata messageMetadata = MessageMetadata.newBuilder().setPublishTime(System.currentTimeMillis()) .setProducerName(producerName).setSequenceId(sequenceId).build(); int expectedChecksum = computeChecksum(messageMetadata, data); ByteBuf clientCommand = Commands.newSend(1, 0, 1, ChecksumType.Crc32c, messageMetadata, data); clientCommand.retain(); ByteBuffer inputBytes = clientCommand.nioBuffer(); ByteBuf receivedBuf = Unpooled.wrappedBuffer(inputBytes); receivedBuf.skipBytes(4); //skip [total-size] int cmdSize = (int) receivedBuf.readUnsignedInt(); receivedBuf.readerIndex(8 + cmdSize); int startMessagePos = receivedBuf.readerIndex(); /*** 1. verify checksum and metadataParsing ***/ boolean hasChecksum = Commands.hasChecksum(receivedBuf); int checksum = Commands.readChecksum(receivedBuf).intValue(); // verify checksum is present assertTrue(hasChecksum);/*from w w w.j a va 2 s. c om*/ // verify checksum value assertEquals(expectedChecksum, checksum); MessageMetadata metadata = Commands.parseMessageMetadata(receivedBuf); // verify metadata parsing assertEquals(metadata.getProducerName(), producerName); /** 2. parseMessageMetadata should skip checksum if present **/ receivedBuf.readerIndex(startMessagePos); metadata = Commands.parseMessageMetadata(receivedBuf); // verify metadata parsing assertEquals(metadata.getProducerName(), producerName); }
From source file:com.yahoo.pulsar.common.compression.CompressionCodecNone.java
License:Apache License
@Override public ByteBuf encode(ByteBuf raw) { // Provides an encoder that simply returns the same uncompressed buffer return raw.retain(); }
From source file:com.yahoo.pulsar.common.compression.CompressionCodecNone.java
License:Apache License
@Override public ByteBuf decode(ByteBuf encoded, int uncompressedSize) throws IOException { // No decompression is required for this codec return encoded.retain(); }
From source file:de.jackwhite20.comix.handler.DownstreamHandler.java
License:Open Source License
@Override protected void messageReceived(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception { upstreamChannel.writeAndFlush(byteBuf.retain()).addListener((future) -> { if (future.isSuccess()) { ctx.channel().read();//from ww w . j a v a 2 s . com } else { ctx.channel().close(); } }); upstreamBytesOut += byteBuf.readableBytes(); downstreamBytesIn += byteBuf.readableBytes(); }
From source file:de.jackwhite20.comix.handler.HandshakeHandler.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception { ByteBuf copy = byteBuf.copy(); Protocol.readVarInt(byteBuf);// w ww. j a va 2 s . co m int packetId = Protocol.readVarInt(byteBuf); if (packetId == 0) { if (protocolMode == ProtocolState.HANDSHAKE) { Protocol.readVarInt(byteBuf); Protocol.readString(byteBuf); byteBuf.readUnsignedShort(); protocolMode = ProtocolState.valueOf((byte) Protocol.readVarInt(byteBuf)); } if (protocolMode == ProtocolState.STATUS) { ByteBuf responseBuffer = Unpooled.buffer(); String response = Comix.getInstance().getStatusResponseString(); response = response.replace("%online%", "" + Comix.getInstance().getClientsOnline()); // Replace online count Protocol.writeVarInt(3 + response.length(), responseBuffer); // Size Protocol.writeVarInt(0, responseBuffer); // Packet id Protocol.writeString(response, responseBuffer); // Data as json string channelHandlerContext.writeAndFlush(responseBuffer); // Sending Pong instant because otherwise the pong will not receive properly! ByteBuf pongBuffer = Unpooled.buffer(); Protocol.writeVarInt(9, pongBuffer); Protocol.writeVarInt(1, pongBuffer); pongBuffer.writeLong(0); channelHandlerContext.writeAndFlush(pongBuffer); channelHandlerContext.close(); } if (protocolMode == ProtocolState.LOGIN) { if (byteBuf.readableBytes() == 0) { upstreamHandler.connectDownstream(copy); downstreamInitialized = true; out.add(copy.retain()); return; } String name = Protocol.readString(byteBuf); //TODO: Improve if (Comix.getInstance().getComixConfig().isMaintenance()) { if (Comix.getInstance().isWhitelistEnabled()) { if (!Comix.getInstance().isWhitelisted(name)) { kick(channelHandlerContext, Comix.getInstance().getWhitelistKickMessage()); } } else { kick(channelHandlerContext, Comix.getInstance().getComixConfig().getMaintenanceKickMessage()); } channelHandlerContext.close(); return; } else if (Comix.getInstance().isWhitelistEnabled() && !Comix.getInstance().isWhitelisted(name)) { kick(channelHandlerContext, Comix.getInstance().getWhitelistKickMessage()); channelHandlerContext.close(); return; } if (!downstreamInitialized) upstreamHandler.connectDownstream(copy); else upstreamHandler.addInitialPacket(copy); ComixClient comixClient = new ComixClient(name, upstreamHandler.getDownstreamHandler(), upstreamHandler); Comix.getInstance().addClient(comixClient); upstreamHandler.setClient(comixClient); channelHandlerContext.channel().pipeline().remove(this); Comix.getLogger().log(Level.INFO, "Handshake", "Player logged in: " + name); out.add(copy.retain()); } } }
From source file:de.jackwhite20.comix.handler.UpstreamHandler.java
License:Open Source License
@Override protected void messageReceived(ChannelHandlerContext ctx, ByteBuf byteBuf) throws Exception { if (downstreamConnected) { downstreamChannel.writeAndFlush(byteBuf.retain()).addListener((future) -> { if (future.isSuccess()) { ctx.channel().read();/* w ww .j av a2 s . c o m*/ } else { ctx.channel().close(); } }); } else { ctx.channel().read(); } upstreamBytesIn += byteBuf.readableBytes(); downstreamBytesOut += byteBuf.readableBytes(); }
From source file:de.saxsys.synchronizefx.netty.base.CommandToBinaryByteBuf.java
License:Open Source License
@Override protected void encode(final ChannelHandlerContext ctx, final List<Command> msg, final List<Object> out) throws Exception { final ByteBuf buffer = Unpooled.wrappedBuffer(serializer.serialize(msg)); buffer.retain(); out.add(buffer);// ww w . j a va2 s . c o m }
From source file:de.saxsys.synchronizefx.netty.websockets.ByteBufToWebSocketFrameCodec.java
License:Open Source License
@Override protected void decode(final ChannelHandlerContext ctx, final WebSocketFrame msg, final List<Object> out) throws Exception { if (msg instanceof BinaryWebSocketFrame) { ByteBuf content = msg.content(); // the content is passed to other handlers so they need to be retained. content.retain(); fragments.add(content);/*from w ww. j a v a 2s. c o m*/ if (msg.isFinalFragment()) { if (fragments.size() == 1) { out.add(fragments.get(0)); } else { ByteBuf[] array = fragments.toArray(BYTE_BUF_TYPE); out.add(Unpooled.wrappedBuffer(array)); } fragments.clear(); } } else if (msg instanceof TextWebSocketFrame) { LOG.warn("Recieved a Websocket text frame. This was not expected. Ignoring it."); } }
From source file:de.unipassau.isl.evs.ssh.core.network.handler.SignatureChecker.java
License:Open Source License
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { try {/* w ww. j ava 2 s .c om*/ if (msg instanceof ByteBuf) { final ByteBuf in = (ByteBuf) msg; final int dataLength = in.readInt(); final ByteBuf data = in.readSlice(dataLength); final int signatureLength = in.readInt(); final byte[] signature = new byte[signatureLength]; in.readBytes(signature); verifySignature.update(data.nioBuffer()); final boolean valid = verifySignature.verify(signature); //Log.v(TAG, "Read " + dataLength + "b of data with " + signatureLength + "b " + // (valid ? "valid" : "invalid") + " signature" + // (Log.isLoggable(TAG, Log.VERBOSE) ? ": " + Arrays.toString(signature) : "")); if (valid) { data.retain(); ctx.fireChannelRead(data); } else { throw new SignatureException("Message has a broken signature, closing connection"); } } else { throw new SignatureException("Can't check signature of message of type " + (msg != null ? msg.getClass() : "null") + ", closing connection"); } } catch (SignatureException | RuntimeException e) { ctx.close(); throw e; } }
From source file:divconq.api.internal.UploadPutHandler.java
License:Open Source License
public void start(final HyperSession parent, ScatteringByteChannel src, String chanid, Map<String, Cookie> cookies, long size, long offset, final OperationCallback callback) { this.src = src; this.cookies = cookies; this.callback = callback; this.dest = this.allocateChannel(parent, callback); if (this.callback.hasErrors()) { callback.complete();// ww w . j a v a 2 s . com return; } // send a request to get things going HttpRequest req = new DefaultHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.PUT, "/upload/" + chanid + "/Final"); req.headers().set(Names.HOST, parent.getInfo().getHost()); req.headers().set(Names.USER_AGENT, "DivConq HyperAPI Client 1.0"); req.headers().set(Names.CONNECTION, HttpHeaders.Values.CLOSE); req.headers().set(Names.COOKIE, ClientCookieEncoder.encode(this.cookies.values())); req.headers().set(HttpHeaders.Names.CONTENT_LENGTH, size - offset); // send request headers - must flush here in case CL = 0 this.dest.writeAndFlush(req); // now start sending the file long sent = offset; callback.getContext().setAmountCompleted((int) (sent * 100 / size)); ByteBuf bb = null; try { bb = Hub.instance.getBufferAllocator().directBuffer(64 * 1024); // TODO review if direct is best here long toskip = offset; if (src instanceof SeekableByteChannel) { ((SeekableByteChannel) src).position(toskip); } else { while (toskip > 0) { int skip = (int) Math.min(bb.capacity(), toskip); toskip -= bb.writeBytes(src, skip); bb.clear(); } } // now start writing the upload int amt = bb.writeBytes(src, bb.capacity()); while (amt != -1) { bb.retain(); // this ups ref cnt to 2 - we plan to reuse the buffer this.dest.writeAndFlush(bb).sync(); sent += amt; if (size > 0) callback.getContext().setAmountCompleted((int) (sent * 100 / size)); // by the time we get here, that buffer has been used up and we can use it for the next buffer if (bb.refCnt() != 1) throw new IOException("Buffer reference count is not correct"); // stop writing if canceled if (!this.dest.isOpen()) { this.finish(); // might already be finished but to be sure (this is helpful when api.abortStream is called) break; } bb.clear(); amt = bb.writeBytes(src, bb.capacity()); } // we are now done with it bb.release(); } catch (Exception x) { try { if (bb != null) bb.release(); } catch (Exception x2) { } callback.error(1, "Local read error: " + x); this.finish(); } }