001: package com.jamonapi.utils;
002:
003: import java.util.*;
004:
005: /** Buffer used to keep the last N recent values based on the comparator. Note the Comparator must
006: * be thread safe.
007: * @author steve souza
008: *
009: */
010: public class NExtremeBufferHolder implements BufferHolder, Comparator {
011:
012: private Object nextToRemove;
013: private List list = new ArrayList();
014:
015: private static final int EQUALTO = 0;
016: private static final int GREATERTHAN = 1;
017: private Comparator comparator;
018:
019: public NExtremeBufferHolder(Comparator comparator) {
020: this .comparator = comparator;
021:
022: }
023:
024: public NExtremeBufferHolder(boolean naturalOrder) {
025: comparator = new JAMonComparator(naturalOrder);
026: }
027:
028: public List getCollection() {
029: return list;
030: }
031:
032: public void setComparator(Comparator comparator) {
033: this .comparator = comparator;
034: }
035:
036: public Comparator getComparator() {
037: return comparator;
038: }
039:
040: private Object getNextToRemove() {
041: return Collections.min(list, comparator);
042: }
043:
044: private boolean isTrue(int newVal) {
045: return (newVal == GREATERTHAN || newVal == EQUALTO) ? true
046: : false;
047:
048: }
049:
050: /**
051: * Method used by the comparator interface. <br><br>
052: * o1 < o2 - returns a negative integer<br>
053: * o1==o2 - returns zero<br>
054: * o1>o2 - returns a postitive integer<br><br>
055: * Iterate through all columns that should be compared (in the proper order)
056: * and call the Comparator for each of the column elements.
057: * Note the column value is always the first argument and the comparison value is always the second
058: *
059: *
060: */
061:
062: /*
063: * Returns
064: * this object is less than - returns a negative integer,
065: * this object equal to - retunrs zero
066: * this object greater than - return positive integer
067: */
068: public int compare(Object newObj, Object existingObj) {
069: return comparator.compare(newObj, existingObj);
070: }
071:
072: public void add(Object replaceWithObj) {
073: list.add(replaceWithObj);
074: }
075:
076: public void remove(Object replaceWithObj) {
077: list.remove(nextToRemove);
078: nextToRemove = getNextToRemove();
079: }
080:
081: public boolean shouldReplaceWith(Object replaceWithObj) {
082: if (nextToRemove == null)
083: nextToRemove = getNextToRemove();
084:
085: return isTrue(compare(replaceWithObj, nextToRemove));
086: }
087:
088: public List getOrderedCollection() {
089: Collections.sort(list, comparator);
090: return list;
091: }
092:
093: public void setCollection(List list) {
094: this .list = list;
095:
096: }
097:
098: public BufferHolder copy() {
099: return new NExtremeBufferHolder(comparator);
100: }
101:
102: }
|