List of usage examples for io.netty.buffer ByteBuf readByte
public abstract byte readByte();
From source file:com.heliosapm.streams.metrics.StreamedMetricValue.java
License:Apache License
/** * Updates this StreamedMetricValue using the next serialized version in the passed ByteBuf. * @param buf The buffer to update from//from ww w . j a va2 s . com * @return this StreamedMetricValue */ @Override public StreamedMetricValue update(final ByteBuf buf) { super.update(buf); if (buf.readByte() == ZERO_BYTE) { isDoubleValue = true; doubleValue = buf.readDouble(); } else { isDoubleValue = false; longValue = buf.readLong(); } return this; }
From source file:com.heliosapm.streams.metrics.StreamedMetricValue.java
License:Apache License
/** * Returns an interator over the StreamMetricValues in the passed buffer * @param singleInstance If true, the StreamMetricValue returns from the iterator will be the same actual instance, updated on each loop of the iterator. * As such, the returned StreamMetricValue should be used before the next iterator loop since the values of that instance will change. * In other words, attempting to stash all the returned StreamMetricValues in a collection, or the like, will void the warranty. * @param buf The buffer to read from/*w w w .j a v a2s. c om*/ * @param releaseOnDone true to release the buffer on iterator end * @return the iterator * FIXME: all this stuff needs to return SM or SMV */ public static Iterable<StreamedMetricValue> streamedMetricValues(final boolean singleInstance, final ByteBuf buf, final boolean releaseOnDone) { final StreamedMetricValue single = singleInstance ? new StreamedMetricValue() : null; return new Iterable<StreamedMetricValue>() { @Override public Iterator<StreamedMetricValue> iterator() { return new Iterator<StreamedMetricValue>() { @Override public boolean hasNext() { final boolean hasNext = buf.readableBytes() > MIN_READABLE_BYTES; if (!hasNext && releaseOnDone) buf.release(); return hasNext; } @Override public StreamedMetricValue next() { if (singleInstance) { buf.readByte(); return single.update(buf); } return read(buf).forValue(1L); } }; } }; }
From source file:com.heliosapm.streams.metrics.StreamedMetricValue.java
License:Apache License
/** * Reads a StreamedMetricValue from the passed buffer * @param buff The buffer to read from/*from w w w . j av a 2 s . c o m*/ * @return the StreamedMetricValue */ public static StreamedMetricValue from(final ByteBuf buff) { buff.readByte(); final byte vt = buff.readByte(); final ValueType valueType = vt == 0 ? null : ValueType.ordinal(vt); final long ts = buff.readLong(); final String mn = BufferManager.readUTF(buff); final int tagCount = buff.readByte(); final Map<String, String> tags = new HashMap<String, String>(tagCount); for (int i = 0; i < tagCount; i++) { tags.put(BufferManager.readUTF(buff), BufferManager.readUTF(buff)); } final byte lord = buff.readByte(); if (lord == 0) { return new StreamedMetricValue(ts, buff.readDouble(), mn, tags).setValueType(valueType); } return new StreamedMetricValue(ts, buff.readLong(), mn, tags).setValueType(valueType); }
From source file:com.heliosapm.streams.metrics.StreamedMetricValue.java
License:Apache License
/** * Creates a StreamedMetricValue from the passed buffer * @param bytes The byte to read the StreamedMetric from * @return the created StreamedMetric/*from w w w . ja v a2s . co m*/ */ static StreamedMetricValue fromBuff(final ByteBuf buff) { final StreamedMetricValue sm = new StreamedMetricValue(); sm.byteSize = buff.readableBytes() + 1; sm.readFromBuff(buff); final byte type = buff.readByte(); if (type == 0) { sm.isDoubleValue = true; sm.doubleValue = buff.readDouble(); } else { sm.isDoubleValue = false; sm.longValue = buff.readLong(); } return sm; }
From source file:com.ibasco.agql.core.utils.ByteBufUtils.java
License:Open Source License
public static String readString(ByteBuf buffer, Charset encoding, boolean readNonNullTerminated, String defaultString) {//from www. jav a2 s . com int length = buffer.bytesBefore((byte) 0); if (length < 0) { if (readNonNullTerminated && buffer.readableBytes() > 0) length = buffer.readableBytes(); else return null; } String data = buffer.readCharSequence(length, encoding).toString(); //Discard the null terminator (if available) if (buffer.readableBytes() > 2 && buffer.getByte(buffer.readerIndex()) == 0) buffer.readByte(); return data; }
From source file:com.ibasco.agql.protocols.valve.source.query.handlers.SourceQueryPacketAssembler.java
License:Open Source License
/** * Process split-packet data// ww w . ja va 2 s.c om * * @param data * The {@link ByteBuf} containing the split-packet data * @param allocator * The {@link ByteBufAllocator} used to create/allocate pooled buffers * * @return Returns a non-null {@link ByteBuf} if the split-packets have been assembled. Null if the * * @throws Exception */ private ByteBuf processSplitPackets(ByteBuf data, ByteBufAllocator allocator, InetSocketAddress senderAddress) throws Exception { int packetCount, packetNumber, requestId, splitSize, packetChecksum = 0; boolean isCompressed; //Start processing requestId = data.readIntLE(); //read the most significant bit is set isCompressed = ((requestId & 0x80000000) != 0); //The total number of packets in the response. packetCount = data.readByte(); //The number of the packet. Starts at 0. packetNumber = data.readByte(); //Create our key for this request (request id + sender ip) final SplitPacketKey key = new SplitPacketKey(requestId, senderAddress); log.debug("Processing split packet {}", key); log.debug( "Split Packet Received = (AbstractRequest {}, Packet Number {}, Packet Count {}, Is Compressed: {})", requestId, packetNumber, packetCount, isCompressed); //Try to retrieve the split packet container for this request (if existing) //If request is not yet on the map, create and retrieve SplitPacketContainer splitPackets = this.requestMap.computeIfAbsent(key, k -> new SplitPacketContainer(packetCount)); //As per protocol specs, the size is only present in the first packet of the response and only if the response is being compressed. //split size = Maximum size of packet before packet switching occurs. The default value is 1248 bytes (0x04E0 if (isCompressed) { splitSize = data.readIntLE(); packetChecksum = data.readIntLE(); } else { splitSize = data.readShortLE(); } //TODO: Handle compressed split packets int bufferSize = Math.min(splitSize, data.readableBytes()); byte[] splitPacket = new byte[bufferSize]; data.readBytes(splitPacket); //transfer the split data into this buffer //Add the split packet to the container splitPackets.addPacket(packetNumber, splitPacket); //Have we received all packets for this request? if (splitPackets.isComplete()) { log.debug( "Split Packets have all been successfully received from AbstractRequest {}. Re-assembling packets.", requestId); //Retrieve total split packets received based on their length int packetSize = splitPackets.getPacketSize(); //Allocate a new buffer to store the re-assembled packets final ByteBuf packetBuffer = allocator.buffer(packetSize); boolean done = false; try { //Start re-assembling split-packets from the container done = reassembleSplitPackets(splitPackets, packetBuffer, isCompressed, splitSize, packetChecksum); } catch (Exception e) { //If an error occurs during re-assembly, make sure we release the allocated buffer packetBuffer.release(); throw e; } finally { if (done) requestMap.remove(key); } return packetBuffer; } //Return null, indicating that we still don't have a complete packet return null; }
From source file:com.ibasco.agql.protocols.valve.source.query.packets.response.SourceInfoResponsePacket.java
License:Open Source License
@Override public SourceServer toObject() { ByteBuf data = getPayloadBuffer(); SourceServer server = new SourceServer(); //Start Decoding server.setNetworkVersion(data.readByte()); server.setName(readString(data));/*from ww w.j a v a2 s .c o m*/ server.setMapName(readString(data)); server.setGameDirectory(readString(data)); server.setGameDescription(readString(data)); server.setAppId(data.readShortLE()); server.setNumOfPlayers(data.readByte()); server.setMaxPlayers(data.readByte()); server.setNumOfBots(data.readByte()); server.setDedicated(data.readByte() == 1); server.setOperatingSystem((char) data.readByte()); server.setPasswordProtected(data.readByte() == 1); server.setSecure(data.readByte() == 1); server.setGameVersion(readString(data)); if (data.readableBytes() > 0) { byte extraDataFlag = data.readByte(); if ((extraDataFlag & EDF_GAME_PORT) != 0) { data.readShortLE(); //discard, we already know which port based on the sender address } if ((extraDataFlag & EDF_SERVER_ID) != 0) { //this.info.put("serverId", Long.reverseBytes((this.contentData.getInt() << 32) | this.contentData.getInt())); server.setServerId(data.readLongLE()); } if ((extraDataFlag & EDF_SOURCE_TV) != 0) { server.setTvPort(data.readShortLE()); server.setTvName(readString(data)); } if ((extraDataFlag & EDF_SERVER_TAGS) != 0) { server.setServerTags(readString(data)); } if ((extraDataFlag & EDF_GAME_ID) != 0) { server.setGameId(data.readLongLE()); //this.info.put("gameId", Long.reverseBytes((this.contentData.getInt() << 32) | this.contentData.getInt())); } } return server; }
From source file:com.ibasco.agql.protocols.valve.source.query.packets.response.SourcePlayerResponsePacket.java
License:Open Source License
@Override public List<SourcePlayer> toObject() { ByteBuf data = getPayloadBuffer(); List<SourcePlayer> playerList = new ArrayList<>(); byte numOfPlayers = data.readByte(); for (int i = 0; i < numOfPlayers; i++) playerList.add(new SourcePlayer(data.readByte(), ByteBufUtils.readString(data, CharsetUtil.UTF_8), data.readIntLE(), Float.intBitsToFloat(data.readIntLE()))); return playerList; }
From source file:com.ibasco.agql.protocols.valve.source.query.SourcePacketBuilder.java
License:Open Source License
@Override public <T extends SourceServerPacket> T construct(ByteBuf data) { //Mark Index/*from w ww. j a v a2 s. c o m*/ data.markReaderIndex(); try { //Reset the index data.readerIndex(0); //Verify size if (data.readableBytes() < 5) throw new IllegalStateException( "Cannot continue processing buffer with less than or equal to 4 bytes"); //Read protocol header int protocolHeader = data.readIntLE(); //Check if this is a split packet if (protocolHeader == 0xFFFFFFFE) throw new IllegalStateException("Cannot construct a response from a partial/split packet."); //Verify that we have a valid header if (protocolHeader != 0xFFFFFFFF) throw new IllegalStateException("Protocol header not supported."); //Read packet header byte packetHeader = data.readByte(); //Read payload byte[] payload = new byte[data.readableBytes()]; data.readBytes(payload); //Verify if packet header is valid SourceServerPacket packet = createResponsePacketFromHeader(packetHeader); //If packet is empty, means the supplied packet header is not supported if (packet == null) return null; packet.setProtocolHeader(ByteUtils.byteArrayFromInteger(protocolHeader)); packet.setHeader(packetHeader); packet.setPayload(payload); return (T) packet; } finally { data.resetReaderIndex(); } }
From source file:com.ibasco.agql.protocols.valve.steam.master.packets.MasterServerResponsePacket.java
License:Open Source License
@Override public Vector<InetSocketAddress> toObject() { ByteBuf data = getPayloadBuffer(); //Clear the list servers.clear();// ww w. ja v a 2 s .c o m int firstOctet, secondOctet, thirdOctet, fourthOctet, portNumber; //Process the content containing list of source ips do { //Clear string ip.setLength(0); firstOctet = data.readByte() & 0xFF; secondOctet = data.readByte() & 0xFF; thirdOctet = data.readByte() & 0xFF; fourthOctet = data.readByte() & 0xFF; portNumber = data.readShort() & 0xFFFF; //Build our ip string ip.append(firstOctet).append(".").append(secondOctet).append(".").append(thirdOctet).append(".") .append(fourthOctet); //Add to the list servers.add(new InetSocketAddress(ip.toString(), portNumber)); //Append port number ip.append(":").append(portNumber); } while (data.readableBytes() > 0); return servers; }