### Configure component properties in pom.xml Source: https://github.com/apache/commons-collections/blob/master/CONTRIBUTING.md Example of setting the required commons.jira.id property within the project's pom.xml file. ```xml MATH ``` -------------------------------- ### Implement Sharding with Bloom Filters Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md This Java example demonstrates how to distribute data across multiple storage locations by using Bloom filters as gatekeepers. It calculates the Hamming distance between the item's Bloom filter and the gatekeeper filters to select the optimal storage location. ```java import org.apache.commons.collections4.bloomfilter.BloomFilter; import org.apache.commons.collections4.bloomfilter.SetOperations; import org.apache.commons.collections4.bloomfilter.Shape; import org.apache.commons.collections4.bloomfilter.SimpleBloomFilter; import Storage; // a class that implements the actual storage I/O class ShardingExample { private BloomFilter[] gatekeeper; private Storage[] storage; /** * Constructor. Assumes 10K items in filter with false positive rate of 0.01 * @param storage The storage locations to store the objects in. */ public ShardingExample(Storage[] storage) { this(storage, Shape.fromNP(10000, 0.01)); } /** * Constructor. * @param storage The storage locations to store the objects in. * @param shape The shape for the gatekeeper Bloom filters. */ public ShardingExample(Storage[] storage, Shape shape) { gatekeeper = new BloomFilter[storage.length]; this.storage = storage; for (int i = 0; i < gatekeeper.length; i++) { gatekeeper[i] = new SimpleBloomFilter(shape); } } /** * Creates the BloomFilter for the key. * @param objectKey The key to hash. * @return the BloomFilter for the key. */ private BloomFilter createBloomFilter(Object objectKey) { byte[] bytes = SerializationUtils.serialize(o); long[] hash = MurmurHash3.hash128(bytes); BloomFilter bloomFilter = new SimpleBloomFilter(gatekeeper[0].getShape()); bloomFilter.merge(new EnhancedDoubleHasher(hash[0], hash[1])); return bloomFilter; } /** * Write an object into the filter. * @param itemKey The item key for the storage layer. * @param itemToStore The item to store. */ public void write(Object itemKey, Object itemToStore) { // create the Bloom filter to for key BloomFilter itemBloomFilter = createBloomFilter(itemKey); // find the storage to insert into. int selected = 0; int hammingValue = Integer.MAX_INT; for (int i = 0; i < gatekeeper.length; i++) { int hamming = SetOperations.hammingDistance(gatekeeper[i], itemBloomFilter); if (hamming < hammingValue) { selected = i; hammingValue = hamming; } } // insert the data. storage[selected].write(itemKey, itemToStore); gatekeeper[selected].merge(itemBloomFilter); } /** * Reads the item from the storage. * @param itemKey The key to look for. * @return The stored object or null if not found. */ public Object read(Object itemKey) { // create the Bloom filter to look for BloomFilter itemBloomFilter = createBloomFilter(itemKey); // assumes storage returns null if key not found. for (int i = 0; i < gatekeeper.length; i++) { if (gatekeeper[i].contains(itemBloomFilter)) { Object itemThatWasStored = storage[i].read(itemKey); if (itemThatWasStored != null) { return itemThatWasStored; } } } return null; } } ``` -------------------------------- ### Populating a Bloom filter Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/implementation.md Demonstrates how to populate a Bloom filter by defining a shape based on expected item count and false positive rate, then merging serialized object hashes. ```java import org.apache.commons.codec.digest.MurmurHash3; import org.apache.commons.collections4.bloomfilter.BloomFilter; import org.apache.commons.collections4.bloomfilter.EnhancedDoubleHasher; import org.apache.commons.collections4.bloomfilter.Shape; import org.apache.commons.lang3.SerializationUtils; public class PopulatingExample { /** * Populates a Bloom filter with the items. Uses a shape that * expects 10K items max and a false positive rate of 0.01. * @param items The items to insert. * @return the Bloom filter populated with the items. */ public static BloomFilter populate(Object[] items) { populate(Shape.fromNP(10000, 0.01), items); } /** * Populates a Bloom filter with the items. * @param shape The shape of the Bloom filter. * @param items The items to insert. * @return the Bloom filter populated with the items. */ public static BloomFilter populate(Shape shape, Object[] items) { BloomFilter collection = new SimpleBloomFilter(shape); for (Object o : items) { // this example serializes the entire object, actual implementation // may want to serialize specific properties into the hash. byte[] bytes = SerializationUtils.serialize(o); long[] hash = MurmurHash3.hash128(bytes); collection.merge(new EnhancedDoubleHasher(hash[0], hash[1])); } // collection now contains all the items from the list of items return collection; } } ``` -------------------------------- ### Regenerate contributing documentation Source: https://github.com/apache/commons-collections/blob/master/CONTRIBUTING.md Command to regenerate the contributing documentation using the commons-build plugin. ```bash mvn commons-build:contributing-md ``` -------------------------------- ### Merge Bloom Filters using Intersection class Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md Demonstrates using the Intersection class to merge two Bloom filters and check for containment against a set of candidate filters. ```java import Intersection; import org.apache.commons.collections4.bloomfilter.BloomFilter; import org.apache.commons.collections4.bloomfilter.LongBiPredicate; import org.apache.commons.collections4.bloomfilter.Shape; class IntersectionExample { public static main(String[] args) { /* start setup */ // get an array of Bloom filters to check BloomFilter[] candidateFilters = getBloomFilterCandidates(); // use two populated Bloom filters. BloomFilter collection1 = populateCollection1(); BloomFilter collection2 = populateCollection2(); /* end setup */ // create the Intersection instance Intersection intersection = new Intersection(collection1.getShape()); // populate the intersection instance with data from the 2 filters. collection1.processBitMapPairs(collection2, intersection); // create a new Bloom filter from the intersection instance. BloomFilter collection1And2 = new BloomFilter(collection1.getShape()); collection1And2.merge(intersection.asExtractor()); // now do the search for filters that are in both collections. for (BloomFilter target : candidateFilters) { if (collection1And2.contains(target)) { // do something interesting } } } } ``` -------------------------------- ### ArrayCountingBloomFilter Implementation Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md The only provided implementation of CountingBloomFilter, using a simple array of integers to track counts. ```APIDOC ## ArrayCountingBloomFilter ### Description The only provided implementation of CountingBloomFilter, using a simple array of integers to track counts. ``` -------------------------------- ### TimerPredicate implementation for LayerManager Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md A predicate that triggers layer creation based on time intervals calculated from layer expiry and count. ```java /** * A cleanup() predicate that triggers when a new layer should be created based on time * and the desired number of layers. */ class TimerPredicate implements Predicate> { long expires; TimerPredicate() { expires = System.currentTimeMillis() + layerExpiry.toMillis() / layerCount; } @Override public boolean test(LayerManager o) { long now = System.currentTimeMillis(); if (expires > now) { return false; } expires = now + layerExpiry.toMillis() / layerCount; return true; } } ``` -------------------------------- ### Layered Bloom Filter containment and cleanup methods Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md Methods to check if a Bloom filter or hasher exists within the layered filter, and a method to trigger cleanup before checking if the filter is empty. ```java /** * Returns true if {@code bf} is found in the layered filter. * * @param bf the filter to look for. * @return true if found. */ public boolean contains(BloomFilter bf) { return bloomFilter.contains(bf); } /** * Returns true if {@code bf} is found in the layered filter. * * @param hasher the hasher representation to search for. * @return true if found. */ public boolean contains(Hasher hasher) { return bloomFilter.contains(hasher); } /** * @return true if there are no entities being tracked for the principal. */ public boolean isEmpty() { bloomFilter.cleanup(); // forces clean return bloomFilter.isEmpty(); } ``` -------------------------------- ### Searching a single Bloom filter Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/implementation.md Uses a Hasher to search a single Bloom filter to reduce the overhead of creating a temporary Bloom filter for the match. ```java import org.apache.commons.codec.digest.MurmurHash3; import org.apache.commons.collections4.bloomfilter.BloomFilter; import org.apache.commons.collections4.bloomfilter.EnhancedDoubleHasher; import org.apache.commons.lang3.SerializationUtils; public class SearchingExample { private Bloomfilter collection; /** * Creates the example from a populated collection. * @param collection the collection to search. */ public SearchingExample(BloomFilter collection) { this.collection = collection; } /** * Perform the search. * @param item the item to look for. * @return true if the item is found, false otherwise. */ public boolean search(Object item) { // create the hasher to look for.= byte[] bytes = SerializationUtils.serialize(o); long[] hash = MurmurHash3.hash128(bytes); return collection.contains(new EnhancedDoubleHasher(hash[0], hash[1])); } } ``` -------------------------------- ### Searching multiple Bloom filters of the same shape Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/implementation.md When checking multiple filters of the same shape, it is more efficient to create a single Bloom filter from the hasher and use that for comparisons. ```java import org.apache.commons.codec.digest.MurmurHash3; import org.apache.commons.collections4.bloomfilter.BloomFilter; import org.apache.commons.collections4.bloomfilter.EnhancedDoubleHasher; import org.apache.commons.collections4.bloomfilter.Shape; import org.apache.commons.lang3.SerializationUtils; public abstract class SearchingExample2 { private BloomFilter[] collections; /** * Create example from an array of populated Bloom filters that all have the same Shape. * @param collections The Bloom filters to search. */ public SearchingExample2(BloomFilter[] collections) { this.collections = collections; } /** * Search the filters for matching items. * @param item the Item t o search for. */ public void search(Object item) { // create the Bloom filter to search for. byte[] bytes = SerializationUtils.serialize(o); long[] hash = MurmurHash3.hash128(bytes); BloomFilter target = new SimpleBloomFilter(collectons[0].getShape()); target.merge(new EnhancedDoubleHasher(hash[0], hash[1])); for (BloomFilter candidate : candidates) { if (candidate.contains(target)) { doSomethingInteresting(candidate, item); } } } /** * The interesting thing to do when a match occurs. * @param collection the Bloom filter that matched. * @param item The item that was being searched for. */ abstract public void doSomethingInteresting(BloomFilter collection, Object item); } ``` -------------------------------- ### CellExtractor Interface Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md The CellExtractor interface extends IndexExtractor and provides methods to process cells and create a CellExtractor from an IndexExtractor. ```APIDOC ## CellExtractor Interface ### Description Extends IndexExtractor to produce the index for every cell with a count greater than 0. ### Methods #### processCells(CellPredicate consumer) - **Parameters**: - consumer (CellPredicate) - Required - The predicate to call for each populated cell. - **Description**: Calls the CellPredicate for each populated cell in the producer. #### from(IndexExtractor indexExtractor) - **Parameters**: - indexExtractor (IndexExtractor) - Required - The index extractor to convert. - **Returns**: CellExtractor - A CellExtractor where each index that appears in the IndexExtractor is a cell with a value of one (1). Duplicate indices are summed together. ``` -------------------------------- ### CellPredicate Interface Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md A functional consumer interface that accepts two integer values: the index and the cell value for each populated cell. ```APIDOC ## CellPredicate Interface ### Description A functional consumer interface that accepts two integer values, the index and the cell value, for each populated cell. ### Method - **accept(int index, int cellValue)** - Called for each populated cell. ``` -------------------------------- ### Maven dependency for commons-collections4 Source: https://github.com/apache/commons-collections/blob/master/README.md Add this dependency to your pom.xml file to include Apache Commons Collections in your project. ```xml org.apache.commons commons-collections4 4.6.0 ``` -------------------------------- ### Implement Intersection using LongBiPredicate Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md Defines a class that implements LongBiPredicate to perform a bitwise AND operation on two Bloom filter bitmaps, allowing the result to be extracted as a new BitMapExtractor. ```java import org.apache.commons.collections4.bloomfilter.BitMap; import org.apache.commons.collections4.bloomfilter.BitMapExtractor; import org.apache.commons.collections4.bloomfilter.LongBiPredicate; import org.apache.commons.collections4.bloomfilter.Shape; /** * Calculates the intersection of two Bloom filters */ class Intersection implements LongBiPredicate { private long[] newMaps; private int idx; /** * Creates an intersection for a specified shape. * @param shape the shape of the Bloom filters being compared. */ Intersection(Shape shape) { newMaps = new long[BitMap.numberOfBitMaps(shape.getNumberOfBits())]; idx = 0; } /** * Implements the LongBiPredicate test. * @param a one BitMap * @param b the other BitMap * @return true always. */ public boolean test(long a, long b) { newMaps[idx++] = a & b; return true; } /** * Returns the intersection as a BitMapExtractor. * @return the the intersection as a BitMapExtractor. */ BitMapExtractor asExtractor() { return BitMapExtractor.fromBitMapArray(newMaps); } } ``` -------------------------------- ### Test for Bloom Filter Saturation Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md This snippet checks if a Bloom filter has reached its saturation point. It is recommended to use filters that track cardinality for accurate results. ```java if (bloomfilter.getShape().estimateMaxN() <= bloomfilter.estimateN()) { // handle saturated case. } ``` -------------------------------- ### TimestampedBloomFilter wrapper class Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md A Bloom filter implementation that wraps a standard filter and adds an expiration timestamp. ```java /** * A Bloom filter implementation that has a timestamp indicating when it expires. * Used as the Bloom filter for the layer in the LayeredBloomFilter */ static class TimestampedBloomFilter extends WrappedBloomFilter { long expires; TimestampedBloomFilter(Shape shape, long ttl) { super(new SimpleBloomFilter(shape)); expires = System.currentTimeMillis() + ttl; } private TimestampedBloomFilter(TimestampedBloomFilter other) { super(other.getWrapped().copy()); this.expires = other.expires; } @Override public TimestampedBloomFilter copy() { return new TimestampedBloomFilter(this); } } ``` -------------------------------- ### CountingBloomFilter Interface Source: https://github.com/apache/commons-collections/blob/master/src/site/markdown/bloomFilters/advanced.md Defines methods for adding, subtracting, removing, validating, and querying the maximum cell value of a counting Bloom filter. ```APIDOC ## CountingBloomFilter Interface ### Description Defines methods for counting Bloom filter operations. ### Methods #### add(CellExtractor other) - **Parameters**: - other (CellExtractor) - Required - The extractor whose cells are added to the counting Bloom filter. - **Description**: Adds the cells of the extractor to the cells of the counting Bloom filter. #### subtract(CellExtractor other) - **Parameters**: - other (CellExtractor) - Required - The extractor whose cells are subtracted from the counting Bloom filter. - **Description**: Subtracts the cells of the extractor from the cells of the counting Bloom filter. #### remove(BitMapExtractor other) - **Parameters**: - other (BitMapExtractor) - Required - The extractor whose associated cells are decremented by 1. - **Description**: Decrements the associated cells by 1. Inverse of the merge() methods. #### remove(BloomFilter other) - **Parameters**: - other (BloomFilter) - Required - The Bloom filter whose associated cells are decremented by 1. - **Description**: Decrements the associated cells by 1. Inverse of the merge() methods. #### remove(Hasher other) - **Parameters**: - other (Hasher) - Required - The hasher whose associated cells are decremented by 1. - **Description**: Decrements the associated cells by 1. Inverse of the merge() methods. #### remove(IndexExtractor other) - **Parameters**: - other (IndexExtractor) - Required - The index extractor whose associated cells are decremented by 1. - **Description**: Decrements the associated cells by 1. Inverse of the merge() methods. #### isValid() - **Returns**: boolean - True if all cells are valid, false otherwise. - **Description**: Verifies that all cells are valid. If false, the CountingBloomFilter is no longer accurate and functions may yield unpredictable results. #### getMaxCell() - **Returns**: int - The maximum value of a cell before it becomes invalid. - **Description**: Defines the maximum value of a cell before it becomes invalid. ```