Java Code Examples for io.netty.util.ReferenceCountUtil

The following are top voted examples for showing how to use io.netty.util.ReferenceCountUtil. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: proxyee   File: HttpProxyClientHandle.java   View source code 7 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
  //客户端channel已关闭则不转发了
  if (!clientChannel.isOpen()) {
    ReferenceCountUtil.release(msg);
    return;
  }
  HttpProxyInterceptPipeline interceptPipeline = ((HttpProxyServerHandle) clientChannel.pipeline()
      .get("serverHandle")).getInterceptPipeline();
  if (msg instanceof HttpResponse) {
    interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpResponse) msg);
  } else if (msg instanceof HttpContent) {
    interceptPipeline.afterResponse(clientChannel, ctx.channel(), (HttpContent) msg);
  } else {
    clientChannel.writeAndFlush(msg);
  }
}
 
Example 2
Project: AgentX   File: XRelayHandler.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                } else {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                    }
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 3
Project: AgentX   File: XRelayHandler.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
    if (dstChannel.isActive()) {
        ByteBuf byteBuf = (ByteBuf) msg;
        try {
            if (!byteBuf.hasArray()) {
                byte[] bytes = new byte[byteBuf.readableBytes()];
                byteBuf.getBytes(0, bytes);
                if (uplink) {
                    bytes = wrapper.unwrap(bytes);
                    if (bytes != null) {
                        dstChannel.writeAndFlush(Unpooled.wrappedBuffer(bytes));
                        log.info("\tClient ==========> Target \tSend [{} bytes]", bytes.length);
                    }
                } else {
                    dstChannel.writeAndFlush(Unpooled.wrappedBuffer(wrapper.wrap(bytes)));
                    log.info("\tClient <========== Target \tGet [{} bytes]", bytes.length);
                }
            }
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 4
Project: nitmproxy   File: Http1FrontendHandler.java   View source code 6 votes vote down vote up
@Override
protected void channelRead0(ChannelHandlerContext ctx,
                            FullHttpRequest request) throws Exception {
    if (master.config().getProxyMode() == ProxyMode.HTTP && !tunneled) {
        if (request.method() == HttpMethod.CONNECT) {
            handleTunnelProxyConnection(ctx, request);
        } else {
            handleHttpProxyConnection(ctx, request);
        }
    } else {
        checkState(outboundChannel != null);
        LOGGER.info("[Client ({})] => [Server ({})] : {}",
                    connectionInfo.getClientAddr(), connectionInfo.getServerAddr(),
                    request);
        outboundChannel.writeAndFlush(ReferenceCountUtil.retain(request));
    }
}
 
Example 5
Project: neoscada   File: MessageChannel.java   View source code 6 votes vote down vote up
private ByteBuf encode ( final ChannelHandlerContext ctx, final Object msg )
{
    ByteBuf buf = ctx.alloc ().buffer ( 255 );
    try
    {
        this.manager.encodeMessage ( msg, buf );
        if ( buf.isReadable () )
        {
            // copy away the reference so it does not get released
            final ByteBuf buf2 = buf;
            buf = null;
            return buf2;
        }
    }
    finally
    {
        ReferenceCountUtil.release ( buf );
    }
    return null;
}
 
Example 6
Project: neoscada   File: APDUEncoder.java   View source code 6 votes vote down vote up
private void handleIFormat ( final InformationTransfer msg, ByteBuf out )
{
    final ByteBuf data = msg.getData ();
    try
    {
        out = out.order ( ByteOrder.LITTLE_ENDIAN );

        final int len = data.readableBytes ();

        if ( len > Constants.APCI_MAX_DATA_LENGTH )
        {
            throw new EncoderException ( String.format ( "Packet too big - %s bytes", len ) );
        }

        out.ensureWritable ( 6 + len );
        out.writeByte ( Constants.START_BYTE );
        out.writeByte ( 4 + len );
        out.writeShort ( msg.getSendSequenceNumber () << 1 );
        out.writeShort ( msg.getReceiveSequenceNumber () << 1 );
        out.writeBytes ( data );
    }
    finally
    {
        ReferenceCountUtil.release ( msg.getData () );
    }
}
 
Example 7
Project: NSS   File: OutRelayHandler.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
	try {
		if (relayChannel.isActive()) {
			ByteBuf bytebuff = (ByteBuf) msg;
			if (!bytebuff.hasArray()) {
				int len = bytebuff.readableBytes();
				byte[] arr = new byte[len];
				bytebuff.getBytes(0, arr);
				connectHandler.sendRemote(arr, arr.length, relayChannel);
			}
		}
	} catch (Exception e) {
		logger.error("send data to remoteServer error",e);
	} finally {
		ReferenceCountUtil.release(msg);
	}
}
 
Example 8
Project: NSS   File: InRelayHandler.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
	try {
		if (relayChannel.isActive()) {
			logger.debug("get remote message" + relayChannel);
			ByteBuf bytebuff = (ByteBuf) msg;
			if (!bytebuff.hasArray()) {
				int len = bytebuff.readableBytes();
				byte[] arr = new byte[len];
				bytebuff.getBytes(0, arr);
				connectHandler.sendLocal(arr, arr.length, relayChannel);
			}
		}
	} catch (Exception e) {
		logger.error("receive remoteServer data error", e);
	} finally {
		ReferenceCountUtil.release(msg);
	}
}
 
Example 9
Project: NioSmtpClient   File: DotStuffingChunkedStreamTest.java   View source code 6 votes vote down vote up
private String dotStuff(String testString, int chunkSize) throws Exception {
  ByteArrayInputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));
  DotStuffingChunkedStream chunkedStream = new DotStuffingChunkedStream(stream, chunkSize);

  CompositeByteBuf destBuffer = ALLOCATOR.compositeBuffer();

  while (!chunkedStream.isEndOfInput()) {
    destBuffer.addComponent(true, chunkedStream.readChunk(ALLOCATOR));
  }

  byte[] bytes = new byte[destBuffer.readableBytes()];
  destBuffer.getBytes(0, bytes);

  ReferenceCountUtil.release(destBuffer);
  return new String(bytes, CharsetUtil.UTF_8);
}
 
Example 10
Project: waterrower-core   File: RxtxSerialHandler.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {

        if (!(msg instanceof AbstractMessage)) {
            Log.warn(SERIAL, "Invalid message received! Message skipped.");
            return;
        }

        Log.debug(SERIAL, "Message received: " + msg);

        // Notify that a message was received.
        onMessageReceived((AbstractMessage) msg);

    } finally {
        ReferenceCountUtil.release(msg);
    }
}
 
Example 11
Project: proxyee-down   File: HttpDownSniffIntercept.java   View source code 6 votes vote down vote up
@Override
public void beforeRequest(Channel clientChannel, HttpContent httpContent,
    HttpProxyInterceptPipeline pipeline) throws Exception {
  if (content != null) {
    ByteBuf temp = httpContent.content().slice();
    content.writeBytes(temp);
    if (httpContent instanceof LastHttpContent) {
      try {
        byte[] contentBts = new byte[content.readableBytes()];
        content.readBytes(contentBts);
        ((HttpRequestInfo) pipeline.getHttpRequest()).setContent(contentBts);
      } finally {
        ReferenceCountUtil.release(content);
        content = null; //状态回归
      }
    }
  }
  pipeline.beforeRequest(clientChannel, httpContent);
}
 
Example 12
Project: QuantBridge   File: MessageServerHandler.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    Message message = (Message) msg;
    try {
        if (Constants.COMMAND_REGISTER.equals(message.getCommand())) {
            Application.Connections.put(message.getContent(), ctx.channel());
            logger.debug("token " + message.getContent() + " ==> remote address " + ctx.channel().remoteAddress());
        } else if (!Application.clientIsOnline(ctx.channel())) {
            ctx.writeAndFlush(Constants.CONTENT_BYE);
            ctx.close();
        } else {
            if (Constants.COMMAND_PULSE.equals(message.getCommand())) {
            } else {
                ctx.writeAndFlush(Constants.CONTENT_BYE);
                ctx.close();
            }
        }
    } finally {
        ReferenceCountUtil.release(msg);
    }
}
 
Example 13
Project: incubator-pulsar   File: ProducerImpl.java   View source code 6 votes vote down vote up
/**
 * fail any pending batch messages that were enqueued, however batch was not closed out
 *
 */
private void failPendingBatchMessages(PulsarClientException ex) {
    if (batchMessageContainer.isEmpty()) {
        return;
    }
    int numMessagesInBatch = batchMessageContainer.numMessagesInBatch;
    semaphore.release(numMessagesInBatch);
    try {
        // Need to protect ourselves from any exception being thrown in the future handler from the application
        batchMessageContainer.firstCallback.sendComplete(ex);
    } catch (Throwable t) {
        log.warn("[{}] [{}] Got exception while completing the callback for msg {}:", topic, producerName,
                batchMessageContainer.sequenceId, t);
    }
    ReferenceCountUtil.safeRelease(batchMessageContainer.getBatchedSingleMessageMetadataAndPayload());
    batchMessageContainer.clear();
}
 
Example 14
Project: LiteGraph   File: AbstractGraphSONMessageSerializerV1d0.java   View source code 6 votes vote down vote up
@Override
public ByteBuf serializeResponseAsBinary(final ResponseMessage responseMessage, final ByteBufAllocator allocator) throws SerializationException {
    ByteBuf encodedMessage = null;
    try {
        final byte[] payload = mapper.writeValueAsBytes(responseMessage);
        encodedMessage = allocator.buffer(payload.length);
        encodedMessage.writeBytes(payload);

        return encodedMessage;
    } catch (Exception ex) {
        if (encodedMessage != null) ReferenceCountUtil.release(encodedMessage);

        logger.warn("Response [{}] could not be serialized by {}.", responseMessage.toString(), AbstractGraphSONMessageSerializerV1d0.class.getName());
        throw new SerializationException(ex);
    }
}
 
Example 15
Project: LiteGraph   File: AbstractGraphSONMessageSerializerV1d0.java   View source code 6 votes vote down vote up
@Override
public ByteBuf serializeRequestAsBinary(final RequestMessage requestMessage, final ByteBufAllocator allocator) throws SerializationException {
    ByteBuf encodedMessage = null;
    try {
        final byte[] header = obtainHeader();
        final byte[] payload = mapper.writeValueAsBytes(requestMessage);

        encodedMessage = allocator.buffer(header.length + payload.length);
        encodedMessage.writeBytes(header);
        encodedMessage.writeBytes(payload);

        return encodedMessage;
    } catch (Exception ex) {
        if (encodedMessage != null) ReferenceCountUtil.release(encodedMessage);

        logger.warn("Request [{}] could not be serialized by {}.", requestMessage.toString(), AbstractGraphSONMessageSerializerV1d0.class.getName());
        throw new SerializationException(ex);
    }
}
 
Example 16
Project: LiteGraph   File: OpExecutorHandler.java   View source code 6 votes vote down vote up
@Override
protected void channelRead0(final ChannelHandlerContext ctx, final Pair<RequestMessage, ThrowingConsumer<Context>> objects) throws Exception {
    final RequestMessage msg = objects.getValue0();
    final ThrowingConsumer<Context> op = objects.getValue1();
    final Context gremlinServerContext = new Context(msg, ctx,
            settings, graphManager, gremlinExecutor, scheduledExecutorService);

    try {
        op.accept(gremlinServerContext);
    } catch (OpProcessorException ope) {
        // Ops may choose to throw OpProcessorException or write the error ResponseMessage down the line
        // themselves
        logger.warn(ope.getMessage(), ope);
        ctx.writeAndFlush(ope.getResponseMessage());
    } catch (Exception ex) {
        // It is possible that an unplanned exception might raise out of an OpProcessor execution. Build a general
        // error to send back to the client
        logger.warn(ex.getMessage(), ex);
        ctx.writeAndFlush(ResponseMessage.build(msg)
                .code(ResponseStatusCode.SERVER_ERROR)
                .statusMessage(ex.getMessage()).create());
    } finally {
        ReferenceCountUtil.release(objects);
    }
}
 
Example 17
Project: moonlight-ss   File: ShadowSocksDecoder.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    ByteBuf in = (ByteBuf) msg;
    if (!readIV) {
        if (in.readableBytes() < ivLength) {
            return;
        } else {
            readIV = true;
            byte[] ivbytes = new byte[ivLength];
            in.readBytes(ivbytes);
            this.decryptCipher = new ShadowSocksCipher(ivbytes, crypto, password, false);
        }
    }
    int length = in.readableBytes();
    if (length > 0) {
        ByteBuf out = ctx.alloc().buffer();
        BytebufCipherUtil.update(decryptCipher, in, out);//update decode
        ctx.fireChannelRead(out);
        ReferenceCountUtil.release(in);
    }
}
 
Example 18
Project: milo   File: ChunkEncoder.java   View source code 6 votes vote down vote up
private static void encode(
    AbstractEncoder encoder,
    SecureChannel channel,
    long requestId,
    ByteBuf messageBuffer,
    MessageType messageType,
    Callback callback) {

    List<ByteBuf> chunks = new ArrayList<>();

    try {
        encoder.encode(chunks, channel, requestId, messageBuffer, messageType, callback);
    } catch (UaException e) {
        callback.onEncodingError(e);

        chunks.forEach(ReferenceCountUtil::safeRelease);
    }
}
 
Example 19
Project: milo   File: UaTcpServerSymmetricHandler.java   View source code 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    chunkBuffers.forEach(ReferenceCountUtil::safeRelease);
    chunkBuffers.clear();

    if (cause instanceof IOException) {
        ctx.close();
        logger.debug("[remote={}] IOException caught; channel closed");
    } else {
        ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause);

        if (cause instanceof UaException) {
            logger.debug("[remote={}] UaException caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        } else {
            logger.error("[remote={}] Exception caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        }
    }
}
 
Example 20
Project: milo   File: UaTcpServerAsymmetricHandler.java   View source code 6 votes vote down vote up
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
    chunkBuffers.forEach(ReferenceCountUtil::safeRelease);
    chunkBuffers.clear();

    if (cause instanceof IOException) {
        ctx.close();
        logger.debug("[remote={}] IOException caught; channel closed");
    } else {
        ErrorMessage errorMessage = ExceptionHandler.sendErrorMessage(ctx, cause);

        if (cause instanceof UaException) {
            logger.debug("[remote={}] UaException caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        } else {
            logger.error("[remote={}] Exception caught; sent {}",
                ctx.channel().remoteAddress(), errorMessage, cause);
        }
    }
}
 
Example 21
Project: reactor-netty   File: ChannelOperationsHandler.java   View source code 6 votes vote down vote up
void discard() {
	for (; ; ) {
		if (pendingWrites == null || pendingWrites.isEmpty()) {
			return;
		}

		ChannelPromise promise;
		Object v = pendingWrites.poll();

		try {
			promise = (ChannelPromise) v;
		}
		catch (Throwable e) {
			ctx.fireExceptionCaught(e);
			return;
		}
		v = pendingWrites.poll();
		if (log.isDebugEnabled()) {
			log.debug("{} Terminated ChannelOperation. Dropping Pending Write: {}",
					ctx.channel().toString(), v);
		}
		ReferenceCountUtil.release(v);
		promise.tryFailure(new AbortedException("Connection has been closed"));
	}
}
 
Example 22
Project: SecureSmartHome   File: SignerTest.java   View source code 6 votes vote down vote up
public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[]{1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000}) {
        buf.capacity(c);
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);
        }

        channel.writeOutbound(buf.duplicate().retain());
        channel.runPendingTasks();
        for (Object msg; (msg = channel.readOutbound()) != null; ) {
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}
 
Example 23
Project: SecureSmartHome   File: CrypterTest.java   View source code 6 votes vote down vote up
public void testRoundtrip() {
    ByteBuf buf = channel.alloc().buffer();
    for (int c : new int[]{1, 1, 5, 10, 50, 100, 500, 1000, 5000, 10000}) {
        buf.capacity(c);
        while (buf.writableBytes() > 0) {
            buf.writeByte(c);
        }

        channel.writeOutbound(buf.duplicate().retain());
        for (ByteBuf msg; (msg = channel.readOutbound()) != null; ) {
            assertNotSame(buf, msg);
            channel.writeInbound(msg);
        }
        assertEquals(buf, channel.readInbound());
    }
    ReferenceCountUtil.release(buf);
}
 
Example 24
Project: reactive-ipc-jvm   File: ChannelToConnectionBridge.java   View source code 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (null == conn || null == inputSubscriber) {
        logger.error("No connection input subscriber available. Disposing data.");
        ReferenceCountUtil.release(msg);
        return;
    }

    try {
        inputSubscriber.onNext((R) msg);
    } catch (ClassCastException e) {
        logger.error("Invalid message type read from the pipeline.", e);
        inputSubscriber.onError(e);
    }
}
 
Example 25
Project: netty4.0.27Learn   File: ByteToMessageDecoderTest.java   View source code 6 votes vote down vote up
/**
 * Verifies that internal buffer of the ByteToMessageDecoder is released once decoder is removed from pipeline. In
 * this case input is read fully.
 */
@Test
public void testInternalBufferClearReadAll() {
    final ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer().writeBytes(new byte[]{'a'}));
    EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            ByteBuf byteBuf = internalBuffer();
            Assert.assertEquals(1, byteBuf.refCnt());
            in.readByte();
            // Removal from pipeline should clear internal buffer
            ctx.pipeline().remove(this);
            Assert.assertEquals(0, byteBuf.refCnt());
        }
    });
    Assert.assertFalse(channel.writeInbound(buf));
    Assert.assertFalse(channel.finish());
}
 
Example 26
Project: coyote   File: NettyInboundRoadRunnerMessage.java   View source code 6 votes vote down vote up
/**
 * Attempt to give the entire trailer to the read callback
 *
 * @param data last chunk of data
 * @return <tt>true</tt> if the callback was updated, <tt>false</tt> otherwise
 */
private boolean doFullRead(ByteBuf data) {
  // not reading the whole buffer at once or we haven't see all the data yet
  if (!readFully || trailerOutstanding > 0) {
    return false;
  }

  LOG.trace("Reading full trailer into callback");

  ByteBuf finalTrailer = buildFullTrailer(trailer, data);
  sendToReader(finalTrailer, true);

  // release all the trailers we've accumulated
  for (ByteBuf buf : trailer) {
    ReferenceCountUtil.release(buf);
  }
  return true;
}
 
Example 27
Project: armeria   File: AbstractStreamMessageDuplicator.java   View source code 6 votes vote down vote up
private int removeElements() {
    final int removalRequestedOffset = lastRemovalRequestedOffset;
    final int numElementsToBeRemoved = removalRequestedOffset - headOffset;
    final int bitMask = elements.length - 1;
    final int oldHead = head;
    int removedLength = 0;
    for (int numRemovals = 0; numRemovals < numElementsToBeRemoved; numRemovals++) {
        final int index = (oldHead + numRemovals) & bitMask;
        final Object o = elements[index];
        if (!(o instanceof CloseEvent)) {
            removedLength += signalLengthGetter.length(o);
        }
        ReferenceCountUtil.safeRelease(o);
        elements[index] = null;
    }
    head = (oldHead + numElementsToBeRemoved) & bitMask;
    headOffset = removalRequestedOffset;
    size = size - numElementsToBeRemoved;
    return removedLength;
}
 
Example 28
Project: bridje-framework   File: HttpWsSwitch.java   View source code 6 votes vote down vote up
@Override
protected void decode(ChannelHandlerContext ctx, HttpObject msg, List<Object> out)
{
    if(!added && msg instanceof HttpRequest)
    {
        String path = ((HttpRequest)msg).getUri();
        WsServerHandler handler = findHandler(path);
        if(handler != null)
        {
            ctx.pipeline().addAfter("switch", "aggregator", new HttpObjectAggregator(65536));
            ctx.pipeline().addAfter("aggregator", "wsprotocol", new WebSocketServerProtocolHandler(path, null, true));
            ctx.pipeline().addAfter("wsprotocol", "wshandler", new WsFrameHandler(handler));
            added = true;
        }
    }
    ReferenceCountUtil.retain(msg);
    out.add(msg);
}
 
Example 29
Project: netty4.0.27Learn   File: SpdyFrameDecoderTest.java   View source code 6 votes vote down vote up
@Test
public void testUnknownSpdyWindowUpdateFrameFlags() throws Exception {
    short type = 9;
    byte flags = (byte) 0xFF; // undefined flags
    int length = 8;
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
    int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(streamId);
    buf.writeInt(deltaWindowSize);

    delegate.readWindowUpdateFrame(streamId, deltaWindowSize);
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
 
Example 30
Project: ethernet-ip   File: GetInstanceAttributeListService.java   View source code 6 votes vote down vote up
@Override
public List<SymbolInstance> decodeResponse(ByteBuf buffer) throws CipResponseException, PartialResponseException {
    MessageRouterResponse response = MessageRouterResponse.decode(buffer);

    int status = response.getGeneralStatus();
    ByteBuf data = response.getData();

    try {
        if (status == 0x00 || status == 0x06) {
            symbols.addAll(decode(data));

            if (status == 0x00) {
                return Lists.newArrayList(symbols);
            } else {
                instanceId = symbols.get(symbols.size() - 1).getInstanceId() + 1;

                throw PartialResponseException.INSTANCE;
            }
        } else {
            throw new CipResponseException(status, response.getAdditionalStatus());
        }
    } finally {
        ReferenceCountUtil.release(data);
    }
}
 
Example 31
Project: netty4.0.27Learn   File: SpdyFrameDecoderTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidSpdyWindowUpdateFrameLength() throws Exception {
    short type = 9;
    byte flags = 0;
    int length = 12; // invalid length
    int streamId = RANDOM.nextInt() & 0x7FFFFFFF;
    int deltaWindowSize = RANDOM.nextInt() & 0x7FFFFFFF | 0x01;

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(streamId);
    buf.writeInt(deltaWindowSize);

    delegate.readFrameError((String) anyObject());
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
 
Example 32
Project: blynk-server   File: BaseSimpleChannelInboundHandler.java   View source code 6 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (type.isInstance(msg)) {
        try {
            if (quotaMeter.getOneMinuteRate() > userQuotaLimit) {
                sendErrorResponseIfTicked();
                return;
            }
            quotaMeter.mark();
            messageReceived(ctx, (I) msg);
        } catch (BaseServerException bse) {
            handleBaseServerException(ctx, bse, getMsgId(msg));
        } catch (Exception e) {
            handleGeneralException(ctx, e);
        } finally {
            ReferenceCountUtil.release(msg);
        }
    }
}
 
Example 33
Project: jetstream   File: HttpErrorRequest.java   View source code 6 votes vote down vote up
public void processRequest() {
    try {
        DefaultHttpServletResponse servletResponse = new DefaultHttpServletResponse(HttpVersion.HTTP_1_1, m_status, 0);
        servletResponse.setHeader(CONTENT_TYPE, "text/plain; charset=UTF-8");

        try {
            servletResponse.flushBuffer();
            postResponse(m_channel, m_request, servletResponse.toNettyHttpResponse());

        } catch (Throwable e) {
            LOGGER.error( e.getMessage(), e);
        }
    } finally {
        ReferenceCountUtil.release(m_request);
    }
}
 
Example 34
Project: blynk-server   File: StaticFileHandler.java   View source code 6 votes vote down vote up
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
    if (!(msg instanceof FullHttpRequest)) {
        return;
    }

    FullHttpRequest req = (FullHttpRequest) msg;

    StaticFile staticFile = getStaticPath(req.uri());
    if (staticFile != null) {
        try {
            serveStatic(ctx, req, staticFile);
        } finally {
            ReferenceCountUtil.release(req);
        }
        return;
    }

    ctx.fireChannelRead(req);
}
 
Example 35
Project: netty4.0.27Learn   File: SpdyFrameDecoderTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidSpdySettingsFrameLength() throws Exception {
    short type = 4;
    byte flags = 0;
    int numSettings = 2;
    int length = 8 * numSettings + 8; // invalid length
    byte idFlags = 0;
    int id = RANDOM.nextInt() & 0x00FFFFFF;
    int value = RANDOM.nextInt();

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(numSettings);
    for (int i = 0; i < numSettings; i++) {
        buf.writeByte(idFlags);
        buf.writeMedium(id);
        buf.writeInt(value);
    }

    delegate.readFrameError((String) anyObject());
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
 
Example 36
Project: netty4.0.27Learn   File: SpdyFrameDecoderTest.java   View source code 6 votes vote down vote up
@Test
public void testInvalidSpdyHeadersFrameStreamId() throws Exception {
    short type = 8;
    byte flags = 0;
    int length = 4;
    int streamId = 0; // invalid stream identifier

    ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(SPDY_HEADER_SIZE + length));
    encodeControlFrameHeader(buf, type, flags, length);
    buf.writeInt(streamId);

    delegate.readFrameError((String) anyObject());
    replay(delegate);
    decoder.decode(buf);
    verify(delegate);
    assertFalse(buf.isReadable());
}
 
Example 37
Project: netty4.0.27Learn   File: HttpContentDecoderTest.java   View source code 6 votes vote down vote up
private void assertHasInboundMessages(EmbeddedChannel channel, boolean hasMessages) {
    Object o;
    if (hasMessages) {
        while (true) {
            o = channel.readInbound();
            assertNotNull(o);
            ReferenceCountUtil.release(o);
            if (o instanceof LastHttpContent) {
                break;
            }
        }
    } else {
        o = channel.readInbound();
        assertNull(o);
    }
}
 
Example 38
Project: netty4.0.27Learn   File: ByteToMessageDecoderTest.java   View source code 6 votes vote down vote up
/**
 * Verifies that internal buffer of the ByteToMessageDecoder is released once decoder is removed from pipeline. In
 * this case input was not fully read.
 */
@Test
public void testInternalBufferClearReadPartly() {
    final ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer().writeBytes(new byte[]{'a', 'b'}));
    EmbeddedChannel channel = new EmbeddedChannel(new ByteToMessageDecoder() {
        @Override
        protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
            ByteBuf byteBuf = internalBuffer();
            Assert.assertEquals(1, byteBuf.refCnt());
            in.readByte();
            // Removal from pipeline should clear internal buffer
            ctx.pipeline().remove(this);
            Assert.assertEquals(0, byteBuf.refCnt());
        }
    });
    Assert.assertTrue(channel.writeInbound(buf));
    Assert.assertTrue(channel.finish());
    Assert.assertEquals(channel.readInbound(), Unpooled.wrappedBuffer(new byte[] {'b'}));
    Assert.assertNull(channel.readInbound());
}
 
Example 39
Project: netty4.0.27Learn   File: ChannelOutboundBuffer.java   View source code 6 votes vote down vote up
/**
 * Will remove the current message, mark its {@link ChannelPromise} as success and return {@code true}. If no
 * flushed message exists at the time this method is called it will return {@code false} to signal that no more
 * messages are ready to be handled.
 */
public boolean remove() {
    Entry e = flushedEntry;
    if (e == null) {
        return false;
    }
    Object msg = e.msg;

    ChannelPromise promise = e.promise;
    int size = e.pendingSize;

    removeEntry(e);

    if (!e.cancelled) {
        // only release message, notify and decrement if it was not canceled before.
        ReferenceCountUtil.safeRelease(msg);
        safeSuccess(promise);
        decrementPendingOutboundBytes(size, false);
    }

    // recycle the entry
    e.recycle();

    return true;
}
 
Example 40
Project: netty4.0.27Learn   File: SpdyHeaderBlockRawDecoderTest.java   View source code 6 votes vote down vote up
@Test
public void testOneNameValuePair() throws Exception {
    ByteBuf headerBlock = ReferenceCountUtil.releaseLater(Unpooled.buffer(21));
    headerBlock.writeInt(1);
    headerBlock.writeInt(4);
    headerBlock.writeBytes(nameBytes);
    headerBlock.writeInt(5);
    headerBlock.writeBytes(valueBytes);
    decoder.decode(ByteBufAllocator.DEFAULT, headerBlock, frame);
    decoder.endHeaderBlock(frame);

    assertFalse(headerBlock.isReadable());
    assertFalse(frame.isInvalid());
    assertEquals(1, frame.headers().names().size());
    assertTrue(frame.headers().contains(name));
    assertEquals(1, frame.headers().getAll(name).size());
    assertEquals(value, frame.headers().get(name));
}