HOW TO: Declarative MIME Type Resolvers

Overview

A MIME type resolver's responsibility is to return on
request a given
FileObject's
MIME content type.

A MIME type resolver can be any object implementing
MIMEResolver.
All MIME resolvers in the system are consulted; they are found by
searching in
lookup
and conventionally should be registered in the folder
Services/MIMEResolver/ in a module's layer.

A MIME resolver would typically try to guess MIME type from
characteristics of the file such as extension or first few lines of
content. In the case that there is a MIME resolver recognizing Ant
project files and another recognizing EJB deployment descriptors, then
files with the *.xml extension would be parsed twice, at
least for their root element.

Problems

This introduces a performance problem as the number of MIME type
resolvers grows. The MIME resolver manager may cache literal file
headers for speed, but invoking an XML parser (for example) still
incurs a penalty.

It is also error-prone to write such a resolver.

Declarative MIME Type Resolvers

To solve both of the above problems a developer should use a
declarative MIME type resolver. The semantics of the MIME resolution
may be specified in a simple manner and an implementation is available
that will interpret the declaration as efficiently as possible.

The semantics is described in an XML document following
a documented DTD. The
DTD documentation
provides details of the permitted syntax.

How to Create a Resolver XML File

Create a valid XML document according to the MIME resolver DTD
grammar and place it in a lookup-registration area (such as
Services/MIMEResolver/).

A simple example follows which might be used to recognize Ant
project files.

First, the DOCTYPE ensures that the XML file will be recognized as
a resolver (by its public ID). The first <file/>
block is a negative template - if it matches the resolver terminates
and returns null (meaning it made no decision about the
file). The second block automatically returns the Ant MIME type (here
an XML subtype) for files tagged as being definitely Ant scripts
(regardless of content and extension). The last block matches any XML
file (that is, *.xml) whose root element is
<project/> and contains at least the attribute
default (value unspecified).

Register this file using @MIMEResolver.Registration
annotation. It allows to specify nice display name and position among other resolvers in the Services/MIMEResolver
folder.

Note that an open position
in the system filesystem should be specified.
Smaller positions mean the resolver runs earlier, which is appropriate for
commonly used file types, or resolvers which logically must take precedence
over more generic resolvers.