Example usage for io.netty.buffer ByteBuf isReadable

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

Introduction

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

Prototype

public abstract boolean isReadable();

Source Link

Document

Returns true if and only if (this.writerIndex - this.readerIndex) is greater than 0 .

Usage

From source file:at.yawk.dbus.protocol.object.ArrayObject.java

@Override
public void serialize(AlignableByteBuf buf) {
    ByteBuf tempBuffer = serializeValues(ArrayObject.allocateBufferForWrite(buf.getBuffer()));

    buf.alignWrite(4);//from   w  ww .ja  v  a 2 s.c  o m
    buf.getBuffer().writeInt(tempBuffer.writerIndex());
    if (tempBuffer.isReadable()) {
        buf.getBuffer().writeBytes(tempBuffer);
    }
    tempBuffer.release();
}

From source file:at.yawk.votifier.LineSplitter.java

License:Mozilla Public License

@Override
protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
    in.markReaderIndex();/*from  w  ww .  j a  v  a  2  s .c o m*/
    int lineLength = 0;
    boolean found = false;
    while (in.isReadable()) {
        if (in.readByte() == '\n') {
            found = true;
            break;
        }
        lineLength++;
    }
    in.resetReaderIndex();
    if (found) {
        byte[] line = new byte[lineLength];
        in.readBytes(line);
        in.readByte(); // newline
        out.add(new String(line, StandardCharsets.UTF_8));
    }
}

From source file:blazingcache.network.netty.DodoMessageUtils.java

License:Apache License

public static Message decodeMessage(ByteBuf encoded) {
    byte version = encoded.readByte();
    if (version != VERSION) {
        throw new RuntimeException("bad protocol version " + version);
    }/* w  w  w . j  av a 2s .  com*/
    int type = encoded.readInt();
    String messageId = readUTF8String(encoded);
    String replyMessageId = null;
    String workerProcessId = null;
    Map<String, Object> params = new HashMap<>();
    while (encoded.isReadable()) {
        byte opcode = encoded.readByte();
        switch (opcode) {
        case OPCODE_REPLYMESSAGEID:
            replyMessageId = readUTF8String(encoded);
            break;
        case OPCODE_WORKERPROCESSID:
            workerProcessId = readUTF8String(encoded);
            break;
        case OPCODE_PARAMETERS:
            int size = encoded.readInt();
            for (int i = 0; i < size; i++) {
                Object key = readEncodedSimpleValue(encoded);
                Object value = readEncodedSimpleValue(encoded);
                params.put((String) key, value);
            }
            break;
        default:
            throw new RuntimeException("invalid opcode: " + opcode);
        }
    }
    Message m = new Message(workerProcessId, type, params);
    if (replyMessageId != null) {
        m.replyMessageId = replyMessageId;
    }
    m.messageId = messageId;
    return m;

}

From source file:blazingcache.network.netty.MessageUtils.java

License:Apache License

public static Message decodeMessage(ByteBuf encoded) {
    byte version = encoded.readByte();
    if (version != VERSION) {
        throw new RuntimeException("bad protocol version " + version);
    }/*from   ww w  .jav  a2 s .  c o m*/
    int type = encoded.readInt();
    String messageId = readUTF8String(encoded);
    String replyMessageId = null;
    String workerProcessId = null;
    Map<String, Object> params = new HashMap<>();
    while (encoded.isReadable()) {
        byte opcode = encoded.readByte();
        switch (opcode) {
        case OPCODE_REPLYMESSAGEID:
            replyMessageId = readUTF8String(encoded);
            break;
        case OPCODE_WORKERPROCESSID:
            workerProcessId = readUTF8String(encoded);
            break;
        case OPCODE_PARAMETERS:
            int size = encoded.readInt();
            for (int i = 0; i < size; i++) {
                Object key = readEncodedSimpleValue(encoded);
                Object value = readEncodedSimpleValue(encoded);
                params.put(((RawString) key).toString(), value);
            }
            break;
        default:
            throw new RuntimeException("invalid opcode: " + opcode);
        }
    }
    Message m = new Message(workerProcessId, type, params);
    if (replyMessageId != null) {
        m.replyMessageId = replyMessageId;
    }
    m.messageId = messageId;
    return m;

}

From source file:bzh.ygu.fun.chitchat.HttpChitChatServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);// ww w.  j  a v  a2s  .com
        }
        String uri = request.uri();
        HttpMethod method = request.method();
        Root root = Root.getInstance();
        buf.setLength(0);
        contentBuf.setLength(0);

        if (method == HttpMethod.POST) {
            if (uri.equals("/chitchat")) {

                currentAction = "Add";
            }
        }
        if (method == HttpMethod.GET) {
            if (uri.startsWith(LATEST)) {
                latestFromWho = decode(uri.substring(LATEST_SIZE));
                currentAction = "Latest";
                Message m = root.getLatest(latestFromWho);
                if (m != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(m.toJSON());
                }
            }
            if (uri.startsWith(THREADCALL)) {
                currentAction = "Thread";
                String threadId = uri.substring(THREADCALL_SIZE);
                MessageThread mt = root.getMessageThread(threadId);
                if (mt != null) {
                    //{"author":"Iron Man", "text":"We have a Hulk !", "thread":3,"createdAt":1404736639715}
                    buf.append(mt.toJSON());
                }

            }
            if (uri.startsWith(SEARCH)) {
                String stringToSearch = decode(uri.substring(SEARCH_SIZE));
                currentAction = "search";
                List<Message> lm = root.search(stringToSearch);
                //[{"author":"Loki", "text":"I have an army !", "thread":3,
                //"createdAt":1404736639710}, {"author":"Iron Man", "text":"We have a Hulk !",
                //   "thread":3, "createdAt":1404736639715}]
                buf.append("[");
                if (!lm.isEmpty()) {
                    Iterator<Message> it = lm.iterator();
                    Message m = it.next();
                    buf.append(m.toJSON());
                    while (it.hasNext()) {
                        m = it.next();
                        buf.append(", ");
                        buf.append(m.toJSON());
                    }
                }

                buf.append("]");
            }
        }
    }

    if (msg instanceof HttpContent) {
        Root root = Root.getInstance();
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            contentBuf.append(content.toString(CharsetUtil.UTF_8));
        }

        if (msg instanceof LastHttpContent) {
            //                buf.append("END OF CONTENT\r\n");
            if (currentAction.equals("Add")) {
                addMessageFromContent(contentBuf.toString(), root);
                currentAction = "None";
            }
            LastHttpContent trailer = (LastHttpContent) msg;

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:ccwihr.client.t2.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;// www.java  2  s .c o m
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf content = msg.content();
        if (content.isReadable()) {
            int contentLength = content.readableBytes();
            byte[] arr = new byte[contentLength];
            content.readBytes(arr);
            System.out.println(new String(arr, 0, contentLength, CharsetUtil.UTF_8));
        }

        entry.getValue().setSuccess();
    }
}

From source file:ch07.handlers.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
    if (msg instanceof HttpRequest) {
        HttpRequest request = this.request = (HttpRequest) msg;

        if (HttpHeaders.is100ContinueExpected(request)) {
            send100Continue(ctx);// w w w .ja v  a 2  s  .c o  m
        }

        buf.setLength(0);
        buf.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
        buf.append("===================================\r\n");

        buf.append("VERSION: ").append(request.protocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.uri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (Map.Entry<String, String> h : headers) {
                String key = h.getKey();
                String value = h.getValue();
                buf.append("HEADER: ").append(key).append(" = ").append(value).append("\r\n");
            }
            buf.append("\r\n");
        }

        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
        Map<String, List<String>> params = queryStringDecoder.parameters();
        if (!params.isEmpty()) {
            for (Entry<String, List<String>> p : params.entrySet()) {
                String key = p.getKey();
                List<String> vals = p.getValue();
                for (String val : vals) {
                    buf.append("PARAM: ").append(key).append(" = ").append(val).append("\r\n");
                }
            }
            buf.append("\r\n");
        }

        appendDecoderResult(buf, request);
    }

    if (msg instanceof HttpContent) {
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            buf.append("CONTENT: ");
            buf.append(content.toString(CharsetUtil.UTF_8));
            buf.append("\r\n");
            appendDecoderResult(buf, request);
        }

        if (msg instanceof LastHttpContent) {
            buf.append("END OF CONTENT\r\n");

            LastHttpContent trailer = (LastHttpContent) msg;
            if (!trailer.trailingHeaders().isEmpty()) {
                buf.append("\r\n");
                for (String name : trailer.trailingHeaders().names()) {
                    for (String value : trailer.trailingHeaders().getAll(name)) {
                        buf.append("TRAILING HEADER: ");
                        buf.append(name).append(" = ").append(value).append("\r\n");
                    }
                }
                buf.append("\r\n");
            }

            if (!writeResponse(trailer, ctx)) {
                // If keep-alive is off, close the connection once the content is fully written.
                ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
            }
        }
    }
}

From source file:cn.jpush.api.common.connection.HttpResponseHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
    Integer streamId = msg.headers().getInt(HttpConversionUtil.ExtensionHeaderNames.STREAM_ID.text());
    if (streamId == null) {
        System.err.println("HttpResponseHandler unexpected message received: " + msg);
        return;// w ww.ja v  a2 s .co m
    } else {
        LOG.debug("HttpResponseHandler response message received: " + msg);
    }

    Entry<ChannelFuture, ChannelPromise> entry = streamidPromiseMap.get(streamId);
    List<String> list = new ArrayList<String>();
    list.add(msg.status().code() + "");
    if (entry == null) {
        System.err.println("Message received for unknown stream id " + streamId);
    } else {
        // Do stuff with the message (for now just print it)
        ByteBuf byteBuf = msg.content();
        if (byteBuf.isReadable()) {
            int contentLength = byteBuf.readableBytes();
            byte[] arr = new byte[contentLength];
            byteBuf.readBytes(arr);
            String content = new String(arr, 0, contentLength, CharsetUtil.UTF_8);
            list.add(content);
            System.out.println("Protocol version: " + msg.protocolVersion());
            System.out.println("status: " + list.get(0) + " response content: " + list.get(1));
            LOG.debug("Protocol version: " + msg.protocolVersion());
            LOG.debug("status: " + list.get(0) + " response content: " + list.get(1));
        }

        mNettyHttp2Client.setResponse(streamId + ctx.channel().id().asShortText(), list);
        if (null != mCallback) {
            ResponseWrapper wrapper = new ResponseWrapper();
            wrapper.responseCode = Integer.valueOf(list.get(0));
            if (list.size() > 1) {
                wrapper.responseContent = list.get(1);
            }
            mCallback.onSucceed(wrapper);
        }

        entry.getValue().setSuccess();
        if (msg instanceof HttpContent) {
            HttpContent content = (HttpContent) msg;
            System.err.println("content: " + content.content().toString(CharsetUtil.UTF_8));
            System.err.flush();

            if (content instanceof LastHttpContent) {
                System.err.println(" end of content");
                //                    ctx.close();
            }
        }

    }
}

From source file:cn.liutils.api.player.ControlData.java

License:Open Source License

public void fromBytes(ByteBuf buf) {
    clear();/* w ww  .  j  av a2  s .co m*/
    while (buf.isReadable()) {
        byte tp = buf.readByte();
        switch (tp) {
        case 0:
            while (buf.isReadable()) {
                byte pre = buf.readByte();
                if (pre == -1)
                    break;
                if (pre == StateType.LOCK_POSITION.ordinal()) {
                    state[pre] = new StateLockPosition(player, buf);
                }
                if (pre == StateType.LOCK_ROTATION.ordinal()) {
                    state[pre] = new StateLockRotation(player, buf);
                }
                if (pre == StateType.LOCK_CONTROL_MOVE.ordinal()) {
                    state[pre] = new StateLockControlMove(player, buf);
                }
                if (pre == StateType.LOCK_CONTROL_JUMP.ordinal()) {
                    state[pre] = new StateLockControlJump(player, buf);
                }
                if (pre == StateType.LOCK_CONTROL_SPIN.ordinal()) {
                    state[pre] = new StateLockControlSpin(player, buf);
                }
            }
            break;
        case -1:
            return;
        default:
            LIUtils.log.warn("Unknown type: " + tp);
        }
    }
}

From source file:code.google.nfs.rpc.netty.serialize.NettyProtocolDecoder.java

License:Apache License

@Override
public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
    ByteBuf buf = internalBuffer();
    int readable = buf.readableBytes();
    if (buf.isReadable()) {
        ByteBuf bytes = buf.readBytes(readable);
        buf.release();/*from   ww  w .jav  a  2  s .c  o  m*/
        ctx.fireChannelRead(bytes);
    }
    cumulation = null;
    ctx.fireChannelReadComplete();
    handlerRemoved0(ctx);
}