Example usage for io.netty.buffer ByteBuf retain

List of usage examples for io.netty.buffer ByteBuf retain

Introduction

In this page you can find the example usage for io.netty.buffer ByteBuf retain.

Prototype

@Override
    public abstract ByteBuf retain();

Source Link

Usage

From source file:org.rzo.netty.ahessian.io.InputStreamBuffer.java

License:Apache License

/**
 * Insert bytes to the input stream// w  w w.j  a  va 2s  .c  o  m
 * 
 * @param buf
 *            bytes received from previous upstream handler
 * 
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void write(ByteBuf buf) throws IOException {
    if (_closed)
        throw new IOException("stream closed");
    _lock.lock();
    try {
        if (_bufs.isEmpty() || buf != _bufs.getLast()) {
            buf.retain();
            _bufs.addLast(buf);
        }
        _available += buf.readableBytes();
        _notEmpty.signal();
    } catch (Exception ex) {
        Constants.ahessianLogger.warn("", ex);
    } finally {
        _lock.unlock();
    }
}

From source file:org.spout.api.protocol.fake.ChannelHandlerContextFaker.java

License:Open Source License

public static FakeChannelHandlerContext setup() {
    if (context == null) {
        context = Mockito.mock(FakeChannelHandlerContext.class, Mockito.CALLS_REAL_METHODS);
        channel = Mockito.mock(Channel.class);
        config = Mockito.mock(ChannelConfig.class);
        alloc = Mockito.mock(ByteBufAllocator.class);
        Mockito.doReturn(channel).when(context).channel();
        Mockito.when(channel.config()).thenReturn(config);
        Mockito.when(config.getAllocator()).thenReturn(alloc);
        Mockito.when(alloc.buffer(Mockito.anyInt())).thenAnswer(new Answer<ByteBuf>() {
            @Override/*from w w  w . j ava2s. c  o m*/
            public ByteBuf answer(InvocationOnMock invocation) throws Throwable {
                ByteBuf buffer = Unpooled.buffer();
                buffer.retain();
                return buffer;
            }
        });
    }
    return context;
}

From source file:org.springframework.messaging.rsocket.annotation.support.DefaultMetadataExtractor.java

License:Apache License

private void processEntry(ByteBuf content, @Nullable String mimeType, Map<String, Object> result) {
    EntryProcessor<?> entryProcessor = this.entryProcessors.get(mimeType);
    if (entryProcessor != null) {
        content.retain();
        entryProcessor.process(content, result);
        return;/*from  w  ww  .ja  v  a  2s  .  c  om*/
    }
    if (MessagingRSocket.ROUTING.toString().equals(mimeType)) {
        // TODO: use rsocket-core API when available
    }
}

From source file:org.thingsboard.mqtt.MqttClientImpl.java

License:Apache License

/**
 * Publish a message to the given payload, using the given qos and optional retain
 *
 * @param topic   The topic to publish to
 * @param payload The payload to send/*  w w  w . j  av a2  s . c  o m*/
 * @param qos     The qos to use while publishing
 * @param retain  true if you want to retain the message on the server, false otherwise
 * @return A future which will be completed when the message is delivered to the server
 */
@Override
public Future<Void> publish(String topic, ByteBuf payload, MqttQoS qos, boolean retain) {
    Promise<Void> future = new DefaultPromise<>(this.eventLoop.next());
    MqttFixedHeader fixedHeader = new MqttFixedHeader(MqttMessageType.PUBLISH, false, qos, retain, 0);
    MqttPublishVariableHeader variableHeader = new MqttPublishVariableHeader(topic,
            getNewMessageId().messageId());
    MqttPublishMessage message = new MqttPublishMessage(fixedHeader, variableHeader, payload);
    MqttPendingPublish pendingPublish = new MqttPendingPublish(variableHeader.messageId(), future,
            payload.retain(), message, qos);
    ChannelFuture channelFuture = this.sendAndFlushPacket(message);

    if (channelFuture != null) {
        pendingPublish.setSent(true);
        if (channelFuture.cause() != null) {
            future.setFailure(channelFuture.cause());
            return future;
        }
    }
    if (pendingPublish.isSent() && pendingPublish.getQos() == MqttQoS.AT_MOST_ONCE) {
        pendingPublish.getFuture().setSuccess(null); //We don't get an ACK for QOS 0
    } else if (pendingPublish.isSent()) {
        this.pendingPublishes.put(pendingPublish.getMessageId(), pendingPublish);
        pendingPublish.startPublishRetransmissionTimer(this.eventLoop.next(), this::sendAndFlushPacket);
    }
    return future;
}

From source file:org.thingsplode.synapse.endpoint.handlers.HttpRequestIntrospector.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpRequest msg) throws Exception {
    try {/*from  w  ww  .j  a  v a 2s  .c o m*/
        if (msg == null) {
            logger.warn("Message@Endpoint received: NULL");
        } else if (logger.isDebugEnabled()) {
            final StringBuilder hb = new StringBuilder();
            msg.headers().entries().forEach(e -> {
                hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n");
            });
            String payloadAsSring = null;
            if (msg instanceof FullHttpRequest) {
                ByteBuf content = ((FullHttpRequest) msg).content();
                byte[] dst = new byte[content.capacity()];
                content.copy().getBytes(0, dst);
                content.retain();
                payloadAsSring = new String(dst, Charset.forName("UTF-8"));
            }
            logger.debug("Message@Endpoint received: \n\n" + "Uri: " + msg.uri() + "\n" + "Method: "
                    + msg.method() + "\n" + hb.toString() + "\n" + "Payload -> "
                    + (!Util.isEmpty(payloadAsSring) ? payloadAsSring + "\n" : "EMPTY\n"));
        }
    } catch (Throwable th) {
        logger.error(th.getClass().getSimpleName() + " caught while introspecting request, with message: "
                + th.getMessage(), th);
    }
    if (msg != null && msg instanceof FullHttpRequest) {
        ((FullHttpRequest) msg).content().retain();
    }
    ctx.fireChannelRead(msg);
}

From source file:org.thingsplode.synapse.proxy.handlers.HttpResponseIntrospector.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpResponse msg) throws Exception {
    if (msg != null) {
        final StringBuilder hb = new StringBuilder();
        msg.headers().entries().forEach(e -> {
            hb.append(e.getKey()).append(" : ").append(e.getValue()).append("\n");
        });/* w w  w  .j  av a2s .co  m*/
        String payloadAsSring = null;
        if (msg instanceof FullHttpResponse) {
            ByteBuf content = ((FullHttpResponse) msg).content();
            byte[] dst = new byte[content.capacity()];
            content.copy().getBytes(0, dst);
            content.retain();
            payloadAsSring = new String(dst, Charset.forName("UTF-8"));
        }
        logger.debug("Message@Proxy received [" + msg.getClass().getSimpleName() + "]: \n\n" + "Status: "
                + msg.status() + "\n" + hb.toString() + "\n" + "Payload -> ["
                + (!Util.isEmpty(payloadAsSring) ? payloadAsSring : "EMPTY") + "]\n");
    }
    ctx.fireChannelRead(msg);
}

From source file:org.traccar.protocol.AtrackProtocolDecoder.java

License:Apache License

@Override
protected Object decode(Channel channel, SocketAddress remoteAddress, Object msg) throws Exception {

    ByteBuf buf = (ByteBuf) msg;

    if (buf.getUnsignedShort(buf.readerIndex()) == 0xfe02) {
        if (channel != null) {
            channel.writeAndFlush(new NetworkMessage(buf.retain(), remoteAddress)); // keep-alive message
        }/*from  ww w.  j  a  v a  2s.co m*/
        return null;
    } else if (buf.getByte(buf.readerIndex()) == '$') {
        return decodeInfo(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII).trim());
    } else if (buf.getByte(buf.readerIndex() + 2) == ',') {
        return decodeText(channel, remoteAddress, buf.toString(StandardCharsets.US_ASCII).trim());
    } else {
        return decodeBinary(channel, remoteAddress, buf);
    }
}

From source file:org.traccar.protocol.WondexFrameDecoder.java

License:Apache License

@Override
protected Object decode(ChannelHandlerContext ctx, Channel channel, ByteBuf buf) throws Exception {

    if (buf.readableBytes() < KEEP_ALIVE_LENGTH) {
        return null;
    }//from  w  ww . ja va 2  s.  c o m

    if (buf.getUnsignedByte(buf.readerIndex()) == 0xD0) {

        // Send response
        ByteBuf frame = buf.readRetainedSlice(KEEP_ALIVE_LENGTH);
        if (channel != null) {
            frame.retain();
            channel.writeAndFlush(new NetworkMessage(frame, channel.remoteAddress()));
        }
        return frame;

    } else {

        int index = BufferUtil.indexOf("\r\n", buf);
        if (index != -1) {
            ByteBuf frame = buf.readRetainedSlice(index - buf.readerIndex());
            buf.skipBytes(2);
            return frame;
        }

    }

    return null;
}

From source file:org.waarp.openr66.protocol.http.rest.client.HttpRestR66ClientResponseHandler.java

License:Apache License

protected void addContent(FullHttpResponse response) throws HttpIncorrectRequestException {
    ByteBuf content = response.content();
    if (content != null && content.isReadable()) {
        content.retain();
        if (cumulativeBody != null) {
            cumulativeBody = Unpooled.wrappedBuffer(cumulativeBody, content);
        } else {//from ww w. j  a  va 2 s . c o m
            cumulativeBody = content;
        }
        // get the Json equivalent of the Body
        try {
            String json = cumulativeBody.toString(WaarpStringUtils.UTF8);
            jsonObject = JsonHandler.getFromString(json);
        } catch (UnsupportedCharsetException e2) {
            logger.warn("Error", e2);
            throw new HttpIncorrectRequestException(e2);
        }
        cumulativeBody = null;
    }
}

From source file:org.waarp.openr66.protocol.http.rest.client.HttpRestR66ClientResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
    HttpObject obj = msg;// www . j  av a2s .  co  m
    if (obj instanceof HttpResponse) {
        HttpResponse response = (HttpResponse) msg;
        HttpResponseStatus status = response.status();
        logger.debug(HttpHeaderNames.REFERER + ": " + response.headers().get(HttpHeaderNames.REFERER)
                + " STATUS: " + status);
        if (response.status().code() != 200) {
            if (response instanceof FullHttpResponse) {
                addContent((FullHttpResponse) response);
            }
            RestArgument ra = null;
            if (jsonObject != null) {
                ra = new RestArgument((ObjectNode) jsonObject);
                RestFuture restFuture = ctx.channel().attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT)
                        .get();
                restFuture.setRestArgument(ra);
                logger.error("Error: " + response.status().code() + " " + response.status().reasonPhrase()
                        + "\n" + ra.prettyPrint());
            } else {
                logger.error("Error: " + response.status().code() + " " + response.status().reasonPhrase());
            }
            if (!afterError(ctx.channel(), ra)) {
                RestFuture restFuture = ctx.channel().attr(HttpRestClientSimpleResponseHandler.RESTARGUMENT)
                        .get();
                restFuture.cancel();
            }
            if (ctx.channel().isActive()) {
                logger.debug("Will close");
                WaarpSslUtility.closingSslChannel(ctx.channel());
            }
        } else {
            if (response instanceof FullHttpResponse) {
                addContent((FullHttpResponse) response);
                actionFromResponse(ctx.channel());
            }
        }
    } else {
        HttpContent chunk = (HttpContent) msg;
        if (chunk instanceof LastHttpContent) {
            ByteBuf content = chunk.content();
            if (content != null && content.isReadable()) {
                content.retain();
                if (cumulativeBody != null) {
                    cumulativeBody = Unpooled.wrappedBuffer(cumulativeBody, content);
                } else {
                    cumulativeBody = content;
                }
            }
            // get the Json equivalent of the Body
            if (cumulativeBody == null) {
                jsonObject = JsonHandler.createObjectNode();
            } else {
                try {
                    String json = cumulativeBody.toString(WaarpStringUtils.UTF8);
                    jsonObject = JsonHandler.getFromString(json);
                } catch (Throwable e2) {
                    logger.warn("Error", e2);
                    throw new HttpIncorrectRequestException(e2);
                }
                cumulativeBody = null;
            }
            actionFromResponse(ctx.channel());
        } else {
            ByteBuf content = chunk.content();
            if (content != null && content.isReadable()) {
                content.retain();
                if (cumulativeBody != null) {
                    cumulativeBody = Unpooled.wrappedBuffer(cumulativeBody, content);
                } else {
                    cumulativeBody = content;
                }
            }
        }
    }
}