List of usage examples for io.netty.buffer ByteBuf isReadable
public abstract boolean isReadable(int size);
From source file:com.antsdb.saltedfish.server.mysql.PacketDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // do we have length field in buffer ? if (!in.isReadable(4)) { return;/*from w ww . j a v a 2 s . c o m*/ } // do we have entire packet in the buffer? in.markReaderIndex(); int size = BufferUtils.readLongInt(in); int sequence = in.readByte() & 0xff; if (size == 0) { out.add(new ShutdownPacket()); return; } if (!in.isReadable(size)) { in.resetReaderIndex(); return; } // is very large packet? this.handler.packetSequence = sequence; if (size == MAX_PACKET_SIZE) { if (this.largePacket == null) { this.largePacket = ctx.alloc().directBuffer(); } this.largePacket.writeBytes(in, MAX_PACKET_SIZE); return; } if (this.largePacket != null) { this.largePacket.writeBytes(in, size); } // parse packet if (this.largePacket == null) { int pos = in.readerIndex(); try { RecievePacket packet = readPacket(in, size); out.add(packet); } finally { in.readerIndex(pos + size); } } else { RecievePacket packet = readPacket(this.largePacket, size); out.add(packet); this.largePacket.release(); this.largePacket = null; } }
From source file:com.antsdb.saltedfish.server.mysql.ReplicationPacketDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { // do we have length field in buffer ? if (!in.isReadable(4)) { return;/* w ww. ja va2 s .c o m*/ } // do we have entire packet in the buffer? in.markReaderIndex(); int size = BufferUtils.readLongInt(in) + 1; if (size == (0x00ffffff + 1)) { return; } if (!in.isReadable(size)) { in.resetReaderIndex(); return; } int pos = in.readerIndex(); try { ReplicationPacket packet = readPacket(in, size); out.add(packet); } finally { int currentPos = in.readerIndex(); in.skipBytes(size - (currentPos - pos)); } }
From source file:com.friz.update.network.codec.UpdateDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buffer, List<Object> out) throws Exception { if (!buffer.isReadable(6)) return;//w w w. j a v a 2 s .co m int opcode = buffer.readUnsignedByte(); if (opcode == 0 || opcode == 1) { int type = buffer.readUnsignedByte(); int file = buffer.readInt(); out.add(new FileRequestEvent(opcode == 1, type, file)); } else if (opcode == 4) { int key = buffer.readUnsignedByte(); buffer.readerIndex(buffer.readerIndex() + 4); out.add(new XorRequestEvent(key)); } else { buffer.readerIndex(buffer.readerIndex() + 5); } }
From source file:com.friz.update.network.codec.UpdateInitDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf buf, List<Object> out) throws Exception { int type = buf.readUnsignedByte(); int size = buf.readUnsignedByte(); if (!buf.isReadable(size)) return;/* www . j a v a 2s. c o m*/ int version = buf.readInt(); int subVersion = buf.readInt(); String key = BufferUtils.getString(buf); int langId = buf.readUnsignedByte(); out.add(new UpdateRequestEvent(type, version, subVersion, key, langId)); }
From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java
License:Apache License
/** * Helper method to parse a bulk string when one is seen * /*ww w .ja v a2 s . com*/ * @param buffer Buffer to read from * @return byte[] representation of the Bulk String read * @throws RedisCommandParserException Thrown when there is illegal syntax */ private byte[] parseBulkString(ByteBuf buffer) throws RedisCommandParserException { int bulkStringLength = parseCurrentNumber(buffer); if (bulkStringLength == Integer.MIN_VALUE) return null; if (bulkStringLength > MAX_BULK_STRING_LENGTH) throw new RedisCommandParserException( "invalid bulk length, cannot exceed max length of " + MAX_BULK_STRING_LENGTH); if (!parseRN(buffer)) return null; if (!buffer.isReadable(bulkStringLength)) return null; byte[] bulkString = new byte[bulkStringLength]; buffer.readBytes(bulkString); if (!parseRN(buffer)) return null; return bulkString; }
From source file:com.gemstone.gemfire.internal.redis.ByteToCommandDecoder.java
License:Apache License
/** * Helper method that is called when the next characters are * supposed to be "\r\n"/*from w ww . j a v a2s . c om*/ * * @param buffer Buffer to read from * @throws RedisCommandParserException Thrown when the next two characters * are not "\r\n" */ private boolean parseRN(ByteBuf buffer) throws RedisCommandParserException { if (!buffer.isReadable(2)) return false; byte b = buffer.readByte(); if (b != rID) throw new RedisCommandParserException("expected \'" + (char) rID + "\', got \'" + (char) b + "\'"); b = buffer.readByte(); if (b != nID) throw new RedisCommandParserException("expected: \'" + (char) nID + "\', got \'" + (char) b + "\'"); return true; }
From source file:com.goodgamenow.source.serverquery.MasterQueryHandler.java
License:Open Source License
/** * Decodes a master server response datagram packet into a list of * game server addresses.// w w w. j a v a2s .c o m * * @param ctx channel handler context * @param msg master server response packet * @exception UnsupportedEncodingException */ @Override protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket msg) throws UnsupportedEncodingException { ByteBuf buf = msg.content(); // sanity check int ADDR_WIDTH = 6; assert (buf.readableBytes() % ADDR_WIDTH) == 0 : "Master response byte count is not 6 byte aligned."; // decode response header String header = decodeIpAddress(buf); assert EXPECTED_HEADER_STRING.equals(header); while (buf.isReadable(ADDR_WIDTH)) { lastAddress = decodeIpAddress(buf); // A last address of 0.0.0.0:0 denotes the end of transmission. if (DEFAULT_IP.equals(lastAddress)) { ctx.flush(); ctx.close(); finishTime = System.currentTimeMillis(); return; } if (parentContext != null) { InetSocketAddress address = createInetSocketAddress(lastAddress); ServerQuery template = query.template; ServerQuery squery = ServerQuery.createFromTemplate(address, template); parentContext.fireChannelRead(squery); } else { if (results == null) { // should never happen throw new IllegalStateException("Results container is null when there is no other " + "ChannelHandlerContext to send results."); } // we are storing for bulk access later. results.add(lastAddress); } } assert buf.readableBytes() == 0; // ask for more results this.channelActive(ctx); }
From source file:com.heliosapm.streams.chronicle.MessageQueue.java
License:Apache License
public static void main(String[] args) { log("MessageQueue Test"); // System.setProperty("io.netty.leakDetection.level", "advanced"); // System.setProperty("Test.chronicle.rollcycle", RollCycles.MINUTELY.name()); final ThreadLocalRandom tlr = ThreadLocalRandom.current(); final MetricRegistry mr = new MetricRegistry(); final Meter listenerEvents = mr.meter("listener.events"); final Timer writerTime = mr.timer("writer.time"); final Counter deserErrors = mr.counter("deser.errors"); final ConsoleReporter cr = ConsoleReporter.forRegistry(mr).convertDurationsTo(TimeUnit.MICROSECONDS) .convertRatesTo(TimeUnit.SECONDS).outputTo(System.err).build(); cr.start(5, TimeUnit.SECONDS); final MessageListener listener = new MessageListener() { @Override//w w w.j av a2s .c o m public int onMetric(final ByteBuf buf) { listenerEvents.mark(); int cnt = 0; try { while (buf.isReadable(20)) { StreamedMetric.read(buf); listenerEvents.mark(); cnt++; } } catch (Exception ex) { deserErrors.inc(); } finally { buf.release(); } return cnt; } }; final MessageQueue mq = MessageQueue.getInstance("Test", listener, System.getProperties()); log("Acquired MessageQueue Instance:" + mq); final int batchSize = 100; final boolean compressed = mq.compression; final Thread producer = new Thread() { @Override public void run() { log("Producer Thread Started"); try { for (int i = 0; i < Integer.MAX_VALUE; i++) { final Context ctx = writerTime.time(); if (compressed) { for (int x = 0; x < batchSize; x++) { mq.writeEntry(new StreamedMetricValue(System.currentTimeMillis(), tlr.nextDouble(), "foo.bar", AgentName.getInstance().getGlobalTags())); } } else { final ByteBuf buffer = BufferManager.getInstance().directBuffer(batchSize * 128); for (int x = 0; x < batchSize; x++) { new StreamedMetricValue(System.currentTimeMillis(), tlr.nextDouble(), "foo.bar", AgentName.getInstance().getGlobalTags()).intoByteBuf(buffer); } mq.writeEntry(buffer); } ctx.stop(); } } catch (Exception ex) { if (ex instanceof InterruptedException) { mq.log.info("Producer Thread is stopping"); } } } }; producer.setDaemon(true); producer.start(); final AtomicBoolean closed = new AtomicBoolean(false); StdInCommandHandler.getInstance().registerCommand("shutdown", new Runnable() { @Override public void run() { if (closed.compareAndSet(false, true)) { mq.log.info(">>>>> Stopping MessageQueue..."); producer.interrupt(); try { mq.close(); } catch (Exception x) { /* No Op */} mq.log.info("<<<<< MessageQueue Stopped"); System.exit(1); } } }).shutdownHook("shutdown").run(); }
From source file:com.heliosapm.streams.metrics.StreamedMetric.java
License:Open Source License
/** * Reads a streamed metric from the passed buffer * @param buff the buffer to read the streamed metric from * @return the appropriate type of StreamedMetric *///from w w w . j a va2 s. c om public static StreamedMetric[] readAll(final ByteBuf buff) { final Set<StreamedMetric> metrics = new HashSet<StreamedMetric>(); while (buff.isReadable(MIN_READABLE_BYTES)) { metrics.add(read(buff)); } return metrics.toArray(new StreamedMetric[metrics.size()]); }
From source file:com.heliosapm.streams.metrics.StreamedMetric.java
License:Open Source License
/** * Returns an interator over the StreamMetrics in the passed buffer * @param buf The buffer to read from//from ww w. j a v a2s. c o m * @param releaseOnDone true to release the buffer on iterator end * @return the iterator */ public static Iterable<StreamedMetric> streamedMetrics(final ByteBuf buf, final boolean releaseOnDone) { return new Iterable<StreamedMetric>() { @Override public Iterator<StreamedMetric> iterator() { return new Iterator<StreamedMetric>() { @Override public boolean hasNext() { final boolean hasNext = buf.isReadable(MIN_READABLE_BYTES); if (releaseOnDone) buf.release(); return hasNext; } @Override public StreamedMetric next() { return read(buf); } }; } }; }