List of usage examples for io.netty.buffer ByteBuf getByte
public abstract byte getByte(int index);
From source file:com.whizzosoftware.hobson.davisvantage.api.codec.VantageSerialFrameDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf buffer, List<Object> list) throws Exception { int ix = buffer.readerIndex(); int readableBytes = buffer.readableBytes(); logger.trace("Readable bytes remaining to read: {}", readableBytes); if (readableBytes > 0) { if (buffer.readableBytes() >= 6 && buffer.getByte(ix) == 'T' && buffer.getByte(ix + 1) == 'E' && buffer.getByte(ix + 2) == 'S' && buffer.getByte(ix + 3) == 'T' && buffer.getByte(ix + 4) == '\n' && buffer.getByte(ix + 5) == '\r') { buffer.readBytes(6);//from w w w .j a v a 2 s . co m logger.trace("Got TEST"); list.add(new Test()); } else if (buffer.getByte(ix) == '\r' || buffer.getByte(ix) == '\n') { logger.trace("Discarding whitespace: {}", (int) buffer.getByte(ix)); buffer.readByte(); } else if (buffer.getByte(ix) == 0x06) { buffer.readByte(); list.add(new ACK()); } else if (buffer.readableBytes() >= 4 && buffer.getByte(ix) == 'O' && buffer.getByte(ix + 1) == 'K' && buffer.getByte(ix + 2) == '\n' && buffer.getByte(ix + 3) == '\r') { logger.trace("Got OK"); buffer.readBytes(4); list.add(new OK()); } else if (buffer.getByte(ix) == 'L' && buffer.getByte(ix + 1) == 'O' && buffer.getByte(ix + 2) == 'O') { if (buffer.readableBytes() >= 99) { logger.trace("Got LOOP"); byte[] bytes = new byte[99]; buffer.readBytes(bytes, 0, 99); list.add(new LoopResponse(bytes)); } } else if ((buffer.getByte(ix) == 'A' && buffer.getByte(ix + 1) == 'p' && buffer.getByte(ix + 2) == 'r') || (buffer.getByte(ix) == 'A' && buffer.getByte(ix + 1) == 'u' && buffer.getByte(ix + 2) == 'g') || (buffer.getByte(ix) == 'D' && buffer.getByte(ix + 1) == 'e' && buffer.getByte(ix + 2) == 'c') || (buffer.getByte(ix) == 'F' && buffer.getByte(ix + 1) == 'e' && buffer.getByte(ix + 2) == 'b') || (buffer.getByte(ix) == 'J' && buffer.getByte(ix + 1) == 'a' && buffer.getByte(ix + 2) == 'n') || (buffer.getByte(ix) == 'J' && buffer.getByte(ix + 1) == 'u' && buffer.getByte(ix + 2) == 'l') || (buffer.getByte(ix) == 'J' && buffer.getByte(ix + 1) == 'u' && buffer.getByte(ix + 2) == 'n') || (buffer.getByte(ix) == 'M' && buffer.getByte(ix + 1) == 'a' && buffer.getByte(ix + 2) == 'r') || (buffer.getByte(ix) == 'M' && buffer.getByte(ix + 1) == 'a' && buffer.getByte(ix + 2) == 'y') || (buffer.getByte(ix) == 'N' && buffer.getByte(ix + 1) == 'o' && buffer.getByte(ix + 2) == 'v') || (buffer.getByte(ix) == 'O' && buffer.getByte(ix + 1) == 'c' && buffer.getByte(ix + 2) == 't') || (buffer.getByte(ix) == 'D' && buffer.getByte(ix + 1) == 'e' && buffer.getByte(ix + 2) == 'c')) { if (buffer.readableBytes() >= 13) { byte[] bytes = new byte[13]; buffer.readBytes(bytes, 0, 13); list.add(new VersionResponse(new String(bytes, 0, 11))); } } else { byte b = buffer.readByte(); logger.trace("Discarding unknown byte: {}", Hex.encodeHexString(new byte[] { b })); } } }
From source file:com.whizzosoftware.hobson.dsc.api.codec.DSCFrameDecoder.java
License:Open Source License
@Override protected Object decode(ChannelHandlerContext ctx, ByteBuf buffer) throws Exception { logger.trace("decode: {}", buffer.toString(CharsetUtil.UTF_8)); ByteBuf frame = (ByteBuf) super.decode(ctx, buffer); if (frame != null) { try {/*from w w w . j a v a2s. c om*/ if (frame.readableBytes() >= 3) { String cmdId = new String(new byte[] { frame.getByte(0), frame.getByte(1), frame.getByte(2) }); switch (cmdId) { case CodeRequired.ID: return new CodeRequired(); case CommandAcknowledge.ID: return new CommandAcknowledge(); case CommandError.ID: return new CommandError(); case LCDUpdate.ID: int lineNumber = frame.getByte(3) - '0'; int columnNumber = Integer .parseInt(new String(new byte[] { frame.getByte(4), frame.getByte(5) })); int length = Integer .parseInt(new String(new byte[] { frame.getByte(6), frame.getByte(7) })); return new LCDUpdate(lineNumber, columnNumber, frame.slice(8, length).toString(CharsetUtil.UTF_8)); case LEDStatus.ID: return new LEDStatus(LEDStatus.LEDType.forOrdinal(frame.getByte(3) - '0'), LEDStatus.Status.forOrdinal(frame.getByte(4) - '0')); case SoftwareVersion.ID: return new SoftwareVersion(frame.slice(3, 4).toString(CharsetUtil.UTF_8)); case PartitionBusy.ID: return new PartitionBusy(frame.getByte(3) - '0'); case PartitionNotReady.ID: return new PartitionNotReady(frame.getByte(3) - '0'); case PartitionReady.ID: return new PartitionReady(frame.getByte(3) - '0'); case TroubleLEDOff.ID: return new TroubleLEDOff(frame.getByte(3) - '0'); case ZoneOpen.ID: return new ZoneOpen(Integer.parseInt( new String(new byte[] { frame.getByte(3), frame.getByte(4), frame.getByte(5) }))); case ZoneRestored.ID: return new ZoneRestored(Integer.parseInt( new String(new byte[] { frame.getByte(3), frame.getByte(4), frame.getByte(5) }))); case TimeDateBroadcast.ID: return new TimeDateBroadcast(frame.slice(3, 10).toString(CharsetUtil.UTF_8)); default: logger.debug("Ignoring unknown command frame: {}", buffer.toString(CharsetUtil.UTF_8)); return null; } } else { throw new CorruptedFrameException("Frame should not be less than 3 bytes"); } } finally { frame.release(); } } else { return null; } }
From source file:com.whizzosoftware.hobson.lifx.api.codec.LIFXFrameDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext context, Object o, List list) throws Exception { if (o instanceof DatagramPacket) { DatagramPacket p = (DatagramPacket) o; ByteBuf buf = p.content(); if (buf.readableBytes() >= 32) { int length = buf.getByte(0) + (buf.getByte(1) << 8); int type = buf.getByte(32) + (buf.getByte(33) << 8); if (buf.readableBytes() >= length) { switch (type) { case DeviceStateService.TYPE: list.add(readDeviceStateService(p.sender(), buf)); break; case LightState.TYPE: list.add(readLightState(p.sender(), buf)); break; case LightStatePower.TYPE: list.add(readLightStatePower(p.sender(), buf)); break; default: logger.debug("Unknown message type received: {}", type); }/*ww w .ja v a 2 s. c om*/ } else { logger.trace("Ignoring datagram with invalid length: {}", length); } } else { logger.trace("Ignoring datagram with invalid length: {}", buf.readableBytes()); } } }
From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java
License:Open Source License
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (logger.isDebugEnabled()) { logger.debug("RCVD: {}", ByteUtil.createString(in)); }/* w w w . j ava2 s . com*/ ByteBuf data; // if there was data left from the last decode call, create a composite ByteBuf that contains both // previous and new data if (previousBuf != null) { CompositeByteBuf cbuf = Unpooled.compositeBuffer(2); cbuf.addComponent(previousBuf.copy()); cbuf.addComponent(in); cbuf.writerIndex(previousBuf.readableBytes() + in.readableBytes()); data = cbuf; // release the data from the previous decode call previousBuf.release(); previousBuf = null; } else { data = in; } while (data.isReadable()) { // check for single ACK/NAK/CAN if (data.readableBytes() == 1 && isSingleByteFrame(data, data.readerIndex())) { out.add(createSingleByteFrame(data)); } else { boolean foundFrame = false; // search for a valid frame in the data for (int searchStartIx = data.readerIndex(); searchStartIx < data.readerIndex() + data.readableBytes(); searchStartIx++) { if (data.getByte(searchStartIx) == DataFrame.START_OF_FRAME) { int frameEndIx = scanForFrame(data, searchStartIx); if (frameEndIx > 0) { if (searchStartIx > data.readerIndex() && isSingleByteFrame(data, searchStartIx - 1)) { data.readerIndex(searchStartIx - 1); out.add(createSingleByteFrame(data)); } else if (searchStartIx > data.readerIndex()) { data.readerIndex(searchStartIx); } DataFrame df = createDataFrame(data); if (df != null) { out.add(df); data.readByte(); // discard checksum foundFrame = true; } else { logger.debug("Unable to determine frame type"); } } } } if (!foundFrame) { previousBuf = data.copy(); break; } } } // make sure we read from the input ByteBuf so Netty doesn't throw an exception in.readBytes(in.readableBytes()); logger.trace("Done processing received data: {}", out); }
From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java
License:Open Source License
private boolean isSingleByteFrame(ByteBuf data, int ix) { byte b = data.getByte(ix); return (b == ACK.ID || b == NAK.ID || b == CAN.ID); }
From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java
License:Open Source License
private int scanForFrame(ByteBuf data, int startIndex) { int readableBytes = data.readableBytes(); if (data.getByte(startIndex) == DataFrame.START_OF_FRAME && startIndex + 1 < data.readerIndex() + readableBytes) { byte frameLen = data.getByte(startIndex + 1); int checksumIx = startIndex + frameLen + 1; if (frameLen > 0 && checksumIx < data.readerIndex() + readableBytes) { byte frameChecksum = data.getByte(checksumIx); byte checksum = 0; for (int i = startIndex + 1; i < checksumIx; i++) { checksum ^= data.getByte(i); }// w w w . j a v a 2 s . c o m checksum = (byte) (~checksum); if (frameChecksum == checksum) { return checksumIx; } } } return -1; }
From source file:com.whizzosoftware.wzwave.codec.ZWaveFrameDecoder.java
License:Open Source License
/** * Creates a Z-Wave DataFrame from a ByteBuf. * * @param buf the buffer to process/*from w w w . ja v a 2 s .c o m*/ * * @return a DataFrame instance (or null if a valid one wasn't found) */ private DataFrame createDataFrame(ByteBuf buf) { if (buf.readableBytes() > 3) { byte messageType = buf.getByte(buf.readerIndex() + 3); switch (messageType) { case Version.ID: return new Version(buf); case MemoryGetId.ID: return new MemoryGetId(buf); case InitData.ID: return new InitData(buf); case NodeProtocolInfo.ID: return new NodeProtocolInfo(buf); case SendData.ID: return new SendData(buf); case ApplicationCommand.ID: return new ApplicationCommand(buf); case ApplicationUpdate.ID: return new ApplicationUpdate(buf); case RequestNodeInfo.ID: return new RequestNodeInfo(buf); case GetRoutingInfo.ID: return new GetRoutingInfo(buf); case GetSUCNodeId.ID: return new GetSUCNodeId(buf); case AddNodeToNetwork.ID: return new AddNodeToNetwork(buf); case RemoveNodeFromNetwork.ID: return new RemoveNodeFromNetwork(buf); case SetDefault.ID: return new SetDefault(buf); } } return null; }
From source file:com.whizzosoftware.wzwave.util.ByteUtil.java
License:Open Source License
static public String createString(ByteBuf buf) { int length = buf.readableBytes(); char[] hexChars = new char[length * 5]; int v;/*from ww w .jav a2s .co m*/ int i = 0; for (int j = buf.readerIndex(); j < buf.readerIndex() + length; j++) { v = buf.getByte(j) & 0xFF; hexChars[i * 5] = '0'; hexChars[i * 5 + 1] = 'x'; hexChars[i * 5 + 2] = hexArray[v >>> 4]; hexChars[i * 5 + 3] = hexArray[v & 0x0F]; hexChars[i * 5 + 4] = ' '; i++; } return new String(hexChars); }
From source file:com.yahoo.pulsar.utils.NumberFormat.java
License:Apache License
static void format(ByteBuf out, long num) { if (num == 0) { out.writeByte('0'); return;//ww w . ja v a 2 s.c om } // Long.MIN_VALUE needs special handling since abs(Long.MIN_VALUE) = abs(Long.MAX_VALUE) + 1 boolean encounteredMinValue = (num == Long.MIN_VALUE); if (num < 0) { out.writeByte('-'); num += encounteredMinValue ? 1 : 0; num *= -1; } // Putting the number in bytebuf in reverse order int start = out.writerIndex(); formatHelper(out, num); int end = out.writerIndex(); if (encounteredMinValue) { out.setByte(start, out.getByte(start) + 1); } // Reversing the digits end--; for (int i = 0; i <= (end - start) / 2; i++) { byte tmp = out.getByte(end - i); out.setByte(end - i, out.getByte(start + i)); out.setByte(start + i, tmp); } }
From source file:dorkbox.network.connection.KryoExtra.java
License:Apache License
/** * This is NOT ENCRYPTED (and is only done on the loopback connection!) */// ww w .j av a2 s . c o m public synchronized void writeCompressed(final Connection_ connection, final ByteBuf buffer, final Object message) throws IOException { // required by RMI and some serializers to determine which connection wrote (or has info about) this object this.rmiSupport = connection.rmiSupport(); ByteBuf objectOutputBuffer = this.tempBuffer; objectOutputBuffer.clear(); // always have to reset everything // write the object to a TEMP buffer! this will be compressed writer.setBuffer(objectOutputBuffer); writeClassAndObject(writer, message); // save off how much data the object took + magic byte int length = objectOutputBuffer.writerIndex(); // NOTE: compression and encryption MUST work with byte[] because they use JNI! // Realistically, it is impossible to get the backing arrays out of a Heap Buffer once they are resized and begin to use // sliced. It's lame that there is a "double copy" of bytes here, but I don't know how to avoid it... // see: https://stackoverflow.com/questions/19296386/netty-java-getting-data-from-bytebuf byte[] inputArray; int inputOffset; // Even if a ByteBuf has a backing array (i.e. buf.hasArray() returns true), the using it isn't always possible because // the buffer might be a slice of other buffer or a pooled buffer: //noinspection Duplicates if (objectOutputBuffer.hasArray() && objectOutputBuffer.array()[0] == objectOutputBuffer.getByte(0) && objectOutputBuffer.array().length == objectOutputBuffer.capacity()) { // we can use it... inputArray = objectOutputBuffer.array(); inputArrayLength = -1; // this is so we don't REUSE this array accidentally! inputOffset = objectOutputBuffer.arrayOffset(); } else { // we can NOT use it. if (length > inputArrayLength) { inputArrayLength = length; inputArray = new byte[length]; this.inputArray = inputArray; } else { inputArray = this.inputArray; } objectOutputBuffer.getBytes(objectOutputBuffer.readerIndex(), inputArray, 0, length); inputOffset = 0; } ////////// compressing data // we ALWAYS compress our data stream -- because of how AES-GCM pads data out, the small input (that would result in a larger // output), will be negated by the increase in size by the encryption byte[] compressOutput = this.compressOutput; int maxLengthLengthOffset = 4; // length is never negative, so 4 is OK (5 means it's negative) int maxCompressedLength = compressor.maxCompressedLength(length); // add 4 so there is room to write the compressed size to the buffer int maxCompressedLengthWithOffset = maxCompressedLength + maxLengthLengthOffset; // lazy initialize the compression output buffer if (maxCompressedLengthWithOffset > compressOutputLength) { compressOutputLength = maxCompressedLengthWithOffset; compressOutput = new byte[maxCompressedLengthWithOffset]; this.compressOutput = compressOutput; } // LZ4 compress. output offset max 4 bytes to leave room for length of tempOutput data int compressedLength = compressor.compress(inputArray, inputOffset, length, compressOutput, maxLengthLengthOffset, maxCompressedLength); // bytes can now be written to, because our compressed data is stored in a temp array. final int lengthLength = OptimizeUtilsByteArray.intLength(length, true); // correct input. compression output is now buffer input inputArray = compressOutput; inputOffset = maxLengthLengthOffset - lengthLength; // now write the ORIGINAL (uncompressed) length to the front of the byte array (this is NOT THE BUFFER!). This is so we can use the FAST decompress version OptimizeUtilsByteArray.writeInt(inputArray, length, true, inputOffset); // have to copy over the orig data, because we used the temp buffer. Also have to account for the length of the uncompressed size buffer.writeBytes(inputArray, inputOffset, compressedLength + lengthLength); }