Creating a Filter with ObjectInputFilter Methods
The ObjectInputFilter
interface includes the following
static methods that enable you to quickly create filters:
- allowFilter(Predicate<Class<?>>, ObjectInputFilter.Status)
- rejectFilter(Predicate<Class<?>>, ObjectInputFilter.Status)
- rejectUndecidedClass(ObjectInputFilter)
- merge(ObjectInputFilter, ObjectInputFilter)
The allowFilter method creates a filter based
on a Predicate
that takes a Class
as its argument. The
created filter returns ObjectInputFilter.Status.ALLOWED
if the
predicate is true. Otherwise, it returns the value of the allowFilter
method’s second argument. The following creates a filter that accepts the
Integer
class. All other classes are considered undecided:
ObjectInputFilter intFilter = ObjectInputFilter.allowFilter(
cl -> cl.equals(Integer.class), ObjectInputFilter.Status.UNDECIDED);
The rejectFilter method is the inverse of
allowFilter
: It creates a filter based on a Predicate that takes a Class as its
argument. The created filter returns ObjectInputFilter.Status.REJECTED if the predicate is true. Otherwise, it
returns the value of the rejectFilter method’s second
argument. The following creates a filter that rejects any class loaded from the
application class loader:
ObjectInputFilter f = ObjectInputFilter.rejectFilter(cl ->
cl.getClassLoader() == ClassLoader.getSystemClassLoader(), Status.UNDECIDED);
The rejectUndecidedClass
method creates a new filter based
on an existing filter by rejecting any class that the existing filter considers as
undecided. The following creates a filter based on intFilter
. It
accepts the Integer
class but rejects all other (undecided) classes:
ObjectInputFilter rejectUndecidedFilter =
ObjectInputFilter.rejectUndecidedClass(intFilter);
The merge
method creates a new filter by merging two
filters. The following merges the filters intFilter
and
f
. It accepts the Integer
class but rejects any
class loaded from the application class loader:
ObjectInputFilter mergedFilter = ObjectInputFilter.merge(intFilter, f);
A merged filter follows these steps when it filters a class:
- Return Status.REJECTED if either of its filters return Status.REJECTED.
- Return Status.ACCEPTED if either of its filters return Status.ACCEPTED.
- Return Status.UNDECIDED (both of its filters return Status.UNDECIDED).
The merge
method is useful in filter factories. Every time
a filter is set on a stream, you can append that filter to the one that the filter
factory creates with the merge
method. See the ObjectInputFilter
API documentation for an example.
Note:
It's a good idea to merge the JVM-wide filter with the requested, stream-specific filter in your filter factory. If you just return the requested filter, then you effectively disable the JVM-wide filter, which will lead to security gaps.