Filter example - accessing the filtered metadata

This example shows how to access the multimap that is used to store metadata added via the filters and implements a filter that iterates over the metadata and prints out the values to the filter log.

This only applies to metadata that is added via document filters to the metadata multimap, including accessibility auditor metadata. Metadata added via Jsoup filters, embedded document metadata and metadata added via content auditor is not stored within the multimap but inserted into the document content.

Iterate over the stored metadata

The following example iterates over the metadata multimap containing all the metadata added via filters (using metadata.put() calls).

DocumentFilterAccessingFilteredMetadata.java
package com.example.pluginexamples;

import com.funnelback.filter.api.documents.FilterableDocument;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.funnelback.filter.api.FilterContext;
import com.funnelback.filter.api.FilterResult;
import com.funnelback.filter.api.filters.Filter;

import com.google.common.collect.ListMultimap;

import java.util.*;

public class DocumentFilterAccessingFilteredMetadata implements Filter {

    private static final Logger log = LogManager.getLogger(DocumentFilterAccessingFilteredMetadata.class);

    @Override
    public FilterResult filter(FilterableDocument document, FilterContext context) {
        // Print out the key and set of values as "key" : ["val1","val2","val3"]

        ListMultimap<String, String> metadata = document.getCopyOfMetadata(); (1)

        Set<String> keySet = metadata.keySet();
        Iterator keyIterator = keySet.iterator();
        while (keyIterator.hasNext()) {
            String valueString ="";
            String key = (String) keyIterator.next();
            Collection<String> values = metadata.get(key);

            // Iterate over all the values for the key
            Iterator valueIterator = values.iterator();
            while(valueIterator.hasNext()) {
                // get the next value
                String value = (String) valueIterator.next();

                // e.g. add the value to a string
                valueString += "\""+value+"\"";
                if (valueIterator.hasNext()) {
                    valueString +=",";
                }
            }

            log.info("\""+key+"\" : ["+valueString+"]");
        }

        // Create a document with the new metadata
        FilterableDocument filteredDocument = document.cloneWithMetadata(metadata);

        return FilterResult.of(filteredDocument);
    }
}
1 Loads the metadata that has been added via previous filters in the chain.