use of io.netty.handler.codec.Delimiters in project openremote by openremote.
the class AbstractIOClientProtocol method getGenericStringEncodersAndDecoders.
/**
* Supplies a set of encoders/decoders that convert from/to {@link String} to/from {@link ByteBuf} based on the generic protocol {@link Attribute}s
*/
public static Supplier<ChannelHandler[]> getGenericStringEncodersAndDecoders(AbstractNettyIOClient<String, ?> client, IOAgent<?, ?, ?> agent) {
boolean hexMode = agent.getMessageConvertHex().orElse(false);
boolean binaryMode = agent.getMessageConvertBinary().orElse(false);
Charset charset = agent.getMessageCharset().map(Charset::forName).orElse(CharsetUtil.UTF_8);
int maxLength = agent.getMessageMaxLength().orElse(Integer.MAX_VALUE);
String[] delimiters = agent.getMessageDelimiters().orElse(new String[0]);
boolean stripDelimiter = agent.getMessageStripDelimiter().orElse(false);
return () -> {
List<ChannelHandler> encodersDecoders = new ArrayList<>();
if (hexMode || binaryMode) {
encodersDecoders.add(new AbstractNettyIOClient.MessageToByteEncoder<>(String.class, client, (msg, out) -> {
byte[] bytes = hexMode ? ProtocolUtil.bytesFromHexString(msg) : ProtocolUtil.bytesFromBinaryString(msg);
out.writeBytes(bytes);
}));
if (delimiters.length > 0) {
ByteBuf[] byteDelimiters = Arrays.stream(delimiters).map(delim -> Unpooled.wrappedBuffer(hexMode ? ProtocolUtil.bytesFromHexString(delim) : ProtocolUtil.bytesFromBinaryString(delim))).toArray(ByteBuf[]::new);
encodersDecoders.add(new DelimiterBasedFrameDecoder(maxLength, stripDelimiter, byteDelimiters));
} else {
encodersDecoders.add(new FixedLengthFrameDecoder(maxLength));
}
// Incoming messages will be bytes
encodersDecoders.add(new AbstractNettyIOClient.ByteToMessageDecoder<>(client, (byteBuf, messages) -> {
byte[] bytes = new byte[byteBuf.readableBytes()];
byteBuf.readBytes(bytes);
String msg = hexMode ? ProtocolUtil.bytesToHexString(bytes) : ProtocolUtil.bytesToBinaryString(bytes);
messages.add(msg);
}));
} else {
encodersDecoders.add(new StringEncoder(charset));
if (agent.getMessageMaxLength().isPresent()) {
encodersDecoders.add(new FixedLengthFrameDecoder(maxLength));
} else {
ByteBuf[] byteDelimiters;
if (delimiters.length > 0) {
byteDelimiters = Arrays.stream(delimiters).map(delim -> Unpooled.wrappedBuffer(delim.getBytes(charset))).toArray(ByteBuf[]::new);
} else {
byteDelimiters = Delimiters.lineDelimiter();
}
encodersDecoders.add(new DelimiterBasedFrameDecoder(maxLength, stripDelimiter, byteDelimiters));
}
encodersDecoders.add(new StringDecoder(charset));
encodersDecoders.add(new AbstractNettyIOClient.MessageToMessageDecoder<>(String.class, client));
}
return encodersDecoders.toArray(new ChannelHandler[0]);
};
}
Aggregations