This tutorial describes how to write a
Macro that uses List Formatters. For an tutorial about list formatters see
List Formatter Tutorial 1. List formatters give you the ability to let your users change the output of your macro. They can be reused by different macro authors, for example to output a AtoZ style with your macro, reuse the AtoZ style formatter.
Introduction
The easiest way to use list formatters with your macros is to inherit from org.snipsnap.snip.filter.macro.ListOutputMacro. Instead of writing to the writer for outputing your list of "things" (Snips, Users, etc.) you use the
output method of ListOutputMacro:
public void output(Writer writer, String listComment,
Collection c, String emptyText, String style,
boolean showSize) throws IOException;
which takes a
java.io.Writer object, a comment for the list, the collection with things to ouput, an empty text to display when the collection is empty and whether the formatter should output the size of the collection.
Example
An example for a Macro using a List Formatter is the index macro:
public void execute(Writer writer, MacroParameter params)
throws IllegalArgumentException,IOException {
String type = null;
boolean showSize = true;
if(params != null) {
if(params.getLength() > 0) {
type = params.get("0");
}
} if (params == null || params.getLength() <= 2) {
output(writer, "All Snips:", SnipSpace.getInstance().getAll(),
"none written yet.", type, showSize);
} else {
throw new IllegalArgumentException("Number of arguments does not match");
}
}
This reads the style of the formatter from the parameters (type), e.g. {index:AtoZ} will put "AtoZ" into type. Then the output method is called with a collection of all snips in the system.
Filtering output
To improve this, the index macro uses a filter to filter all snips out that start with "comment-". To do this use Collections.filter:
Collections.filter(SnipSpace.getInstance().getAll(),
new Filterator() {
public boolean filter(Object obj) {
String name = ((Snip) obj).getName();
if (name.startsWith("comment-")) {
return true;
}
return false;
}
}
Sorting output
The same idea could be used to sort the snips before output. To do this, use
java.util.Collections with the
sort method.