3.4 - Formatting packets for text output
Sometimes you want to just take a look at what the packet looks like. You can use a packet formatter to dump as normal text the contents of the packet.
All packets have a builtin
TextFormatter hooked onto its
JPacket.toString() method. This text formatter uses a standard JRE
StringBuilder as the output device, formats and dumps the contents of the packet to the string buffer and at the end does a
return buffer.toString() to convert the contents of the string buffer to a normal string.
This is a pretty looking output to prints out full detail about every header within the packet. There are additional formatters such as
XmlFormatter. This formatter dumps the contents of the packet in XML format. Additional formatters will be supplied in the future, and if the user develops an interesting formatter contributions back to the project are apprechiated.
Additional formatters that are planned for the future are
HtmlTableFormatter. The first would generate HTML out which depends on CSS for layout, while the second formatter would generate output layed out using standard HTML tables. Both would be suitable for sending to a HTML browser for pretty output of the packet.
Now that we've seen and talked about the basics. It is inefficient to generate what sometimes can be many kilo bytes of textual output, convert that output to a long inefficient string to only send it out standard output device. The better approach is to use the
JFormater.format() method where we supply our packet as a parameter. This way we have the option of creating a formatter that sends its output to
System.out directly instead of intermediate buffers.
XmlFormatter out = new XmlFormatter(System.out); out.format(packet);
And we get nice XML output sent to our console. We could have used output type. The only requirement that
JFormatter constructor sets is the
Appendable interface. As you may suspect both StringBuilder and Syste.out's
PrintStream implement the
Appendable interface. It would be a trivial task to setup a TCP socket between systems enclose the socket in a
PrintStream implementation and pass that in to our formatter which would sent its output directly to a socket.