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:com.spotify.netty.handler.codec.zmtp.ZMTPFrame.java

License:Apache License

/**
 * Create a new frame from a channel buffer.
 *//*w  ww  .j a  v a2s . c  o  m*/
public static ZMTPFrame create(ByteBuf buf) {
    if (!buf.isReadable()) {
        return EMPTY_FRAME;
    } else {
        byte[] dst = new byte[buf.capacity()];
        buf.readBytes(dst);
        return new ZMTPFrame(dst);
    }
}

From source file:com.spotify.netty4.handler.codec.zmtp.ZMTPFramingDecoder.java

License:Apache License

@Override
protected void decode(final ChannelHandlerContext ctx, final ByteBuf in, final List<Object> out)
        throws ZMTPParsingException {
    while (in.isReadable()) {
        if (!headerParsed) {
            final int mark = in.readerIndex();
            headerParsed = header.read(in);
            if (!headerParsed) {
                // Wait for more data
                in.readerIndex(mark);/*from   w w w .ja  v a2  s . co  m*/
                return;
            }
            decoder.header(ctx, header.length(), header.more(), out);
            remaining = header.length();
        }

        final int writerMark = in.writerIndex();
        final int n = (int) min(remaining, in.readableBytes());
        final int readerMark = in.readerIndex();
        in.writerIndex(readerMark + n);
        decoder.content(ctx, in, out);
        in.writerIndex(writerMark);
        final int read = in.readerIndex() - readerMark;
        remaining -= read;
        if (remaining > 0) {
            // Wait for more data
            return;
        }
        if (!header.more()) {
            decoder.finish(ctx, out);
        }
        headerParsed = false;
    }
}

From source file:com.springapp.mvc.netty.example.http.snoop.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  ww  .j  a  v  a  2s  .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.getProtocolVersion()).append("\r\n");
        buf.append("HOSTNAME: ").append(HttpHeaders.getHost(request, "unknown")).append("\r\n");
        buf.append("REQUEST_URI: ").append(request.getUri()).append("\r\n\r\n");

        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
            for (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.getUri());
        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:com.srotya.sidewinder.core.ingress.http.HTTPDataPointDecoder.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {// www .  ja va 2  s  .  co  m
        if (msg instanceof HttpRequest) {
            HttpRequest request = this.request = (HttpRequest) msg;
            if (HttpUtil.is100ContinueExpected(request)) {
                send100Continue(ctx);
            }

            QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.uri());
            path = queryStringDecoder.path();

            Map<String, List<String>> params = queryStringDecoder.parameters();
            if (!params.isEmpty()) {
                for (Entry<String, List<String>> p : params.entrySet()) {
                    String key = p.getKey();
                    if (key.equalsIgnoreCase("db")) {
                        dbName = p.getValue().get(0);
                    }
                }
            }

            if (path != null && path.contains("query")) {
                Gson gson = new Gson();
                JsonObject obj = new JsonObject();
                JsonArray ary = new JsonArray();
                ary.add(new JsonObject());
                obj.add("results", ary);
                responseString.append(gson.toJson(obj));
            }
        }

        if (msg instanceof HttpContent) {
            HttpContent httpContent = (HttpContent) msg;
            ByteBuf byteBuf = httpContent.content();
            if (byteBuf.isReadable()) {
                requestBuffer.append(byteBuf.toString(CharsetUtil.UTF_8));
            }

            if (msg instanceof LastHttpContent) {
                // LastHttpContent lastHttpContent = (LastHttpContent) msg;
                // if (!lastHttpContent.trailingHeaders().isEmpty()) {
                // }

                if (dbName == null) {
                    responseString.append("Invalid database null");
                    logger.severe("Invalid database null");
                } else {
                    String payload = requestBuffer.toString();
                    logger.fine("Request:" + payload);
                    List<DataPoint> dps = dataPointsFromString(dbName, payload);
                    for (DataPoint dp : dps) {
                        try {
                            engine.writeDataPoint(dp);
                            logger.fine("Accepted:" + dp + "\t" + new Date(dp.getTimestamp()));
                        } catch (IOException e) {
                            logger.fine("Dropped:" + dp + "\t" + e.getMessage());
                            responseString.append("Dropped:" + dp);
                        }
                    }
                }
                if (writeResponse(request, ctx)) {
                    ctx.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.streamsets.pipeline.lib.parser.net.DelimitedLengthFieldBasedFrameDecoder.java

License:Apache License

public DelimitedLengthFieldBasedFrameDecoder(int maxFrameLength, int lengthAdjustment, boolean failFast,
        ByteBuf delimiter, Charset lengthFieldCharset, boolean trimLengthString) {
    if (delimiter == null) {
        throw new NullPointerException("delimiter");
    }//from   w ww. j  a va  2  s  .  c o m
    if (!delimiter.isReadable()) {
        throw new IllegalArgumentException("empty delimiter");
    }

    this.delimiter = delimiter.slice(delimiter.readerIndex(), delimiter.readableBytes());
    this.lengthFieldCharset = lengthFieldCharset;

    this.maxFrameLength = maxFrameLength;
    this.lengthAdjustment = lengthAdjustment;
    this.failFast = failFast;
    this.trimLengthString = trimLengthString;
}

From source file:com.superman.netty.handler.DiscardServerHandler.java

License:Apache License

@Override
public void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
    try {/*  www  . j  a  v  a  2s .  c o m*/
        ByteBuf bb = (ByteBuf) msg;
        while (bb.isReadable()) {
            System.out.print((char) bb.readByte());
            System.out.flush();
        }
    } finally {
        // ((ByteBuf) msg).release();
        ReferenceCountUtil.release(msg);
    }
    LOGGER.info("?");
}

From source file:com.tesora.dve.db.mysql.common.MysqlAPIUtils.java

License:Open Source License

public static ArrayList<Integer> locateLengthCodedStrings(ByteBuf cb, int skipAmount) {
    ArrayList<Integer> offsets = new ArrayList<>();
    ByteBuf slice = cb.slice().order(ByteOrder.LITTLE_ENDIAN);
    slice.skipBytes(skipAmount);// w w  w. j  a va 2 s  .  c o  m
    while (slice.isReadable()) {
        offsets.add(slice.readerIndex());
        skipLengthCodedString(slice);
    }
    return offsets;
}

From source file:com.tesora.dve.db.mysql.libmy.MyOKResponse.java

License:Open Source License

@Override
public void unmarshallMessage(ByteBuf cb) {
    cb.readByte(); // field count - always 0
    affectedRows = MysqlAPIUtils.getLengthCodedLong(cb);
    insertId = MysqlAPIUtils.getLengthCodedLong(cb);
    serverStatus = cb.readUnsignedShort();
    warningCount = cb.readUnsignedShort();
    if (cb.isReadable())
        message = MysqlAPIUtils.readBytesAsString(cb, CharsetUtil.UTF_8);
}

From source file:com.tesora.dve.mysqlapi.repl.messages.MyStatusVariables.java

License:Open Source License

public void parseStatusVariables(ByteBuf cb, int svLen) throws PEException {
    if (svLen > 0) {
        ByteBuf statsVarsBuf = cb.readBytes(svLen);
        while (statsVarsBuf.isReadable()) {
            byte code = statsVarsBuf.readByte();
            MyQueryEventCode mqec = MyQueryEventCode.fromByte(code);
            if (mqec == null) {
                throw new PEException("Replication could not decode query event code: '" + code + "' (0x"
                        + Integer.toHexString(code) + ")");
            }//from  w ww  .java  2  s.  c  om

            switch (mqec) {
            case Q_FLAGS2_CODE:
                int flags = statsVarsBuf.readInt();
                suppliedEventCodes.add(new QueryFlags2Event(flags));
                break;

            case Q_SQL_MODE_CODE:
                long sqlMode = statsVarsBuf.readLong();
                suppliedEventCodes.add(new QuerySQLModeEvent(sqlMode));
                break;

            case Q_CATALOG_CODE: {
                byte len = statsVarsBuf.readByte();
                String catalog = MysqlAPIUtils.readBytesAsString(statsVarsBuf, len, CharsetUtil.UTF_8);
                statsVarsBuf.readByte(); // null terminated byte

                suppliedEventCodes.add(new QueryCatalogEvent(catalog));
                break;
            }
            case Q_AUTO_INCREMENT:
                int autoIncrementIncrement = statsVarsBuf.readUnsignedShort();
                int autoIncrementOffset = statsVarsBuf.readUnsignedShort();

                suppliedEventCodes
                        .add(new QueryAutoIncrementEvent(autoIncrementIncrement, autoIncrementOffset));
                break;

            case Q_CHARSET_CODE:
                int charSetClient = statsVarsBuf.readUnsignedShort();
                int collationConnection = statsVarsBuf.readUnsignedShort();
                int collationServer = statsVarsBuf.readUnsignedShort();

                suppliedEventCodes
                        .add(new QueryCharSetCodeEvent(charSetClient, collationConnection, collationServer));
                break;

            case Q_TIME_ZONE_CODE: {
                byte len = statsVarsBuf.readByte();
                String timeZone = MysqlAPIUtils.readBytesAsString(statsVarsBuf, len, CharsetUtil.UTF_8);

                suppliedEventCodes.add(new QueryTimeZoneCodeEvent(timeZone));
                break;
            }
            case Q_CATALOG_NZ_CODE: {
                byte catalogLen = statsVarsBuf.readByte();
                String catalog = MysqlAPIUtils.readBytesAsString(statsVarsBuf, catalogLen, CharsetUtil.UTF_8);

                suppliedEventCodes.add(new QueryCatalogNZEvent(catalog));
                break;
            }
            case Q_LC_TIME_NAMES_CODE:
                short monthDayNames = statsVarsBuf.readShort();

                suppliedEventCodes.add(new QueryTimeNamesEvent(monthDayNames));
                break;

            case Q_CHARSET_DATABASE_CODE:
                short collationDatabase = statsVarsBuf.readShort();

                suppliedEventCodes.add(new QueryCollationDatabaseEvent(collationDatabase));
                break;

            case Q_TABLE_MAP_FOR_UPDATE_CODE:
                long tableMapForUpdate = statsVarsBuf.readLong();

                suppliedEventCodes.add(new QueryTableMapEvent(tableMapForUpdate));
                break;

            case Q_MASTER_DATA_WRITTEN_CODE:
                int originalLength = statsVarsBuf.readInt();

                suppliedEventCodes.add(new QueryMasterDataWrittenEvent(originalLength));
                break;

            case Q_INVOKER:
                int userLen = statsVarsBuf.readByte();
                String user = MysqlAPIUtils.readBytesAsString(statsVarsBuf, userLen, CharsetUtil.UTF_8);
                int hostLen = statsVarsBuf.readByte();
                String host = MysqlAPIUtils.readBytesAsString(statsVarsBuf, hostLen, CharsetUtil.UTF_8);

                suppliedEventCodes.add(new QueryInvokerEvent(user, host));
                break;

            case Q_UPDATED_DB_NAMES:
                List<String> dbNames = new ArrayList<String>();
                int numDbs = statsVarsBuf.readByte();
                if (numDbs > 0) {
                    for (int i = 0; i < numDbs; i++) {
                        dbNames.add(statsVarsBuf.readSlice(statsVarsBuf.bytesBefore((byte) 0))
                                .toString(CharsetUtil.UTF_8));
                        statsVarsBuf.readByte(); //read null byte
                    }
                }
                suppliedEventCodes.add(new QueryUpdatedDBNamesEvent(dbNames));
                break;

            case Q_MICROSECONDS:
                int microseconds = statsVarsBuf.readMedium();

                suppliedEventCodes.add(new QueryMicrosecondsEvent(microseconds));
                break;

            case Q_HRNOW:
                //TODO: this was apparently added for MariaDB, but I can't find a lot of info on it. skip for now.
                suppliedEventCodes.add(new QueryMicrosecondsEvent(statsVarsBuf.readUnsignedMedium()));
                break;

            default:
                throw new PEException("Replication encountered an unknown query event code: '" + code + "' (0x"
                        + Integer.toHexString(code) + ")");
            }
        }
    }
}

From source file:com.topsec.bdc.platform.api.server.http.HttpSnoopServerHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {

    if (msg instanceof HttpRequest) {
        //?HTTP?//from  ww  w.  j a  va  2  s. com
        //HttpRequest request = this._request = (HttpRequest) msg;
        this._request = (HttpRequest) msg;
        //
        _requestBodyBuf.setLength(0);
        /*
        System.out.println("===================================\r\n");
                
        System.out.println("VERSION: " + request.getProtocolVersion());
        System.out.println("HOSTNAME: " + HttpHeaders.getHost(request, "unknown"));
        System.out.println("REQUEST_URI: " + request.getUri());
                
        HttpHeaders headers = request.headers();
        if (!headers.isEmpty()) {
        for (Map.Entry<String, String> h : headers) {
            String key = h.getKey();
            String value = h.getValue();
            System.out.println("HEADER: " + key + " = " + value);
        }
        }
                
        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) {
                System.out.println("PARAM: " + key + " = " + val);
            }
        }
        }
        //
        System.out.println("===================================");
        */

    }

    if (msg instanceof HttpContent) {
        //?HTTP BODY BODY?chunked?CHUNKED????
        HttpContent httpContent = (HttpContent) msg;

        ByteBuf content = httpContent.content();
        if (content.isReadable()) {
            _requestBodyBuf.append(content.toString(CharsetUtil.UTF_8));
            //content.release();
        }
        //??Response??
        if (msg instanceof LastHttpContent) {
            //
            LastHttpContent trailer = (LastHttpContent) msg;
            //
            String responseContent = null;
            //
            //fill response
            if (trailer.getDecoderResult().isSuccess() == false) {
                _responseStatus = HttpResponseStatus.BAD_REQUEST;
                responseContent = HttpResponseStatus.BAD_REQUEST.reasonPhrase();
            } else {
                try {
                    _responseStatus = HttpResponseStatus.OK;
                    responseContent = fireListenerSucceed(_requestBodyBuf.toString());
                } catch (Throwable e) {
                    e.printStackTrace();
                    _responseStatus = HttpResponseStatus.SERVICE_UNAVAILABLE;
                    responseContent = e.toString();
                }
            }

            try {
                //send back response and close connection
                writeResponseAndClose(ctx, responseContent);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                _requestBodyBuf.setLength(0);
            }
        }
    }
}