FilterChains
can be compared to Unix pipes. Unix pipes add a
great deal of flexibility to command line operations; for example, if you wanted to
copy just those lines that contained the string blee
from the
first 10 lines of a file called foo
to a file called
bar
, you could do:
cat foo | head -n10 | grep blee > bar
Something like this is not possible with the tasks and types that we have learned
about thus far, and this is where the incredible usefulness of
FilterChains
becomes apparent. They emulate Unix pipes and
provide a powerful dimension of file/stream manipulation for the tasks that support
them.
FilterChain
usage is quite straightforward: you pass the
complex Phing type filterchain
to a task that supports
FilterChains and add individual filters to the FilterChain. In the course of
executing the task, the filters are applied (in the order in which they appear in
the XML) to the contents of the files that are being manipulated by your task.
<filterchain> <replacetokens> <token key="BC_PATH" value="${top.builddir}/"/> <token key="BC_PATH_USER" value="${top.builddir}/testsite/user/${lang}/"/> </replacetokens> <filterreader classname="phing.filters.TailFilter"> <param name="lines" value="10"/> </filterreader> </filterchain>
The code listing above shows you some example of how to use filter chains. For a
complete reference see Core Types. This filter chain would
replace all occurrences of BC_PATH
and
BC_PATH_USER
with the values assigned to them in lines 4 and
5. Additionally, it will only return the last 10 lines of the files.
Notice above that FilterChain
filters have a "shorthand"
notation and a long, generic notation. Most filters can be described using both of
these forms:
<replacetokens> <token key="BC_PATH" value="${top.builddir}/"/> <token key="BC_PATH_USER" value="${top.builddir}/testsite/user/${lang}/"/> </replacetokens> <!-- OR: --> <filterreader classname="phing.filters.ReplaceTokens"> <param type="token" name="BC_PATH" value="${top.builddir}/"/> <param type="token" name="BC_PATH" value="${top.builddir}/testsite/user/${lang}/"/> </filterreader>
As the pipe concept in Unix, the filter concept is quite complex but powerful. To get a better understanding of different filters and how they can be used, take a look at any of the many uses of FilterChains in the build files for the binarycloud Bibliography project.