libcommons-collections-java-2.1.1.orig/0040755000175000017500000000000010072641277016555 5ustar toratoralibcommons-collections-java-2.1.1.orig/src/0040755000175000017500000000000010055172376017344 5ustar toratoralibcommons-collections-java-2.1.1.orig/src/conf/0040755000175000017500000000000010072637470020271 5ustar toratoralibcommons-collections-java-2.1.1.orig/src/conf/MANIFEST.MF0100644000175000017500000000032410055172376021717 0ustar toratoraExtension-Name: org.apache.commons.collections Specification-Vendor: Apache Software Foundation Specification-Version: 2.1.1 Implementation-Vendor: Apache Software Foundation Implementation-Version: 2.1.1 libcommons-collections-java-2.1.1.orig/src/java/0040755000175000017500000000000010055172376020265 5ustar toratoralibcommons-collections-java-2.1.1.orig/src/java/org/0040755000175000017500000000000010055172376021054 5ustar toratoralibcommons-collections-java-2.1.1.orig/src/java/org/apache/0040755000175000017500000000000010055172376022275 5ustar toratoralibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/0040755000175000017500000000000010055172376023750 5ustar toratoralibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/0040755000175000017500000000000010072637466026273 5ustar toratora././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/IteratorEnumeration.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/IteratorEnumeration.0100644000175000017500000000312610055172400032252 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Iterator; /** Adapter to make an {@link Iterator Iterator} instance appear to be an {@link java.util.Enumeration Enumeration} instances * * @since 1.0 * @author James Strachan * @deprecated this class has been moved to the iterators subpackage */ public class IteratorEnumeration extends org.apache.commons.collections.iterators.IteratorEnumeration { /** * Constructs a new IteratorEnumeration that will not * function until {@link #setIterator(Iterator) setIterator} is * invoked. */ public IteratorEnumeration() { super(); } /** * Constructs a new IteratorEnumeration that will use * the given iterator. * * @param iterator the iterator to use */ public IteratorEnumeration( Iterator iterator ) { super(iterator); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/MultiHashMap.java0100644000175000017500000001203010055172400031442 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * MultiHashMap is the default implementation of the * {@link org.apache.commons.collections.MultiMap MultiMap} interface. * A MultiMap is a Map with slightly different semantics. * Instead of returning an Object, it returns a Collection. * So for example, you can put( key, new Integer(1) ); * and then a Object get( key ); will return you a Collection * instead of an Integer. * * @since 2.0 * @author Christopher Berry * @author James Strachan * @author Steve Downey * @author Stephen Colebourne */ public class MultiHashMap extends HashMap implements MultiMap { //----------------- Data private static int sCount = 0; private String mName = null; public MultiHashMap() { super(); setName(); } public MultiHashMap( int initialCapacity ) { super( initialCapacity ); setName(); } public MultiHashMap(int initialCapacity, float loadFactor ) { super( initialCapacity, loadFactor); setName(); } public MultiHashMap( Map mapToCopy ) { super( mapToCopy ); } private void setName() { sCount++; mName = "MultiMap-" + sCount; } public String getName() { return mName; } public Object put( Object key, Object value ) { // NOTE:: put might be called during deserialization !!!!!! // so we must provide a hook to handle this case // This means that we cannot make MultiMaps of ArrayLists !!! if ( value instanceof ArrayList ) { return ( super.put( key, value ) ); } ArrayList keyList = (ArrayList)(super.get( key )); if ( keyList == null ) { keyList = new ArrayList(10); super.put( key, keyList ); } boolean results = keyList.add( value ); return ( results ? value : null ); } public boolean containsValue( Object value ) { Set pairs = super.entrySet(); if ( pairs == null ) return false; Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); if( list.contains( value ) ) return true; } return false; } public Object remove( Object key, Object item ) { ArrayList valuesForKey = (ArrayList) super.get( key ); if ( valuesForKey == null ) return null; valuesForKey.remove( item ); return item; } public void clear() { Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); list.clear(); } super.clear(); } public void putAll( Map mapToPut ) { super.putAll( mapToPut ); } public Collection values() { ArrayList returnList = new ArrayList( super.size() ); Set pairs = super.entrySet(); Iterator pairsIterator = pairs.iterator(); while ( pairsIterator.hasNext() ) { Map.Entry keyValuePair = (Map.Entry)(pairsIterator.next()); ArrayList list = (ArrayList)(keyValuePair.getValue()); Object[] values = list.toArray(); for ( int ii=0; ii < values.length; ii++ ) { returnList.add( values[ii] ); } } return returnList; } // FIXME:: do we need to implement this?? // public boolean equals( Object obj ) {} // --------------- From Cloneable public Object clone() { MultiHashMap obj = (MultiHashMap)(super.clone()); obj.mName = mName; return obj; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BoundedFifoBuffer.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BoundedFifoBuffer.ja0100644000175000017500000002046110055172376032120 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; /** * The BoundedFifoBuffer is a very efficient implementation of * Buffer that does not alter the size of the buffer at runtime. *

* The removal order of a BoundedFifoBuffer is based on the * insertion order; elements are removed in the same order in which they * were added. The iteration order is the same as the removal order. *

* The {@link #add(Object)}, {@link #remove()} and {@link #get()} operations * all perform in constant time. All other operations perform in linear * time or worse. *

* Note that this implementation is not synchronized. The following can be * used to provide synchronized access to your BoundedFifoBuffer: *

 *   Buffer fifo = BufferUtils.synchronizedBuffer(new BoundedFifoBuffer());
 * 
*

* This buffer prevents null objects from being added. * * @author Avalon * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @since 2.1 * @version $Id: BoundedFifoBuffer.java,v 1.5.2.1 2004/05/22 12:14:02 scolebourne Exp $ */ public class BoundedFifoBuffer extends AbstractCollection implements Buffer { private final Object[] m_elements; private int m_start = 0; private int m_end = 0; private boolean m_full = false; /** * Constructs a new BoundedFifoBuffer big enough to hold * 32 elements. */ public BoundedFifoBuffer() { this(32); } /** * Constructs a new BoundedFifoBuffer big enough to hold * the specified number of elements. * * @param size the maximum number of elements for this fifo * @throws IllegalArgumentException if the size is less than 1 */ public BoundedFifoBuffer(int size) { if (size <= 0) { throw new IllegalArgumentException("The size must be greater than 0"); } m_elements = new Object[size]; } /** * Constructs a new BoundedFifoBuffer big enough to hold all * of the elements in the specified collection. That collection's * elements will also be added to the buffer. * * @param coll the collection whose elements to add */ public BoundedFifoBuffer(Collection coll) { this(coll.size()); addAll(coll); } /** * Returns the number of elements stored in the buffer. * * @return this buffer's size */ public int size() { int size = 0; if (m_end < m_start) { size = m_elements.length - m_start + m_end; } else if (m_end == m_start) { size = (m_full ? m_elements.length : 0); } else { size = m_end - m_start; } return size; } /** * Returns true if this buffer is empty; false otherwise. * * @return true if this buffer is empty */ public boolean isEmpty() { return size() == 0; } /** * Clears this buffer. */ public void clear() { m_full = false; m_start = 0; m_end = 0; Arrays.fill(m_elements, null); } /** * Adds the given element to this buffer. * * @param element the element to add * @return true, always * @throws NullPointerException if the given element is null * @throws BufferOverflowException if this buffer is full */ public boolean add(Object element) { if (null == element) { throw new NullPointerException("Attempted to add null object to buffer"); } if (m_full) { throw new BufferOverflowException("The buffer cannot hold more than " + m_elements.length + " objects."); } m_elements[m_end++] = element; if (m_end >= m_elements.length) { m_end = 0; } if (m_end == m_start) { m_full = true; } return true; } /** * Returns the least recently inserted element in this buffer. * * @return the least recently inserted element * @throws BufferUnderflowException if the buffer is empty */ public Object get() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } return m_elements[m_start]; } /** * Removes the least recently inserted element from this buffer. * * @return the least recently inserted element * @throws BufferUnderflowException if the buffer is empty */ public Object remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } Object element = m_elements[m_start]; if (null != element) { m_elements[m_start++] = null; if (m_start >= m_elements.length) { m_start = 0; } m_full = false; } return element; } /** * Increments the internal index. * * @param index the index to increment * @return the updated index */ private int increment(int index) { index++; if (index >= m_elements.length) { index = 0; } return index; } /** * Decrements the internal index. * * @param index the index to decrement * @return the updated index */ private int decrement(int index) { index--; if (index < 0) { index = m_elements.length - 1; } return index; } /** * Returns an iterator over this buffer's elements. * * @return an iterator over this buffer's elements */ public Iterator iterator() { return new Iterator() { private int index = m_start; private int lastReturnedIndex = -1; private boolean isFirst = m_full; public boolean hasNext() { return isFirst || (index != m_end); } public Object next() { if (!hasNext()) throw new NoSuchElementException(); isFirst = false; lastReturnedIndex = index; index = increment(index); return m_elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) throw new IllegalStateException(); // First element can be removed quickly if (lastReturnedIndex == m_start) { BoundedFifoBuffer.this.remove(); lastReturnedIndex = -1; return; } // Other elements require us to shift the subsequent elements int i = lastReturnedIndex + 1; while (i != m_end) { if (i >= m_elements.length) { m_elements[i - 1] = m_elements[0]; i = 0; } else { m_elements[i - 1] = m_elements[i]; i++; } } lastReturnedIndex = -1; m_end = decrement(m_end); m_elements[m_end] = null; m_full = false; index = decrement(index); } }; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SingletonIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SingletonIterator.ja0100644000175000017500000000251010055172400032235 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /**

SingletonIterator is an {@link java.util.Iterator Iterator} over a single * object instance.

* * @since 2.0 * @author James Strachan * @version $Revision: 1.8.2.1 $ * @deprecated this class has been moved to the iterators subpackage */ public class SingletonIterator extends org.apache.commons.collections.iterators.SingletonIterator { /** * Constructs a new SingletonIterator. * * @param object the single object to return from the iterator */ public SingletonIterator(Object object) { super(object); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/Buffer.java0100644000175000017500000000432610055172402030332 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; /** * A Buffer is a collection that allows objects to be removed in some * well-defined order. The removal order can be based on insertion order * (eg, a FIFO queue or a LIFO stack), on access order (eg, an LRU cache), * on some arbitrary comparator (eg, a priority queue) or on any other * well-defined ordering.

* * Note that the removal order is not necessarily the same as the iteration * order. A Buffer implementation may have equivalent removal * and iteration orders, but this is not required.

* * This interface does not specify any behavior for * {@link Object#equals(Object)} and {@link Object#hashCode} methods. It * is therefore possible for a Buffer implementation to also * also implement {@link java.util.List}, {@link java.util.Set} or * {@link Bag}. * * @author Avalon * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @version $Id: Buffer.java,v 1.3.2.1 2004/05/22 12:14:01 scolebourne Exp $ * @since 2.1 */ public interface Buffer extends Collection { /** * Removes the next object from the buffer. * * @return the removed object * @throws BufferUnderflowException if the buffer is already empty */ Object remove(); /** * Returns the next object in the buffer without removing it. * * @return the next object in the buffer * @throws BufferUnderflowException if the buffer is empty */ Object get(); } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/PriorityQueue.java0100644000175000017500000000374010055172400031744 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.NoSuchElementException; /** * Interface for priority queues. * This interface does not dictate whether it is min or max heap. * * @since 1.0 * @author Peter Donald */ public interface PriorityQueue { /** * Clear all elements from queue. */ void clear(); /** * Test if queue is empty. * * @return true if queue is empty else false. */ boolean isEmpty(); /** * Insert an element into queue. * * @param element the element to be inserted * * @exception ClassCastException if the specified element's * type prevents it from being compared to other items in the queue to * determine its relative priority. */ void insert( Object element ); /** * Return element on top of heap but don't remove it. * * @return the element at top of heap * @exception NoSuchElementException if isEmpty() == true */ Object peek() throws NoSuchElementException; /** * Return element on top of heap and remove it. * * @return the element at top of heap * @exception NoSuchElementException if isEmpty() == true */ Object pop() throws NoSuchElementException; } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/0040755000175000017500000000000010072637465030624 5ustar toratora././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/TransformingComparator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/Transfor0100644000175000017500000000441510055172400032326 0ustar toratora/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.util.Comparator; import org.apache.commons.collections.Transformer; /** * Decorates another Comparator with transformation behavior. That is, the * return value from the transform operation will be passed to the decorated * Comparator#compare method. *

* @see org.apache.commons.collections.Transformer * @see org.apache.commons.collections.comparators.ComparableComparator */ public class TransformingComparator implements Comparator { protected Comparator decorated; protected Transformer transformer; /** * Constructs an instance with the given Transformer and a ComparableComparator. * @param transformer what will transform the instance. */ public TransformingComparator(Transformer transformer) { this(transformer, new ComparableComparator()); } /** * Constructs an instance with the given Transformer and Comparator * @param decorated the decorated Comparator * @param getterName the getter name */ public TransformingComparator(Transformer transformer, Comparator decorated) { this.decorated = decorated; this.transformer = transformer; } /** * Returns the result of comparing the values from the transform operation. * @return the result of comparing the values from the transform operation */ public int compare(Object o1, Object o2) { Object value1 = this.transformer.transform(o1); Object value2 = this.transformer.transform(o2); return this.decorated.compare(value1, value2); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ReverseComparator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ReverseC0100644000175000017500000000427110055172400032246 0ustar toratora/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.Comparator; /** * Reverses the order of another comparator. * * @since 2.0 * @author bayard@generationjava.com * @author Michael A. Smith * @version $Id: ReverseComparator.java,v 1.8.2.1 2004/05/22 12:14:04 scolebourne Exp $ */ public class ReverseComparator implements Comparator,Serializable { private Comparator comparator; /** * Creates a comparator that compares objects based on the inverse of their * natural ordering. Using this Constructor will create a ReverseComparator * that is functionaly identical to the Comparator returned by * java.util.Collections.reverseOrder(). * * @see java.util.Collections#reverseOrder() */ public ReverseComparator() { this(null); } /** * Creates a reverse comparator that inverts the comparison * of the passed in comparator. If you pass in a null, * the ReverseComparator defaults to reversing the * natural order, as per * java.util.Collections.reverseOrder(). * * @param comparator Comparator to reverse */ public ReverseComparator(Comparator comparator) { if(comparator != null) { this.comparator = comparator; } else { this.comparator = ComparableComparator.getInstance(); } } public int compare(Object o1, Object o2) { return comparator.compare(o2, o1); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ComparableComparator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/Comparab0100644000175000017500000000755710055172400032266 0ustar toratora/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.lang.Comparable; import java.util.Comparator; /** * A Comparator that compares Comparable objects. * Throws ClassCastExceptions if the objects are not * Comparable, or if they are null. * Throws ClassCastException if the compareTo of both * objects do not provide an inverse result of each other * as per the Comparable javadoc. This Comparator is useful, for example, * for enforcing the natural order in custom implementations * of SortedSet and SortedMap. * * @since 2.0 * @author bayard@generationjava.com * @version $Id: ComparableComparator.java,v 1.5.2.1 2004/05/22 12:14:04 scolebourne Exp $ */ public class ComparableComparator implements Comparator,Serializable { private static final ComparableComparator instance = new ComparableComparator(); /** * Return a shared instance of a ComparableComparator. Developers are * encouraged to use the comparator returned from this method instead of * constructing a new instance to reduce allocation and GC overhead when * multiple comparable comparators may be used in the same VM. **/ public static ComparableComparator getInstance() { return instance; } private static final long serialVersionUID=-291439688585137865L; public ComparableComparator() { } public int compare(Object o1, Object o2) { if( (o1 == null) || (o2 == null) ) { throw new ClassCastException( "There were nulls in the arguments for this method: "+ "compare("+o1 + ", " + o2 + ")" ); } if(o1 instanceof Comparable) { if(o2 instanceof Comparable) { int result1 = ((Comparable)o1).compareTo(o2); int result2 = ((Comparable)o2).compareTo(o1); // enforce comparable contract if(result1 == 0 && result2 == 0) { return 0; } else if(result1 < 0 && result2 > 0) { return result1; } else if(result1 > 0 && result2 < 0) { return result1; } else { // results inconsistent throw new ClassCastException("o1 not comparable to o2"); } } else { // o2 wasn't comparable throw new ClassCastException( "The first argument of this method was not a Comparable: " + o2.getClass().getName() ); } } else if(o2 instanceof Comparable) { // o1 wasn't comparable throw new ClassCastException( "The second argument of this method was not a Comparable: " + o1.getClass().getName() ); } else { // neither were comparable throw new ClassCastException( "Both arguments of this method were not Comparables: " + o1.getClass().getName() + " and " + o2.getClass().getName() ); } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ComparatorChain.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/Comparat0100644000175000017500000002273410055172400032302 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.ArrayList; import java.util.BitSet; import java.util.Comparator; import java.util.Iterator; import java.util.List; /** *

A ComparatorChain is a Comparator that wraps one or * more Comparators in sequence. The ComparatorChain * calls each Comparator in sequence until either 1) * any single Comparator returns a non-zero result * (and that result is then returned), * or 2) the ComparatorChain is exhausted (and zero is * returned). This type of sorting is very similar * to multi-column sorting in SQL, and this class * allows Java classes to emulate that kind of behaviour * when sorting a List.

* *

To further facilitate SQL-like sorting, the order of * any single Comparator in the list can be reversed.

* *

Calling a method that adds new Comparators or * changes the ascend/descend sort after compare(Object, * Object) has been called will result in an * UnsupportedOperationException. However, take care * to not alter the underlying List of Comparators * or the BitSet that defines the sort order.

* *

Instances of ComparatorChain are not synchronized. * The class is not thread-safe at construction time, but * it is thread-safe to perform multiple comparisons * after all the setup operations are complete.

* * @since 2.0 * @author Morgan Delagrange */ public class ComparatorChain implements Comparator,Serializable { protected List comparatorChain = null; // 0 = ascend; 1 = descend protected BitSet orderingBits = null; // ComparatorChain is "locked" after the first time // compare(Object,Object) is called protected boolean isLocked = false; /** * Construct a ComparatorChain with no Comparators. * You must add at least one Comparator before calling * the compare(Object,Object) method, or an * UnsupportedOperationException is thrown */ public ComparatorChain() { this(new ArrayList(),new BitSet()); } /** * Construct a ComparatorChain with a single Comparator, * sorting in the forward order * * @param comparator First comparator in the Comparator chain */ public ComparatorChain(Comparator comparator) { this(comparator,false); } /** * Construct a Comparator chain with a single Comparator, * sorting in the given order * * @param comparator First Comparator in the ComparatorChain * @param reverse false = forward sort; true = reverse sort */ public ComparatorChain(Comparator comparator, boolean reverse) { comparatorChain = new ArrayList(); comparatorChain.add(comparator); orderingBits = new BitSet(1); if (reverse == true) { orderingBits.set(0); } } /** * Construct a ComparatorChain from the Comparators in the * List. All Comparators will default to the forward * sort order. * * @param list List of Comparators * @see #ComparatorChain(List,BitSet) */ public ComparatorChain(List list) { this(list,new BitSet(list.size())); } /** * Construct a ComparatorChain from the Comparators in the * given List. The sort order of each column will be * drawn from the given BitSet. When determining the sort * order for Comparator at index i in the List, * the ComparatorChain will call BitSet.get(i). * If that method returns false, the forward * sort order is used; a return value of true * indicates reverse sort order. * * @param list List of Comparators. NOTE: This constructor does not perform a * defensive copy of the list * @param bits Sort order for each Comparator. Extra bits are ignored, * unless extra Comparators are added by another method. */ public ComparatorChain(List list, BitSet bits) { comparatorChain = list; orderingBits = bits; } /** * Add a Comparator to the end of the chain using the * forward sort order * * @param comparator Comparator with the forward sort order */ public void addComparator(Comparator comparator) { addComparator(comparator,false); } /** * Add a Comparator to the end of the chain using the * given sort order * * @param comparator Comparator to add to the end of the chain * @param reverse false = forward sort order; true = reverse sort order */ public void addComparator(Comparator comparator, boolean reverse) { checkLocked(); comparatorChain.add(comparator); if (reverse == true) { orderingBits.set(comparatorChain.size() - 1); } } /** * Replace the Comparator at the given index, maintaining * the existing sort order. * * @param index index of the Comparator to replace * @param comparator Comparator to place at the given index * @exception IndexOutOfBoundsException * if index < 0 or index > size() */ public void setComparator(int index, Comparator comparator) throws IndexOutOfBoundsException { setComparator(index,comparator,false); } /** * Replace the Comparator at the given index in the * ComparatorChain, using the given sort order * * @param index index of the Comparator to replace * @param comparator Comparator to set * @param reverse false = forward sort order; true = reverse sort order */ public void setComparator(int index, Comparator comparator, boolean reverse) { checkLocked(); comparatorChain.set(index,comparator); if (reverse == true) { orderingBits.set(index); } else { orderingBits.clear(index); } } /** * Change the sort order at the given index in the * ComparatorChain to a forward sort. * * @param index Index of the ComparatorChain */ public void setForwardSort(int index) { checkLocked(); orderingBits.clear(index); } /** * Change the sort order at the given index in the * ComparatorChain to a reverse sort. * * @param index Index of the ComparatorChain */ public void setReverseSort(int index) { checkLocked(); orderingBits.set(index); } /** * Number of Comparators in the current ComparatorChain. * * @return Comparator count */ public int size() { return comparatorChain.size(); } /** * Determine if modifications can still be made to the * ComparatorChain. ComparatorChains cannot be modified * once they have performed a comparison. * * @return true = ComparatorChain cannot be modified; false = * ComparatorChain can still be modified. */ public boolean isLocked() { return isLocked; } // throw an exception if the ComparatorChain is locked private void checkLocked() { if (isLocked == true) { throw new UnsupportedOperationException("Comparator ordering cannot be changed after the first comparison is performed"); } } private void checkChainIntegrity() { if (comparatorChain.size() == 0) { throw new UnsupportedOperationException("ComparatorChains must contain at least one Comparator"); } } /** * Perform comaparisons on the Objects as per * Comparator.compare(o1,o2). * * @param o1 object 1 * @param o2 object 2 * @return -1, 0, or 1 * @exception UnsupportedOperationException * if the ComparatorChain does not contain at least one * Comparator */ public int compare(Object o1, Object o2) throws UnsupportedOperationException { if (isLocked == false) { checkChainIntegrity(); isLocked = true; } // iterate over all comparators in the chain Iterator comparators = comparatorChain.iterator(); for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) { Comparator comparator = (Comparator) comparators.next(); int retval = comparator.compare(o1,o2); if (retval != 0) { // invert the order if it is a reverse sort if (orderingBits.get(comparatorIndex) == true) { retval *= -1; } return retval; } } // if comparators are exhausted, return 0 return 0; } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/NullComparator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/NullComp0100644000175000017500000001503210055172400032256 0ustar toratora/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.comparators; import java.io.Serializable; import java.util.Comparator; /** * A Comparator that will compare nulls to be either lower or higher than * other objects. * * @author Michael A. Smith * @version $Id: NullComparator.java,v 1.4.2.1 2004/05/22 12:14:04 scolebourne Exp $ **/ public class NullComparator implements Comparator, Serializable { /** * The comparator to use when comparing two non-null objects. **/ private Comparator nonNullComparator; /** * Specifies whether a null are compared as higher than * non-null objects. **/ private boolean nullsAreHigh; /** * Construct an instance that sorts null higher than any * non-null object it is compared with. When comparing two * non-null objects, the {@link ComparableComparator} is * used. **/ public NullComparator() { this(ComparableComparator.getInstance(), true); } /** * Construct an instance that sorts null higher than any * non-null object it is compared with. When comparing two * non-null objects, the specified {@link Comparator} is * used. * * @param nonNullComparator the comparator to use when comparing two * non-null objects. This argument cannot be * null * * @exception NullPointerException if nonNullComparator is * null **/ public NullComparator(Comparator nonNullComparator) { this(nonNullComparator, true); } /** * Construct an instance that sorts null higher or lower than * any non-null object it is compared with. When comparing * two non-null objects, the {@link ComparableComparator} is * used. * * @param nullsAreHigh a true value indicates that * null should be compared as higher than a * non-null object. A false value indicates * that null should be compared as lower than a * non-null object. **/ public NullComparator(boolean nullsAreHigh) { this(ComparableComparator.getInstance(), nullsAreHigh); } /** * Cosntruct an instance that sorts null higher or lower than * any non-null object it is compared with. When comparing * two non-null objects, the specified {@link Comparator} is * used. * * @param nonNullComparator the comparator to use when comparing two * non-null objects. This argument cannot be * null * * @param nullsAreHigh a true value indicates that * null should be compared as higher than a * non-null object. A false value indicates * that null should be compared as lower than a * non-null object. * * @exception NullPointerException if nonNullComparator is * null **/ public NullComparator(Comparator nonNullComparator, boolean nullsAreHigh) { this.nonNullComparator = nonNullComparator; this.nullsAreHigh = nullsAreHigh; if(nonNullComparator == null) { throw new NullPointerException("null nonNullComparator"); } } /** * Perform a comparison between two objects. If both objects are * null, a 0 value is returned. If one object * is null and the other is not, the result is determined on * whether the Comparator was constructed to have nulls as higher or lower * than other objects. If neither object is null, an * underlying comparator specified in the constructor (or the default) is * used to compare the non-null objects. * * @param o1 the first object to compare * * @param o2 the object to compare it to. * * @return -1 if o1 is "lower" than (less than, * before, etc.) o2; 1 if o1 is * "higher" than (greater than, after, etc.) o2; or * 0 if o1 and o2 are equal. **/ public int compare(Object o1, Object o2) { if(o1 == o2) return 0; if(o1 == null) return (this.nullsAreHigh ? 1 : -1); if(o2 == null) return (this.nullsAreHigh ? -1 : 1); return this.nonNullComparator.compare(o1, o2); } /** * Implement a hash code for this comparator that is consistent with * {@link #equals(Object)}. * * @return a hash code for this comparator. **/ public int hashCode() { return (nullsAreHigh ? -1 : 1) * nonNullComparator.hashCode(); } /** * Determines whether the specified object represents a comparator that is * equal to this comparator. * * @param o the object to compare this comparator with. * * @return true if the specified object is a NullComparator * with equivalant null comparison behavior * (i.e. null high or low) and with equivalent underlying * non-null object comparators. **/ public boolean equals(Object obj) { if(obj == null) return false; if(obj == this) return true; if(!obj.getClass().equals(this.getClass())) return false; NullComparator other = (NullComparator)obj; return ((this.nullsAreHigh == other.nullsAreHigh) && (this.nonNullComparator.equals(other.nonNullComparator))); } private static final long serialVersionUID = -5820772575483504339L; } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/package.htmllibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/package.0100644000175000017500000000045610055172376032216 0ustar toratora Contains concrete {@link java.util.Comparator Comparator} implementations. You may also consider using {@link org.apache.commons.collections.ComparatorUtils CompatorUtils}, which is a single class that uses static methods to construct instances of the classes in this package. libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/LRUMap.java0100644000175000017500000001535010055172400030216 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.Iterator; /** *

* An implementation of a Map which has a maximum size and uses a Least Recently Used * algorithm to remove items from the Map when the maximum size is reached and new items are added. *

* *

* A synchronized version can be obtained with: * Collections.synchronizedMap( theMapToSynchronize ) * If it will be accessed by multiple threads, you _must_ synchronize access * to this Map. Even concurrent get(Object) operations produce indeterminate * behaviour. *

* *

* Unlike the Collections 1.0 version, this version of LRUMap does use a true * LRU algorithm. The keys for all gets and puts are moved to the front of * the list. LRUMap is now a subclass of SequencedHashMap, and the "LRU" * key is now equivalent to LRUMap.getFirst(). *

* * @since 1.0 * @author James Strachan * @author Morgan Delagrange */ public class LRUMap extends SequencedHashMap implements Externalizable { private int maximumSize = 0; /** * Default constructor, primarily for the purpose of * de-externalization. This constructors sets a default * LRU limit of 100 keys, but this value may be overridden * internally as a result of de-externalization. */ public LRUMap() { this( 100 ); } /** * Create a new LRUMap with a maximum capacity of i. * Once i capacity is achieved, subsequent gets * and puts will push keys out of the map. See . * * @param i Maximum capacity of the LRUMap */ public LRUMap(int i) { super( i ); maximumSize = i; } /** *

Get the value for a key from the Map. The key * will be promoted to the Most Recently Used position. * Note that get(Object) operations will modify * the underlying Collection. Calling get(Object) * inside of an iteration over keys, values, etc. is * currently unsupported.

* * @param key Key to retrieve * @return Returns the value. Returns null if the key has a * null value or if the key has no value. */ public Object get(Object key) { if(!containsKey(key)) return null; Object value = remove(key); super.put(key,value); return value; } /** *

Removes the key and its Object from the Map.

* *

(Note: this may result in the "Least Recently Used" * object being removed from the Map. In that case, * the removeLRU() method is called. See javadoc for * removeLRU() for more details.)

* * @param key Key of the Object to add. * @param value Object to add * @return Former value of the key * @see #removeLRU */ public Object put( Object key, Object value ) { int mapSize = size(); Object retval = null; if ( mapSize >= maximumSize ) { // don't retire LRU if you are just // updating an existing key if (!containsKey(key)) { // lets retire the least recently used item in the cache removeLRU(); } } retval = super.put(key,value); return retval; } /** * This method is used internally by the class for * finding and removing the LRU Object. */ protected void removeLRU() { Object key = getFirstKey(); // be sure to call super.get(key), or you're likely to // get infinite promotion recursion Object value = super.get(key); remove(key); processRemovedLRU(key,value); } /** * Subclasses of LRUMap may hook into this method to * provide specialized actions whenever an Object is * automatically removed from the cache. By default, * this method does nothing. * * @param key key that was removed * @param value value of that key (can be null) */ protected void processRemovedLRU(Object key, Object value) { } // Externalizable interface //------------------------------------------------------------------------- public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { maximumSize = in.readInt(); int size = in.readInt(); for( int i = 0; i < size; i++ ) { Object key = in.readObject(); Object value = in.readObject(); put(key,value); } } public void writeExternal( ObjectOutput out ) throws IOException { out.writeInt( maximumSize ); out.writeInt( size() ); for( Iterator iterator = keySet().iterator(); iterator.hasNext(); ) { Object key = iterator.next(); out.writeObject( key ); // be sure to call super.get(key), or you're likely to // get infinite promotion recursion Object value = super.get( key ); out.writeObject( value ); } } // Properties //------------------------------------------------------------------------- /** Getter for property maximumSize. * @return Value of property maximumSize. */ public int getMaximumSize() { return maximumSize; } /** Setter for property maximumSize. * @param maximumSize New value of property maximumSize. */ public void setMaximumSize(int maximumSize) { this.maximumSize = maximumSize; while (size() > maximumSize) { removeLRU(); } } // add a serial version uid, so that if we change things in the future // without changing the format, we can still deserialize properly. private static final long serialVersionUID = 2197433140769957051L; } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/UnboundedFifoBuffer.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/UnboundedFifoBuffer.0100644000175000017500000001762510055172400032144 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.Iterator; import java.util.NoSuchElementException; /** * UnboundedFifoBuffer is a very efficient buffer implementation. * According to performance testing, it exhibits a constant access time, but it * also outperforms ArrayList when used for the same purpose. *

* The removal order of an UnboundedFifoBuffer is based on the insertion * order; elements are removed in the same order in which they were added. * The iteration order is the same as the removal order. *

* The {@link #remove()} and {@link #get()} operations perform in constant time. * The {@link #add(Object)} operation performs in amortized constant time. All * other operations perform in linear time or worse. *

* Note that this implementation is not synchronized. The following can be * used to provide synchronized access to your UnboundedFifo: *

 *   Buffer fifo = BufferUtils.synchronizedBuffer(new UnboundedFifo());
 * 
*

* This buffer prevents null objects from being added. * * @author Avalon * @author Federico Barbieri * @author Berin Loritsch * @author Paul Jack * @author Stephen Colebourne * @since 2.1 * @version $Id: UnboundedFifoBuffer.java,v 1.5.2.1 2004/05/22 12:14:02 scolebourne Exp $ */ public final class UnboundedFifoBuffer extends AbstractCollection implements Buffer { protected Object[] m_buffer; protected int m_head; protected int m_tail; /** * Constructs an UnboundedFifoBuffer with the default number of elements. * It is exactly the same as performing the following: * *

     *   new UnboundedFifoBuffer(32);
     * 
*/ public UnboundedFifoBuffer() { this(32); } /** * Constructs an UnboundedFifoBuffer with the specified number of elements. * The integer must be a positive integer. * * @throws IllegalArgumentException if the size is less than 1 */ public UnboundedFifoBuffer(int size) { if (size <= 0) { throw new IllegalArgumentException("The size must be greater than 0"); } m_buffer = new Object[size + 1]; m_head = 0; m_tail = 0; } /** * Returns the number of elements stored in the buffer. * * @return this buffer's size */ public int size() { int size = 0; if (m_tail < m_head) { size = m_buffer.length - m_head + m_tail; } else { size = m_tail - m_head; } return size; } /** * Returns true if this buffer is empty; false otherwise. * * @return true if this buffer is empty */ public boolean isEmpty() { return (size() == 0); } /** * Adds the given element to this buffer. * * @param element the element to add * @return true, always * @throws NullPointerException if the given element is null * @throws BufferOverflowException if this buffer is full */ public boolean add(final Object o) { if (null == o) { throw new NullPointerException("Attempted to add null object to buffer"); } if (size() + 1 >= m_buffer.length) { Object[] tmp = new Object[((m_buffer.length - 1) * 2) + 1]; int j = 0; for (int i = m_head; i != m_tail;) { tmp[j] = m_buffer[i]; m_buffer[i] = null; j++; i++; if (i == m_buffer.length) { i = 0; } } m_buffer = tmp; m_head = 0; m_tail = j; } m_buffer[m_tail] = o; m_tail++; if (m_tail >= m_buffer.length) { m_tail = 0; } return true; } /** * Returns the next object in the buffer. * * @return the next object in the buffer * @throws BufferUnderflowException if this buffer is empty */ public Object get() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } return m_buffer[m_head]; } /** * Removes the next object from the buffer * * @return the removed object * @throws BufferUnderflowException if this buffer is empty */ public Object remove() { if (isEmpty()) { throw new BufferUnderflowException("The buffer is already empty"); } Object element = m_buffer[m_head]; if (null != element) { m_buffer[m_head] = null; m_head++; if (m_head >= m_buffer.length) { m_head = 0; } } return element; } /** * Increments the internal index. * * @param index the index to increment * @return the updated index */ private int increment(int index) { index++; if (index >= m_buffer.length) index = 0; return index; } /** * Decrements the internal index. * * @param index the index to decrement * @return the updated index */ private int decrement(int index) { index--; if (index < 0) index = m_buffer.length - 1; return index; } /** * Returns an iterator over this buffer's elements. * * @return an iterator over this buffer's elements */ public Iterator iterator() { return new Iterator() { private int index = m_head; private int lastReturnedIndex = -1; public boolean hasNext() { return index != m_tail; } public Object next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedIndex = index; index = increment(index); return m_buffer[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) throw new IllegalStateException(); // First element can be removed quickly if (lastReturnedIndex == m_head) { UnboundedFifoBuffer.this.remove(); lastReturnedIndex = -1; return; } // Other elements require us to shift the subsequent elements int i = lastReturnedIndex + 1; while (i != m_tail) { if (i >= m_buffer.length) { m_buffer[i - 1] = m_buffer[0]; i = 0; } else { m_buffer[i - 1] = m_buffer[i]; i++; } } lastReturnedIndex = -1; m_tail = decrement(m_tail); m_buffer[m_tail] = null; index = decrement(index); } }; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/FilterListIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/FilterListIterator.j0100644000175000017500000000532410055172376032235 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ListIterator; /** * A proxy {@link ListIterator ListIterator} which * takes a {@link Predicate Predicate} instance to filter * out objects from an underlying ListIterator * instance. Only objects for which the specified * Predicate evaluates to true are * returned by the iterator. * * @since 2.0 * @version $Revision: 1.7.2.1 $ $Date: 2004/05/22 12:14:02 $ * @author Rodney Waldhoff * @deprecated this class has been moved to the iterators subpackage */ public class FilterListIterator extends org.apache.commons.collections.iterators.FilterListIterator { // Constructors //------------------------------------------------------------------------- /** * Constructs a new FilterListIterator that will not * function until * {@link ProxyListIterator#setListIterator(ListIterator) setListIterator} * and {@link #setPredicate(Predicate) setPredicate} are invoked. */ public FilterListIterator() { super(); } /** * Constructs a new FilterListIterator that will not * function until {@link #setPredicate(Predicate) setPredicate} is invoked. * * @param iterator the iterator to use */ public FilterListIterator(ListIterator iterator ) { super(iterator); } /** * Constructs a new FilterListIterator. * * @param iterator the iterator to use * @param predicate the predicate to use */ public FilterListIterator(ListIterator iterator, Predicate predicate) { super(iterator, predicate); } /** * Constructs a new FilterListIterator that will not * function until * {@link ProxyListIterator#setListIterator(ListIterator) setListIterator} * is invoked. * * @param predicate the predicate to use. */ public FilterListIterator(Predicate predicate) { super(predicate); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ExtendedProperties.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ExtendedProperties.j0100644000175000017500000016016310055172376032262 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.IOException; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.LineNumberReader; import java.io.OutputStream; import java.io.PrintWriter; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Properties; import java.util.StringTokenizer; import java.util.Vector; /** * This class extends normal Java properties by adding the possibility * to use the same key many times concatenating the value strings * instead of overwriting them. * *

The Extended Properties syntax is explained here: * *

* *

Here is an example of a valid extended properties file: * *

 *      # lines starting with # are comments
 *
 *      # This is the simplest property
 *      key = value
 *
 *      # A long property may be separated on multiple lines
 *      longvalue = aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa \
 *                  aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 *
 *      # This is a property with many tokens
 *      tokens_on_a_line = first token, second token
 *
 *      # This sequence generates exactly the same result
 *      tokens_on_multiple_lines = first token
 *      tokens_on_multiple_lines = second token
 *
 *      # commas may be escaped in tokens
 *      commas.excaped = Hi\, what'up?
 * 
* *

NOTE: this class has not been written for * performance nor low memory usage. In fact, it's way slower than it * could be and generates too much memory garbage. But since * performance is not an issue during intialization (and there is not * much time to improve it), I wrote it this way. If you don't like * it, go ahead and tune it up! * * * @since 1.0 * @author Stefano Mazzocchi * @author Jon S. Stevens * @author Dave Bryson * @author Jason van Zyl * @author Geir Magnusson Jr. * @author Leon Messerschmidt * @author Kent Johnson * @author Daniel Rall * @author Ilkka Priha * @version $Id: ExtendedProperties.java,v 1.7.2.1 2004/05/22 12:14:02 scolebourne Exp $ */ public class ExtendedProperties extends Hashtable { /** * Default configurations repository. */ private ExtendedProperties defaults; /** * The file connected to this repository (holding comments and * such). * * @serial */ protected String file; /** * Base path of the configuration file used to create * this ExtendedProperties object. */ protected String basePath; /** * File separator. */ protected String fileSeparator = System.getProperty("file.separator"); /** * Has this configuration been intialized. */ protected boolean isInitialized = false; /** * This is the name of the property that can point to other * properties file for including other properties files. */ protected static String include = "include"; /** * These are the keys in the order they listed * in the configuration file. This is useful when * you wish to perform operations with configuration * information in a particular order. */ protected ArrayList keysAsListed = new ArrayList(); protected final static String START_TOKEN="${"; protected final static String END_TOKEN="}"; protected String interpolate(String base) { if (base == null) { return null; } int begin = -1; int end = -1; int prec = 0 - END_TOKEN.length(); String variable = null; StringBuffer result = new StringBuffer(); // FIXME: we should probably allow the escaping of the start token while ( ((begin=base.indexOf(START_TOKEN,prec+END_TOKEN.length()))>-1) && ((end=base.indexOf(END_TOKEN,begin))>-1) ) { result.append(base.substring(prec+END_TOKEN.length(),begin)); variable = base.substring(begin+START_TOKEN.length(),end); if (get(variable)!=null) { result.append(get(variable)); } prec=end; } result.append(base.substring(prec+END_TOKEN.length(),base.length())); return result.toString(); } /** * This class is used to read properties lines. These lines do * not terminate with new-line chars but rather when there is no * backslash sign a the end of the line. This is used to * concatenate multiple lines for readability. */ class PropertiesReader extends LineNumberReader { /** * Constructor. * * @param reader A Reader. */ public PropertiesReader(Reader reader) { super(reader); } /** * Read a property. * * @return A String. * @exception IOException. */ public String readProperty() throws IOException { StringBuffer buffer = new StringBuffer(); try { while (true) { String line = readLine().trim(); if ((line.length() != 0) && (line.charAt(0) != '#')) { if (line.endsWith("\\")) { line = line.substring(0, line.length() - 1); buffer.append(line); } else { buffer.append(line); break; } } } } catch (NullPointerException e) { return null; } return buffer.toString(); } } /** * This class divides into tokens a property value. Token * separator is "," but commas into the property value are escaped * using the backslash in front. */ class PropertiesTokenizer extends StringTokenizer { /** * The property delimiter used while parsing (a comma). */ static final String DELIMITER = ","; /** * Constructor. * * @param string A String. */ public PropertiesTokenizer(String string) { super(string, DELIMITER); } /** * Check whether the object has more tokens. * * @return True if the object has more tokens. */ public boolean hasMoreTokens() { return super.hasMoreTokens(); } /** * Get next token. * * @return A String. */ public String nextToken() { StringBuffer buffer = new StringBuffer(); while (hasMoreTokens()) { String token = super.nextToken(); if (token.endsWith("\\")) { buffer.append(token.substring(0, token.length() - 1)); buffer.append(DELIMITER); } else { buffer.append(token); break; } } return buffer.toString().trim(); } } /** * Creates an empty extended properties object. */ public ExtendedProperties() { super(); } /** * Creates and loads the extended properties from the specified * file. * * @param file A String. * @exception IOException. */ public ExtendedProperties(String file) throws IOException { this(file,null); } /** * Creates and loads the extended properties from the specified * file. * * @param file A String. * @exception IOException. */ public ExtendedProperties(String file, String defaultFile) throws IOException { this.file = file; basePath = new File(file).getAbsolutePath(); basePath = basePath.substring(0, basePath.lastIndexOf(fileSeparator) + 1); this.load(new FileInputStream(file)); if (defaultFile != null) { defaults = new ExtendedProperties(defaultFile); } } /** * Private initializer method that sets up the generic * resources. * * @exception IOException, if there was an I/O problem. */ private void init( ExtendedProperties exp ) throws IOException { isInitialized = true; } /** * Indicate to client code whether property * resources have been initialized or not. */ public boolean isInitialized() { return isInitialized; } /** * Gets the property value for including other properties files. * By default it is "include". * * @return A String. */ public String getInclude() { return this.include; } /** * Sets the property value for including other properties files. * By default it is "include". * * @param inc A String. */ public void setInclude(String inc) { this.include = inc; } /** * Load the properties from the given input stream. * * @param input An InputStream. * @exception IOException. */ public void load( InputStream input ) throws IOException { load(input,null); } /** * Load the properties from the given input stream * and using the specified encoding. * * @param input An InputStream. * @param enc An encoding. * @exception IOException. */ public synchronized void load(InputStream input, String enc) throws IOException { PropertiesReader reader = null; if (enc != null) { try { reader = new PropertiesReader(new InputStreamReader(input,enc)); } catch (UnsupportedEncodingException e) { // Get one with the default encoding... } } if (reader == null) { reader = new PropertiesReader(new InputStreamReader(input)); } try { while (true) { String line = reader.readProperty(); int equalSign = line.indexOf('='); if (equalSign > 0) { String key = line.substring(0, equalSign).trim(); String value = line.substring(equalSign + 1).trim(); /* * Configure produces lines like this ... just * ignore them. */ if ("".equals(value)) continue; if (getInclude() != null && key.equalsIgnoreCase(getInclude())) { /* * Recursively load properties files. */ File file = null; if (value.startsWith(fileSeparator)) { /* * We have an absolute path so we'll * use this. */ file = new File(value); } else { /* * We have a relative path, and we have * two possible forms here. If we have the * "./" form then just strip that off first * before continuing. */ if (value.startsWith("." + fileSeparator)) { value = value.substring(2); } file = new File(basePath + value); } if (file != null && file.exists() && file.canRead()) { load ( new FileInputStream(file)); } } else { addProperty(key,value); } } } } catch (NullPointerException e) { /* * Should happen only when EOF is reached. */ return; } } /** * Gets a property from the configuration. * * @param key property to retrieve * @return value as object. Will return user value if exists, * if not then default value if exists, otherwise null */ public Object getProperty( String key) { /* * first, try to get from the 'user value' store */ Object o = this.get(key); if ( o == null) { /* * if there isn't a value there, get it from the * defaults if we have them */ if (defaults != null) { o = defaults.get(key); } } return o; } /** * Add a property to the configuration. If it already * exists then the value stated here will be added * to the configuration entry. For example, if * * resource.loader = file * * is already present in the configuration and you * * addProperty("resource.loader", "classpath") * * Then you will end up with a Vector like the * following: * * ["file", "classpath"] * * @param String key * @param String value */ public void addProperty(String key, Object token) { Object o = this.get(key); /* * $$$ GMJ * FIXME : post 1.0 release, we need to not assume * that a scalar is a String - it can be an Object * so we should make a little vector-like class * say, Foo that wraps (not extends Vector), * so we can do things like * if ( !( o instanceof Foo) ) * so we know it's our 'vector' container * * This applies throughout */ if (o instanceof String) { Vector v = new Vector(2); v.addElement(o); v.addElement(token); put(key, v); } else if (o instanceof Vector) { ((Vector) o).addElement(token); } else { /* * This is the first time that we have seen * request to place an object in the * configuration with the key 'key'. So * we just want to place it directly into * the configuration ... but we are going to * make a special exception for String objects * that contain "," characters. We will take * CSV lists and turn the list into a vector of * Strings before placing it in the configuration. * This is a concession for Properties and the * like that cannot parse multiple same key * values. */ if (token instanceof String && ((String)token).indexOf(PropertiesTokenizer.DELIMITER) > 0) { PropertiesTokenizer tokenizer = new PropertiesTokenizer((String)token); while (tokenizer.hasMoreTokens()) { String value = tokenizer.nextToken(); /* * we know this is a string, so make sure it * just goes in rather than risking vectorization * if it contains an escaped comma */ addStringProperty(key,value); } } else { /* * We want to keep track of the order the keys * are parsed, or dynamically entered into * the configuration. So when we see a key * for the first time we will place it in * an ArrayList so that if a client class needs * to perform operations with configuration * in a definite order it will be possible. */ addPropertyDirect( key, token ); } } } /** * Adds a key/value pair to the map. This routine does * no magic morphing. It ensures the keylist is maintained * * @param key key to use for mapping * @param obj object to store */ private void addPropertyDirect( String key, Object obj ) { /* * safety check */ if( !containsKey( key ) ) { keysAsListed.add(key); } /* * and the value */ put(key, obj); } /** * Sets a string property w/o checking for commas - used * internally when a property has been broken up into * strings that could contain escaped commas to prevent * the inadvertant vectorization. * * Thanks to Leon Messerschmidt for this one. * */ private void addStringProperty(String key, String token) { Object o = this.get(key); /* * $$$ GMJ * FIXME : post 1.0 release, we need to not assume * that a scalar is a String - it can be an Object * so we should make a little vector-like class * say, Foo that wraps (not extends Vector), * so we can do things like * if ( !( o instanceof Foo) ) * so we know it's our 'vector' container * * This applies throughout */ /* * do the usual thing - if we have a value and * it's scalar, make a vector, otherwise add * to the vector */ if (o instanceof String) { Vector v = new Vector(2); v.addElement(o); v.addElement(token); put(key, v); } else if (o instanceof Vector) { ((Vector) o).addElement(token); } else { addPropertyDirect( key, token ); } } /** * Set a property, this will replace any previously * set values. Set values is implicitly a call * to clearProperty(key), addProperty(key,value). * * @param String key * @param String value */ public void setProperty(String key, Object value) { clearProperty(key); addProperty(key,value); } /** * Save the properties to the given outputstream. * * @param output An OutputStream. * @param header A String. * @exception IOException. */ public synchronized void save(OutputStream output, String Header) throws IOException { if(output != null) { PrintWriter theWrtr = new PrintWriter(output); if(Header != null) { theWrtr.println(Header); } Enumeration theKeys = keys(); while(theKeys.hasMoreElements()) { String key = (String) theKeys.nextElement(); Object value = get((Object) key); if(value != null) { if(value instanceof String) { StringBuffer currentOutput = new StringBuffer(); currentOutput.append(key); currentOutput.append("="); currentOutput.append((String) value); theWrtr.println(currentOutput.toString()); } else if(value instanceof Vector) { Vector values = (Vector) value; Enumeration valuesEnum = values.elements(); while(valuesEnum.hasMoreElements()) { String currentElement = (String) valuesEnum.nextElement(); StringBuffer currentOutput = new StringBuffer(); currentOutput.append(key); currentOutput.append("="); currentOutput.append(currentElement); theWrtr.println(currentOutput.toString()); } } } theWrtr.println(); theWrtr.flush(); } } } /** * Combines an existing Hashtable with this Hashtable. * * Warning: It will overwrite previous entries without warning. * * @param ExtendedProperties */ public void combine( ExtendedProperties c ) { for (Iterator i = c.getKeys() ; i.hasNext() ;) { String key = (String) i.next(); setProperty( key, c.get(key) ); } } /** * Clear a property in the configuration. * * @param String key to remove along with corresponding value. */ public void clearProperty(String key) { if (containsKey(key)) { /* * we also need to rebuild the keysAsListed or else * things get *very* confusing */ for(int i = 0; i < keysAsListed.size(); i++) { if ( ( (String) keysAsListed.get(i)).equals( key ) ) { keysAsListed.remove(i); break; } } remove(key); } } /** * Get the list of the keys contained in the configuration * repository. * * @return An Iterator. */ public Iterator getKeys() { return keysAsListed.iterator(); } /** * Get the list of the keys contained in the configuration * repository that match the specified prefix. * * @param prefix The prefix to test against. * @return An Iterator of keys that match the prefix. */ public Iterator getKeys(String prefix) { Iterator keys = getKeys(); ArrayList matchingKeys = new ArrayList(); while( keys.hasNext() ) { Object key = keys.next(); if( key instanceof String && ((String) key).startsWith(prefix) ) { matchingKeys.add(key); } } return matchingKeys.iterator(); } /** * Create an ExtendedProperties object that is a subset * of this one. Take into account duplicate keys * by using the setProperty() in ExtendedProperties. * * @param String prefix */ public ExtendedProperties subset(String prefix) { ExtendedProperties c = new ExtendedProperties(); Iterator keys = getKeys(); boolean validSubset = false; while( keys.hasNext() ) { Object key = keys.next(); if( key instanceof String && ((String) key).startsWith(prefix) ) { if (!validSubset) { validSubset = true; } String newKey = null; /* * Check to make sure that c.subset(prefix) doesn't * blow up when there is only a single property * with the key prefix. This is not a useful * subset but it is a valid subset. */ if ( ((String)key).length() == prefix.length()) { newKey = prefix; } else { newKey = ((String)key).substring(prefix.length() + 1); } /* * use addPropertyDirect() - this will plug the data as * is into the Map, but will also do the right thing * re key accounting */ c.addPropertyDirect( newKey, get(key) ); } } if (validSubset) { return c; } else { return null; } } /** * Display the configuration for debugging * purposes. */ public void display() { Iterator i = getKeys(); while (i.hasNext()) { String key = (String) i.next(); Object value = get(key); System.out.println(key + " => " + value); } } /** * Get a string associated with the given configuration key. * * @param key The configuration key. * @return The associated string. * @exception ClassCastException is thrown if the key maps to an * object that is not a String. */ public String getString(String key) { return getString(key, null); } /** * Get a string associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated string if key is found, * default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a String. */ public String getString(String key, String defaultValue) { Object value = get(key); if (value instanceof String) { return (String) interpolate((String)value); } else if (value == null) { if (defaults != null) { return interpolate(defaults.getString(key, defaultValue)); } else { return interpolate(defaultValue); } } else if (value instanceof Vector) { return interpolate((String) ((Vector) value).get(0)); } else { throw new ClassCastException( '\'' + key + "' doesn't map to a String object"); } } /** * Get a list of properties associated with the given * configuration key. * * @param key The configuration key. * @return The associated properties if key is found. * @exception ClassCastException is thrown if the key maps to an * object that is not a String/Vector. * @exception IllegalArgumentException if one of the tokens is * malformed (does not contain an equals sign). */ public Properties getProperties(String key) { return getProperties(key, new Properties()); } /** * Get a list of properties associated with the given * configuration key. * * @param key The configuration key. * @return The associated properties if key is found. * @exception ClassCastException is thrown if the key maps to an * object that is not a String/Vector. * @exception IllegalArgumentException if one of the tokens is * malformed (does not contain an equals sign). */ public Properties getProperties(String key, Properties defaults) { /* * Grab an array of the tokens for this key. */ String[] tokens = getStringArray(key); /* * Each token is of the form 'key=value'. */ Properties props = new Properties(defaults); for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; int equalSign = token.indexOf('='); if (equalSign > 0) { String pkey = token.substring(0, equalSign).trim(); String pvalue = token.substring(equalSign + 1).trim(); props.put(pkey, pvalue); } else { throw new IllegalArgumentException('\'' + token + "' does not contain " + "an equals sign"); } } return props; } /** * Get an array of strings associated with the given configuration * key. * * @param key The configuration key. * @return The associated string array if key is found. * @exception ClassCastException is thrown if the key maps to an * object that is not a String/Vector. */ public String[] getStringArray(String key) { Object value = get(key); // What's your vector, Victor? Vector vector; if (value instanceof String) { vector = new Vector(1); vector.addElement(value); } else if (value instanceof Vector) { vector = (Vector)value; } else if (value == null) { if (defaults != null) { return defaults.getStringArray(key); } else { return new String[0]; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a String/Vector object"); } String[] tokens = new String[vector.size()]; for (int i = 0; i < tokens.length; i++) { tokens[i] = (String)vector.elementAt(i); } return tokens; } /** * Get a Vector of strings associated with the given configuration * key. * * @param key The configuration key. * @return The associated Vector. * @exception ClassCastException is thrown if the key maps to an * object that is not a Vector. */ public Vector getVector(String key) { return getVector(key, null); } /** * Get a Vector of strings associated with the given configuration * key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated Vector. * @exception ClassCastException is thrown if the key maps to an * object that is not a Vector. */ public Vector getVector(String key, Vector defaultValue) { Object value = get(key); if (value instanceof Vector) { return (Vector) value; } else if (value instanceof String) { Vector v = new Vector(1); v.addElement((String) value); put(key, v); return v; } else if (value == null) { if (defaults != null) { return defaults.getVector(key, defaultValue); } else { return ((defaultValue == null) ? new Vector() : defaultValue); } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Vector object"); } } /** * Get a boolean associated with the given configuration key. * * @param key The configuration key. * @return The associated boolean. * @exception NoSuchElementException is thrown if the key doesn't * map to an existing object. * @exception ClassCastException is thrown if the key maps to an * object that is not a Boolean. */ public boolean getBoolean(String key) { Boolean b = getBoolean(key, (Boolean) null); if (b != null) { return b.booleanValue(); } else { throw new NoSuchElementException( '\'' + key + "' doesn't map to an existing object"); } } /** * Get a boolean associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated boolean. * @exception ClassCastException is thrown if the key maps to an * object that is not a Boolean. */ public boolean getBoolean(String key, boolean defaultValue) { return getBoolean(key, new Boolean(defaultValue)).booleanValue(); } /** * Get a boolean associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated boolean if key is found and has valid * format, default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a Boolean. */ public Boolean getBoolean(String key, Boolean defaultValue) { Object value = get(key); if (value instanceof Boolean) { return (Boolean) value; } else if (value instanceof String) { String s = testBoolean((String)value); Boolean b = new Boolean(s); put(key, b); return b; } else if (value == null) { if (defaults != null) { return defaults.getBoolean(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Boolean object"); } } /** * Test whether the string represent by value maps to a boolean * value or not. We will allow true, on, * and yes for a true boolean value, and * false, off, and no for * false boolean values. Case of value to test for * boolean status is ignored. * * @param String The value to test for boolean state. * @return true or false if the supplied * text maps to a boolean value, or null otherwise. */ public String testBoolean(String value) { String s = ((String)value).toLowerCase(); if (s.equals("true") || s.equals("on") || s.equals("yes")) { return "true"; } else if (s.equals("false") || s.equals("off") || s.equals("no")) { return "false"; } else { return null; } } /** * Get a byte associated with the given configuration key. * * @param key The configuration key. * @return The associated byte. * @exception NoSuchElementException is thrown if the key doesn't * map to an existing object. * @exception ClassCastException is thrown if the key maps to an * object that is not a Byte. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public byte getByte(String key) { Byte b = getByte(key, null); if (b != null) { return b.byteValue(); } else { throw new NoSuchElementException( '\'' + key + " doesn't map to an existing object"); } } /** * Get a byte associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated byte. * @exception ClassCastException is thrown if the key maps to an * object that is not a Byte. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public byte getByte(String key, byte defaultValue) { return getByte(key, new Byte(defaultValue)).byteValue(); } /** * Get a byte associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated byte if key is found and has valid * format, default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a Byte. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Byte getByte(String key, Byte defaultValue) { Object value = get(key); if (value instanceof Byte) { return (Byte) value; } else if (value instanceof String) { Byte b = new Byte((String) value); put(key, b); return b; } else if (value == null) { if (defaults != null) { return defaults.getByte(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Byte object"); } } /** * Get a short associated with the given configuration key. * * @param key The configuration key. * @return The associated short. * @exception NoSuchElementException is thrown if the key doesn't * map to an existing object. * @exception ClassCastException is thrown if the key maps to an * object that is not a Short. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public short getShort(String key) { Short s = getShort(key, null); if (s != null) { return s.shortValue(); } else { throw new NoSuchElementException( '\'' + key + "' doesn't map to an existing object"); } } /** * Get a short associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated short. * @exception ClassCastException is thrown if the key maps to an * object that is not a Short. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public short getShort(String key, short defaultValue) { return getShort(key, new Short(defaultValue)).shortValue(); } /** * Get a short associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated short if key is found and has valid * format, default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a Short. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Short getShort(String key, Short defaultValue) { Object value = get(key); if (value instanceof Short) { return (Short) value; } else if (value instanceof String) { Short s = new Short((String) value); put(key, s); return s; } else if (value == null) { if (defaults != null) { return defaults.getShort(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Short object"); } } /** * The purpose of this method is to get the configuration resource * with the given name as an integer. * * @param name The resource name. * @return The value of the resource as an integer. */ public int getInt(String name) { return getInteger(name); } /** * The purpose of this method is to get the configuration resource * with the given name as an integer, or a default value. * * @param name The resource name * @param def The default value of the resource. * @return The value of the resource as an integer. */ public int getInt(String name, int def) { return getInteger(name, def); } /** * Get a int associated with the given configuration key. * * @param key The configuration key. * @return The associated int. * @exception NoSuchElementException is thrown if the key doesn't * map to an existing object. * @exception ClassCastException is thrown if the key maps to an * object that is not a Integer. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public int getInteger(String key) { Integer i = getInteger(key, null); if (i != null) { return i.intValue(); } else { throw new NoSuchElementException( '\'' + key + "' doesn't map to an existing object"); } } /** * Get a int associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated int. * @exception ClassCastException is thrown if the key maps to an * object that is not a Integer. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public int getInteger(String key, int defaultValue) { Integer i = getInteger(key, null); if (i == null) { return defaultValue; } return i.intValue(); } /** * Get a int associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated int if key is found and has valid * format, default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a Integer. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Integer getInteger(String key, Integer defaultValue) { Object value = get(key); if (value instanceof Integer) { return (Integer) value; } else if (value instanceof String) { Integer i = new Integer((String) value); put(key, i); return i; } else if (value == null) { if (defaults != null) { return defaults.getInteger(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Integer object"); } } /** * Get a long associated with the given configuration key. * * @param key The configuration key. * @return The associated long. * @exception NoSuchElementException is thrown if the key doesn't * map to an existing object. * @exception ClassCastException is thrown if the key maps to an * object that is not a Long. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public long getLong(String key) { Long l = getLong(key, null); if (l != null) { return l.longValue(); } else { throw new NoSuchElementException( '\'' + key + "' doesn't map to an existing object"); } } /** * Get a long associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated long. * @exception ClassCastException is thrown if the key maps to an * object that is not a Long. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public long getLong(String key, long defaultValue) { return getLong(key, new Long(defaultValue)).longValue(); } /** * Get a long associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated long if key is found and has valid * format, default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a Long. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Long getLong(String key, Long defaultValue) { Object value = get(key); if (value instanceof Long) { return (Long) value; } else if (value instanceof String) { Long l = new Long((String) value); put(key, l); return l; } else if (value == null) { if (defaults != null) { return defaults.getLong(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Long object"); } } /** * Get a float associated with the given configuration key. * * @param key The configuration key. * @return The associated float. * @exception NoSuchElementException is thrown if the key doesn't * map to an existing object. * @exception ClassCastException is thrown if the key maps to an * object that is not a Float. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public float getFloat(String key) { Float f = getFloat(key, null); if (f != null) { return f.floatValue(); } else { throw new NoSuchElementException( '\'' + key + "' doesn't map to an existing object"); } } /** * Get a float associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated float. * @exception ClassCastException is thrown if the key maps to an * object that is not a Float. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public float getFloat(String key, float defaultValue) { return getFloat(key, new Float(defaultValue)).floatValue(); } /** * Get a float associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated float if key is found and has valid * format, default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a Float. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Float getFloat(String key, Float defaultValue) { Object value = get(key); if (value instanceof Float) { return (Float) value; } else if (value instanceof String) { Float f = new Float((String) value); put(key, f); return f; } else if (value == null) { if (defaults != null) { return defaults.getFloat(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Float object"); } } /** * Get a double associated with the given configuration key. * * @param key The configuration key. * @return The associated double. * @exception NoSuchElementException is thrown if the key doesn't * map to an existing object. * @exception ClassCastException is thrown if the key maps to an * object that is not a Double. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public double getDouble(String key) { Double d = getDouble(key, null); if (d != null) { return d.doubleValue(); } else { throw new NoSuchElementException( '\'' + key + "' doesn't map to an existing object"); } } /** * Get a double associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated double. * @exception ClassCastException is thrown if the key maps to an * object that is not a Double. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public double getDouble(String key, double defaultValue) { return getDouble(key, new Double(defaultValue)).doubleValue(); } /** * Get a double associated with the given configuration key. * * @param key The configuration key. * @param defaultValue The default value. * @return The associated double if key is found and has valid * format, default value otherwise. * @exception ClassCastException is thrown if the key maps to an * object that is not a Double. * @exception NumberFormatException is thrown if the value mapped * by the key has not a valid number format. */ public Double getDouble(String key, Double defaultValue) { Object value = get(key); if (value instanceof Double) { return (Double) value; } else if (value instanceof String) { Double d = new Double((String) value); put(key, d); return d; } else if (value == null) { if (defaults != null) { return defaults.getDouble(key, defaultValue); } else { return defaultValue; } } else { throw new ClassCastException( '\'' + key + "' doesn't map to a Double object"); } } /** * Convert a standard properties class into a configuration * class. * * @param p properties object to convert into * a ExtendedProperties object. * * @return ExtendedProperties configuration created from the * properties object. */ public static ExtendedProperties convertProperties(Properties p) { ExtendedProperties c = new ExtendedProperties(); for (Enumeration e = p.keys(); e.hasMoreElements() ; ) { String s = (String) e.nextElement(); c.setProperty(s, p.getProperty(s)); } return c; } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ArrayStack.java0100644000175000017500000001431710055172376031200 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.EmptyStackException; /** * An implementation of the {@link java.util.Stack} API that is based on an * ArrayList instead of a Vector, so it is not * synchronized to protect against multi-threaded access. The implementation * is therefore operates faster in environments where you do not need to * worry about multiple thread contention. *

* The removal order of an ArrayStack is based on insertion * order: The most recently added element is removed first. The iteration * order is not the same as the removal order. The iterator returns * elements from the bottom up, whereas the {@link #remove()} method removes * them from the top down. *

* Unlike Stack, ArrayStack accepts null entries. * * @author Craig R. McClanahan * @author Paul Jack * @author Stephen Colebourne * @since 1.0 * @version $Id: ArrayStack.java,v 1.10.2.1 2004/05/22 12:14:01 scolebourne Exp $ * @see java.util.Stack */ public class ArrayStack extends ArrayList implements Buffer { final private static long serialVersionUID = 2130079159931574599L; //, local class serialVersionUID = -3491241305852305742 /** * Constructs a new empty ArrayStack. The initial size * is controlled by ArrayList and is currently 10. */ public ArrayStack() { super(); } /** * Constructs a new empty ArrayStack with an initial size. * * @param initialSize the initial size to use * @throws IllegalArgumentException if the specified initial size * is negative */ public ArrayStack(int initialSize) { super(initialSize); } /** * Return true if this stack is currently empty. *

* This method exists for compatability with java.util.Stack. * New users of this class should use isEmpty instead. * * @return true if the stack is currently empty */ public boolean empty() { return isEmpty(); } /** * Returns the top item off of this stack without removing it. * * @return the top item on the stack * @throws EmptyStackException if the stack is empty */ public Object peek() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return get(n - 1); } } /** * Returns the n'th item down (zero-relative) from the top of this * stack without removing it. * * @param n the number of items down to go * @return the n'th item on the stack, zero relative * @throws EmptyStackException if there are not enough items on the * stack to satisfy this request */ public Object peek(int n) throws EmptyStackException { int m = (size() - n) - 1; if (m < 0) { throw new EmptyStackException(); } else { return get(m); } } /** * Pops the top item off of this stack and return it. * * @return the top item on the stack * @throws EmptyStackException if the stack is empty */ public Object pop() throws EmptyStackException { int n = size(); if (n <= 0) { throw new EmptyStackException(); } else { return remove(n - 1); } } /** * Pushes a new item onto the top of this stack. The pushed item is also * returned. This is equivalent to calling add. * * @param item the item to be added * @return the item just pushed */ public Object push(Object item) { add(item); return item; } /** * Returns the one-based position of the distance from the top that the * specified object exists on this stack, where the top-most element is * considered to be at distance 1. If the object is not * present on the stack, return -1 instead. The * equals() method is used to compare to the items * in this stack. * * @param object the object to be searched for * @return the 1-based depth into the stack of the object, or -1 if not found */ public int search(Object object) { int i = size() - 1; // Current index int n = 1; // Current distance while (i >= 0) { Object current = get(i); if ((object == null && current == null) || (object != null && object.equals(current))) { return n; } i--; n++; } return -1; } /** * Returns the element on the top of the stack. * * @return the element on the top of the stack * @throws BufferUnderflowException if the stack is empty */ public Object get() { int size = size(); if (size == 0) { throw new BufferUnderflowException(); } return get(size - 1); } /** * Removes the element on the top of the stack. * * @return the removed element * @throws BufferUnderflowException if the stack is empty */ public Object remove() { int size = size(); if (size == 0) { throw new BufferUnderflowException(); } return remove(size - 1); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/FastArrayList.java0100644000175000017500000011115710055172400031650 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** *

A customized implementation of java.util.ArrayList designed * to operate in a multithreaded environment where the large majority of * method calls are read-only, instead of structural changes. When operating * in "fast" mode, read calls are non-synchronized and write calls perform the * following steps:

* *

When first created, objects of this class default to "slow" mode, where * all accesses of any type are synchronized but no cloning takes place. This * is appropriate for initially populating the collection, followed by a switch * to "fast" mode (by calling setFast(true)) after initialization * is complete.

* *

NOTE: If you are creating and accessing an * ArrayList only within a single thread, you should use * java.util.ArrayList directly (with no synchronization), for * maximum performance.

* *

NOTE: This class is not cross-platform. * Using it may cause unexpected failures on some architectures. * It suffers from the same problems as the double-checked locking idiom. * In particular, the instruction that clones the internal collection and the * instruction that sets the internal reference to the clone can be executed * or perceived out-of-order. This means that any read operation might fail * unexpectedly, as it may be reading the state of the internal collection * before the internal collection is fully formed. * For more information on the double-checked locking idiom, see the * * Double-Checked Locking Idiom Is Broken Declartion.

* * @since 1.0 * @author Craig R. McClanahan * @version $Revision: 1.9.2.1 $ $Date: 2004/05/22 12:14:02 $ */ public class FastArrayList extends ArrayList { // ----------------------------------------------------------- Constructors /** * Construct a an empty list. */ public FastArrayList() { super(); this.list = new ArrayList(); } /** * Construct an empty list with the specified capacity. * * @param capacity The initial capacity of the empty list */ public FastArrayList(int capacity) { super(); this.list = new ArrayList(capacity); } /** * Construct a list containing the elements of the specified collection, * in the order they are returned by the collection's iterator. * * @param collection The collection whose elements initialize the contents * of this list */ public FastArrayList(Collection collection) { super(); this.list = new ArrayList(collection); } // ----------------------------------------------------- Instance Variables /** * The underlying list we are managing. */ protected ArrayList list = null; // ------------------------------------------------------------- Properties /** * Are we operating in "fast" mode? */ protected boolean fast = false; /** * Returns true if this list is operating in fast mode. * * @return true if this list is operating in fast mode */ public boolean getFast() { return (this.fast); } /** * Sets whether this list will operate in fast mode. * * @param fast true if the list should operate in fast mode */ public void setFast(boolean fast) { this.fast = fast; } // --------------------------------------------------------- Public Methods /** * Appends the specified element to the end of this list. * * @param element The element to be appended */ public boolean add(Object element) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.add(element); list = temp; return (result); } } else { synchronized (list) { return (list.add(element)); } } } /** * Insert the specified element at the specified position in this list, * and shift all remaining elements up one position. * * @param index Index at which to insert this element * @param element The element to be inserted * * @exception IndexOutOfBoundsException if the index is out of range */ public void add(int index, Object element) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.add(index, element); list = temp; } } else { synchronized (list) { list.add(index, element); } } } /** * Append all of the elements in the specified Collection to the end * of this list, in the order that they are returned by the specified * Collection's Iterator. * * @param collection The collection to be appended */ public boolean addAll(Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.addAll(collection); list = temp; return (result); } } else { synchronized (list) { return (list.addAll(collection)); } } } /** * Insert all of the elements in the specified Collection at the specified * position in this list, and shift any previous elements upwards as * needed. * * @param index Index at which insertion takes place * @param collection The collection to be added * * @exception IndexOutOfBoundsException if the index is out of range */ public boolean addAll(int index, Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.addAll(index, collection); list = temp; return (result); } } else { synchronized (list) { return (list.addAll(index, collection)); } } } /** * Remove all of the elements from this list. The list will be empty * after this call returns. * * @exception UnsupportedOperationException if clear() * is not supported by this list */ public void clear() { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.clear(); list = temp; } } else { synchronized (list) { list.clear(); } } } /** * Return a shallow copy of this FastArrayList instance. * The elements themselves are not copied. */ public Object clone() { FastArrayList results = null; if (fast) { results = new FastArrayList(list); } else { synchronized (list) { results = new FastArrayList(list); } } results.setFast(getFast()); return (results); } /** * Return true if this list contains the specified element. * * @param element The element to test for */ public boolean contains(Object element) { if (fast) { return (list.contains(element)); } else { synchronized (list) { return (list.contains(element)); } } } /** * Return true if this list contains all of the elements * in the specified Collection. * * @param collection Collection whose elements are to be checked */ public boolean containsAll(Collection collection) { if (fast) { return (list.containsAll(collection)); } else { synchronized (list) { return (list.containsAll(collection)); } } } /** * Increase the capacity of this ArrayList instance, if * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. * * @param capacity The new minimum capacity */ public void ensureCapacity(int capacity) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.ensureCapacity(capacity); list = temp; } } else { synchronized (list) { list.ensureCapacity(capacity); } } } /** * Compare the specified object with this list for equality. This * implementation uses exactly the code that is used to define the * list equals function in the documentation for the * List.equals method. * * @param o Object to be compared to this list */ public boolean equals(Object o) { // Simple tests that require no synchronization if (o == this) return (true); else if (!(o instanceof List)) return (false); List lo = (List) o; // Compare the sets of elements for equality if (fast) { ListIterator li1 = list.listIterator(); ListIterator li2 = lo.listIterator(); while (li1.hasNext() && li2.hasNext()) { Object o1 = li1.next(); Object o2 = li2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return (false); } return (!(li1.hasNext() || li2.hasNext())); } else { synchronized (list) { ListIterator li1 = list.listIterator(); ListIterator li2 = lo.listIterator(); while (li1.hasNext() && li2.hasNext()) { Object o1 = li1.next(); Object o2 = li2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return (false); } return (!(li1.hasNext() || li2.hasNext())); } } } /** * Return the element at the specified position in the list. * * @param index The index of the element to return * * @exception IndexOutOfBoundsException if the index is out of range */ public Object get(int index) { if (fast) { return (list.get(index)); } else { synchronized (list) { return (list.get(index)); } } } /** * Return the hash code value for this list. This implementation uses * exactly the code that is used to define the list hash function in the * documentation for the List.hashCode method. */ public int hashCode() { if (fast) { int hashCode = 1; java.util.Iterator i = list.iterator(); while (i.hasNext()) { Object o = i.next(); hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); } return (hashCode); } else { synchronized (list) { int hashCode = 1; java.util.Iterator i = list.iterator(); while (i.hasNext()) { Object o = i.next(); hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); } return (hashCode); } } } /** * Search for the first occurrence of the given argument, testing * for equality using the equals() method, and return * the corresponding index, or -1 if the object is not found. * * @param element The element to search for */ public int indexOf(Object element) { if (fast) { return (list.indexOf(element)); } else { synchronized (list) { return (list.indexOf(element)); } } } /** * Test if this list has no elements. */ public boolean isEmpty() { if (fast) { return (list.isEmpty()); } else { synchronized (list) { return (list.isEmpty()); } } } /** * Return an iterator over the elements in this list in proper sequence. *

* IMPLEMENTATION NOTE - If the list is operating in fast * mode, an Iterator is returned, and a structural modification to the * list is made, then the Iterator will continue over the previous contents * of the list (at the time that the Iterator was created), rather than * failing due to concurrent modifications. */ public Iterator iterator() { if (fast) { return new ListIter(0); } else { return list.iterator(); } } /** * Search for the last occurrence of the given argument, testing * for equality using the equals() method, and return * the corresponding index, or -1 if the object is not found. * * @param element The element to search for */ public int lastIndexOf(Object element) { if (fast) { return (list.lastIndexOf(element)); } else { synchronized (list) { return (list.lastIndexOf(element)); } } } /** * Return an iterator of the elements of this list, in proper sequence. * See the implementation note on iterator(). */ public ListIterator listIterator() { if (fast) { return new ListIter(0); } else { return list.listIterator(); } } /** * Return an iterator of the elements of this list, in proper sequence, * starting at the specified position. * See the implementation note on iterator(). * * @param index The starting position of the iterator to return * * @exception IndexOutOfBoundsException if the index is out of range */ public ListIterator listIterator(int index) { if (fast) { return new ListIter(index); } else { return list.listIterator(index); } } /** * Remove the element at the specified position in the list, and shift * any subsequent elements down one position. * * @param index Index of the element to be removed * * @exception IndexOutOfBoundsException if the index is out of range */ public Object remove(int index) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); Object result = temp.remove(index); list = temp; return (result); } } else { synchronized (list) { return (list.remove(index)); } } } /** * Remove the first occurrence of the specified element from the list, * and shift any subsequent elements down one position. * * @param element Element to be removed */ public boolean remove(Object element) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.remove(element); list = temp; return (result); } } else { synchronized (list) { return (list.remove(element)); } } } /** * Remove from this collection all of its elements that are contained * in the specified collection. * * @param collection Collection containing elements to be removed * * @exception UnsupportedOperationException if this optional operation * is not supported by this list */ public boolean removeAll(Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.removeAll(collection); list = temp; return (result); } } else { synchronized (list) { return (list.removeAll(collection)); } } } /** * Remove from this collection all of its elements except those that are * contained in the specified collection. * * @param collection Collection containing elements to be retained * * @exception UnsupportedOperationException if this optional operation * is not supported by this list */ public boolean retainAll(Collection collection) { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); boolean result = temp.retainAll(collection); list = temp; return (result); } } else { synchronized (list) { return (list.retainAll(collection)); } } } /** * Replace the element at the specified position in this list with * the specified element. Returns the previous object at that position. *

* IMPLEMENTATION NOTE - This operation is specifically * documented to not be a structural change, so it is safe to be performed * without cloning. * * @param index Index of the element to replace * @param element The new element to be stored * * @exception IndexOutOfBoundsException if the index is out of range */ public Object set(int index, Object element) { if (fast) { return (list.set(index, element)); } else { synchronized (list) { return (list.set(index, element)); } } } /** * Return the number of elements in this list. */ public int size() { if (fast) { return (list.size()); } else { synchronized (list) { return (list.size()); } } } /** * Return a view of the portion of this list between fromIndex * (inclusive) and toIndex (exclusive). The returned list is backed * by this list, so non-structural changes in the returned list are * reflected in this list. The returned list supports * all of the optional list operations supported by this list. * * @param fromIndex The starting index of the sublist view * @param toIndex The index after the end of the sublist view * * @exception IndexOutOfBoundsException if an index is out of range */ public List subList(int fromIndex, int toIndex) { if (fast) { return new SubList(fromIndex, toIndex); } else { return list.subList(fromIndex, toIndex); } } /** * Return an array containing all of the elements in this list in the * correct order. */ public Object[] toArray() { if (fast) { return (list.toArray()); } else { synchronized (list) { return (list.toArray()); } } } /** * Return an array containing all of the elements in this list in the * correct order. The runtime type of the returned array is that of * the specified array. If the list fits in the specified array, it is * returned therein. Otherwise, a new array is allocated with the * runtime type of the specified array, and the size of this list. * * @param array Array defining the element type of the returned list * * @exception ArrayStoreException if the runtime type of array * is not a supertype of the runtime type of every element in this list */ public Object[] toArray(Object array[]) { if (fast) { return (list.toArray(array)); } else { synchronized (list) { return (list.toArray(array)); } } } /** * Return a String representation of this object. */ public String toString() { StringBuffer sb = new StringBuffer("FastArrayList["); sb.append(list.toString()); sb.append("]"); return (sb.toString()); } /** * Trim the capacity of this ArrayList instance to be the * list's current size. An application can use this operation to minimize * the storage of an ArrayList instance. */ public void trimToSize() { if (fast) { synchronized (this) { ArrayList temp = (ArrayList) list.clone(); temp.trimToSize(); list = temp; } } else { synchronized (list) { list.trimToSize(); } } } private class SubList implements List { private int first; private int last; private List expected; public SubList(int first, int last) { this.first = first; this.last = last; this.expected = list; } private List get(List l) { if (list != expected) { throw new ConcurrentModificationException(); } return l.subList(first, last); } public void clear() { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); get(temp).clear(); last = first; list = temp; expected = temp; } } else { synchronized (list) { get(expected).clear(); } } } public boolean remove(Object o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).remove(o); if (r) last--; list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).remove(o); } } } public boolean removeAll(Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); List sub = get(temp); boolean r = sub.removeAll(o); if (r) last = first + sub.size(); list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).removeAll(o); } } } public boolean retainAll(Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); List sub = get(temp); boolean r = sub.retainAll(o); if (r) last = first + sub.size(); list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).retainAll(o); } } } public int size() { if (fast) { return get(expected).size(); } else { synchronized (list) { return get(expected).size(); } } } public boolean isEmpty() { if (fast) { return get(expected).isEmpty(); } else { synchronized (list) { return get(expected).isEmpty(); } } } public boolean contains(Object o) { if (fast) { return get(expected).contains(o); } else { synchronized (list) { return get(expected).contains(o); } } } public boolean containsAll(Collection o) { if (fast) { return get(expected).containsAll(o); } else { synchronized (list) { return get(expected).containsAll(o); } } } public Object[] toArray(Object[] o) { if (fast) { return get(expected).toArray(o); } else { synchronized (list) { return get(expected).toArray(o); } } } public Object[] toArray() { if (fast) { return get(expected).toArray(); } else { synchronized (list) { return get(expected).toArray(); } } } public boolean equals(Object o) { if (o == this) return true; if (fast) { return get(expected).equals(o); } else { synchronized (list) { return get(expected).equals(o); } } } public int hashCode() { if (fast) { return get(expected).hashCode(); } else { synchronized (list) { return get(expected).hashCode(); } } } public boolean add(Object o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).add(o); if (r) last++; list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).add(o); } } } public boolean addAll(Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).addAll(o); if (r) last += o.size(); list = temp; expected = temp; return r; } } else { synchronized (list) { return get(expected).addAll(o); } } } public void add(int i, Object o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); get(temp).add(i, o); last++; list = temp; expected = temp; } } else { synchronized (list) { get(expected).add(i, o); } } } public boolean addAll(int i, Collection o) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); boolean r = get(temp).addAll(i, o); list = temp; if (r) last += o.size(); expected = temp; return r; } } else { synchronized (list) { return get(expected).addAll(i, o); } } } public Object remove(int i) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); Object o = get(temp).remove(i); last--; list = temp; expected = temp; return o; } } else { synchronized (list) { return get(expected).remove(i); } } } public Object set(int i, Object a) { if (fast) { synchronized (FastArrayList.this) { ArrayList temp = (ArrayList) list.clone(); Object o = get(temp).set(i, a); list = temp; expected = temp; return o; } } else { synchronized (list) { return get(expected).set(i, a); } } } public Iterator iterator() { return new SubListIter(0); } public ListIterator listIterator() { return new SubListIter(0); } public ListIterator listIterator(int i) { return new SubListIter(i); } public Object get(int i) { if (fast) { return get(expected).get(i); } else { synchronized (list) { return get(expected).get(i); } } } public int indexOf(Object o) { if (fast) { return get(expected).indexOf(o); } else { synchronized (list) { return get(expected).indexOf(o); } } } public int lastIndexOf(Object o) { if (fast) { return get(expected).lastIndexOf(o); } else { synchronized (list) { return get(expected).lastIndexOf(o); } } } public List subList(int f, int l) { if (list != expected) { throw new ConcurrentModificationException(); } return new SubList(first + f, f + l); } private class SubListIter implements ListIterator { private List expected; private ListIterator iter; private int lastReturnedIndex = -1; public SubListIter(int i) { this.expected = list; this.iter = SubList.this.get(expected).listIterator(i); } private void checkMod() { if (list != expected) { throw new ConcurrentModificationException(); } } List get() { return SubList.this.get(expected); } public boolean hasNext() { checkMod(); return iter.hasNext(); } public Object next() { checkMod(); lastReturnedIndex = iter.nextIndex(); return iter.next(); } public boolean hasPrevious() { checkMod(); return iter.hasPrevious(); } public Object previous() { checkMod(); lastReturnedIndex = iter.previousIndex(); return iter.previous(); } public int previousIndex() { checkMod(); return iter.previousIndex(); } public int nextIndex() { checkMod(); return iter.nextIndex(); } public void remove() { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().remove(lastReturnedIndex); last--; expected = list; iter = get().listIterator(previousIndex()); lastReturnedIndex = -1; } public void set(Object o) { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().set(lastReturnedIndex, o); expected = list; iter = get().listIterator(previousIndex() + 1); } public void add(Object o) { checkMod(); int i = nextIndex(); get().add(i, o); last++; iter = get().listIterator(i + 1); lastReturnedIndex = 1; } } } private class ListIter implements ListIterator { private List expected; private ListIterator iter; private int lastReturnedIndex = -1; public ListIter(int i) { this.expected = list; this.iter = get().listIterator(i); } private void checkMod() { if (list != expected) { throw new ConcurrentModificationException(); } } List get() { return expected; } public boolean hasNext() { checkMod(); return iter.hasNext(); } public Object next() { checkMod(); lastReturnedIndex = iter.nextIndex(); return iter.next(); } public boolean hasPrevious() { checkMod(); return iter.hasPrevious(); } public Object previous() { checkMod(); lastReturnedIndex = iter.previousIndex(); return iter.previous(); } public int previousIndex() { checkMod(); return iter.previousIndex(); } public int nextIndex() { checkMod(); return iter.nextIndex(); } public void remove() { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().remove(lastReturnedIndex); expected = list; iter = get().listIterator(previousIndex()); lastReturnedIndex = -1; } public void set(Object o) { checkMod(); if (lastReturnedIndex < 0) { throw new IllegalStateException(); } get().set(lastReturnedIndex, o); expected = list; iter = get().listIterator(previousIndex() + 1); } public void add(Object o) { checkMod(); int i = nextIndex(); get().add(i, o); iter = get().listIterator(i + 1); lastReturnedIndex = 1; } } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SoftRefHashMap.java0100644000175000017500000002113210055172400031723 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.TreeSet; /**

* HashMap with SoftReference links to values which allows the values of the Map * to be garbage collected by the JVM if it becomes low on memory. * Derive from this class and * override the factory method createReference() method to make * a Map wrapped in other types of Reference. *

* *

* A synchronized version can be obtained with: * Collections.synchronizedMap( theMapToSynchronize ) *

* *

* WARNING the values() and entrySet() methods require optimisation * like the standard {@link HashMap} implementations so that iteration * over this Map is efficient. *

* * @since 1.0 * @author James.Dodd * @author James Strachan * @deprecated This class is all kinds of wonky; use ReferenceMap instead. * @see * Bug#9571 */ public class SoftRefHashMap implements Map { /** The wrapped HashMap */ private Map hashMap = new HashMap(); public SoftRefHashMap() { } /** * Removes References that have had their referents garbage collected */ public void purge() { Map map = getMap(); Set keys = map.keySet(); if ( keys == null ) { return; } for ( Iterator i = keys.iterator(); i.hasNext(); ) { Object key = (Object) i.next(); Reference ref = (Reference) map.get( key ); if ( ref.get() == null ) { map.remove( key ); } } } // Map implementation // ------------------------------------------------------- /** * Retrieves the referent of the Referenced value * @param key The key with which to retrieve the value */ public Object get( final Object key ) { Reference ref = (Reference) getMap().get( key ); if ( ref == null ) { return null; } return ref.get(); } /** * Adds a key-value mapping, wrapping the value in a Reference */ public Object put( final Object key, final Object value ) { Object answer = getMap().put( key, createReference( value ) ); if ( answer != null ) { return ((Reference) answer).get(); } return null; } /** * Returns a collection of the Referenced values */ public Collection values() { Set wrappedValues = (Set) getMap().values(); Set values = new TreeSet(); if ( wrappedValues == null ) { return values; } for ( Iterator i = wrappedValues.iterator(); i.hasNext(); ) { Reference ref = (Reference) i.next(); if ( ref != null ) { values.add( ref.get() ); } } return values; } /** * Answers whether the argument is in the domain of the mappings */ public boolean containsKey( Object key ) { return getMap().containsKey( key ); } /** * Answers whether the argument is a Referenced value */ public boolean containsValue( Object value ) { Collection values = (Collection) getMap().values(); if ( values == null ) { return false; } for ( Iterator i = values.iterator(); i.hasNext(); ) { Reference ref = (Reference) i.next(); if ( ref == null ) { continue; } Object target = ref.get(); if ( target == value ) { return true; } } return false; } /** * Put all of the mappings in the argument into this wrapped map */ public void putAll( final java.util.Map map ) { if ( map == null || map.size() == 0 ) { return; } for ( Iterator i = map.keySet().iterator(); i.hasNext(); ) { Object key = (Object) i.next(); put( key, map.get( key ) ); } } /** * Returns a set view of the mappings in the wrapped map */ public Set entrySet() { Set entries = new HashSet(); if ( size() == 0 ) { return entries; } for ( Iterator i = keySet().iterator(); i.hasNext(); ) { Object key = i.next(); Object value = get( key ); Entry entry = new Entry( key, value ); entries.add( entry ); } return entries; } /** * Removes a mapping from this map */ public Object remove( final Object key ) { Reference ref = (Reference) getMap().remove( key ); if ( ref != null ) { return ref.get(); } return null; } /** * Clears all mappings */ public void clear() { getMap().clear(); } /** * Calculates the hash code for this map */ public int hashCode() { return getMap().hashCode(); } /** * Returns the domain of the mappings */ public Set keySet() { return getMap().keySet(); } /** * Answers whether there are any mappings */ public boolean isEmpty() { return getMap().isEmpty(); } /** * Answers whether this map and the argument are 'the same' */ public boolean equals( final Object object ) { return getMap().equals( object ); } /** * Returns the number of mappings in this map */ public int size() { return getMap().size(); } // Inner Classes // --------------------------------------------------------------------- /** * A map entry, which is backed by this RefHashMap */ class Entry implements Map.Entry { /** * Constructor */ public Entry( Object key, Object value ) { this.key = key; this.value = value; } // Map.Entry interface // ----------------------------------------------------------- /** * Retrieves the key of this mapping */ public Object getKey() { return key; } /** * Retrieves the value of this mapping */ public Object getValue() { return value; } /** * Sets the value of this mapping */ public Object setValue( Object value ) { this.value = value; put( key, value ); return value; } /** * Return the hash code of this mapping. * This algorithm was taken from the JavaDoc for Map.Entry */ public int hashCode() { return ( getKey() == null ? 0 : getKey().hashCode() ) ^ ( getValue() == null ? 0 : getValue().hashCode() ); } /** The domain of this mapping */ private Object key; /** The range of this mapping */ private Object value; } /** * Returns a reference to the argument. * Override this method to make wrapped maps for other Reference types */ protected Reference createReference( Object referent ) { return new SoftReference( referent ); } /** * Retrieves the wrapped HashMap * @return The wrapped HashMap */ protected Map getMap() { return hashMap; } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/Predicate.java0100644000175000017500000000223510055172376031030 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** Performs some predicate which returns true or false based on the input object. * Predicate instances can be used to implement queries or to do filtering. * * @since 1.0 * @author James Strachan */ public interface Predicate { /** * Returns true if the input object matches this predicate. * * @return true if the input object matches this predicate, else returns false */ public boolean evaluate(Object input); } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/Factory.java0100644000175000017500000000210010055172376030526 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * Factory * A simple interface that describes the most basic means of having the ability * to create an object. * * @author Arron Bates * @version $Revision: 1.3.2.1 $ * @since 2.1 */ public interface Factory { /** Simple method from which will come the new object from the factory. * * @return Object reference to the new object. */ public Object create(); } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/CollectionUtils.java0100644000175000017500000010313010055172376032240 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import org.apache.commons.collections.iterators.ArrayIterator; import org.apache.commons.collections.iterators.EnumerationIterator; /** * A set of {@link Collection} related utility methods. * * @since 1.0 * @author Rodney Waldhoff * @author Paul Jack * @author Stephen Colebourne * @author Steve Downey * @version $Revision: 1.18.2.2 $ $Date: 2004/05/22 12:14:02 $ */ public class CollectionUtils { /** * The empty iterator (immutable). * @deprecated use IteratorUtils.EMPTY_ITERATOR */ public static final Iterator EMPTY_ITERATOR = IteratorUtils.EMPTY_ITERATOR; /** * Please don't ever instantiate a CollectionUtils. */ public CollectionUtils() { } /** * Returns a {@link Collection} containing the union * of the given {@link Collection}s. *

* The cardinality of each element in the returned {@link Collection} * will be equal to the maximum of the cardinality of that element * in the two given {@link Collection}s. * * @see Collection#addAll */ public static Collection union(final Collection a, final Collection b) { ArrayList list = new ArrayList(); Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Set elts = new HashSet(a); elts.addAll(b); Iterator it = elts.iterator(); while(it.hasNext()) { Object obj = it.next(); for(int i=0,m=Math.max(getFreq(obj,mapa),getFreq(obj,mapb));i * The cardinality of each element in the returned {@link Collection} * will be equal to the minimum of the cardinality of that element * in the two given {@link Collection}s. * * @see Collection#retainAll * @see #containsAny */ public static Collection intersection(final Collection a, final Collection b) { ArrayList list = new ArrayList(); Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Set elts = new HashSet(a); elts.addAll(b); Iterator it = elts.iterator(); while(it.hasNext()) { Object obj = it.next(); for(int i=0,m=Math.min(getFreq(obj,mapa),getFreq(obj,mapb));i * The cardinality of each element e in the returned {@link Collection} * will be equal to * max(cardinality(e,a),cardinality(e,b)) - min(cardinality(e,a),cardinality(e,b)). *

* This is equivalent to * {@link #subtract subtract}({@link #union union(a,b)},{@link #intersection intersection(a,b)}) * or * {@link #union union}({@link #subtract subtract(a,b)},{@link #subtract subtract(b,a)}). */ public static Collection disjunction(final Collection a, final Collection b) { ArrayList list = new ArrayList(); Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Set elts = new HashSet(a); elts.addAll(b); Iterator it = elts.iterator(); while(it.hasNext()) { Object obj = it.next(); for(int i=0,m=((Math.max(getFreq(obj,mapa),getFreq(obj,mapb)))-(Math.min(getFreq(obj,mapa),getFreq(obj,mapb))));ia - b. * The cardinality of each element e in the returned {@link Collection} * will be the cardinality of e in a minus the cardinality * of e in b, or zero, whichever is greater. * * @see Collection#removeAll */ public static Collection subtract(final Collection a, final Collection b) { ArrayList list = new ArrayList( a ); Iterator it = b.iterator(); while(it.hasNext()) { list.remove(it.next()); } return list; } /** * Returns true iff some element of a * is also an element of b (or, equivalently, if * some element of b is also an element of a). * In other words, this method returns true * iff the {@link #intersection} of a and b * is not empty. * @since 2.1 * @param a a non-null Collection * @param b a non-null Collection * @return true iff the intersection of a and b is non-empty * @see #intersection */ public static boolean containsAny(final Collection a, final Collection b) { // TO DO: we may be able to optimize this by ensuring either a or b // is the larger of the two Collections, but I'm not sure which. for(Iterator iter = a.iterator(); iter.hasNext();) { if(b.contains(iter.next())) { return true; } } return false; } /** * Returns a {@link Map} mapping each unique element in * the given {@link Collection} to an {@link Integer} * representing the number of occurances of that element * in the {@link Collection}. * An entry that maps to null indicates that the * element does not appear in the given {@link Collection}. */ public static Map getCardinalityMap(final Collection col) { HashMap count = new HashMap(); Iterator it = col.iterator(); while(it.hasNext()) { Object obj = it.next(); Integer c = (Integer)(count.get(obj)); if(null == c) { count.put(obj,new Integer(1)); } else { count.put(obj,new Integer(c.intValue() + 1)); } } return count; } /** * Returns true iff a is a sub-collection of b, * that is, iff the cardinality of e in a is less * than or equal to the cardinality of e in b, * for each element e in a. * * @see #isProperSubCollection * @see Collection#containsAll */ public static boolean isSubCollection(final Collection a, final Collection b) { Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); Iterator it = a.iterator(); while (it.hasNext()) { Object obj = it.next(); if (getFreq(obj, mapa) > getFreq(obj, mapb)) { return false; } } return true; } /** * Returns true iff a is a proper sub-collection of b, * that is, iff the cardinality of e in a is less * than or equal to the cardinality of e in b, * for each element e in a, and there is at least one * element f such that the cardinality of f in b * is strictly greater than the cardinality of f in a. * * @see #isSubCollection * @see Collection#containsAll */ public static boolean isProperSubCollection(final Collection a, final Collection b) { // XXX optimize me! return CollectionUtils.isSubCollection(a,b) && (!(CollectionUtils.isEqualCollection(a,b))); } /** * Returns true iff the given {@link Collection}s contain * exactly the same elements with exactly the same cardinality. *

* That is, iff the cardinality of e in a is * equal to the cardinality of e in b, * for each element e in a or b. */ public static boolean isEqualCollection(final Collection a, final Collection b) { if(a.size() != b.size()) { return false; } else { Map mapa = getCardinalityMap(a); Map mapb = getCardinalityMap(b); if(mapa.size() != mapb.size()) { return false; } else { Iterator it = mapa.keySet().iterator(); while(it.hasNext()) { Object obj = it.next(); if(getFreq(obj,mapa) != getFreq(obj,mapb)) { return false; } } return true; } } } /** * Returns the number of occurrences of obj * in col. */ public static int cardinality(Object obj, final Collection col) { int count = 0; Iterator it = col.iterator(); while(it.hasNext()) { Object elt = it.next(); if((null == obj && null == elt) || obj.equals(elt)) { count++; } } return count; } /** * Finds the first element in the given collection which matches the given predicate. *

* If the input collection or predicate is null, null is returned. * * @param collection the collection to search, may be null * @param predicate the predicate to use, may be null * @return the first element of the collection which matches the predicate or null if none could be found */ public static Object find(Collection collection, Predicate predicate) { if (collection != null && predicate != null) { for (Iterator iter = collection.iterator(); iter.hasNext();) { Object item = iter.next(); if (predicate.evaluate(item)) { return item; } } } return null; } /** * Executes the given closure on each element in the collection. *

* If the input collection is null, there is no change made. * * @param collection the collection to get the input from, may be null * @param closure the closure to perform, may not be null * @throws NullPointerException if the closure is null */ public static void forAllDo(Collection collection, Closure closure) { if (collection != null) { for (Iterator iter = collection.iterator(); iter.hasNext();) { Object element = iter.next(); closure.execute(element); } } } /** * Filter the collection by applying a Predicate to each element. If the * predicate returns false, remove the element. *

* If the input collection or predicate is null, there is no change made. * * @param collection the collection to get the input from, may be null * @param predicate the predicate to use as a filter, may be null */ public static void filter(Collection collection, Predicate predicate) { if (collection != null && predicate != null) { for (Iterator iter = collection.iterator(); iter.hasNext();) { Object element = iter.next(); if (predicate.evaluate(element) == false) { iter.remove(); } } } } /** * Transform the collection by applying a Transformer to each element. *

* If the input collection or transformer is null, there is no change made. *

* This routine is best for Lists and uses set(), however it adapts for all * Collections that support clear() and addAll(). *

* If the input collection controls its input, such as a Set, and the * Transformer creates duplicates (or are otherwise invalid), the * collection may reduce in size due to calling this method. * * @param collection the collection to get the input from, may be null * @param transformer the transformer to perform, may be null */ public static void transform(Collection collection, Transformer transformer) { if (collection != null && transformer != null) { if (collection instanceof List) { List list = (List) collection; for (ListIterator iter = list.listIterator(); iter.hasNext();) { Object element = iter.next(); iter.set(transformer.transform(element)); } } else { Collection resultCollection = collect(collection, transformer); collection.clear(); collection.addAll(resultCollection); } } } /** * Selects all elements from input collection which match the given predicate * into an output collection. * * @param inputCollection the collection to get the input from, may not be null * @param predicate the predicate to use, may be null * @return the elements matching the predicate (new list) * @throws NullPointerException if the input collection is null */ public static Collection select(Collection inputCollection, Predicate predicate) { ArrayList answer = new ArrayList(inputCollection.size()); select(inputCollection, predicate, answer); return answer; } /** * Selects all elements from input collection which match the given predicate * and adds them to outputCollection. *

* If the input collection or predicate is null, there is no change to the * output collection. * * @param inputCollection the collection to get the input from, may be null * @param predicate the predicate to use, may be null * @param outputCollection the collection to output into, may not be null * @return the outputCollection with the the elements matching the predicate added * @throws NullPointerException if the input collection is null */ public static void select(Collection inputCollection, Predicate predicate, Collection outputCollection) { if (inputCollection != null && predicate != null) { for (Iterator iter = inputCollection.iterator(); iter.hasNext();) { Object item = iter.next(); if (predicate.evaluate(item)) { outputCollection.add(item); } } } } /** * Transforms all elements from inputCollection with the given transformer * and adds them to the outputCollection. *

* If the input transfomer is null, the result is an empty list. * * @param inputCollection the collection to get the input from, may not be null * @param transformer the transformer to use, may be null * @return the transformed result (new list) * @throws NullPointerException if the input collection is null */ public static Collection collect(Collection inputCollection, Transformer transformer) { ArrayList answer = new ArrayList(inputCollection.size()); collect(inputCollection, transformer, answer); return answer; } /** * Transforms all elements from the inputIterator with the given transformer * and adds them to the outputCollection. *

* If the input iterator or transfomer is null, the result is an empty list. * * @param inputIterator the iterator to get the input from, may be null * @param transformer the transformer to use, may be null * @return the transformed result (new list) */ public static Collection collect(Iterator inputIterator, Transformer transformer) { ArrayList answer = new ArrayList(); collect(inputIterator, transformer, answer); return answer; } /** * Transforms all elements from inputCollection with the given transformer * and adds them to the outputCollection. *

* If the input collection or transfomer is null, there is no change to the * output collection. * * @param inputCollection the collection to get the input from, may be null * @param transformer the transformer to use, may be null * @param outputCollection the collection to output into, may not be null * @return the outputCollection with the transformed input added * @throws NullPointerException if the output collection is null */ public static Collection collect(Collection inputCollection, final Transformer transformer, final Collection outputCollection) { if (inputCollection != null) { return collect(inputCollection.iterator(), transformer, outputCollection); } return outputCollection; } /** * Transforms all elements from the inputIterator with the given transformer * and adds them to the outputCollection. *

* If the input iterator or transfomer is null, there is no change to the * output collection. * * @param inputIterator the iterator to get the input from, may be null * @param transformer the transformer to use, may be null * @param outputCollection the collection to output into, may not be null * @return the outputCollection with the transformed input added * @throws NullPointerException if the output collection is null */ public static Collection collect(Iterator inputIterator, final Transformer transformer, final Collection outputCollection) { if (inputIterator != null && transformer != null) { while (inputIterator.hasNext()) { Object item = inputIterator.next(); Object value = transformer.transform(item); outputCollection.add(value); } } return outputCollection; } /** * Adds all elements in the iteration to the given collection. * * @param collection the collection to add to * @param iterator the iterator of elements to add, may not be null * @throws NullPointerException if the collection or iterator is null */ public static void addAll(Collection collection, Iterator iterator) { while (iterator.hasNext()) { collection.add(iterator.next()); } } /** * Adds all elements in the enumeration to the given collection. * * @param collection the collection to add to * @param enumeration the enumeration of elements to add, may not be null * @throws NullPointerException if the collection or enumeration is null */ public static void addAll(Collection collection, Enumeration enumeration) { while (enumeration.hasMoreElements()) { collection.add(enumeration.nextElement()); } } /** * Adds all elements in the array to the given collection. * * @param collection the collection to add to * @param elements the array of elements to add, may be null * @throws NullPointerException if the collection or array is null */ public static void addAll(Collection collection, Object[] elements) { for (int i = 0, size = elements.length; i < size; i++) { collection.add(elements[i]); } } /** * Given an Object, and an index, it will get the nth value in the * object. *

* * @param obj the object to get an index of * @param index the index to get * @throws IndexOutOfBoundsException * @throws NoSuchElementException */ public static Object index(Object obj, int idx) { return index(obj, new Integer(idx)); } /** * Given an Object, and a key (index), it will get value associated with * that key in the Object. The following checks are made: * * * @param obj the object to get an index of * @param index the index to get * @return the object at the specified index * @throws IndexOutOfBoundsException * @throws NoSuchElementException */ public static Object index(Object obj, Object index) { if(obj instanceof Map) { Map map = (Map)obj; if(map.containsKey(index)) { return map.get(index); } } int idx = -1; if(index instanceof Integer) { idx = ((Integer)index).intValue(); } if(idx < 0) { return obj; } else if(obj instanceof Map) { Map map = (Map)obj; Iterator iterator = map.keySet().iterator(); return index(iterator, idx); } else if(obj instanceof List) { return ((List)obj).get(idx); } else if(obj instanceof Object[]) { return ((Object[])obj)[idx]; } else if(obj instanceof Enumeration) { Enumeration enumeration = (Enumeration)obj; while(enumeration.hasMoreElements()) { idx--; if(idx == -1) { return enumeration.nextElement(); } else { enumeration.nextElement(); } } } else if(obj instanceof Iterator) { return index((Iterator)obj, idx); } else if(obj instanceof Collection) { Iterator iterator = ((Collection)obj).iterator(); return index(iterator, idx); } return obj; } private static Object index(Iterator iterator, int idx) { while(iterator.hasNext()) { idx--; if(idx == -1) { return iterator.next(); } else { iterator.next(); } } return iterator; } /** * Returns an Iterator for the given object. Currently this method can handle * Iterator, Enumeration, Collection, Map, Object[] or array. * * @deprecated use IteratorUtils version instead */ public static Iterator getIterator(Object obj) { if(obj instanceof Iterator) { return (Iterator)obj; } else if(obj instanceof Collection) { return ((Collection)obj).iterator(); } else if(obj instanceof Object[]) { return new ArrayIterator( obj ); } else if(obj instanceof Enumeration) { return new EnumerationIterator( (Enumeration)obj ); } else if(obj instanceof Map) { return ((Map)obj).values().iterator(); } else if(obj != null && obj.getClass().isArray()) { return new ArrayIterator( obj ); } else{ return null; } } /** Reverses the order of the given array */ public static void reverseArray(Object[] array) { int i = 0; int j = array.length - 1; Object tmp; while(j>i) { tmp = array[j]; array[j] = array[i]; array[i] = tmp; j--; i++; } } private static final int getFreq(final Object obj, final Map freqMap) { try { return ((Integer)(freqMap.get(obj))).intValue(); } catch(NullPointerException e) { // ignored } catch(NoSuchElementException e) { // ignored } return 0; } /** * Base class for collection decorators. I decided to do it this way * because it seemed to result in the most reuse. * * Inner class tree looks like: *
     *       CollectionWrapper
     *          PredicatedCollection
     *             PredicatedSet
     *             PredicatedList
     *             PredicatedBag
     *             PredicatedBuffer
     *          UnmodifiableCollection
     *             UnmodifiableBag
     *             UnmodifiableBuffer
     *          LazyCollection
     *             LazyList
     *             LazyBag
     *       SynchronizedCollection
     *          SynchronizedBuffer
     *          SynchronizedBag
     *          SynchronizedBuffer
     * 
*/ static class CollectionWrapper implements Collection { protected final Collection collection; public CollectionWrapper(Collection collection) { if (collection == null) { throw new IllegalArgumentException("Collection must not be null"); } this.collection = collection; } public int size() { return collection.size(); } public boolean isEmpty() { return collection.isEmpty(); } public boolean contains(Object o) { return collection.contains(o); } public Iterator iterator() { return collection.iterator(); } public Object[] toArray() { return collection.toArray(); } public Object[] toArray(Object[] o) { return collection.toArray(o); } public boolean add(Object o) { return collection.add(o); } public boolean remove(Object o) { return collection.remove(o); } public boolean containsAll(Collection c2) { return collection.containsAll(c2); } public boolean addAll(Collection c2) { return collection.addAll(c2); } public boolean removeAll(Collection c2) { return collection.removeAll(c2); } public boolean retainAll(Collection c2) { return collection.retainAll(c2); } public void clear() { collection.clear(); } public boolean equals(Object o) { if (o == this) return true; return collection.equals(o); } public int hashCode() { return collection.hashCode(); } public String toString() { return collection.toString(); } } static class PredicatedCollection extends CollectionWrapper { protected final Predicate predicate; public PredicatedCollection(Collection c, Predicate p) { super(c); if (p == null) { throw new IllegalArgumentException("Predicate must not be null"); } this.predicate = p; for (Iterator iter = c.iterator(); iter.hasNext(); ) { validate(iter.next()); } } public boolean add(Object o) { validate(o); return collection.add(o); } public boolean addAll(Collection c2) { for (Iterator iter = c2.iterator(); iter.hasNext(); ) { validate(iter.next()); } return collection.addAll(c2); } protected void validate(Object o) { if (!predicate.evaluate(o)) { throw new IllegalArgumentException("Cannot add Object - Predicate rejected it"); } } } static class UnmodifiableCollection extends CollectionWrapper { public UnmodifiableCollection(Collection c) { super(c); } public boolean add(Object o) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public Iterator iterator() { return new UnmodifiableIterator(collection.iterator()); } } static class SynchronizedCollection { protected final Collection collection; public SynchronizedCollection(Collection collection) { if (collection == null) { throw new IllegalArgumentException("Collection must not be null"); } this.collection = collection; } public synchronized int size() { return collection.size(); } public synchronized boolean isEmpty() { return collection.isEmpty(); } public synchronized boolean contains(Object o) { return collection.contains(o); } public Iterator iterator() { return collection.iterator(); } public synchronized Object[] toArray() { return collection.toArray(); } public synchronized Object[] toArray(Object[] o) { return collection.toArray(o); } public synchronized boolean add(Object o) { return collection.add(o); } public synchronized boolean remove(Object o) { return collection.remove(o); } public synchronized boolean containsAll(Collection c2) { return collection.containsAll(c2); } public synchronized boolean addAll(Collection c2) { return collection.addAll(c2); } public synchronized boolean removeAll(Collection c2) { return collection.removeAll(c2); } public synchronized boolean retainAll(Collection c2) { return collection.retainAll(c2); } public synchronized void clear() { collection.clear(); } public synchronized boolean equals(Object o) { return collection.equals(o); } public synchronized int hashCode() { return collection.hashCode(); } public synchronized String toString() { return collection.toString(); } } static class UnmodifiableIterator implements Iterator { protected final Iterator iterator; public UnmodifiableIterator(Iterator iterator) { if (iterator == null) { throw new IllegalArgumentException("Iterator must not be null"); } this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public Object next() { return iterator.next(); } public void remove() { throw new UnsupportedOperationException(); } } /** * Returns a predicated collection backed by the given collection. * Only objects that pass the test in the given predicate can be * added to the collection. * It is important not to use the original collection after invoking this * method, as it is a backdoor for adding unvalidated objects. * * @param collection the collection to predicate, must not be null * @param predicate the predicate for the collection, must not be null * @return a predicated collection backed by the given collection * @throws IllegalArgumentException if the Collection is null */ public static Collection predicatedCollection(Collection collection, Predicate predicate) { return new PredicatedCollection(collection, predicate); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/IteratorUtils.java0100644000175000017500000005644110055172376031752 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.lang.reflect.Array; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.Dictionary; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NoSuchElementException; import org.apache.commons.collections.iterators.ArrayIterator; import org.apache.commons.collections.iterators.CollatingIterator; import org.apache.commons.collections.iterators.EnumerationIterator; import org.apache.commons.collections.iterators.FilterIterator; import org.apache.commons.collections.iterators.FilterListIterator; import org.apache.commons.collections.iterators.IteratorChain; import org.apache.commons.collections.iterators.IteratorEnumeration; import org.apache.commons.collections.iterators.ListIteratorWrapper; import org.apache.commons.collections.iterators.SingletonIterator; import org.apache.commons.collections.iterators.SingletonListIterator; import org.apache.commons.collections.iterators.TransformIterator; /** * Provides static utility methods and decorators for {@link Iterator} * instances. The implementations are provided in the * org.apache.commons.collections.iterators subpackage. * * @author Stephen Colebourne * @version $Id: IteratorUtils.java,v 1.4.2.2 2004/05/22 12:14:01 scolebourne Exp $ * @since 2.1 */ public class IteratorUtils { // validation is done in this class in certain cases because the // public classes allow invalid states /** * An iterator over no elements. * @deprecated Use EmptyIterator.INSTANCE */ public static final Iterator EMPTY_ITERATOR = new EmptyIterator(); /** * A list iterator over no elements * @deprecated Use EmptyListIterator.INSTANCE */ public static final ListIterator EMPTY_LIST_ITERATOR = new EmptyListIterator(); /** * Prevents instantiation. */ private IteratorUtils() { } /** * Gets an empty iterator. *

* This iterator is a valid iterator object that will iterate over * nothing. * * @return an iterator over nothing * @deprecated Use EmptyIterator.INSTANCE */ public static Iterator emptyIterator() { return EMPTY_ITERATOR; } /** * Gets an empty list iterator. *

* This iterator is a valid list iterator object that will iterate * over nothing. * * @return a list iterator over nothing * @deprecated Use EmptyListIterator.INSTANCE */ public static ListIterator emptyListIterator() { return EMPTY_LIST_ITERATOR; } /** * Gets a singleton iterator. *

* This iterator is a valid iterator object that will iterate over * the specified object. * * @param object the single object over which to iterate * @return a singleton iterator over the object * @deprecated Use new SingletonIterator(object) */ public static Iterator singletonIterator(Object object) { return new SingletonIterator(object); } /** * Gets a singleton list iterator. *

* This iterator is a valid list iterator object that will iterate over * the specified object. * * @param object the single object over which to iterate * @return a singleton list iterator over the object */ public static ListIterator singletonListIterator(Object object) { return new SingletonListIterator(object); } /** * Gets an iterator over an array. * * @param array the array over which to iterate * @return an iterator over the array * @throws NullPointerException if array is null * @deprecated Use new ArrayIterator(array) */ public static Iterator arrayIterator(Object[] array) { return new ArrayIterator(array); } /** * Gets an iterator over the end part of an array. * * @param array the array over which to iterate * @param start the index to start iterating at * @return an iterator over part of the array * @throws IllegalArgumentException if array bounds are invalid * @throws NullPointerException if array is null * @deprecated Use new ArrayIterator(array,start) */ public static Iterator arrayIterator(Object[] array, int start) { return new ArrayIterator(array, start); } /** * Gets an iterator over part of an array. * * @param array the array over which to iterate * @param start the index to start iterating at * @param end the index to finish iterating at * @return an iterator over part of the array * @throws IllegalArgumentException if array bounds are invalid * @throws NullPointerException if array is null * @deprecated Use new ArrayIterator(array,start,end) */ public static Iterator arrayIterator(Object[] array, int start, int end) { return new ArrayIterator(array, start, end); } // /** // * Gets a list iterator over an array. // * // * @param array the array over which to iterate // * @return a list iterator over the array // * @throws NullPointerException if array is null // */ // public static ListIterator arrayListIterator(Object[] array) { // return new ArrayListIterator(array); // } // // /** // * Gets a list iterator over the end part of an array. // * // * @param array the array over which to iterate // * @param start the index to start iterating at // * @return a list iterator over part of the array // * @throws IllegalArgumentException if array bounds are invalid // * @throws NullPointerException if array is null // */ // public static ListIterator arrayListIterator(Object[] array, int start) { // return new ArrayListIterator(array, start); // } // // /** // * Gets a list iterator over part of an array. // * // * @param array the array over which to iterate // * @param start the index to start iterating at // * @param end the index to finish iterating at // * @return a list iterator over part of the array // * @throws IllegalArgumentException if array bounds are invalid // * @throws NullPointerException if array is null // */ // public static ListIterator arrayListIterator(Object[] array, int start, int end) { // return new ArrayListIterator(array, start, end); // } /** * Gets an iterator that iterates through two {@link Iterator}s * one after another. * * @param iterator1 the first iterators to use, not null * @param iterator2 the first iterators to use, not null * @return a combination iterator over the iterators * @throws NullPointerException if either iterator is null */ public static Iterator chainedIterator(Iterator iterator1, Iterator iterator2) { return new IteratorChain(iterator1, iterator2); } /** * Gets an iterator that iterates through an array of {@link Iterator}s * one after another. * * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators array is null or contains a null */ public static Iterator chainedIterator(Iterator[] iterators) { return new IteratorChain(iterators); } /** * Gets an iterator that iterates through a collections of {@link Iterator}s * one after another. * * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators collection is null or contains a null * @throws ClassCastException if the iterators collection contains the wrong object type */ public static Iterator chainedIterator(Collection iterators) { return new IteratorChain(iterators); } /** * Gets an iterator that provides an ordered iteration over the elements * contained in a collection of ordered {@link Iterator}s. *

* Given two ordered {@link Iterator}s A and B, * the {@link Iterator#next()} method will return the lesser of * A.next() and B.next(). *

* The comparator is optional. If null is specified then natural order is used. * * @param comparator the comparator to use, may be null for natural order * @param iterator1 the first iterators to use, not null * @param iterator2 the first iterators to use, not null * @return a combination iterator over the iterators * @throws NullPointerException if either iterator is null */ public static Iterator collatedIterator(Comparator comparator, Iterator iterator1, Iterator iterator2) { return new CollatingIterator(comparator, iterator1, iterator2); } /** * Gets an iterator that provides an ordered iteration over the elements * contained in an array of {@link Iterator}s. *

* Given two ordered {@link Iterator}s A and B, * the {@link Iterator#next()} method will return the lesser of * A.next() and B.next() and so on. *

* The comparator is optional. If null is specified then natural order is used. * * @param comparator the comparator to use, may be null for natural order * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators array is null or contains a null */ public static Iterator collatedIterator(Comparator comparator, Iterator[] iterators) { return new CollatingIterator(comparator, iterators); } /** * Gets an iterator that provides an ordered iteration over the elements * contained in a collection of {@link Iterator}s. *

* Given two ordered {@link Iterator}s A and B, * the {@link Iterator#next()} method will return the lesser of * A.next() and B.next() and so on. *

* The comparator is optional. If null is specified then natural order is used. * * @param comparator the comparator to use, may be null for natural order * @param iterators the iterators to use, not null or empty or contain nulls * @return a combination iterator over the iterators * @throws NullPointerException if iterators collection is null or contains a null * @throws ClassCastException if the iterators collection contains the wrong object type */ public static Iterator collatedIterator(Comparator comparator, Collection iterators) { return new CollatingIterator(comparator, iterators); } /** * Gets an iterator that transforms the elements of another iterator. *

* The transformation occurs during the next() method and the underlying * iterator is unaffected by the transformation. * * @param iterator the iterator to use, not null * @param transform the transform to use, not null * @throws NullPointerException if either parameter is null */ public static Iterator transformedIterator(Iterator iterator, Transformer transform) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (transform == null) { throw new NullPointerException("Transformer must not be null"); } return new TransformIterator(iterator, transform); } /** * Gets an iterator that filters another iterator. *

* The returned iterator will only return objects that match the specified * filtering predicate. * * @param iterator the iterator to use, not null * @param predicate the predicate to use as a filter, not null * @throws NullPointerException if either parameter is null */ public static Iterator filteredIterator(Iterator iterator, Predicate predicate) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (predicate == null) { throw new NullPointerException("Predicate must not be null"); } return new FilterIterator(iterator, predicate); } /** * Gets a list iterator that filters another list iterator. *

* The returned iterator will only return objects that match the specified * filtering predicate. * * @param listIterator the list iterator to use, not null * @param predicate the predicate to use as a filter, not null * @throws NullPointerException if either parameter is null */ public static ListIterator filteredListIterator(ListIterator listIterator, Predicate predicate) { if (listIterator == null) { throw new NullPointerException("ListIterator must not be null"); } if (predicate == null) { throw new NullPointerException("Predicate must not be null"); } return new FilterListIterator(listIterator, predicate); } /** * Gets an iterator that provides an iterator view of the given enumeration. * * @param enumeration the enumeration to use */ public static Iterator asIterator(Enumeration enumeration) { if (enumeration == null) { throw new NullPointerException("Enumeration must not be null"); } return new EnumerationIterator(enumeration); } /** * Gets an iterator that provides an iterator view of the given enumeration * that will remove elements from the specified collection. * * @param enumeration the enumeration to use * @param collection the collection to remove elements form */ public static Iterator asIterator(Enumeration enumeration, Collection removeCollection) { if (enumeration == null) { throw new NullPointerException("Enumeration must not be null"); } if (removeCollection == null) { throw new NullPointerException("Collection must not be null"); } return new EnumerationIterator(enumeration, removeCollection); } /** * Gets an enumeration that wraps an iterator. * * @param iterator the iterator to use, not null * @throws NullPointerException if iterator is null */ public static Enumeration asEnumeration(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } return new IteratorEnumeration(iterator); } /** * Gets a list iterator based on a simple iterator. *

* As the wrapped Iterator is traversed, a LinkedList of its values is * cached, permitting all required operations of ListIterator. * * @param iterator the iterator to use, not null * @throws NullPointerException if iterator parameter is null */ public static ListIterator toListIterator(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } return new ListIteratorWrapper(iterator); } /** * Gets an array based on an iterator. *

* As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, this is converted to an array. * * @param iterator the iterator to use, not null * @throws NullPointerException if iterator parameter is null */ public static Object[] toArray(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } List list = toList(iterator, 100); return list.toArray(); } /** * Gets an array based on an iterator. *

* As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, this is converted to an array. * * @param iterator the iterator to use, not null * @param arrayClass the class of array to create * @throws NullPointerException if iterator parameter is null * @throws NullPointerException if arrayClass is null * @throws ClassCastException if the arrayClass is invalid */ public static Object[] toArray(Iterator iterator, Class arrayClass) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (arrayClass == null) { throw new NullPointerException("Array class must not be null"); } List list = toList(iterator, 100); return list.toArray((Object[]) Array.newInstance(arrayClass, list.size())); } /** * Gets a list based on an iterator. *

* As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, the list is returned. * * @param iterator the iterator to use, not null * @throws NullPointerException if iterator parameter is null */ public static List toList(Iterator iterator) { return toList(iterator, 10); } /** * Gets a list based on an iterator. *

* As the wrapped Iterator is traversed, an ArrayList of its values is * created. At the end, the list is returned. * * @param iterator the iterator to use, not null * @param estimatedSize the initial size of the ArrayList * @throws NullPointerException if iterator parameter is null * @throws IllegalArgumentException if the size is less than 1 */ public static List toList(Iterator iterator, int estimatedSize) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } if (estimatedSize < 1) { throw new IllegalArgumentException("Estimated size must be greater than 0"); } List list = new ArrayList(estimatedSize); while (iterator.hasNext()) { list.add(iterator.next()); } return list; } /** * Gets a suitable Iterator for the given object. *

* This method can handles objects as follows *

* * @param obj the object to convert to an iterator * @return a suitable iterator, never null */ public static Iterator getIterator(Object obj) { if (obj == null) { return emptyIterator(); } else if (obj instanceof Iterator) { return (Iterator) obj; } else if (obj instanceof Collection) { return ((Collection) obj).iterator(); } else if (obj instanceof Object[]) { return new ArrayIterator(obj); } else if (obj instanceof Enumeration) { return new EnumerationIterator((Enumeration) obj); } else if (obj instanceof Map) { return ((Map) obj).values().iterator(); } else if (obj instanceof Dictionary) { return new EnumerationIterator(((Dictionary) obj).elements()); } else if (obj != null && obj.getClass().isArray()) { return new ArrayIterator(obj); } else { try { Method method = obj.getClass().getMethod("iterator", null); if (Iterator.class.isAssignableFrom(method.getReturnType())) { Iterator it = (Iterator) method.invoke(obj, null); if (it != null) { return it; } } } catch (Exception ex) { // ignore } return singletonIterator(obj); } } /** * EmptyIterator class */ static class EmptyIterator implements Iterator { /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return false; } /** * @see java.util.Iterator#next() */ public Object next() { throw new NoSuchElementException(); } /** * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException("remove() not supported for empty Iterator"); } } /** * EmptyListIterator class */ static class EmptyListIterator extends EmptyIterator implements ListIterator { /** * @see java.util.ListIterator#hasPrevious() */ public boolean hasPrevious() { return false; } /** * @see java.util.ListIterator#previous() */ public Object previous() { throw new NoSuchElementException(); } /** * @see java.util.ListIterator#nextIndex() */ public int nextIndex() { return 0; } /** * @see java.util.ListIterator#previousIndex() */ public int previousIndex() { return -1; } /** * @see java.util.ListIterator#add(Object) */ public void add(Object o) { throw new UnsupportedOperationException("add() not supported for empty Iterator"); } /** * @see java.util.ListIterator#set(Object) */ public void set(Object o) { throw new UnsupportedOperationException("set() not supported for empty Iterator"); } } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/StringStack.java0100644000175000017500000001401210055172400031344 0ustar toratora/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.Serializable; import java.util.Iterator; import java.util.Stack; /** * This class implements a stack for String objects. *

* This class provides a way to collect a list of unique strings and join * them with an optional separator. * * @deprecated This class is not a Stack, it is a String utility. As such * it is deprecated in favour of the StringUtils class in * the [lang] project. * @since 2.0 * @author John D. McNally * @author Daniel Rall * @author Stephen Colebourne * @version $Id: StringStack.java,v 1.3.2.1 2004/05/22 12:14:01 scolebourne Exp $ */ public class StringStack implements Serializable { /** * The stack of String objects. */ private Stack stack = null; /** * Creates an empty instance. */ public StringStack() { stack = new Stack(); } /** * Adds the String to the collection if it does not already * contain it. * * @param s The String object to add to this stack * (if it is not null and doesn't already exist in * the stack). * @return A reference to this stack (useful for when this method * is called repeatedly). */ public StringStack add(String s) { if (s != null && !contains(s)) { stack.push(s); } return this; } /** * Adds all Strings in the given StringStack to the collection * (skipping those it already contains) * * @param ss The stack of String objects to add to * this stack (if it is not null and doesn't already * exist in the stack). * @return A reference to this stack (useful for when this method * is called repeatedly). */ public StringStack addAll(StringStack ss) { Iterator i = ss.stack.iterator(); while (i.hasNext()) { add((String) i.next()); } return this; } /** * Clears the stack. */ public void clear() { stack.clear(); } /** * Returns whether this stack contain the specified text. * * @param s The text to search for. * @return Whether the stack contains the text. */ public boolean contains(String s) { return (stack.search(s) != -1); } /** * Whether the stack is empty. * * @return Whether the stack is empty. */ public final boolean empty() { return stack.empty(); } /** * Get a string off the stack at a certain position. * * @param i The position. * @return A the string from the specified position. */ public String get(int i) { return (String) stack.elementAt(i); } /** * Returns the size of the stack. * * @return The size of the stack. */ public final int size() { return stack.size(); } /** * Converts the stack to a single {@link java.lang.String} with no * separator. * * @return The stack elements as a single block of text. */ public String toString() { return toString(""); } /** * Converts the stack to a single {@link java.lang.String}. * * @param separator The text to use as glue between elements in * the stack. * @return The stack elements--glued together by * separator--as a single block of text. */ public String toString( String separator ) { String s; if (size() > 0) { if ( separator == null ) { separator = ""; } // Determine what size to pre-allocate for the buffer. int totalSize = 0; for (int i = 0; i < stack.size(); i++) { totalSize += get(i).length(); } totalSize += (stack.size() - 1) * separator.length(); StringBuffer sb = new StringBuffer(totalSize).append( get(0) ); for (int i = 1; i < stack.size(); i++) { sb.append(separator).append(get(i)); } s = sb.toString(); } else { s = ""; } return s; } /** * Compares two StringStacks. Considered equal if the * toString() method returns such. */ public boolean equals(Object ssbuf) { boolean isEquiv = false; if ( ssbuf == null || !(ssbuf instanceof StringStack) ) { isEquiv = false; } else if ( ssbuf == this ) { isEquiv = true; } else if ( this.toString().equals(ssbuf.toString()) ) { isEquiv = true; } return isEquiv; } /** * Turns this stack into an array. * * @return This stack as an array. */ public String[] toStringArray() { String[] array = new String[size()]; for (int i = 0; i < size(); i++) { array[i] = get(i); } return array; } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BinaryHeap.java0100644000175000017500000003731710055172400031147 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Comparator; /** * Binary heap implementation of {@link PriorityQueue} and {@link Buffer}. *

* The removal order of a binary heap is based on either the natural sort * order of its elements or a specified {@link Comparator}. The * {@link #remove()} method always returns the first element as determined * by the sort order. (The isMinHeap flag in the constructors * can be used to reverse the sort order, in which case {@link #remove()} * will always remove the last element.) The removal order is * not the same as the order of iteration; elements are * returned by the iterator in no particular order. *

* The {@link #add(Object)} and {@link #remove()} operations perform * in logarithmic time. The {@link #get()} operation performs in constant * time. All other operations perform in linear time or worse. *

* Note that this implementation is not synchronized. Use * {@link BufferUtils#synchronizedBuffer(Buffer)} to provide * synchronized access to a BinaryHeap: * *

 * Buffer heap = BufferUtils.synchronizedBuffer(new BinaryHeap());
 * 
* * @author Peter Donald * @author Ram Chidambaram * @author Michael A. Smith * @author Paul Jack * @author Stephen Colebourne * @since 1.0 * @version $Id: BinaryHeap.java,v 1.11.2.1 2004/05/22 12:14:02 scolebourne Exp $ */ public final class BinaryHeap extends AbstractCollection implements PriorityQueue, Buffer { /** * The default capacity for a binary heap. */ private final static int DEFAULT_CAPACITY = 13; /** * The number of elements currently in this heap. */ int m_size; // package scoped for testing /** * The elements in this heap. */ Object[] m_elements; // package scoped for testing /** * If true, the first element as determined by the sort order will * be returned. If false, the last element as determined by the * sort order will be returned. */ boolean m_isMinHeap; // package scoped for testing /** * The comparator used to order the elements */ Comparator m_comparator; // package scoped for testing /** * Constructs a new minimum binary heap. */ public BinaryHeap() { this(DEFAULT_CAPACITY, true); } /** * Constructs a new BinaryHeap that will use the given * comparator to order its elements. * * @param comparator the comparator used to order the elements, null * means use natural order */ public BinaryHeap(Comparator comparator) { this(); m_comparator = comparator; } /** * Constructs a new minimum binary heap with the specified initial capacity. * * @param capacity The initial capacity for the heap. This value must * be greater than zero. * @throws IllegalArgumentException * if capacity is <= 0 */ public BinaryHeap(int capacity) { this(capacity, true); } /** * Constructs a new BinaryHeap. * * @param capacity the initial capacity for the heap * @param comparator the comparator used to order the elements, null * means use natural order * @throws IllegalArgumentException * if capacity is <= 0 */ public BinaryHeap(int capacity, Comparator comparator) { this(capacity); m_comparator = comparator; } /** * Constructs a new minimum or maximum binary heap * * @param isMinHeap if true the heap is created as a * minimum heap; otherwise, the heap is created as a maximum heap */ public BinaryHeap(boolean isMinHeap) { this(DEFAULT_CAPACITY, isMinHeap); } /** * Constructs a new BinaryHeap. * * @param isMinHeap true to use the order imposed by the given * comparator; false to reverse that order * @param comparator the comparator used to order the elements, null * means use natural order */ public BinaryHeap(boolean isMinHeap, Comparator comparator) { this(isMinHeap); m_comparator = comparator; } /** * Constructs a new minimum or maximum binary heap with the specified * initial capacity. * * @param capacity the initial capacity for the heap. This value must * be greater than zero. * @param isMinHeap if true the heap is created as a * minimum heap; otherwise, the heap is created as a maximum heap. * @throws IllegalArgumentException * if capacity is <= 0 */ public BinaryHeap(int capacity, boolean isMinHeap) { if (capacity <= 0) { throw new IllegalArgumentException("invalid capacity"); } m_isMinHeap = isMinHeap; //+1 as 0 is noop m_elements = new Object[capacity + 1]; } /** * Constructs a new BinaryHeap. * * @param capacity the initial capacity for the heap * @param isMinHeap true to use the order imposed by the given * comparator; false to reverse that order * @param comparator the comparator used to order the elements, null * means use natural order * @throws IllegalArgumentException * if capacity is <= 0 */ public BinaryHeap(int capacity, boolean isMinHeap, Comparator comparator) { this(capacity, isMinHeap); m_comparator = comparator; } /** * Clears all elements from queue. */ public void clear() { m_elements = new Object[m_elements.length]; // for gc m_size = 0; } /** * Tests if queue is empty. * * @return true if queue is empty; false * otherwise. */ public boolean isEmpty() { return m_size == 0; } /** * Tests if queue is full. * * @return true if queue is full; false * otherwise. */ public boolean isFull() { //+1 as element 0 is noop return m_elements.length == m_size + 1; } /** * Inserts an element into queue. * * @param element the element to be inserted */ public void insert(Object element) { if (isFull()) { grow(); } //percolate element to it's place in tree if (m_isMinHeap) { percolateUpMinHeap(element); } else { percolateUpMaxHeap(element); } } /** * Returns the element on top of heap but don't remove it. * * @return the element at top of heap * @throws NoSuchElementException if isEmpty() == true */ public Object peek() throws NoSuchElementException { if (isEmpty()) { throw new NoSuchElementException(); } else { return m_elements[1]; } } /** * Returns the element on top of heap and remove it. * * @return the element at top of heap * @throws NoSuchElementException if isEmpty() == true */ public Object pop() throws NoSuchElementException { final Object result = peek(); m_elements[1] = m_elements[m_size--]; // set the unused element to 'null' so that the garbage collector // can free the object if not used anywhere else.(remove reference) m_elements[m_size + 1] = null; if (m_size != 0) { // percolate top element to it's place in tree if (m_isMinHeap) { percolateDownMinHeap(1); } else { percolateDownMaxHeap(1); } } return result; } /** * Percolates element down heap from top. * Assume it is a maximum heap. * * @param index the index for the element */ protected void percolateDownMinHeap(final int index) { final Object element = m_elements[index]; int hole = index; while ((hole * 2) <= m_size) { int child = hole * 2; // if we have a right child and that child can not be percolated // up then move onto other child if (child != m_size && compare(m_elements[child + 1], m_elements[child]) < 0) { child++; } // if we found resting place of bubble then terminate search if (compare(m_elements[child], element) >= 0) { break; } m_elements[hole] = m_elements[child]; hole = child; } m_elements[hole] = element; } /** * Percolates element down heap from top. * Assume it is a maximum heap. * * @param index the index of the element */ protected void percolateDownMaxHeap(final int index) { final Object element = m_elements[index]; int hole = index; while ((hole * 2) <= m_size) { int child = hole * 2; // if we have a right child and that child can not be percolated // up then move onto other child if (child != m_size && compare(m_elements[child + 1], m_elements[child]) > 0) { child++; } // if we found resting place of bubble then terminate search if (compare(m_elements[child], element) <= 0) { break; } m_elements[hole] = m_elements[child]; hole = child; } m_elements[hole] = element; } /** * Percolates element up heap from bottom. * Assume it is a maximum heap. * * @param element the element */ protected void percolateUpMinHeap(final Object element) { int hole = ++m_size; m_elements[hole] = element; while (hole > 1 && compare(element, m_elements[hole / 2]) < 0) { // save element that is being pushed down // as the element "bubble" is percolated up final int next = hole / 2; m_elements[hole] = m_elements[next]; hole = next; } m_elements[hole] = element; } /** * Percolates element up heap from bottom. * Assume it is a maximum heap. * * @param element the element */ protected void percolateUpMaxHeap(final Object element) { int hole = ++m_size; while (hole > 1 && compare(element, m_elements[hole / 2]) > 0) { // save element that is being pushed down // as the element "bubble" is percolated up final int next = hole / 2; m_elements[hole] = m_elements[next]; hole = next; } m_elements[hole] = element; } /** * Compares two objects using the comparator if specified, or the * natural order otherwise. * * @param a the first object * @param b the second object * @return -ve if a less than b, 0 if they are equal, +ve if a greater than b */ private int compare(Object a, Object b) { if (m_comparator != null) { return m_comparator.compare(a, b); } else { return ((Comparable) a).compareTo(b); } } /** * Increases the size of the heap to support additional elements */ protected void grow() { final Object[] elements = new Object[m_elements.length * 2]; System.arraycopy(m_elements, 0, elements, 0, m_elements.length); m_elements = elements; } /** * Returns a string representation of this heap. The returned string * is similar to those produced by standard JDK collections. * * @return a string representation of this heap */ public String toString() { final StringBuffer sb = new StringBuffer(); sb.append("[ "); for (int i = 1; i < m_size + 1; i++) { if (i != 1) { sb.append(", "); } sb.append(m_elements[i]); } sb.append(" ]"); return sb.toString(); } /** * Returns an iterator over this heap's elements. * * @return an iterator over this heap's elements */ public Iterator iterator() { return new Iterator() { private int index = 1; private int lastReturnedIndex = -1; public boolean hasNext() { return index <= m_size; } public Object next() { if (!hasNext()) throw new NoSuchElementException(); lastReturnedIndex = index; index++; return m_elements[lastReturnedIndex]; } public void remove() { if (lastReturnedIndex == -1) throw new IllegalStateException(); m_elements[ lastReturnedIndex ] = m_elements[ m_size ]; m_elements[ m_size ] = null; m_size--; if( m_size != 0 ) { //percolate top element to it's place in tree if( m_isMinHeap ) percolateDownMinHeap( lastReturnedIndex ); else percolateDownMaxHeap( lastReturnedIndex ); } index--; lastReturnedIndex = -1; } }; } /** * Adds an object to this heap. Same as {@link #insert(Object)}. * * @param object the object to add * @return true, always */ public boolean add(Object object) { insert(object); return true; } /** * Returns the priority element. Same as {@link #peek()}. * * @return the priority element * @throws BufferUnderflowException if this heap is empty */ public Object get() { try { return peek(); } catch (NoSuchElementException e) { throw new BufferUnderflowException(); } } /** * Removes the priority element. Same as {@link #pop()}. * * @return the removed priority element * @throws BufferUnderflowException if this heap is empty */ public Object remove() { try { return pop(); } catch (NoSuchElementException e) { throw new BufferUnderflowException(); } } /** * Returns the number of elements in this heap. * * @return the number of elements in this heap */ public int size() { return m_size; } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/Transformer.java0100644000175000017500000000210410055172400031411 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** An object capable of transforming an input object into some output object. * * @since 1.0 * @author James Strachan */ public interface Transformer { /** Transforms the input object (leaving it unchanged) into some output object. * @return the transformation of the input object to the output object */ public Object transform(Object input); } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/CursorableLinkedList.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/CursorableLinkedList0100644000175000017500000013212410055172400032261 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.util.ListIterator; import java.util.ConcurrentModificationException; import java.util.NoSuchElementException; import java.io.Serializable; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.IOException; import java.lang.reflect.Array; /** * A doubly-linked list implementation of the {@link List} interface, * supporting a {@link ListIterator} that allows concurrent modifications * to the underlying list. *

* Implements all of the optional {@link List} operations, the * stack/queue/dequeue operations available in {@link java.util.LinkedList} * and supports a {@link ListIterator} that allows concurrent modifications * to the underlying list (see {@link #cursor}). *

* Note that this implementation is not synchronized. * * @since 1.0 * @author Rodney Waldhoff * @version $Id: CursorableLinkedList.java,v 1.10.2.1 2004/05/22 12:14:02 scolebourne Exp $ * @see java.util.LinkedList */ public class CursorableLinkedList implements List, Serializable { //--- public methods --------------------------------------------- /** * Appends the specified element to the end of this list. * * @param o element to be appended to this list. * @return true */ public boolean add(Object o) { insertListable(_head.prev(),null,o); return true; } /** * Inserts the specified element at the specified position in this list. * Shifts the element currently at that position (if any) and any subsequent * elements to the right (adds one to their indices). * * @param index index at which the specified element is to be inserted. * @param element element to be inserted. * * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index > size()). */ public void add(int index, Object element) { if(index == _size) { add(element); } else { if(index < 0 || index > _size) { throw new IndexOutOfBoundsException(String.valueOf(index) + " < 0 or " + String.valueOf(index) + " > " + _size); } Listable succ = (isEmpty() ? null : getListableAt(index)); Listable pred = (null == succ ? null : succ.prev()); insertListable(pred,succ,element); } } /** * Appends all of the elements in the specified collection to the end of * this list, in the order that they are returned by the specified * {@link Collection}'s {@link Iterator}. The behavior of this operation is * unspecified if the specified collection is modified while * the operation is in progress. (Note that this will occur if the * specified collection is this list, and it's nonempty.) * * @param c collection whose elements are to be added to this list. * @return true if this list changed as a result of the call. * * @throws ClassCastException if the class of an element in the specified * collection prevents it from being added to this list. * @throws IllegalArgumentException if some aspect of an element in the * specified collection prevents it from being added to this * list. */ public boolean addAll(Collection c) { if(c.isEmpty()) { return false; } Iterator it = c.iterator(); while(it.hasNext()) { insertListable(_head.prev(),null,it.next()); } return true; } /** * Inserts all of the elements in the specified collection into this * list at the specified position. Shifts the element currently at * that position (if any) and any subsequent elements to the right * (increases their indices). The new elements will appear in this * list in the order that they are returned by the specified * {@link Collection}'s {@link Iterator}. The behavior of this operation is * unspecified if the specified collection is modified while the * operation is in progress. (Note that this will occur if the specified * collection is this list, and it's nonempty.) * * @param index index at which to insert first element from the specified * collection. * @param c elements to be inserted into this list. * @return true if this list changed as a result of the call. * * @throws ClassCastException if the class of one of elements of the * specified collection prevents it from being added to this * list. * @throws IllegalArgumentException if some aspect of one of elements of * the specified collection prevents it from being added to * this list. * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index > size()). */ public boolean addAll(int index, Collection c) { if(c.isEmpty()) { return false; } else if(_size == index || _size == 0) { return addAll(c); } else { Listable succ = getListableAt(index); Listable pred = (null == succ) ? null : succ.prev(); Iterator it = c.iterator(); while(it.hasNext()) { pred = insertListable(pred,succ,it.next()); } return true; } } /** * Inserts the specified element at the beginning of this list. * (Equivalent to {@link #add(int,java.lang.Object) add(0,o)}). * * @param o element to be prepended to this list. * @return true */ public boolean addFirst(Object o) { insertListable(null,_head.next(),o); return true; } /** * Inserts the specified element at the end of this list. * (Equivalent to {@link #add(java.lang.Object)}). * * @param o element to be appended to this list. * @return true */ public boolean addLast(Object o) { insertListable(_head.prev(),null,o); return true; } /** * Removes all of the elements from this list. This * list will be empty after this call returns (unless * it throws an exception). */ public void clear() { /* // this is the quick way, but would force us // to break all the cursors _modCount++; _head.setNext(null); _head.setPrev(null); _size = 0; */ Iterator it = iterator(); while(it.hasNext()) { it.next(); it.remove(); } } /** * Returns true if this list contains the specified element. * More formally, returns true if and only if this list contains * at least one element e such that * (o==null ? e==null : o.equals(e)). * * @param o element whose presence in this list is to be tested. * @return true if this list contains the specified element. */ public boolean contains(Object o) { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if((null == o && null == elt.value()) || (o != null && o.equals(elt.value()))) { return true; } } return false; } /** * Returns true if this list contains all of the elements of the * specified collection. * * @param c collection to be checked for containment in this list. * @return true if this list contains all of the elements of the * specified collection. */ public boolean containsAll(Collection c) { Iterator it = c.iterator(); while(it.hasNext()) { if(!this.contains(it.next())) { return false; } } return true; } /** * Returns a {@link ListIterator} for iterating through the * elements of this list. Unlike {@link #iterator}, a cursor * is not bothered by concurrent modifications to the * underlying list. *

* Specifically, when elements are added to the list before or * after the cursor, the cursor simply picks them up automatically. * When the "current" (i.e., last returned by {@link ListIterator#next} * or {@link ListIterator#previous}) element of the list is removed, * the cursor automatically adjusts to the change (invalidating the * last returned value--i.e., it cannot be removed). *

* Note that the returned {@link ListIterator} does not support the * {@link ListIterator#nextIndex} and {@link ListIterator#previousIndex} * methods (they throw {@link UnsupportedOperationException} when invoked. *

* Clients must close the cursor when they are done using it. * The returned {@link ListIterator} will be an instance of * {@link CursorableLinkedList.Cursor}. To close the cursor, * cast the {@link ListIterator} to {@link CursorableLinkedList.Cursor} * and invoke the {@link CursorableLinkedList.Cursor#close} method. * * @see #cursor(int) * @see #listIterator * @see CursorableLinkedList.Cursor */ public CursorableLinkedList.Cursor cursor() { return new Cursor(0); } /** * Returns a {@link ListIterator} for iterating through the * elements of this list, initialized such that * {@link ListIterator#next} will return the element at * the specified index (if any) and {@link ListIterator#previous} * will return the element immediately preceeding it (if any). * Unlike {@link #iterator}, a cursor * is not bothered by concurrent modifications to the * underlying list. * * @see #cursor * @see #listIterator(int) * @see CursorableLinkedList.Cursor * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index > size()). */ public CursorableLinkedList.Cursor cursor(int i) { return new Cursor(i); } /** * Compares the specified object with this list for equality. Returns * true if and only if the specified object is also a list, both * lists have the same size, and all corresponding pairs of elements in * the two lists are equal. (Two elements e1 and * e2 are equal if (e1==null ? e2==null : * e1.equals(e2)).) In other words, two lists are defined to be * equal if they contain the same elements in the same order. This * definition ensures that the equals method works properly across * different implementations of the List interface. * * @param o the object to be compared for equality with this list. * @return true if the specified object is equal to this list. */ public boolean equals(Object o) { if(o == this) { return true; } else if(!(o instanceof List)) { return false; } Iterator it = ((List)o).listIterator(); for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if(!it.hasNext() || (null == elt.value() ? null != it.next() : !(elt.value().equals(it.next()))) ) { return false; } } return !it.hasNext(); } /** * Returns the element at the specified position in this list. * * @param index index of element to return. * @return the element at the specified position in this list. * * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index >= size()). */ public Object get(int index) { return getListableAt(index).value(); } /** * Returns the element at the beginning of this list. */ public Object getFirst() { try { return _head.next().value(); } catch(NullPointerException e) { throw new NoSuchElementException(); } } /** * Returns the element at the end of this list. */ public Object getLast() { try { return _head.prev().value(); } catch(NullPointerException e) { throw new NoSuchElementException(); } } /** * Returns the hash code value for this list. The hash code of a list * is defined to be the result of the following calculation: *

     *  hashCode = 1;
     *  Iterator i = list.iterator();
     *  while (i.hasNext()) {
     *      Object obj = i.next();
     *      hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
     *  }
     * 
* This ensures that list1.equals(list2) implies that * list1.hashCode()==list2.hashCode() for any two lists, * list1 and list2, as required by the general * contract of Object.hashCode. * * @return the hash code value for this list. * @see Object#hashCode() * @see Object#equals(Object) * @see #equals(Object) */ public int hashCode() { int hash = 1; for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { hash = 31*hash + (null == elt.value() ? 0 : elt.value().hashCode()); } return hash; } /** * Returns the index in this list of the first occurrence of the specified * element, or -1 if this list does not contain this element. * More formally, returns the lowest index i such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * * @param o element to search for. * @return the index in this list of the first occurrence of the specified * element, or -1 if this list does not contain this element. */ public int indexOf(Object o) { int ndx = 0; // perform the null check outside of the loop to save checking every // single time through the loop. if (null == o) { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if (null == elt.value()) { return ndx; } ndx++; } } else { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if (o.equals(elt.value())) { return ndx; } ndx++; } } return -1; } /** * Returns true if this list contains no elements. * @return true if this list contains no elements. */ public boolean isEmpty() { return(0 == _size); } /** * Returns a fail-fast iterator. * @see List#iterator */ public Iterator iterator() { return listIterator(0); } /** * Returns the index in this list of the last occurrence of the specified * element, or -1 if this list does not contain this element. * More formally, returns the highest index i such that * (o==null ? get(i)==null : o.equals(get(i))), * or -1 if there is no such index. * * @param o element to search for. * @return the index in this list of the last occurrence of the specified * element, or -1 if this list does not contain this element. */ public int lastIndexOf(Object o) { int ndx = _size-1; // perform the null check outside of the loop to save checking every // single time through the loop. if (null == o) { for(Listable elt = _head.prev(), past = null; null != elt && past != _head.next(); elt = (past = elt).prev()) { if (null == elt.value()) { return ndx; } ndx--; } } else { for(Listable elt = _head.prev(), past = null; null != elt && past != _head.next(); elt = (past = elt).prev()) { if (o.equals(elt.value())) { return ndx; } ndx--; } } return -1; } /** * Returns a fail-fast ListIterator. * @see List#listIterator */ public ListIterator listIterator() { return listIterator(0); } /** * Returns a fail-fast ListIterator. * @see List#listIterator(int) */ public ListIterator listIterator(int index) { if(index<0 || index > _size) { throw new IndexOutOfBoundsException(index + " < 0 or > " + _size); } return new ListIter(index); } /** * Removes the first occurrence in this list of the specified element. * If this list does not contain the element, it is * unchanged. More formally, removes the element with the lowest index i * such that (o==null ? get(i)==null : o.equals(get(i))) (if * such an element exists). * * @param o element to be removed from this list, if present. * @return true if this list contained the specified element. */ public boolean remove(Object o) { for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if(null == o && null == elt.value()) { removeListable(elt); return true; } else if(o != null && o.equals(elt.value())) { removeListable(elt); return true; } } return false; } /** * Removes the element at the specified position in this list (optional * operation). Shifts any subsequent elements to the left (subtracts one * from their indices). Returns the element that was removed from the * list. * * @param index the index of the element to removed. * @return the element previously at the specified position. * * @throws IndexOutOfBoundsException if the index is out of range (index * < 0 || index >= size()). */ public Object remove(int index) { Listable elt = getListableAt(index); Object ret = elt.value(); removeListable(elt); return ret; } /** * Removes from this list all the elements that are contained in the * specified collection. * * @param c collection that defines which elements will be removed from * this list. * @return true if this list changed as a result of the call. */ public boolean removeAll(Collection c) { if(0 == c.size() || 0 == _size) { return false; } else { boolean changed = false; Iterator it = iterator(); while(it.hasNext()) { if(c.contains(it.next())) { it.remove(); changed = true; } } return changed; } } /** * Removes the first element of this list, if any. */ public Object removeFirst() { if(_head.next() != null) { Object val = _head.next().value(); removeListable(_head.next()); return val; } else { throw new NoSuchElementException(); } } /** * Removes the last element of this list, if any. */ public Object removeLast() { if(_head.prev() != null) { Object val = _head.prev().value(); removeListable(_head.prev()); return val; } else { throw new NoSuchElementException(); } } /** * Retains only the elements in this list that are contained in the * specified collection. In other words, removes * from this list all the elements that are not contained in the specified * collection. * * @param c collection that defines which elements this set will retain. * * @return true if this list changed as a result of the call. */ public boolean retainAll(Collection c) { boolean changed = false; Iterator it = iterator(); while(it.hasNext()) { if(!c.contains(it.next())) { it.remove(); changed = true; } } return changed; } /** * Replaces the element at the specified position in this list with the * specified element. * * @param index index of element to replace. * @param element element to be stored at the specified position. * @return the element previously at the specified position. * * @throws ClassCastException if the class of the specified element * prevents it from being added to this list. * @throws IllegalArgumentException if some aspect of the specified * element prevents it from being added to this list. * @throws IndexOutOfBoundsException if the index is out of range * (index < 0 || index >= size()). */ public Object set(int index, Object element) { Listable elt = getListableAt(index); Object val = elt.setValue(element); broadcastListableChanged(elt); return val; } /** * Returns the number of elements in this list. * @return the number of elements in this list. */ public int size() { return _size; } /** * Returns an array containing all of the elements in this list in proper * sequence. Obeys the general contract of the {@link Collection#toArray} method. * * @return an array containing all of the elements in this list in proper * sequence. */ public Object[] toArray() { Object[] array = new Object[_size]; int i = 0; for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { array[i++] = elt.value(); } return array; } /** * Returns an array containing all of the elements in this list in proper * sequence; the runtime type of the returned array is that of the * specified array. Obeys the general contract of the * {@link Collection#toArray} method. * * @param a the array into which the elements of this list are to * be stored, if it is big enough; otherwise, a new array of the * same runtime type is allocated for this purpose. * @return an array containing the elements of this list. * @exception ArrayStoreException * if the runtime type of the specified array * is not a supertype of the runtime type of every element in * this list. */ public Object[] toArray(Object a[]) { if(a.length < _size) { a = (Object[])Array.newInstance(a.getClass().getComponentType(), _size); } int i = 0; for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { a[i++] = elt.value(); } if(a.length > _size) { a[_size] = null; // should we null out the rest of the array also? java.util.LinkedList doesn't } return a; } /** * Returns a {@link String} representation of this list, suitable for debugging. * @return a {@link String} representation of this list, suitable for debugging. */ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("["); for(Listable elt = _head.next(), past = null; null != elt && past != _head.prev(); elt = (past = elt).next()) { if(_head.next() != elt) { buf.append(", "); } buf.append(elt.value()); } buf.append("]"); return buf.toString(); } /** * Returns a fail-fast sublist. * @see List#subList(int,int) */ public List subList(int i, int j) { if(i < 0 || j > _size || i > j) { throw new IndexOutOfBoundsException(); } else if(i == 0 && j == _size) { return this; } else { return new CursorableSubList(this,i,j); } } //--- protected methods ------------------------------------------ /** * Inserts a new value into my * list, after the specified before element, and before the * specified after element * * @return the newly created * {@link org.apache.commons.collections.CursorableLinkedList.Listable} */ protected Listable insertListable(Listable before, Listable after, Object value) { _modCount++; _size++; Listable elt = new Listable(before,after,value); if(null != before) { before.setNext(elt); } else { _head.setNext(elt); } if(null != after) { after.setPrev(elt); } else { _head.setPrev(elt); } broadcastListableInserted(elt); return elt; } /** * Removes the given * {@link org.apache.commons.collections.CursorableLinkedList.Listable} * from my list. */ protected void removeListable(Listable elt) { _modCount++; _size--; if(_head.next() == elt) { _head.setNext(elt.next()); } if(null != elt.next()) { elt.next().setPrev(elt.prev()); } if(_head.prev() == elt) { _head.setPrev(elt.prev()); } if(null != elt.prev()) { elt.prev().setNext(elt.next()); } broadcastListableRemoved(elt); } /** * Returns the * {@link org.apache.commons.collections.CursorableLinkedList.Listable} * at the specified index. * * @throws IndexOutOfBoundsException if index is less than zero or * greater than or equal to the size of this list. */ protected Listable getListableAt(int index) { if(index < 0 || index >= _size) { throw new IndexOutOfBoundsException(String.valueOf(index) + " < 0 or " + String.valueOf(index) + " >= " + _size); } if(index <=_size/2) { Listable elt = _head.next(); for(int i = 0; i < index; i++) { elt = elt.next(); } return elt; } else { Listable elt = _head.prev(); for(int i = (_size-1); i > index; i--) { elt = elt.prev(); } return elt; } } /** * Registers a {@link CursorableLinkedList.Cursor} to be notified * of changes to this list. */ protected void registerCursor(Cursor cur) { _cursors.add(cur); } /** * Removes a {@link CursorableLinkedList.Cursor} from * the set of cursors to be notified of changes to this list. */ protected void unregisterCursor(Cursor cur) { _cursors.remove(cur); } /** * Informs all of my registerd cursors that they are now * invalid. */ protected void invalidateCursors() { Iterator it = _cursors.iterator(); while(it.hasNext()) { ((Cursor)it.next()).invalidate(); it.remove(); } } /** * Informs all of my registerd cursors that the specified * element was changed. * @see #set(int,java.lang.Object) */ protected void broadcastListableChanged(Listable elt) { Iterator it = _cursors.iterator(); while(it.hasNext()) { ((Cursor)it.next()).listableChanged(elt); } } /** * Informs all of my registered cursors tha the specifed * element was just removed from my list. */ protected void broadcastListableRemoved(Listable elt) { Iterator it = _cursors.iterator(); while(it.hasNext()) { ((Cursor)it.next()).listableRemoved(elt); } } /** * Informs all of my registered cursors tha the specifed * element was just added to my list. */ protected void broadcastListableInserted(Listable elt) { Iterator it = _cursors.iterator(); while(it.hasNext()) { ((Cursor)it.next()).listableInserted(elt); } } private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(_size); Listable cur = _head.next(); while(cur != null) { out.writeObject(cur.value()); cur = cur.next(); } } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); _size = 0; _head = new Listable(null,null,null); int size = in.readInt(); for(int i=0;i * _head.next() points to the first element in the list, * _head.prev() to the last. Note that it is possible for * _head.next().prev() and _head.prev().next() to be * non-null, as when I am a sublist for some larger list. * Use == _head.next() and == _head.prev() to determine * if a given * {@link org.apache.commons.collections.CursorableLinkedList.Listable} * is the first or last element in the list. */ transient protected Listable _head = new Listable(null,null,null); /** Tracks the number of structural modifications to me. */ protected int _modCount = 0; /** * A list of the currently {@link CursorableLinkedList.Cursor}s currently * open in this list. */ protected List _cursors = new ArrayList(); //--- inner classes ---------------------------------------------- class Listable implements Serializable { private Listable _prev = null; private Listable _next = null; private Object _val = null; Listable(Listable prev, Listable next, Object val) { _prev = prev; _next = next; _val = val; } Listable next() { return _next; } Listable prev() { return _prev; } Object value() { return _val; } void setNext(Listable next) { _next = next; } void setPrev(Listable prev) { _prev = prev; } Object setValue(Object val) { Object temp = _val; _val = val; return temp; } } class ListIter implements ListIterator { Listable _cur = null; Listable _lastReturned = null; int _expectedModCount = _modCount; int _nextIndex = 0; ListIter(int index) { if(index == 0) { _cur = new Listable(null,_head.next(),null); _nextIndex = 0; } else if(index == _size) { _cur = new Listable(_head.prev(),null,null); _nextIndex = _size; } else { Listable temp = getListableAt(index); _cur = new Listable(temp.prev(),temp,null); _nextIndex = index; } } public Object previous() { checkForComod(); if(!hasPrevious()) { throw new NoSuchElementException(); } else { Object ret = _cur.prev().value(); _lastReturned = _cur.prev(); _cur.setNext(_cur.prev()); _cur.setPrev(_cur.prev().prev()); _nextIndex--; return ret; } } public boolean hasNext() { checkForComod(); return(null != _cur.next() && _cur.prev() != _head.prev()); } public Object next() { checkForComod(); if(!hasNext()) { throw new NoSuchElementException(); } else { Object ret = _cur.next().value(); _lastReturned = _cur.next(); _cur.setPrev(_cur.next()); _cur.setNext(_cur.next().next()); _nextIndex++; return ret; } } public int previousIndex() { checkForComod(); if(!hasPrevious()) { return -1; } return _nextIndex-1; } public boolean hasPrevious() { checkForComod(); return(null != _cur.prev() && _cur.next() != _head.next()); } public void set(Object o) { checkForComod(); try { _lastReturned.setValue(o); } catch(NullPointerException e) { throw new IllegalStateException(); } } public int nextIndex() { checkForComod(); if(!hasNext()) { return size(); } return _nextIndex; } public void remove() { checkForComod(); if(null == _lastReturned) { throw new IllegalStateException(); } else { _cur.setNext(_lastReturned == _head.prev() ? null : _lastReturned.next()); _cur.setPrev(_lastReturned == _head.next() ? null : _lastReturned.prev()); removeListable(_lastReturned); _lastReturned = null; _nextIndex--; _expectedModCount++; } } public void add(Object o) { checkForComod(); _cur.setPrev(insertListable(_cur.prev(),_cur.next(),o)); _lastReturned = null; _nextIndex++; _expectedModCount++; } protected void checkForComod() { if(_expectedModCount != _modCount) { throw new ConcurrentModificationException(); } } } public class Cursor extends ListIter implements ListIterator { boolean _valid = false; Cursor(int index) { super(index); _valid = true; registerCursor(this); } public int previousIndex() { throw new UnsupportedOperationException(); } public int nextIndex() { throw new UnsupportedOperationException(); } public void add(Object o) { checkForComod(); Listable elt = insertListable(_cur.prev(),_cur.next(),o); _cur.setPrev(elt); _cur.setNext(elt.next()); _lastReturned = null; _nextIndex++; _expectedModCount++; } protected void listableRemoved(Listable elt) { if(null == _head.prev()) { _cur.setNext(null); } else if(_cur.next() == elt) { _cur.setNext(elt.next()); } if(null == _head.next()) { _cur.setPrev(null); } else if(_cur.prev() == elt) { _cur.setPrev(elt.prev()); } if(_lastReturned == elt) { _lastReturned = null; } } protected void listableInserted(Listable elt) { if(null == _cur.next() && null == _cur.prev()) { _cur.setNext(elt); } else if(_cur.prev() == elt.prev()) { _cur.setNext(elt); } if(_cur.next() == elt.next()) { _cur.setPrev(elt); } if(_lastReturned == elt) { _lastReturned = null; } } protected void listableChanged(Listable elt) { if(_lastReturned == elt) { _lastReturned = null; } } protected void checkForComod() { if(!_valid) { throw new ConcurrentModificationException(); } } protected void invalidate() { _valid = false; } public void close() { if(_valid) { _valid = false; unregisterCursor(this); } } } } class CursorableSubList extends CursorableLinkedList implements List { //--- constructors ----------------------------------------------- CursorableSubList(CursorableLinkedList list, int from, int to) { if(0 > from || list.size() < to) { throw new IndexOutOfBoundsException(); } else if(from > to) { throw new IllegalArgumentException(); } _list = list; if(from < list.size()) { _head.setNext(_list.getListableAt(from)); _pre = (null == _head.next()) ? null : _head.next().prev(); } else { _pre = _list.getListableAt(from-1); } if(from == to) { _head.setNext(null); _head.setPrev(null); if(to < list.size()) { _post = _list.getListableAt(to); } else { _post = null; } } else { _head.setPrev(_list.getListableAt(to-1)); _post = _head.prev().next(); } _size = to - from; _modCount = _list._modCount; } //--- public methods ------------------------------------------ public void clear() { checkForComod(); Iterator it = iterator(); while(it.hasNext()) { it.next(); it.remove(); } } public Iterator iterator() { checkForComod(); return super.iterator(); } public int size() { checkForComod(); return super.size(); } public boolean isEmpty() { checkForComod(); return super.isEmpty(); } public Object[] toArray() { checkForComod(); return super.toArray(); } public Object[] toArray(Object a[]) { checkForComod(); return super.toArray(a); } public boolean contains(Object o) { checkForComod(); return super.contains(o); } public boolean remove(Object o) { checkForComod(); return super.remove(o); } public Object removeFirst() { checkForComod(); return super.removeFirst(); } public Object removeLast() { checkForComod(); return super.removeLast(); } public boolean addAll(Collection c) { checkForComod(); return super.addAll(c); } public boolean add(Object o) { checkForComod(); return super.add(o); } public boolean addFirst(Object o) { checkForComod(); return super.addFirst(o); } public boolean addLast(Object o) { checkForComod(); return super.addLast(o); } public boolean removeAll(Collection c) { checkForComod(); return super.removeAll(c); } public boolean containsAll(Collection c) { checkForComod(); return super.containsAll(c); } public boolean addAll(int index, Collection c) { checkForComod(); return super.addAll(index,c); } public int hashCode() { checkForComod(); return super.hashCode(); } public boolean retainAll(Collection c) { checkForComod(); return super.retainAll(c); } public Object set(int index, Object element) { checkForComod(); return super.set(index,element); } public boolean equals(Object o) { checkForComod(); return super.equals(o); } public Object get(int index) { checkForComod(); return super.get(index); } public Object getFirst() { checkForComod(); return super.getFirst(); } public Object getLast() { checkForComod(); return super.getLast(); } public void add(int index, Object element) { checkForComod(); super.add(index,element); } public ListIterator listIterator(int index) { checkForComod(); return super.listIterator(index); } public Object remove(int index) { checkForComod(); return super.remove(index); } public int indexOf(Object o) { checkForComod(); return super.indexOf(o); } public int lastIndexOf(Object o) { checkForComod(); return super.lastIndexOf(o); } public ListIterator listIterator() { checkForComod(); return super.listIterator(); } public List subList(int fromIndex, int toIndex) { checkForComod(); return super.subList(fromIndex,toIndex); } //--- protected methods ------------------------------------------ /** * Inserts a new value into my * list, after the specified before element, and before the * specified after element * * @return the newly created {@link CursorableLinkedList.Listable} */ protected Listable insertListable(Listable before, Listable after, Object value) { _modCount++; _size++; Listable elt = _list.insertListable((null == before ? _pre : before), (null == after ? _post : after),value); if(null == _head.next()) { _head.setNext(elt); _head.setPrev(elt); } if(before == _head.prev()) { _head.setPrev(elt); } if(after == _head.next()) { _head.setNext(elt); } broadcastListableInserted(elt); return elt; } /** * Removes the given {@link CursorableLinkedList.Listable} from my list. */ protected void removeListable(Listable elt) { _modCount++; _size--; if(_head.next() == elt && _head.prev() == elt) { _head.setNext(null); _head.setPrev(null); } if(_head.next() == elt) { _head.setNext(elt.next()); } if(_head.prev() == elt) { _head.setPrev(elt.prev()); } _list.removeListable(elt); broadcastListableRemoved(elt); } /** * Test to see if my underlying list has been modified * by some other process. If it has, throws a * {@link ConcurrentModificationException}, otherwise * quietly returns. * * @throws ConcurrentModificationException */ protected void checkForComod() throws ConcurrentModificationException { if(_modCount != _list._modCount) { throw new ConcurrentModificationException(); } } //--- protected attributes --------------------------------------- /** My underlying list */ protected CursorableLinkedList _list = null; /** The element in my underlying list preceding the first element in my list. */ protected Listable _pre = null; /** The element in my underlying list following the last element in my list. */ protected Listable _post = null; } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ReferenceMap.java0100644000175000017500000006234510055172376031474 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; /** * Hashtable-based {@link Map} implementation that allows * mappings to be removed by the garbage collector.

* * When you construct a ReferenceMap, you can * specify what kind of references are used to store the * map's keys and values. If non-hard references are * used, then the garbage collector can remove mappings * if a key or value becomes unreachable, or if the * JVM's memory is running low. For information on how * the different reference types behave, see * {@link Reference}.

* * Different types of references can be specified for keys * and values. The keys can be configured to be weak but * the values hard, in which case this class will behave * like a * WeakHashMap. However, you * can also specify hard keys and weak values, or any other * combination. The default constructor uses hard keys * and soft values, providing a memory-sensitive cache.

* * The algorithms used are basically the same as those * in {@link java.util.HashMap}. In particular, you * can specify a load factor and capacity to suit your * needs. All optional {@link Map} operations are * supported.

* * However, this {@link Map} implementation does not * allow null elements. Attempting to add a null key or * or a null value to the map will raise a * NullPointerException.

* * As usual, this implementation is not synchronized. You * can use {@link java.util.Collections#synchronizedMap} to * provide synchronized access to a ReferenceMap. * * @author Paul Jack * @version $Id: ReferenceMap.java,v 1.7.2.1 2004/05/22 12:14:01 scolebourne Exp $ * @since 2.1 * @see java.lang.ref.Reference */ public class ReferenceMap extends AbstractMap { /** * For serialization. */ final private static long serialVersionUID = -3370601314380922368L; /** * Constant indicating that hard references should be used. */ final public static int HARD = 0; /** * Constant indiciating that soft references should be used. */ final public static int SOFT = 1; /** * Constant indicating that weak references should be used. */ final public static int WEAK = 2; // --- serialized instance variables: /** * The reference type for keys. Must be HARD, SOFT, WEAK. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private int keyType; /** * The reference type for values. Must be HARD, SOFT, WEAK. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private int valueType; /** * The threshold variable is calculated by multiplying * table.length and loadFactor. * Note: I originally marked this field as final, but then this class * didn't compile under JDK1.2.2. * @serial */ private float loadFactor; // -- Non-serialized instance variables /** * ReferenceQueue used to eliminate stale mappings. * @see #purge */ private transient ReferenceQueue queue = new ReferenceQueue(); /** * The hash table. Its length is always a power of two. */ private transient Entry[] table; /** * Number of mappings in this map. */ private transient int size; /** * When size reaches threshold, the map is resized. * @see resize */ private transient int threshold; /** * Number of times this map has been modified. */ private transient volatile int modCount; /** * Cached key set. May be null if key set is never accessed. */ private transient Set keySet; /** * Cached entry set. May be null if entry set is never accessed. */ private transient Set entrySet; /** * Cached values. May be null if values() is never accessed. */ private transient Collection values; /** * Constructs a new ReferenceMap that will * use hard references to keys and soft references to values. */ public ReferenceMap() { this(HARD, SOFT); } /** * Constructs a new ReferenceMap that will * use the specified types of references. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} */ public ReferenceMap(int keyType, int valueType) { this(keyType, valueType, 16, 0.75f); } /** * Constructs a new ReferenceMap with the * specified reference types, load factor and initial * capacity. * * @param keyType the type of reference to use for keys; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param valueType the type of reference to use for values; * must be {@link #HARD}, {@link #SOFT}, {@link #WEAK} * @param capacity the initial capacity for the map * @param loadFactor the load factor for the map */ public ReferenceMap(int keyType, int valueType, int capacity, float loadFactor) { super(); verify("keyType", keyType); verify("valueType", valueType); if (capacity <= 0) { throw new IllegalArgumentException("capacity must be positive"); } if ((loadFactor <= 0.0f) || (loadFactor >= 1.0f)) { throw new IllegalArgumentException("Load factor must be greater than 0 and less than 1."); } this.keyType = keyType; this.valueType = valueType; int v = 1; while (v < capacity) v *= 2; this.table = new Entry[v]; this.loadFactor = loadFactor; this.threshold = (int)(v * loadFactor); } // used by constructor private static void verify(String name, int type) { if ((type < HARD) || (type > WEAK)) { throw new IllegalArgumentException(name + " must be HARD, SOFT, WEAK."); } } /** * Writes this object to the given output stream. * * @param out the output stream to write to * @throws IOException if the stream raises it */ private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); out.writeInt(table.length); // Have to use null-terminated list because size might shrink // during iteration for (Iterator iter = entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry)iter.next(); out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } out.writeObject(null); } /** * Reads the contents of this object from the given input stream. * * @param inp the input stream to read from * @throws IOException if the stream raises it * @throws ClassNotFoundException if the stream raises it */ private void readObject(ObjectInputStream inp) throws IOException, ClassNotFoundException { inp.defaultReadObject(); table = new Entry[inp.readInt()]; threshold = (int)(table.length * loadFactor); queue = new ReferenceQueue(); Object key = inp.readObject(); while (key != null) { Object value = inp.readObject(); put(key, value); key = inp.readObject(); } } /** * Constructs a reference of the given type to the given * referent. The reference is registered with the queue * for later purging. * * @param type HARD, SOFT or WEAK * @param referent the object to refer to * @param hash the hash code of the key of the mapping; * this number might be different from referent.hashCode() if * the referent represents a value and not a key */ private Object toReference(int type, Object referent, int hash) { switch (type) { case HARD: return referent; case SOFT: return new SoftRef(hash, referent, queue); case WEAK: return new WeakRef(hash, referent, queue); default: throw new Error(); } } /** * Returns the entry associated with the given key. * * @param key the key of the entry to look up * @return the entry associated with that key, or null * if the key is not in this map */ private Entry getEntry(Object key) { if (key == null) return null; int hash = key.hashCode(); int index = indexFor(hash); for (Entry entry = table[index]; entry != null; entry = entry.next) { if ((entry.hash == hash) && key.equals(entry.getKey())) { return entry; } } return null; } /** * Converts the given hash code into an index into the * hash table. */ private int indexFor(int hash) { // mix the bits to avoid bucket collisions... hash += ~(hash << 15); hash ^= (hash >>> 10); hash += (hash << 3); hash ^= (hash >>> 6); hash += ~(hash << 11); hash ^= (hash >>> 16); return hash & (table.length - 1); } /** * Resizes this hash table by doubling its capacity. * This is an expensive operation, as entries must * be copied from the old smaller table to the new * bigger table. */ private void resize() { Entry[] old = table; table = new Entry[old.length * 2]; for (int i = 0; i < old.length; i++) { Entry next = old[i]; while (next != null) { Entry entry = next; next = next.next; int index = indexFor(entry.hash); entry.next = table[index]; table[index] = entry; } old[i] = null; } threshold = (int)(table.length * loadFactor); } /** * Purges stale mappings from this map.

* * Ordinarily, stale mappings are only removed during * a write operation; typically a write operation will * occur often enough that you'll never need to manually * invoke this method.

* * Note that this method is not synchronized! Special * care must be taken if, for instance, you want stale * mappings to be removed on a periodic basis by some * background thread. */ private void purge() { Reference ref = queue.poll(); while (ref != null) { purge(ref); ref = queue.poll(); } } private void purge(Reference ref) { // The hashCode of the reference is the hashCode of the // mapping key, even if the reference refers to the // mapping value... int hash = ref.hashCode(); int index = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if (entry.purge(ref)) { if (previous == null) table[index] = entry.next; else previous.next = entry.next; this.size--; return; } previous = entry; entry = entry.next; } } /** * Returns the size of this map. * * @return the size of this map */ public int size() { purge(); return size; } /** * Returns true if this map is empty. * * @return true if this map is empty */ public boolean isEmpty() { purge(); return size == 0; } /** * Returns true if this map contains the given key. * * @return true if the given key is in this map */ public boolean containsKey(Object key) { purge(); Entry entry = getEntry(key); if (entry == null) return false; return entry.getValue() != null; } /** * Returns the value associated with the given key, if any. * * @return the value associated with the given key, or null * if the key maps to no value */ public Object get(Object key) { purge(); Entry entry = getEntry(key); if (entry == null) return null; return entry.getValue(); } /** * Associates the given key with the given value.

* Neither the key nor the value may be null. * * @param key the key of the mapping * @param value the value of the mapping * @return the last value associated with that key, or * null if no value was associated with the key * @throws NullPointerException if either the key or value * is null */ public Object put(Object key, Object value) { if (key == null) throw new NullPointerException("null keys not allowed"); if (value == null) throw new NullPointerException("null values not allowed"); purge(); if (size + 1 > threshold) resize(); int hash = key.hashCode(); int index = indexFor(hash); Entry entry = table[index]; while (entry != null) { if ((hash == entry.hash) && key.equals(entry.getKey())) { Object result = entry.getValue(); entry.setValue(value); return result; } entry = entry.next; } this.size++; modCount++; key = toReference(keyType, key, hash); value = toReference(valueType, value, hash); table[index] = new Entry(key, hash, value, table[index]); return null; } /** * Removes the key and its associated value from this map. * * @param key the key to remove * @return the value associated with that key, or null if * the key was not in the map */ public Object remove(Object key) { if (key == null) return null; purge(); int hash = key.hashCode(); int index = indexFor(hash); Entry previous = null; Entry entry = table[index]; while (entry != null) { if ((hash == entry.hash) && key.equals(entry.getKey())) { if (previous == null) table[index] = entry.next; else previous.next = entry.next; this.size--; modCount++; return entry.getValue(); } previous = entry; entry = entry.next; } return null; } /** * Clears this map. */ public void clear() { Arrays.fill(table, null); size = 0; while (queue.poll() != null); // drain the queue } /** * Returns a set view of this map's entries. * * @return a set view of this map's entries */ public Set entrySet() { if (entrySet != null) return entrySet; entrySet = new AbstractSet() { public int size() { return ReferenceMap.this.size(); } public void clear() { ReferenceMap.this.clear(); } public boolean contains(Object o) { if (o == null) return false; if (!(o instanceof Map.Entry)) return false; Map.Entry e = (Map.Entry)o; Entry e2 = getEntry(e.getKey()); return (e2 != null) && e.equals(e2); } public boolean remove(Object o) { boolean r = contains(o); if (r) { Map.Entry e = (Map.Entry)o; ReferenceMap.this.remove(e.getKey()); } return r; } public Iterator iterator() { return new EntryIterator(); } public Object[] toArray() { return toArray(new Object[0]); } public Object[] toArray(Object[] arr) { ArrayList list = new ArrayList(); Iterator iterator = iterator(); while (iterator.hasNext()) { Entry e = (Entry)iterator.next(); list.add(new DefaultMapEntry(e.getKey(), e.getValue())); } return list.toArray(arr); } }; return entrySet; } /** * Returns a set view of this map's keys. * * @return a set view of this map's keys */ public Set keySet() { if (keySet != null) return keySet; keySet = new AbstractSet() { public int size() { return size; } public Iterator iterator() { return new KeyIterator(); } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { Object r = ReferenceMap.this.remove(o); return r != null; } public void clear() { ReferenceMap.this.clear(); } }; return keySet; } /** * Returns a collection view of this map's values. * * @return a collection view of this map's values. */ public Collection values() { if (values != null) return values; values = new AbstractCollection() { public int size() { return size; } public void clear() { ReferenceMap.this.clear(); } public Iterator iterator() { return new ValueIterator(); } }; return values; } // If getKey() or getValue() returns null, it means // the mapping is stale and should be removed. private class Entry implements Map.Entry { Object key; Object value; int hash; Entry next; public Entry(Object key, int hash, Object value, Entry next) { this.key = key; this.hash = hash; this.value = value; this.next = next; } public Object getKey() { return (keyType > HARD) ? ((Reference)key).get() : key; } public Object getValue() { return (valueType > HARD) ? ((Reference)value).get() : value; } public Object setValue(Object object) { Object old = getValue(); if (valueType > HARD) ((Reference)value).clear(); value = toReference(valueType, object, hash); return old; } public boolean equals(Object o) { if (o == null) return false; if (o == this) return true; if (!(o instanceof Map.Entry)) return false; Map.Entry entry = (Map.Entry)o; Object key = entry.getKey(); Object value = entry.getValue(); if ((key == null) || (value == null)) return false; return key.equals(getKey()) && value.equals(getValue()); } public int hashCode() { Object v = getValue(); return hash ^ ((v == null) ? 0 : v.hashCode()); } public String toString() { return getKey() + "=" + getValue(); } boolean purge(Reference ref) { boolean r = (keyType > HARD) && (key == ref); r = r || ((valueType > HARD) && (value == ref)); if (r) { if (keyType > HARD) ((Reference)key).clear(); if (valueType > HARD) ((Reference)value).clear(); } return r; } } private class EntryIterator implements Iterator { // These fields keep track of where we are in the table. int index; Entry entry; Entry previous; // These Object fields provide hard references to the // current and next entry; this assures that if hasNext() // returns true, next() will actually return a valid element. Object nextKey, nextValue; Object currentKey, currentValue; int expectedModCount; public EntryIterator() { index = (size() != 0 ? table.length : 0); // have to do this here! size() invocation above // may have altered the modCount. expectedModCount = modCount; } public boolean hasNext() { checkMod(); while (nextNull()) { Entry e = entry; int i = index; while ((e == null) && (i > 0)) { i--; e = table[i]; } entry = e; index = i; if (e == null) { currentKey = null; currentValue = null; return false; } nextKey = e.getKey(); nextValue = e.getValue(); if (nextNull()) entry = entry.next; } return true; } private void checkMod() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } private boolean nextNull() { return (nextKey == null) || (nextValue == null); } protected Entry nextEntry() { checkMod(); if (nextNull() && !hasNext()) throw new NoSuchElementException(); previous = entry; entry = entry.next; currentKey = nextKey; currentValue = nextValue; nextKey = null; nextValue = null; return previous; } public Object next() { return nextEntry(); } public void remove() { checkMod(); if (previous == null) throw new IllegalStateException(); ReferenceMap.this.remove(currentKey); previous = null; currentKey = null; currentValue = null; expectedModCount = modCount; } } private class ValueIterator extends EntryIterator { public Object next() { return nextEntry().getValue(); } } private class KeyIterator extends EntryIterator { public Object next() { return nextEntry().getKey(); } } // These two classes store the hashCode of the key of // of the mapping, so that after they're dequeued a quick // lookup of the bucket in the table can occur. private static class SoftRef extends SoftReference { private int hash; public SoftRef(int hash, Object r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } private static class WeakRef extends WeakReference { private int hash; public WeakRef(int hash, Object r, ReferenceQueue q) { super(r, q); this.hash = hash; } public int hashCode() { return hash; } } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ProxyMap.java0100644000175000017500000001002110055172400030663 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Map; import java.util.Set; /** *

This Map wraps another Map * implementation, using the wrapped instance for its default * implementation. This class is used as a framework on which to * build to extensions for its wrapped Map object which * would be unavailable or inconvenient via sub-classing (but usable * via composition).

* *

An example use case is where the wrapped Map needs * synchronization (to make it thread-safe), but the Map * returned by Collections.synchronizedMap(map) * hides part of map's public interface.

* * @since 2.0 * @author Daniel Rall */ public abstract class ProxyMap implements Map { /** * The Map used for default implementations. */ protected Map map; /** * Creates a new instance acting as a representative for the * specified Map. * * @param map The Map to whose operations to wrap. */ public ProxyMap(Map map) { this.map = map; } /** * Invokes the underlying {@link Map#clear()} method. */ public void clear() { map.clear(); } /** * Invokes the underlying {@link Map#containsKey(Object)} method. */ public boolean containsKey(Object key) { return map.containsKey(key); } /** * Invokes the underlying {@link Map#containsValue(Object)} method. */ public boolean containsValue(Object value) { return map.containsValue(value); } /** * Invokes the underlying {@link Map#entrySet()} method. */ public Set entrySet() { return map.entrySet(); } /** * Invokes the underlying {@link Map#equals(Object)} method. */ public boolean equals(Object m) { return map.equals(m); } /** * Invokes the underlying {@link Map#get(Object)} method. */ public Object get(Object key) { return map.get(key); } /** * Invokes the underlying {@link Map#hashCode()} method. */ public int hashCode() { return map.hashCode(); } /** * Invokes the underlying {@link Map#isEmpty()} method. */ public boolean isEmpty() { return map.isEmpty(); } /** * Invokes the underlying {@link Map#keySet()} method. */ public Set keySet() { return map.keySet(); } /** * Invokes the underlying {@link Map#put(Object,Object)} method. */ public Object put(Object key, Object value) { return map.put(key, value); } /** * Invokes the underlying {@link Map#putAll(Map)} method. */ public void putAll(Map t) { map.putAll(t); } /** * Invokes the underlying {@link Map#remove(Object)} method. */ public Object remove(Object key) { return map.remove(key); } /** * Invokes the underlying {@link Map#size()} method. */ public int size() { return map.size(); } /** * Invokes the underlying {@link Map#values()} method. */ public Collection values() { return map.values(); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/Bag.java0100644000175000017500000001602710055172376027625 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Iterator; import java.util.Set; /** * A {@link Collection} that counts the number of times an object appears in * the collection. Suppose you have a Bag that contains {a, a, b, * c}. Calling {@link #getCount(Object)} on a would return * 2, while calling {@link #uniqueSet()} would return {a, b, c}. * *

Note that this interface violates the {@link Collection} contract. * The behavior specified in many of these methods is not the same * as the behavior specified by {@link Collection}. The noncompliant methods * are clearly marked with "(Violation)" in their summary line. A future * version of this class will specify the same behavior as {@link Collection}, * which unfortunately will break backwards compatibility with this version. * * @since 2.0 * @author Chuck Burdick **/ public interface Bag extends Collection { /** * Return the number of occurrences (cardinality) of the given * object currently in the bag. If the object does not exist in the * bag, return 0. **/ public int getCount(Object o); /** * (Violation) * Add the given object to the bag and keep a count. If the object * is already in the {@link #uniqueSet()} then increment its count as * reported by {@link #getCount(Object)}. Otherwise add it to the {@link * #uniqueSet()} and report its count as 1.

* * Since this method always increases the size of the bag, * according to the {@link Collection#add(Object)} contract, it * should always return true. Since it sometimes returns * false, this method violates the contract. A future * version of this method will comply by always returning true. * * @return true if the object was not already in the * uniqueSet * @see #getCount(Object) **/ public boolean add(Object o); /** * Add i copies of the given object to the bag and * keep a count. * @return true if the object was not already in the * uniqueSet * @see #add(Object) * @see #getCount(Object) **/ public boolean add(Object o, int i); /** * (Violation) * Remove all occurrences of the given object from the bag, and do * not represent the object in the {@link #uniqueSet()}. * *

According to the {@link Collection#remove(Object)} method, * this method should only remove the first occurrence of the * given object, not all occurrences. A future version of this * method will comply with the contract by only removing one occurrence * of the given object. * * @see #remove(Object, int) * @return true if this call changed the collection **/ public boolean remove(Object o); /** * Remove the given number of occurrences from the bag. If the bag * contains i occurrences or less, the item will be * removed from the {@link #uniqueSet()}. * @see #getCount(Object) * @see #remove(Object) * @return true if this call changed the collection **/ public boolean remove(Object o, int i); /** * The {@link Set} of unique members that represent all members in * the bag. Uniqueness constraints are the same as those in {@link * Set}. **/ public Set uniqueSet(); /** * Returns the total number of items in the bag across all types. **/ public int size(); /** * (Violation) * Returns true if the bag contains all elements in * the given collection, respecting cardinality. That is, if the * given collection C contains n copies * of a given object, calling {@link #getCount(Object)} on that object must * be >= n for all n in C. * *

The {@link Collection#containsAll(Collection)} method specifies * that cardinality should not be respected; this method should * return true if the bag contains at least one of every object contained * in the given collection. A future version of this method will comply * with that contract. **/ public boolean containsAll(Collection c); /** * (Violation) * Remove all elements represented in the given collection, * respecting cardinality. That is, if the given collection * C contains n copies of a given object, * the bag will have n fewer copies, assuming the bag * had at least n copies to begin with. * *

The {@link Collection#removeAll(Collection)} method specifies * that cardinality should not be respected; this method should * remove all occurrences of every object contained in the * given collection. A future version of this method will comply * with that contract. * * @return true if this call changed the collection **/ public boolean removeAll(Collection c); /** * (Violation) * Remove any members of the bag that are not in the given * collection, respecting cardinality. That is, if the given * collection C contains n copies of a * given object and the bag has m > n copies, then * delete m - n copies from the bag. In addition, if * e is an object in the bag but * !C.contains(e), then remove e and any * of its copies. * *

The {@link Collection#retainAll(Collection)} method specifies * that cardinality should not be respected; this method should * keep all occurrences of every object contained in the * given collection. A future version of this method will comply * with that contract. * * @return true if this call changed the collection **/ public boolean retainAll(Collection c); /** * Returns an {@link Iterator} over the entire set of members, * including copies due to cardinality. This iterator is fail-fast * and will not tolerate concurrent modifications. **/ public Iterator iterator(); } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/DefaultMapBag.java0100644000175000017500000002530710055172376031571 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; /** * This class provides a skeletal implementation of the {@link Bag} * interface to minimize the effort required for target implementations. * Subclasses need only to call {@link #setMap(Map)} in their constructor * specifying a map instance that will be used to store the contents of * the bag.

* * The map will be used to map bag elements to a number; the number represents * the number of occurrences of that element in the bag.

* * @since 2.0 * @author Chuck Burdick * @author Michael A. Smith **/ public abstract class DefaultMapBag implements Bag { private Map _map = null; private int _total = 0; private int _mods = 0; /** * Constructor. Subclasses should invoke {@link #setMap(Map)} in * their constructors. */ public DefaultMapBag() { } /** * Adds a new element to the bag by incrementing its count in the * underlying map. * * @see Bag#add(Object) */ public boolean add(Object o) { return add(o, 1); } /** * Adds a new element to the bag by incrementing its count in the map. * * @see Bag#add(Object, int) */ public boolean add(Object o, int i) { _mods++; if (i > 0) { int count = (i + getCount(o)); _map.put(o, new Integer(count)); _total += i; return (count == i); } else { return false; } } /** * Invokes {@link #add(Object)} for each element in the given collection. * * @see Bag#addAll(Collection) */ public boolean addAll(Collection c) { boolean changed = false; Iterator i = c.iterator(); while (i.hasNext()) { boolean added = add(i.next()); changed = changed || added; } return changed; } /** * Clears the bag by clearing the underlying map. */ public void clear() { _mods++; _map.clear(); _total = 0; } /** * Determines if the bag contains the given element by checking if the * underlying map contains the element as a key. * * @return true if the bag contains the given element */ public boolean contains(Object o) { return _map.containsKey(o); } public boolean containsAll(Collection c) { return containsAll(new HashBag(c)); } /** * Returns true if the bag contains all elements in * the given collection, respecting cardinality. * @see #containsAll(Collection) **/ public boolean containsAll(Bag other) { boolean result = true; Iterator i = other.uniqueSet().iterator(); while (i.hasNext()) { Object current = i.next(); boolean contains = getCount(current) >= ((Bag)other).getCount(current); result = result && contains; } return result; } /** * Returns true if the given object is not null, has the precise type * of this bag, and contains the same number of occurrences of all the * same elements. * * @param o the object to test for equality * @return true if that object equals this bag */ public boolean equals(Object o) { return (o == this || (o != null && o.getClass().equals(this.getClass()) && ((DefaultMapBag)o)._map.equals(this._map))); } /** * Returns the hash code of the underlying map. * * @return the hash code of the underlying map */ public int hashCode() { return _map.hashCode(); } /** * Returns true if the underlying map is empty. * * @return true if there are no elements in this bag */ public boolean isEmpty() { return _map.isEmpty(); } public Iterator iterator() { return new BagIterator(this, extractList().iterator()); } private class BagIterator implements Iterator { private DefaultMapBag _parent = null; private Iterator _support = null; private Object _current = null; private int _mods = 0; public BagIterator(DefaultMapBag parent, Iterator support) { _parent = parent; _support = support; _current = null; _mods = parent.modCount(); } public boolean hasNext() { return _support.hasNext(); } public Object next() { if (_parent.modCount() != _mods) { throw new ConcurrentModificationException(); } _current = _support.next(); return _current; } public void remove() { if (_parent.modCount() != _mods) { throw new ConcurrentModificationException(); } _support.remove(); _parent.remove(_current, 1); _mods++; } } public boolean remove (Object o) { return remove(o, getCount(o)); } public boolean remove (Object o, int i) { _mods++; boolean result = false; int count = getCount(o); if (i <= 0) { result = false; } else if (count > i) { _map.put(o, new Integer(count - i)); result = true; _total -= i; } else { // count > 0 && count <= i // need to remove all result = (_map.remove(o) != null); _total -= count; } return result; } public boolean removeAll(Collection c) { boolean result = false; if (c != null) { Iterator i = c.iterator(); while (i.hasNext()) { boolean changed = remove(i.next(), 1); result = result || changed; } } return result; } /** * Remove any members of the bag that are not in the given * bag, respecting cardinality. * * @return true if this call changed the collection */ public boolean retainAll(Collection c) { return retainAll(new HashBag(c)); } /** * Remove any members of the bag that are not in the given * bag, respecting cardinality. * @see #retainAll(Collection) * @return true if this call changed the collection **/ public boolean retainAll(Bag other) { boolean result = false; Bag excess = new HashBag(); Iterator i = uniqueSet().iterator(); while (i.hasNext()) { Object current = i.next(); int myCount = getCount(current); int otherCount = other.getCount(current); if (1 <= otherCount && otherCount <= myCount) { excess.add(current, myCount - otherCount); } else { excess.add(current, myCount); } } if (!excess.isEmpty()) { result = removeAll(excess); } return result; } /** * Returns an array of all of this bag's elements. * * @return an array of all of this bag's elements */ public Object[] toArray() { return extractList().toArray(); } /** * Returns an array of all of this bag's elements. * * @param a the array to populate * @return an array of all of this bag's elements */ public Object[] toArray(Object[] a) { return extractList().toArray(a); } /** * Returns the number of occurrence of the given element in this bag * by looking up its count in the underlying map. * * @see Bag#getCount(Object) */ public int getCount(Object o) { int result = 0; Integer count = MapUtils.getInteger(_map, o); if (count != null) { result = count.intValue(); } return result; } /** * Returns an unmodifiable view of the underlying map's key set. * * @return the set of unique elements in this bag */ public Set uniqueSet() { return Collections.unmodifiableSet(_map.keySet()); } /** * Returns the number of elements in this bag. * * @return the number of elements in this bag */ public int size() { return _total; } /** * Actually walks the bag to make sure the count is correct and * resets the running total **/ protected int calcTotalSize() { _total = extractList().size(); return _total; } /** * Utility method for implementations to set the map that backs * this bag. Not intended for interactive use outside of * subclasses. **/ protected void setMap(Map m) { _map = m; } /** * Utility method for implementations to access the map that backs * this bag. Not intended for interactive use outside of * subclasses. **/ protected Map getMap() { return _map; } /** * Create a list for use in iteration, etc. **/ private List extractList() { List result = new ArrayList(); Iterator i = uniqueSet().iterator(); while (i.hasNext()) { Object current = i.next(); for (int index = getCount(current); index > 0; index--) { result.add(current); } } return result; } /** * Return number of modifications for iterator **/ private int modCount() { return _mods; } /** * Implement a toString() method suitable for debugging **/ public String toString() { StringBuffer buf = new StringBuffer(); buf.append("["); Iterator i = uniqueSet().iterator(); while(i.hasNext()) { Object current = i.next(); int count = getCount(current); buf.append(count); buf.append(":"); buf.append(current); if(i.hasNext()) { buf.append(","); } } buf.append("]"); return buf.toString(); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/StaticBucketMap.java0100644000175000017500000004733610055172400032152 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.ArrayList; import java.util.NoSuchElementException; /** * A StaticBucketMap is an efficient, thread-safe implementation of * java.util.Map that performs well in in a highly * thread-contentious environment. The map supports very efficient * {@link #get(Object) get}, {@link #put(Object,Object) put}, * {@link #remove(Object) remove} and {@link #containsKey(Object) containsKey} * operations, assuming (approximate) uniform hashing and * that the number of entries does not exceed the number of buckets. If the * number of entries exceeds the number of buckets or if the hashcodes of the * objects are not uniformly distributed, these operations have a worst case * scenario that is proportional to the number of elements in the map * (O(n)).

* * Each bucket in the hash table has its own monitor, so two threads can * safely operate on the map at the same time, often without incurring any * monitor contention. This means that you don't have to wrap instances * of this class with {@link java.util.Collections#synchronizedMap(Map)}; * instances are already thread-safe. Unfortunately, however, this means * that this map implementation behaves in ways you may find disconcerting. * Bulk operations, such as {@link #putAll(Map) putAll} or the * {@link Collection#retainAll(Collection) retainAll} operation in collection * views, are not atomic. If two threads are simultaneously * executing * *

 *   staticBucketMapInstance.putAll(map);
 * 
* * and * *
 *   staticBucketMapInstance.entrySet().removeAll(map.entrySet());
 * 
* * then the results are generally random. Those two statement could cancel * each other out, leaving staticBucketMapInstance essentially * unchanged, or they could leave some random subset of map in * staticBucketMapInstance.

* * Also, much like an encyclopedia, the results of {@link #size()} and * {@link #isEmpty()} are out-of-date as soon as they are produced.

* * The iterators returned by the collection views of this class are not * fail-fast. They will never raise a * {@link java.util.ConcurrentModificationException}. Keys and values * added to the map after the iterator is created do not necessarily appear * during iteration. Similarly, the iterator does not necessarily fail to * return keys and values that were removed after the iterator was created.

* * Finally, unlike {@link java.util.HashMap}-style implementations, this * class never rehashes the map. The number of buckets is fixed * at construction time and never altered. Performance may degrade if * you do not allocate enough buckets upfront.

* * The {@link #atomic(Runnable)} method is provided to allow atomic iterations * and bulk operations; however, overuse of {@link #atomic(Runnable) atomic} * will basically result in a map that's slower than an ordinary synchronized * {@link java.util.HashMap}. * * Use this class if you do not require reliable bulk operations and * iterations, or if you can make your own guarantees about how bulk * operations will affect the map.

* * @author Berin Loritsch * @author Gerhard Froehlich * @author Michael A. Smith * @author Paul Jack * @version CVS $Revision: 1.6.2.1 $ $Date: 2004/05/22 12:14:02 $ * @since Collections 2.1 */ public final class StaticBucketMap implements Map { private static final int DEFAULT_BUCKETS = 255; private Node[] m_buckets; private Lock[] m_locks; /** * Initializes the map with the default number of buckets (255). */ public StaticBucketMap() { this( DEFAULT_BUCKETS ); } /** * Initializes the map with a specified number of buckets. The number * of buckets is never below 17, and is always an odd number (StaticBucketMap * ensures this). The number of buckets is inversely proportional to the * chances for thread contention. The fewer buckets, the more chances for * thread contention. The more buckets the fewer chances for thread * contention. * * @param numBuckets the number of buckets for this map */ public StaticBucketMap( int numBuckets ) { int size = Math.max( 17, numBuckets ); // Ensure that bucketSize is never a power of 2 (to ensure maximal distribution) if( size % 2 == 0 ) { size--; } m_buckets = new Node[ size ]; m_locks = new Lock[ size ]; for( int i = 0; i < size; i++ ) { m_locks[ i ] = new Lock(); } } /** * Determine the exact hash entry for the key. The hash algorithm * is rather simplistic, but it does the job: * *

     *   He = |Hk mod n|
     * 
* *

* He is the entry's hashCode, Hk is the key's hashCode, and n is * the number of buckets. *

*/ private final int getHash( Object key ) { if( key == null ) return 0; int hash = key.hashCode(); hash += ~(hash << 15); hash ^= (hash >>> 10); hash += (hash << 3); hash ^= (hash >>> 6); hash += ~(hash << 11); hash ^= (hash >>> 16); hash %= m_buckets.length; return ( hash < 0 ) ? hash * -1 : hash; } /** * Implements {@link Map#keySet()}. */ public Set keySet() { return new KeySet(); } /** * Implements {@link Map#size()}. */ public int size() { int cnt = 0; for( int i = 0; i < m_buckets.length; i++ ) { cnt += m_locks[i].size; } return cnt; } /** * Implements {@link Map#put(Object, Object)}. */ public Object put( final Object key, final Object value ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_buckets[ hash ]; if( n == null ) { n = new Node(); n.key = key; n.value = value; m_buckets[ hash ] = n; m_locks[hash].size++; return null; } // Set n to the last node in the linked list. Check each key along the way // If the key is found, then change the value of that node and return // the old value. for( Node next = n; next != null; next = next.next ) { n = next; if( n.key == key || ( n.key != null && n.key.equals( key ) ) ) { Object returnVal = n.value; n.value = value; return returnVal; } } // The key was not found in the current list of nodes, add it to the end // in a new node. Node newNode = new Node(); newNode.key = key; newNode.value = value; n.next = newNode; m_locks[hash].size++; } return null; } /** * Implements {@link Map#get(Object)}. */ public Object get( final Object key ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_buckets[ hash ]; while( n != null ) { if( n.key == key || ( n.key != null && n.key.equals( key ) ) ) { return n.value; } n = n.next; } } return null; } /** * Implements {@link Map#containsKey(Object)}. */ public boolean containsKey( final Object key ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_buckets[ hash ]; while( n != null ) { if( n.key == null || ( n.key != null && n.key.equals( key ) ) ) { return true; } n = n.next; } } return false; } /** * Implements {@link Map#containsValue(Object)}. */ public boolean containsValue( final Object value ) { for( int i = 0; i < m_buckets.length; i++ ) { synchronized( m_locks[ i ] ) { Node n = m_buckets[ i ]; while( n != null ) { if( n.value == value || (n.value != null && n.value.equals( value ) ) ) { return true; } n = n.next; } } } return false; } /** * Implements {@link Map#values()}. */ public Collection values() { return new Values(); } /** * Implements {@link Map#entrySet()}. */ public Set entrySet() { return new EntrySet(); } /** * Implements {@link Map#putAll(Map)}. */ public void putAll( Map other ) { Iterator i = other.keySet().iterator(); while( i.hasNext() ) { Object key = i.next(); put( key, other.get( key ) ); } } /** * Implements {@link Map#remove(Object)}. */ public Object remove( Object key ) { int hash = getHash( key ); synchronized( m_locks[ hash ] ) { Node n = m_buckets[ hash ]; Node prev = null; while( n != null ) { if( n.key == null || ( n.key != null && n.key.equals( key ) ) ) { // Remove this node from the linked list of nodes. if( null == prev ) { // This node was the head, set the next node to be the new head. m_buckets[ hash ] = n.next; } else { // Set the next node of the previous node to be the node after this one. prev.next = n.next; } m_locks[hash].size--; return n.value; } prev = n; n = n.next; } } return null; } /** * Implements {@link Map#isEmpty()}. */ public final boolean isEmpty() { return size() == 0; } /** * Implements {@link Map#clear()}. */ public final void clear() { for( int i = 0; i < m_buckets.length; i++ ) { Lock lock = m_locks[i]; synchronized (lock) { m_buckets[ i ] = null; lock.size = 0; } } } /** * Implements {@link Map#equals(Object)}. */ public final boolean equals( Object obj ) { if( obj == null ) return false; if( obj == this ) return true; if( !( obj instanceof Map ) ) return false; Map other = (Map)obj; return entrySet().equals(other.entrySet()); } /** * Implements {@link Map#hashCode()}. */ public final int hashCode() { int hashCode = 0; for( int i = 0; i < m_buckets.length; i++ ) { synchronized( m_locks[ i ] ) { Node n = m_buckets[ i ]; while( n != null ) { hashCode += n.hashCode(); n = n.next; } } } return hashCode; } /** * The Map.Entry for the StaticBucketMap. */ private final class Node implements Map.Entry { protected Object key; protected Object value; protected Node next; public Object getKey() { return key; } public Object getValue() { return value; } public int hashCode() { return ( ( key == null ? 0 : key.hashCode() ) ^ ( value == null ? 0 : value.hashCode() ) ); } public boolean equals(Object o) { if( o == null ) return false; if( o == this ) return true; if ( ! (o instanceof Map.Entry ) ) return false; Map.Entry e2 = (Map.Entry)o; return ((key == null ? e2.getKey() == null : key.equals(e2.getKey())) && (value == null ? e2.getValue() == null : value.equals(e2.getValue()))); } public Object setValue( Object val ) { Object retVal = value; value = val; return retVal; } } private final static class Lock { public int size; } private class EntryIterator implements Iterator { private ArrayList current = new ArrayList(); private int bucket; private Map.Entry last; public boolean hasNext() { if (current.size() > 0) return true; while (bucket < m_buckets.length) { synchronized (m_locks[bucket]) { Node n = m_buckets[bucket]; while (n != null) { current.add(n); n = n.next; } bucket++; if (current.size() > 0) return true; } } return false; } protected Map.Entry nextEntry() { if (!hasNext()) throw new NoSuchElementException(); last = (Map.Entry)current.remove(current.size() - 1); return last; } public Object next() { return nextEntry(); } public void remove() { if (last == null) throw new IllegalStateException(); StaticBucketMap.this.remove(last.getKey()); last = null; } } private class ValueIterator extends EntryIterator { public Object next() { return nextEntry().getValue(); } } private class KeyIterator extends EntryIterator { public Object next() { return nextEntry().getKey(); } } private class EntrySet extends AbstractSet { public int size() { return StaticBucketMap.this.size(); } public void clear() { StaticBucketMap.this.clear(); } public Iterator iterator() { return new EntryIterator(); } public boolean contains(Object o) { Map.Entry entry = (Map.Entry)o; int hash = getHash(entry.getKey()); synchronized (m_locks[hash]) { for (Node n = m_buckets[hash]; n != null; n = n.next) { if (n.equals(entry)) return true; } } return false; } public boolean remove(Object o) { Map.Entry entry = (Map.Entry)o; int hash = getHash(entry.getKey()); synchronized (m_locks[hash]) { for (Node n = m_buckets[hash]; n != null; n = n.next) { if (n.equals(entry)) { StaticBucketMap.this.remove(n.getKey()); return true; } } } return false; } } private class KeySet extends AbstractSet { public int size() { return StaticBucketMap.this.size(); } public void clear() { StaticBucketMap.this.clear(); } public Iterator iterator() { return new KeyIterator(); } public boolean contains(Object o) { return StaticBucketMap.this.containsKey(o); } public boolean remove(Object o) { int hash = getHash(o); synchronized (m_locks[hash]) { for (Node n = m_buckets[hash]; n != null; n = n.next) { Object k = n.getKey(); if ((k == o) || ((k != null) && k.equals(o))) { StaticBucketMap.this.remove(k); return true; } } } return false; } } private class Values extends AbstractCollection { public int size() { return StaticBucketMap.this.size(); } public void clear() { StaticBucketMap.this.clear(); } public Iterator iterator() { return new ValueIterator(); } } /** * Prevents any operations from occuring on this map while the * given {@link Runnable} executes. This method can be used, for * instance, to execute a bulk operation atomicly: * *
     *    staticBucketMapInstance.atomic(new Runnable() {
     *        public void run() {
     *            staticBucketMapInstance.putAll(map);
     *        }
     *    });
     *  
* * It can also be used if you need a reliable iterator: * *
     *    staticBucketMapInstance.atomic(new Runnable() {
     *        public void run() {
     *            Iterator iterator = staticBucketMapInstance.iterator();
     *            while (iterator.hasNext()) {
     *                foo(iterator.next();
     *            }
     *        }
     *    });
     *  
* * Implementation note: This method requires a lot of time * and a ton of stack space. Essentially a recursive algorithm is used * to enter each bucket's monitor. If you have twenty thousand buckets * in your map, then the recursive method will be invoked twenty thousand * times. You have been warned. * * @param r the code to execute atomicly */ public void atomic(Runnable r) { if (r == null) throw new NullPointerException(); atomic(r, 0); } private void atomic(Runnable r, int bucket) { if (bucket >= m_buckets.length) { r.run(); return; } synchronized (m_locks[bucket]) { atomic(r, bucket + 1); } } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BufferUtils.java0100644000175000017500000001424510055172376031366 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; /** * Contains static utility methods for operating on {@link Buffer} objects. * * @author Paul Jack * @author Stephen Colebourne * @version $Id: BufferUtils.java,v 1.9.2.1 2004/05/22 12:14:02 scolebourne Exp $ * @since 2.1 */ public class BufferUtils { /** * Restrictive constructor */ private BufferUtils() { } /** * Returns a synchronized buffer backed by the given buffer. * Much like the synchronized collections returned by * {@link java.util.Collections}, you must manually synchronize on * the returned buffer's iterator to avoid non-deterministic behavior: * *
     * Buffer b = BufferUtils.synchronizedBuffer(myBuffer);
     * synchronized (b) {
     *     Iterator i = b.iterator();
     *     while (i.hasNext()) {
     *         process (i.next());
     *     }
     * }
     * 
* * @param buffer the buffer to synchronize, must not be null * @return a synchronized buffer backed by that buffer * @throws IllegalArgumentException if the Buffer is null */ public static Buffer synchronizedBuffer(final Buffer buffer) { return new SynchronizedBuffer(buffer); } /** * Returns a synchronized buffer backed by the given buffer that will * block on {@link Buffer#get()} and {@link Buffer#remove()} operations. * If the buffer is empty, then the {@link Buffer#get()} and * {@link Buffer#remove()} operations will block until new elements * are added to the buffer, rather than immediately throwing a * BufferUnderflowException. * * @param buffer the buffer to synchronize, must not be null * @return a blocking buffer backed by that buffer * @throws IllegalArgumentException if the Buffer is null */ public static Buffer blockingBuffer(Buffer buffer) { return new SynchronizedBuffer(buffer) { public synchronized boolean add(Object o) { boolean r = collection.add(o); notify(); return r; } public synchronized boolean addAll(Collection c) { boolean r = collection.addAll(c); notifyAll(); return r; } public synchronized Object get() { while (collection.isEmpty()) { try { wait(); } catch (InterruptedException e) { throw new BufferUnderflowException(); } } return ((Buffer)collection).get(); } public synchronized Object remove() { while (collection.isEmpty()) { try { wait(); } catch (InterruptedException e) { throw new BufferUnderflowException(); } } return ((Buffer)collection).remove(); } }; } /** * Returns an unmodifiable buffer backed by the given buffer. * * @param buffer the buffer to make unmodifiable, must not be null * @return an unmodifiable buffer backed by that buffer * @throws IllegalArgumentException if the Buffer is null */ public static Buffer unmodifiableBuffer(Buffer buffer) { return new UnmodifiableBuffer(buffer); } /** * Returns a predicated buffer backed by the given buffer. Elements are * evaluated with the given predicate before being added to the buffer. * If the predicate evaluation returns false, then an * IllegalArgumentException is raised and the element is not added to * the buffer. * * @param buffer the buffer to predicate, must not be null * @param predicate the predicate used to evaluate new elements, must not be null * @return a predicated buffer * @throws IllegalArgumentException if the Buffer or Predicate is null */ public static Buffer predicatedBuffer(Buffer buffer, final Predicate predicate) { return new PredicatedBuffer(buffer, predicate); } static class SynchronizedBuffer extends CollectionUtils.SynchronizedCollection implements Buffer { public SynchronizedBuffer(Buffer b) { super(b); } public synchronized Object get() { return ((Buffer)collection).get(); } public synchronized Object remove() { return ((Buffer)collection).remove(); } } static class UnmodifiableBuffer extends CollectionUtils.UnmodifiableCollection implements Buffer { public UnmodifiableBuffer(Buffer b) { super(b); } public Object get() { return ((Buffer)collection).get(); } public Object remove() { throw new UnsupportedOperationException(); } } static class PredicatedBuffer extends CollectionUtils.PredicatedCollection implements Buffer { public PredicatedBuffer(Buffer b, Predicate p) { super(b, p); } public Object get() { return ((Buffer)collection).get(); } public Object remove() { return ((Buffer)collection).remove(); } } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ArrayIterator.java0100644000175000017500000000572310055172400031711 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** Implements an {@link java.util.Iterator} over an array of objects. * * @since 1.0 * @author James Strachan * @author Mauricio S. Moura * @author Michael A. Smith * @version $Revision: 1.17.2.1 $ * @deprecated this class has been moved to the iterators subpackage */ public class ArrayIterator extends org.apache.commons.collections.iterators.ArrayIterator { /** * Construct an ArrayIterator. Using this constructor, the iterator is * equivalent to an empty iterator until {@link #setArray(Object)} is * called to establish the array to iterate over. **/ public ArrayIterator() { super(); } /** * Construct an ArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over. * * @exception IllegalArgumentException if array is not an * array. * * @exception NullPointerException * if array is null **/ public ArrayIterator(Object array) { super(array); } /** * Construct an ArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over. * @param start the index to start iterating at. * * @exception IllegalArgumentException if array is not an * array. * * @exception NullPointerException * if array is null **/ public ArrayIterator(Object array, int start) { super(array, start); } /** * Construct an ArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over. * @param start the index to start iterating at. * @param end the index to finish iterating at. * * @exception IllegalArgumentException if array is not an * array. * * @exception NullPointerException * if array is null **/ public ArrayIterator(Object array, int start, int end) { super(array, start, end); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/0040755000175000017500000000000010072637465030306 5ustar toratora././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/IteratorEnumeration.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/IteratorEn0100644000175000017500000000527310055172376032305 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Enumeration; import java.util.Iterator; /** Adapter to make an {@link Iterator Iterator} instance appear to be an {@link Enumeration Enumeration} instances * * @since 1.0 * @author James Strachan */ public class IteratorEnumeration implements Enumeration { private Iterator iterator; /** * Constructs a new IteratorEnumeration that will not * function until {@link #setIterator(Iterator) setIterator} is * invoked. */ public IteratorEnumeration() { } /** * Constructs a new IteratorEnumeration that will use * the given iterator. * * @param iterator the iterator to use */ public IteratorEnumeration( Iterator iterator ) { this.iterator = iterator; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if the underlying iterator has more elements. * * @return true if the underlying iterator has more elements */ public boolean hasMoreElements() { return iterator.hasNext(); } /** * Returns the next element from the underlying iterator. * * @return the next element from the underlying iterator. * @throws NoSuchElementException if the underlying iterator has no * more elements */ public Object nextElement() { return iterator.next(); } // Properties //------------------------------------------------------------------------- /** * Returns the underlying iterator. * * @return the underlying iterator */ public Iterator getIterator() { return iterator; } /** * Sets the underlying iterator. * * @param iterator the new underlying iterator */ public void setIterator( Iterator iterator ) { this.iterator = iterator; } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/SingletonIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/SingletonI0100644000175000017500000000475410055172402032275 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; /** *

SingletonIterator is an {@link Iterator} over a single * object instance.

* * @since 2.0 * @author James Strachan * @author Stephen Colebourne * @version $Revision: 1.2.2.1 $ */ public class SingletonIterator implements Iterator { private boolean first = true; private Object object; /** * Constructs a new SingletonIterator. * * @param object the single object to return from the iterator */ public SingletonIterator(Object object) { super(); this.object = object; } /** * Is another object available from the iterator. *

* This returns true if the single object hasn't been returned yet. * * @return true if the single object hasn't been returned yet */ public boolean hasNext() { return first; } /** * Get the next object from the iterator. *

* This returns the single object if it hasn't been returned yet. * * @return the single object * @throws NoSuchElementException if the single object has already * been returned */ public Object next() { if (!first) { throw new NoSuchElementException(); } Object answer = object; object = null; first = false; return answer; } /** * Remove always throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() is not supported by this iterator"); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/CollatingIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/CollatingI0100644000175000017500000003057710055172400032247 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.ArrayList; import java.util.BitSet; /** * Provides an ordered iteration over the elements contained in * a collection of ordered {@link Iterator}s. In other words, * given two ordered {@link Iterator}s A and B, * my {@link #next} method will return the lesser of * A.next() and B.next(). * * @since 2.1 * @author Rodney Waldhoff * @author Stephen Colebourne * @version $Revision: 1.3.2.1 $ $Date: 2004/05/22 12:14:04 $ */ public class CollatingIterator implements Iterator { /** My {@link Comparator}. */ private Comparator comparator = null; /** My list of {@link Iterator}s. */ private ArrayList iterators = null; /** {@link Iterator#next Next} objects peeked from each iterator. */ private ArrayList values = null; /** Whether or not each {@link #values} element has been set. */ private BitSet valueSet = null; /** Index of the {@link #iterators iterator} from whom the last returned value was obtained. */ private int lastReturned = -1; // Constructors // ------------------------------------------------------------------- /** * Constructs a new CollatingIterator. Natural sort order * will be used, and child iterators will have to be manually added * using the {@link #addIterator(Iterator)} method. */ public CollatingIterator() { this(null,2); } /** * Constructs a new CollatingIterator that will used the * specified comparator for ordering. Child iterators will have to be * manually added using the {@link #addIterator(Iterator)} method. * * @param comp the comparator to use for ordering, or null * to use natural sort order */ public CollatingIterator(Comparator comp) { this(comp,2); } /** * Constructs a new CollatingIterator that will used the * specified comparator for ordering and have the specified initial * capacity. Child iterators will have to be * manually added using the {@link #addIterator(Iterator)} method. * * @param comp the comparator to use for ordering, or null * to use natural sort order * @param initIterCapacity the initial capacity for the internal list * of child iterators */ public CollatingIterator(Comparator comp, int initIterCapacity) { iterators = new ArrayList(initIterCapacity); setComparator(comp); } /** * Constructs a new CollatingIterator that will use the * specified comparator to provide ordered iteration over the two * given iterators. * * @param comp the comparator to use to sort, or null to use natural * sort order * @param a the first child ordered iterator * @param b the second child ordered iterator * @throws NullPointerException if either iterator is null */ public CollatingIterator(Comparator comp, Iterator a, Iterator b) { this(comp,2); addIterator(a); addIterator(b); } /** * Constructs a new CollatingIterator that will use the * specified comparator to provide ordered iteration over the array * of iterators. * * @param comp the comparator to use to sort, or null to use natural * sort order * @param iterators the array of iterators * @throws NullPointerException if iterators array is or contains null */ public CollatingIterator(Comparator comp, Iterator[] iterators) { this(comp, iterators.length); for (int i = 0; i < iterators.length; i++) { addIterator(iterators[i]); } } /** * Constructs a new CollatingIterator that will use the * specified comparator to provide ordered iteration over the collection * of iterators. * * @param comp the comparator to use to sort, or null to use natural * sort order * @param iterators the collection of iterators * @throws NullPointerException if the iterators collection is or contains null * @throws ClassCastException if the iterators collection contains an * element that's not an {@link Iterator} */ public CollatingIterator(Comparator comp, Collection iterators) { this(comp, iterators.size()); for (Iterator it = iterators.iterator(); it.hasNext();) { Iterator item = (Iterator) it.next(); addIterator(item); } } // Public Methods // ------------------------------------------------------------------- /** * Add the given {@link Iterator} to my collection to collate. * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void addIterator(Iterator iterator) { checkNotStarted(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iterators.add(iterator); } /** * Set the Iterator at the given index * * @param index index of the Iterator to replace * @param iterator Iterator to place at the given index * @throws IndexOutOfBoundsException if index < 0 or index > size() * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void setIterator(int index, Iterator iterator) throws IndexOutOfBoundsException { checkNotStarted(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iterators.set(index, iterator); } /** * Get the list of Iterators (unmodifiable) * * @return the unmodifiable list of iterators added */ public List getIterators() { return Collections.unmodifiableList(iterators); } /** * Set the {@link Comparator} by which I collate. * @throws IllegalStateException if I've already started iterating */ public void setComparator(Comparator comp) { checkNotStarted(); comparator = comp; } /** * Get the {@link Comparator} by which I collate. */ public Comparator getComparator() { return comparator; } // Iterator Methods // ------------------------------------------------------------------- /** * Returns true if any child iterator has remaining elements. * * @return true if this iterator has remaining elements */ public boolean hasNext() { start(); return anyValueSet(valueSet) || anyHasNext(iterators); } /** * Returns the next ordered element from a child iterator. * * @return the next ordered element * @throws NoSuchElementException if no child iterator has any more * elements */ public Object next() throws NoSuchElementException { if(!hasNext()) { throw new NoSuchElementException(); } else { int leastIndex = least(); if(leastIndex == -1) { throw new NoSuchElementException(); } else { Object val = values.get(leastIndex); clear(leastIndex); lastReturned = leastIndex; return val; } } } /** * Removes the last returned element from the child iterator that * produced it. * * @throws IllegalStateException if there is no last returned element, * or if the last returned element has already been removed */ public void remove() { if(-1 == lastReturned) { throw new NoSuchElementException("No value has been returned yet."); } else { Iterator iter = (Iterator)(iterators.get(lastReturned)); iter.remove(); } } // Private Methods // ------------------------------------------------------------------- /** Initialize my collating state if it hasn't been already. */ private void start() { if(null == values) { values = new ArrayList(iterators.size()); valueSet = new BitSet(iterators.size()); for(int i=0;ii to the next value of the * {@link #iterators iterator} at position i, or * clear them if the ith iterator * has no next value. * * @return false iff there was no value to set */ private boolean set(int i) { Iterator iter = (Iterator)(iterators.get(i)); if(iter.hasNext()) { values.set(i,iter.next()); valueSet.set(i); return true; } else { values.set(i,null); valueSet.clear(i); return false; } } /** * Clear the {@link #values} and {@link #valueSet} attributes * at position i. */ private void clear(int i) { values.set(i,null); valueSet.clear(i); } /** * Throw {@link IllegalStateException} iff I've been {@link #start started}. * @throws IllegalStateException iff I've been {@link #start started} */ private void checkNotStarted() throws IllegalStateException { if (null != values) { throw new IllegalStateException("Can't do that after next or hasNext has been called."); } } /** * Returns the index of the least element in {@link #values}, * {@link #set(int) setting} any uninitialized values. */ private int least() throws IllegalStateException { int leastIndex = -1; Object leastObject = null; for(int i=0;itrue iff any bit in the given set is * true. */ private boolean anyValueSet(BitSet set) { for(int i=0;itrue iff any {@link Iterator} * in the given list has a next value. */ private boolean anyHasNext(ArrayList iters) { for(int i=0;iListIterator * instance. Only objects for which the specified * Predicate evaluates to true are * returned by the iterator. * * @since 2.0 * @version $Revision: 1.1.2.1 $ $Date: 2004/05/22 12:14:04 $ * @author Rodney Waldhoff */ public class FilterListIterator extends ProxyListIterator { // Constructors //------------------------------------------------------------------------- /** * Constructs a new FilterListIterator that will not * function until * {@link ProxyListIterator#setListIterator(ListIterator) setListIterator} * and {@link #setPredicate(Predicate) setPredicate} are invoked. */ public FilterListIterator() { } /** * Constructs a new FilterListIterator that will not * function until {@link #setPredicate(Predicate) setPredicate} is invoked. * * @param iterator the iterator to use */ public FilterListIterator(ListIterator iterator ) { super(iterator); } /** * Constructs a new FilterListIterator. * * @param iterator the iterator to use * @param predicate the predicate to use */ public FilterListIterator(ListIterator iterator, Predicate predicate) { super(iterator); this.predicate = predicate; } /** * Constructs a new FilterListIterator that will not * function until * {@link ProxyListIterator#setListIterator(ListIterator) setListIterator} * is invoked. * * @param predicate the predicate to use. */ public FilterListIterator(Predicate predicate) { this.predicate = predicate; } // ListIterator interface //------------------------------------------------------------------------- /** Not supported. */ public void add(Object o) { throw new UnsupportedOperationException("FilterListIterator.add(Object) is not supported."); } public boolean hasNext() { if(nextObjectSet) { return true; } else { return setNextObject(); } } public boolean hasPrevious() { if(previousObjectSet) { return true; } else { return setPreviousObject(); } } public Object next() { if(!nextObjectSet) { if(!setNextObject()) { throw new NoSuchElementException(); } } nextIndex++; Object temp = nextObject; clearNextObject(); return temp; } public int nextIndex() { return nextIndex; } public Object previous() { if(!previousObjectSet) { if(!setPreviousObject()) { throw new NoSuchElementException(); } } nextIndex--; Object temp = previousObject; clearPreviousObject(); return temp; } public int previousIndex() { return (nextIndex-1); } /** Not supported. */ public void remove() { throw new UnsupportedOperationException("FilterListIterator.remove() is not supported."); } /** Not supported. */ public void set(Object o) { throw new UnsupportedOperationException("FilterListIterator.set(Object) is not supported."); } // Properties //------------------------------------------------------------------------- /** * Getter for the predicate property. * @return value of the predicate property. */ public Predicate getPredicate() { return predicate; } /** * Setter for the predicate property. * @param predicate new value for the predicate property. */ public void setPredicate(Predicate predicate) { this.predicate = predicate; } // Private Methods //------------------------------------------------------------------------- private void clearNextObject() { nextObject = null; nextObjectSet = false; } private boolean setNextObject() { ListIterator iterator = getListIterator(); Predicate predicate = getPredicate(); // if previousObjectSet, // then we've walked back one step in the // underlying list (due to a hasPrevious() call) // so skip ahead one matching object if(previousObjectSet) { clearPreviousObject(); if(!setNextObject()) { return false; } else { clearNextObject(); } } while(iterator.hasNext()) { Object object = iterator.next(); if(predicate.evaluate(object)) { nextObject = object; nextObjectSet = true; return true; } } return false; } private void clearPreviousObject() { previousObject = null; previousObjectSet = false; } private boolean setPreviousObject() { ListIterator iterator = getListIterator(); Predicate predicate = getPredicate(); // if nextObjectSet, // then we've walked back one step in the // underlying list (due to a hasNext() call) // so skip ahead one matching object if(nextObjectSet) { clearNextObject(); if(!setPreviousObject()) { return false; } else { clearPreviousObject(); } } while(iterator.hasPrevious()) { Object object = iterator.previous(); if(predicate.evaluate(object)) { previousObject = object; previousObjectSet = true; return true; } } return false; } // Attributes //------------------------------------------------------------------------- /** Holds value of property "predicate". */ private Predicate predicate; /** * The value of the next (matching) object, when * {@link #nextObjectSet} is true. */ private Object nextObject; /** * Whether or not the {@link #nextObject} has been set * (possibly to null). */ private boolean nextObjectSet = false; /** * The value of the previous (matching) object, when * {@link #previousObjectSet} is true. */ private Object previousObject; /** * Whether or not the {@link #previousObject} has been set * (possibly to null). */ private boolean previousObjectSet = false; /** * The index of the element that would be returned by {@link #next}. */ private int nextIndex = 0; } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/AbstractEmptyIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/AbstractEm0100644000175000017500000000363710055172400032244 0ustar toratora/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.NoSuchElementException; /** * Provides an implementation of an empty iterator. * * @since Commons Collections 2.1.1 and 3.1 * @version $Revision: 1.1.2.2 $ $Date: 2004/05/22 11:54:53 $ * * @author Stephen Colebourne */ abstract class AbstractEmptyIterator { /** * Constructor. */ protected AbstractEmptyIterator() { super(); } public boolean hasNext() { return false; } public Object next() { throw new NoSuchElementException("Iterator contains no elements"); } public boolean hasPrevious() { return false; } public Object previous() { throw new NoSuchElementException("Iterator contains no elements"); } public int nextIndex() { return 0; } public int previousIndex() { return -1; } public void add(Object obj) { throw new UnsupportedOperationException("add() not supported for empty Iterator"); } public void set(Object obj) { throw new IllegalStateException("Iterator contains no elements"); } public void remove() { throw new IllegalStateException("Iterator contains no elements"); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/SingletonListIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/SingletonL0100644000175000017500000001073510055172400032272 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; import java.util.NoSuchElementException; /** *

SingletonIterator is an {@link ListIterator} over a single * object instance.

* * @since 2.1 * @author Stephen Colebourne * @version $Id: SingletonListIterator.java,v 1.2.2.1 2004/05/22 12:14:04 scolebourne Exp $ */ public class SingletonListIterator implements ListIterator { private boolean first = true; private boolean nextCalled = false; private Object object; /** * Constructs a new SingletonListIterator. * * @param object the single object to return from the iterator */ public SingletonListIterator(Object object) { super(); this.object = object; } /** * Is another object available from the iterator. *

* This returns true if the single object hasn't been returned yet. * * @return true if the single object hasn't been returned yet */ public boolean hasNext() { return first; } /** * Is a previous object available from the iterator. *

* This returns true if the single object has been returned. * * @return true if the single object has been returned */ public boolean hasPrevious() { return !first; } /** * Returns the index of the element that would be returned by a subsequent * call to next. * * @return 0 or 1 depending on current state. */ public int nextIndex() { return (first ? 0 : 1); } /** * Returns the index of the element that would be returned by a subsequent * call to previous. A return value of -1 indicates that the iterator is currently at * the start. * * @return 0 or -1 depending on current state. */ public int previousIndex() { return (first ? -1 : 0); } /** * Get the next object from the iterator. *

* This returns the single object if it hasn't been returned yet. * * @return the single object * @throws NoSuchElementException if the single object has already * been returned */ public Object next() { if (!first) { throw new NoSuchElementException(); } first = false; nextCalled = true; return object; } /** * Get the previous object from the iterator. *

* This returns the single object if it has been returned. * * @return the single object * @throws NoSuchElementException if the single object has not already * been returned */ public Object previous() { if (first) { throw new NoSuchElementException(); } first = true; return object; } /** * Remove always throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException("remove() is not supported by this iterator"); } /** * Add always throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void add(Object obj) { throw new UnsupportedOperationException("add() is not supported by this iterator"); } /** * Set sets the value of the singleton. * * @param obj the object to set * @throws IllegalStateException if next has not been called */ public void set(Object obj) { if (nextCalled == false) { throw new IllegalStateException(); } this.object = obj; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ArrayIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ArrayItera0100644000175000017500000001554010055172376032272 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.lang.reflect.Array; import java.util.Iterator; import java.util.NoSuchElementException; /** Implements an {@link Iterator} over an array of objects. * * @since 1.0 * @author James Strachan * @author Mauricio S. Moura * @author Michael A. Smith * @version $Revision: 1.1.2.1 $ */ public class ArrayIterator implements Iterator { private Object array; private int length = 0; private int index = 0; /** * Construct an ArrayIterator. Using this constructor, the iterator is * equivalent to an empty iterator until {@link #setArray(Object)} is * called to establish the array to iterate over. **/ public ArrayIterator() { } /** * Construct an ArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over. * * @exception IllegalArgumentException if array is not an * array. * * @exception NullPointerException * if array is null **/ public ArrayIterator(Object array) { setArray( array ); } /** * Construct an ArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over. * @param start the index to start iterating at. * * @exception IllegalArgumentException if array is not an * array. * * @exception NullPointerException * if array is null **/ public ArrayIterator(Object array, int start) { setArray( array ); checkBound(start, "start"); this.index = start; } /** * Construct an ArrayIterator that will iterate over the values in the * specified array. * * @param array the array to iterate over. * @param start the index to start iterating at. * @param end the index to finish iterating at. * * @exception IllegalArgumentException if array is not an * array. * * @exception NullPointerException * if array is null **/ public ArrayIterator(Object array, int start, int end) { setArray( array ); checkBound(start, "start"); checkBound(end, "end"); if(end <= start) { throw new IllegalArgumentException( "End index must be greater than start index. " ); } this.index = start; this.length = end; } private void checkBound(int bound, String type ) { if(bound > this.length) { throw new ArrayIndexOutOfBoundsException( "Attempt to make an ArrayIterator that "+type+ "s beyond the end of the array. " ); } if(bound < 0) { throw new ArrayIndexOutOfBoundsException( "Attempt to make an ArrayIterator that "+type+ "s before the start of the array. " ); } } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if there are more elements to return from the array. * * @return true if there is a next element to return */ public boolean hasNext() { return index < length; } /** * Returns the next element in the array. * * @return the next element in the array * @throws NoSuchElementException if all the elements in the array * have already been returned */ public Object next() { if(!hasNext()) { throw new NoSuchElementException(); } return Array.get( array, index++ ); } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException( "remove() method is not supported" ); } // Properties //------------------------------------------------------------------------- /** * Retrieves the array that this iterator is iterating over. * * @return the array this iterator iterates over, or null if * the no-arg constructor was used and {@link #setArray(Object)} has never * been called with a valid array. **/ public Object getArray() { return array; } /** * Changes the array that the ArrayIterator should iterate over. If an * array has previously been set (using the single-arg constructor or this * method), that array along with the current iterator position within * that array is discarded in favor of the argument to this method. This * method can be used in combination with {@link #getArray()} to "reset" * the iterator to the beginning of the array: * *

     *    ArrayIterator iterator = ...
     *    ...
     *    iterator.setArray(iterator.getArray());
     *  
* * Note: Using i.setArray(i.getArray()) may throw a NullPointerException * if no array has ever been set for the iterator (see {@link * #getArray()}) * * @param array the array that the iterator should iterate over. * * @exception IllegalArgumentException if array is not an * array. * * @exception NullPointerException * if array is null **/ public void setArray( Object array ) { // Array.getLength throws IllegalArgumentException if the object is not // an array or NullPointerException if the object is null. This call // is made before saving the array and resetting the index so that the // array iterator remains in a consistent state if the argument is not // an array or is null. this.length = Array.getLength( array ); this.array = array; this.index = 0; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/IteratorChain.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/IteratorCh0100644000175000017500000002460210055172400032256 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; /** *

An IteratorChain is an Iterator that wraps one or * more Iterators. When any method from the * Iterator interface is called, the IteratorChain will * proxy to a single underlying Iterator. The * IteratorChain will invoke the Iterators in sequence until * all Iterators are exhausted completely.

* *

Under many circumstances, linking Iterators together * in this manner is more efficient (and convenient) * than reading out the contents of each Iterator into a * List and creating a new Iterator.

* *

Calling a method that adds new Iteratorafter * a method in the Iterator interface * has been called will result in an * UnsupportedOperationException. Subclasses should take care * to not alter the underlying List of Iterators.

* * @since 2.1 * @author Morgan Delagrange * @author Stephen Colebourne * @version $Id: IteratorChain.java,v 1.2.2.1 2004/05/22 12:14:04 scolebourne Exp $ */ public class IteratorChain implements Iterator { protected final List iteratorChain = new ArrayList(); protected int currentIteratorIndex = 0; protected Iterator currentIterator = null; // the "last used" Iterator is the Iterator upon which // next() or hasNext() was most recently called // used for the remove() operation only protected Iterator lastUsedIterator = null; // ComparatorChain is "locked" after the first time // compare(Object,Object) is called protected boolean isLocked = false; // Constructors // ------------------------------------------------------------------- /** * Construct an IteratorChain with no Iterators. * You must add at least Iterator before calling * any method from the Iterator interface, or an * UnsupportedOperationException is thrown */ public IteratorChain() { super(); } /** * Construct an IteratorChain with a single Iterator. * * @param iterator first Iterator in the IteratorChain * @throws NullPointerException if the iterator is null */ public IteratorChain(Iterator iterator) { super(); addIterator(iterator); } /** * Constructs a new IteratorChain over the two * given iterators. * * @param a the first child iterator * @param b the second child iterator * @throws NullPointerException if either iterator is null */ public IteratorChain(Iterator a, Iterator b) { super(); addIterator(a); addIterator(b); } /** * Constructs a new IteratorChain over the array * of iterators. * * @param iterators the array of iterators * @throws NullPointerException if iterators array is or contains null */ public IteratorChain(Iterator[] iterators) { super(); for (int i = 0; i < iterators.length; i++) { addIterator(iterators[i]); } } /** * Constructs a new IteratorChain over the collection * of iterators. * * @param iterators the collection of iterators * @throws NullPointerException if iterators collection is or contains null * @throws ClassCastException if iterators collection doesn't contain an iterator */ public IteratorChain(Collection iterators) { super(); for (Iterator it = iterators.iterator(); it.hasNext();) { Iterator item = (Iterator) it.next(); addIterator(item); } } // Public Methods // ------------------------------------------------------------------- /** * Add an Iterator to the end of the chain * * @param iterator Iterator to add * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void addIterator(Iterator iterator) { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.add(iterator); } /** * Set the Iterator at the given index * * @param index index of the Iterator to replace * @param iterator Iterator to place at the given index * @throws IndexOutOfBoundsException if index < 0 or index > size() * @throws IllegalStateException if I've already started iterating * @throws NullPointerException if the iterator is null */ public void setIterator(int index, Iterator iterator) throws IndexOutOfBoundsException { checkLocked(); if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } iteratorChain.set(index, iterator); } /** * Get the list of Iterators (unmodifiable) * * @return the unmodifiable list of iterators added */ public List getIterators() { return Collections.unmodifiableList(iteratorChain); } /** * Number of Iterators in the current IteratorChain. * * @return Iterator count */ public int size() { return iteratorChain.size(); } /** * Determine if modifications can still be made to the * IteratorChain. IteratorChains cannot be modified * once they have executed a method from the Iterator * interface. * * @return true = IteratorChain cannot be modified; false = * IteratorChain can still be modified. */ public boolean isLocked() { return isLocked; } // throw an exception if the IteratorChain is locked private void checkLocked() { if (isLocked == true) { throw new UnsupportedOperationException("IteratorChain cannot be changed after the first use of a method from the Iterator interface"); } } private void checkChainIntegrity() { if (iteratorChain.size() == 0) { throw new UnsupportedOperationException("IteratorChains must contain at least one Iterator"); } } // you MUST call this method whenever you call a method in the Iterator interface, because // this method also assigns the initial value of the currentIterator variable private void lockChain() { if (isLocked == false) { checkChainIntegrity(); isLocked = true; } } // call this before any Iterator method to make sure that the current Iterator // is not exhausted protected void updateCurrentIterator() { if (currentIterator == null) { currentIterator = (Iterator) iteratorChain.get(0); // set last used iterator here, in case the user calls remove // before calling hasNext() or next() (although they shouldn't) lastUsedIterator = currentIterator; return; } if (currentIteratorIndex == (iteratorChain.size() - 1)) { return; } while (currentIterator.hasNext() == false) { ++currentIteratorIndex; currentIterator = (Iterator) iteratorChain.get(currentIteratorIndex); if (currentIteratorIndex == (iteratorChain.size() - 1)) { return; } } } /** * Return true if any Iterator in the IteratorChain has a remaining * element. * * @return true if elements remain * @exception UnsupportedOperationException * if the IteratorChain does not contain at least one * Iterator */ public boolean hasNext() throws UnsupportedOperationException { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.hasNext(); } /** * Returns the next Object of the current Iterator * * @return Object from the current Iterator * @exception NoSuchElementException * if all the Iterators are exhausted * @exception UnsupportedOperationException * if the IteratorChain does not contain at least one * Iterator */ public Object next() throws NoSuchElementException, UnsupportedOperationException { lockChain(); updateCurrentIterator(); lastUsedIterator = currentIterator; return currentIterator.next(); } /** * Removes from the underlying collection the last element * returned by the Iterator. As with next() and hasNext(), * this method calls remove() on the underlying Iterator. * Therefore, this method may throw an * UnsupportedOperationException if the underlying * Iterator does not support this method. * * @exception UnsupportedOperationException * if the remove operator is not supported by the underlying * Iterator or if there are no Iterators in the IteratorChain * @exception IllegalStateException * if the next method has not yet been called, or the * remove method has already been called after the last * call to the next method. */ public void remove() throws UnsupportedOperationException, IllegalStateException { lockChain(); updateCurrentIterator(); lastUsedIterator.remove(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/EmptyListIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/EmptyListI0100644000175000017500000000301710055172400032252 0ustar toratora/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; /** * Provides an implementation of an empty list iterator. *

* This class provides an implementation of an empty list iterator. * This class provides for binary compatability between Commons Collections * 2.1.1 and 3.1 due to issues with IteratorUtils. * * @since Commons Collections 2.1.1 and 3.1 * @version $Revision: 1.1.2.2 $ $Date: 2004/05/22 11:54:53 $ * * @author Stephen Colebourne */ public final class EmptyListIterator extends AbstractEmptyIterator implements ListIterator { /** * Singleton instance of the iterator. * @since Commons Collections 2.1.1 and 3.1 */ public static final ListIterator INSTANCE = new EmptyListIterator(); /** * Constructor. */ protected EmptyListIterator() { super(); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ProxyListIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ProxyListI0100644000175000017500000001121610055172376032311 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.ListIterator; /** * A proxy {@link ListIterator ListIterator} which delegates its * methods to a proxy instance. * * @since 2.0 * @see ProxyIterator * @version $Revision: 1.1.2.1 $ $Date: 2004/05/22 12:14:04 $ * @author Rodney Waldhoff */ public class ProxyListIterator implements ListIterator { // Constructor //------------------------------------------------------------------------- /** * Constructs a new ProxyListIterator that will not * function until {@link #setListIterator(ListIterator) setListIterator} * is invoked. */ public ProxyListIterator() { } /** * Constructs a new ProxyListIterator that will use the * given list iterator. * * @param iterator the list iterator to use */ public ProxyListIterator(ListIterator iterator) { this.iterator = iterator; } // ListIterator interface //------------------------------------------------------------------------- /** * Invokes the underlying {@link ListIterator#add(Object)} method. * * @throws NullPointerException if the underyling iterator is null */ public void add(Object o) { getListIterator().add(o); } /** * Invokes the underlying {@link ListIterator#hasNext()} method. * * @throws NullPointerException if the underyling iterator is null */ public boolean hasNext() { return getListIterator().hasNext(); } /** * Invokes the underlying {@link ListIterator#hasPrevious()} method. * * @throws NullPointerException if the underyling iterator is null */ public boolean hasPrevious() { return getListIterator().hasPrevious(); } /** * Invokes the underlying {@link ListIterator#next()} method. * * @throws NullPointerException if the underyling iterator is null */ public Object next() { return getListIterator().next(); } /** * Invokes the underlying {@link ListIterator#nextIndex()} method. * * @throws NullPointerException if the underyling iterator is null */ public int nextIndex() { return getListIterator().nextIndex(); } /** * Invokes the underlying {@link ListIterator#previous()} method. * * @throws NullPointerException if the underyling iterator is null */ public Object previous() { return getListIterator().previous(); } /** * Invokes the underlying {@link ListIterator#previousIndex()} method. * * @throws NullPointerException if the underyling iterator is null */ public int previousIndex() { return getListIterator().previousIndex(); } /** * Invokes the underlying {@link ListIterator#remove()} method. * * @throws NullPointerException if the underyling iterator is null */ public void remove() { getListIterator().remove(); } /** * Invokes the underlying {@link ListIterator#set(Object)} method. * * @throws NullPointerException if the underyling iterator is null */ public void set(Object o) { getListIterator().set(o); } // Properties //------------------------------------------------------------------------- /** * Getter for property iterator. * @return Value of property iterator. */ public ListIterator getListIterator() { return iterator; } /** * Setter for property iterator. * @param iterator New value of property iterator. */ public void setListIterator(ListIterator iterator) { this.iterator = iterator; } // Attributes //------------------------------------------------------------------------- /** Holds value of property "iterator". */ private ListIterator iterator; } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/TransformIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/TransformI0100644000175000017500000000664010055172376032314 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import org.apache.commons.collections.Transformer; /** A Proxy {@link Iterator Iterator} which uses a {@link Transformer Transformer} instance to * transform the contents of the {@link Iterator Iterator} into some other form * * @since 1.0 * @author James Strachan */ public class TransformIterator extends ProxyIterator { /** Holds value of property transformer. */ private Transformer transformer; /** * Constructs a new TransformIterator that will not function * until the {@link #setIterator(Iterator) setIterator} method is * invoked. */ public TransformIterator() { } /** * Constructs a new TransformIterator that won't transform * elements from the given iterator. * * @param iterator the iterator to use */ public TransformIterator( Iterator iterator ) { super( iterator ); } /** * Constructs a new TransformIterator that will use the * given iterator and transformer. If the given transformer is null, * then objects will not be transformed. * * @param iterator the iterator to use * @param transformer the transformer to use */ public TransformIterator( Iterator iterator, Transformer transformer ) { super( iterator ); this.transformer = transformer; } // Iterator interface //------------------------------------------------------------------------- public Object next() { return transform( super.next() ); } // Properties //------------------------------------------------------------------------- /** Getter for property transformer. * @return Value of property transformer. */ public Transformer getTransformer() { return transformer; } /** Setter for property transformer. * @param transformer New value of property transformer. */ public void setTransformer(Transformer transformer) { this.transformer = transformer; } // Implementation methods //------------------------------------------------------------------------- /** * Transforms the given object using the transformer. If the * transformer is null, the original object is returned as-is. * * @param source the object to transform * @return the transformed object */ protected Object transform( Object source ) { Transformer transformer = getTransformer(); if ( transformer != null ) { return transformer.transform( source ); } return source; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/FilterIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/FilterIter0100644000175000017500000001123310055172400032257 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.NoSuchElementException; import org.apache.commons.collections.Predicate; /** A Proxy {@link Iterator Iterator} which takes a {@link Predicate Predicate} instance to filter * out objects from an underlying {@link Iterator Iterator} instance. * Only objects for which the * specified Predicate evaluates to true are * returned. * * @since 1.0 * @author James Strachan * @author Jan Sorensen */ public class FilterIterator extends ProxyIterator { /** Holds value of property predicate. */ private Predicate predicate; private Object nextObject; private boolean nextObjectSet = false; //------------------------------------------------------------------------- /** * Constructs a new FilterIterator that will not function * until {@link #setIterator(Iterator) setIterator} is invoked. */ public FilterIterator() { } /** * Constructs a new FilterIterator that will not function * until {@link #setPredicate(Predicate) setPredicate} is invoked. * * @param iterator the iterator to use */ public FilterIterator( Iterator iterator ) { super( iterator ); } /** * Constructs a new FilterIterator that will use the * given iterator and predicate. * * @param iterator the iterator to use * @param predicate the predicate to use */ public FilterIterator( Iterator iterator, Predicate predicate ) { super( iterator ); this.predicate = predicate; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if the underlying iterator contains an object that * matches the predicate. * * @return true if there is another object that matches the predicate */ public boolean hasNext() { if ( nextObjectSet ) { return true; } else { return setNextObject(); } } /** * Returns the next object that matches the predicate. * * @return the next object which matches the given predicate * @throws NoSuchElementException if there are no more elements that * match the predicate */ public Object next() { if ( !nextObjectSet ) { if (!setNextObject()) { throw new NoSuchElementException(); } } nextObjectSet = false; return nextObject; } /** * Always throws UnsupportedOperationException as this class * does look-ahead with its internal iterator. * * @throws UnsupportedOperationException always */ public void remove() { throw new UnsupportedOperationException(); } // Properties //------------------------------------------------------------------------- /** Getter for property predicate. * @return Value of property predicate. */ public Predicate getPredicate() { return predicate; } /** Setter for property predicate. * @param predicate New value of property predicate. */ public void setPredicate(Predicate predicate) { this.predicate = predicate; } /** * Set nextObject to the next object. If there are no more * objects then return false. Otherwise, return true. */ private boolean setNextObject() { Iterator iterator = getIterator(); Predicate predicate = getPredicate(); while ( iterator.hasNext() ) { Object object = iterator.next(); if ( predicate.evaluate( object ) ) { nextObject = object; nextObjectSet = true; return true; } } return false; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ListIteratorWrapper.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ListIterat0100644000175000017500000001236510055172400032301 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; import java.util.LinkedList; import java.util.ListIterator; import java.util.NoSuchElementException; /** * As the wrapped Iterator is traversed, ListIteratorWrapper * builds a LinkedList of its values, permitting all required * operations of ListIterator. * * @since 2.1 * @author Morgan Delagrange * @author Stephen Colebourne * @version $Id: ListIteratorWrapper.java,v 1.2.2.1 2004/05/22 12:14:04 scolebourne Exp $ */ public class ListIteratorWrapper implements ListIterator { /** Holds value of property "iterator" */ private final Iterator iterator; private final LinkedList list = new LinkedList(); // position of this iterator private int currentIndex = 0; // position of the wrapped iterator // this Iterator should only be used to populate the list private int wrappedIteratorIndex = 0; private static final String UNSUPPORTED_OPERATION_MESSAGE = "ListIteratorWrapper does not support optional operations of ListIterator."; // Constructor //------------------------------------------------------------------------- /** * Constructs a new ListIteratorWrapper that will wrap * the given iterator. * * @param iterator the iterator to wrap * @throws NullPointerException if the iterator is null */ public ListIteratorWrapper(Iterator iterator) { if (iterator == null) { throw new NullPointerException("Iterator must not be null"); } this.iterator = iterator; } // ListIterator interface //------------------------------------------------------------------------- /** * Throws {@link UnsupportedOperationException}. * * @param o ignored * @throws UnsupportedOperationException always */ public void add(Object o) throws UnsupportedOperationException { throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } /** * Returns true if there are more elements in the iterator. * * @return true if there are more elements */ public boolean hasNext() { if (currentIndex == wrappedIteratorIndex) { return iterator.hasNext(); } return true; } /** * Returns true if there are previous elements in the iterator. * * @return true if there are previous elements */ public boolean hasPrevious() { if (currentIndex == 0) { return false; } return true; } /** * Returns the next element from the iterator. * * @return the next element from the iterator * @throws NoSuchElementException if there are no more elements */ public Object next() throws NoSuchElementException { if (currentIndex < wrappedIteratorIndex) { ++currentIndex; return list.get(currentIndex - 1); } Object retval = iterator.next(); list.add(retval); ++currentIndex; ++wrappedIteratorIndex; return retval; } /** * Returns in the index of the next element. * * @return the index of the next element */ public int nextIndex() { return currentIndex; } /** * Returns the the previous element. * * @return the previous element * @throws NoSuchElementException if there are no previous elements */ public Object previous() throws NoSuchElementException { if (currentIndex == 0) { throw new NoSuchElementException(); } --currentIndex; return list.get(currentIndex); } /** * Returns the index of the previous element. * * @return the index of the previous element */ public int previousIndex() { return currentIndex - 1; } /** * Throws {@link UnsupportedOperationException}. * * @throws UnsupportedOperationException always */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } /** * Throws {@link UnsupportedOperationException}. * * @param o ignored * @throws UnsupportedOperationException always */ public void set(Object o) throws UnsupportedOperationException { throw new UnsupportedOperationException(UNSUPPORTED_OPERATION_MESSAGE); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/EnumerationIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/Enumeratio0100644000175000017500000001044410055172400032321 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; /** Adapter to make {@link Enumeration Enumeration} instances appear * to be {@link Iterator Iterator} instances. * * @since 1.0 * @author James Strachan * @author Daniel Rall */ public class EnumerationIterator implements Iterator { private Collection collection; private Enumeration enumeration; private Object last; /** * Constructs a new EnumerationIterator that will not * function until {@link #setEnumeration(Enumeration)} is called. */ public EnumerationIterator() { this(null, null); } /** * Constructs a new EnumerationIterator that provides * an iterator view of the given enumeration. * * @param enumeration the enumeration to use */ public EnumerationIterator( Enumeration enumeration ) { this(enumeration, null); } /** * Constructs a new EnumerationIterator that will remove * elements from the specified collection. * * @param enumeration the enumeration to use * @param collection the collection to remove elements from */ public EnumerationIterator( Enumeration enumeration, Collection collection ) { this.enumeration = enumeration; this.collection = collection; this.last = null; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if the underlying enumeration has more elements. * * @return true if the underlying enumeration has more elements * @throws NullPointerException if the underlying enumeration is null */ public boolean hasNext() { return enumeration.hasMoreElements(); } /** * Returns the next object from the enumeration. * * @return the next object from the enumeration * @throws NullPointerException if the enumeration is null */ public Object next() { last = enumeration.nextElement(); return last; } /** * Functions if an associated Collection is known. * If so, the first occurrence of the last returned object from this * iterator will be removed from the collection. * * @exception IllegalStateException next() not called. * @exception UnsupportedOperationException No associated * Collection. */ public void remove() { if (collection != null) { if (last != null) { collection.remove(last); } else { throw new IllegalStateException ("next() must have been called for remove() to function"); } } else { throw new UnsupportedOperationException ("No Collection associated with this Iterator"); } } // Properties //------------------------------------------------------------------------- /** * Returns the underlying enumeration. * * @return the underlying enumeration */ public Enumeration getEnumeration() { return enumeration; } /** * Sets the underlying enumeration. * * @param enumeration the new underlying enumeration */ public void setEnumeration( Enumeration enumeration ) { this.enumeration = enumeration; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/EmptyIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/EmptyItera0100644000175000017500000000275510055172400032302 0ustar toratora/* * Copyright 2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; /** * Provides an implementation of an empty iterator. *

* This class provides an implementation of an empty iterator. * This class provides for binary compatability between Commons Collections * 2.1.1 and 3.1 due to issues with IteratorUtils. * * @since Commons Collections 2.1.1 and 3.1 * @version $Revision: 1.1.2.2 $ $Date: 2004/05/22 11:54:53 $ * * @author Stephen Colebourne */ public final class EmptyIterator extends AbstractEmptyIterator implements Iterator { /** * Singleton instance of the iterator. * @since Commons Collections 2.1.1 and 3.1 */ public static final Iterator INSTANCE = new EmptyIterator(); /** * Constructor. */ protected EmptyIterator() { super(); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ProxyIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/ProxyItera0100644000175000017500000000562210055172376032335 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.Iterator; /** A Proxy {@link Iterator Iterator} which delegates its methods to a proxy instance. * * @since 1.0 * @see ProxyListIterator * @version $Revision: 1.1.2.1 $ $Date: 2004/05/22 12:14:04 $ * * @author James Strachan */ public class ProxyIterator implements Iterator { /** Holds value of property iterator. */ private Iterator iterator; /** * Constructs a new ProxyIterator that will not function * until {@link #setIterator(Iterator)} is called. */ public ProxyIterator() { } /** * Constructs a new ProxyIterator that will use the * given iterator. * * @param iterator the underyling iterator */ public ProxyIterator( Iterator iterator ) { this.iterator = iterator; } // Iterator interface //------------------------------------------------------------------------- /** * Returns true if the underlying iterator has more elements. * * @return true if the underlying iterator has more elements */ public boolean hasNext() { return getIterator().hasNext(); } /** * Returns the next element from the underlying iterator. * * @return the next element from the underlying iterator * @throws NoSuchElementException if the underlying iterator * raises it because it has no more elements */ public Object next() { return getIterator().next(); } /** * Removes the last returned element from the collection that spawned * the underlying iterator. */ public void remove() { getIterator().remove(); } // Properties //------------------------------------------------------------------------- /** Getter for property iterator. * @return Value of property iterator. */ public Iterator getIterator() { return iterator; } /** Setter for property iterator. * @param iterator New value of property iterator. */ public void setIterator(Iterator iterator) { this.iterator = iterator; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/package.htmllibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/package.ht0100644000175000017500000000045310055172400032215 0ustar toratora Contains concrete {@link java.util.Iterator} implementations and utilities. You may also consider using {@link org.apache.commons.collections.IteratorUtils IteratorUtils}, which is a single class that uses static methods to construct instances of the classes in this package. ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/UniqueFilterIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/UniqueFilt0100644000175000017500000000334310055172400032276 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections.iterators; import java.util.HashSet; import java.util.Iterator; import org.apache.commons.collections.Predicate; /** A FilterIterator which only returns "unique" Objects. Internally, * the Iterator maintains a Set of objects it has already encountered, * and duplicate Objects are skipped. * * @author Morgan Delagrange * @version $Id: UniqueFilterIterator.java,v 1.2.2.1 2004/05/22 12:14:04 scolebourne Exp $ * @since 2.1 */ public class UniqueFilterIterator extends FilterIterator { //------------------------------------------------------------------------- /** * Constructs a new UniqueFilterIterator. * * @param iterator the iterator to use */ public UniqueFilterIterator( Iterator iterator ) { super( iterator, new UniquePredicate() ); } private static class UniquePredicate implements Predicate { HashSet set = new HashSet(); public boolean evaluate(Object object) { return set.add(object); } } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ListUtils.java0100644000175000017500000003415010055172376031065 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Contains static utility methods and decorators for {@link List} * instances. * * @since 1.0 * @author Federico Barbieri * @author Peter Donald * @author Paul Jack * @author Stephen Colebourne */ public class ListUtils { /** * Please don't ever instantiate a ListUtils. */ public ListUtils() { } /** * Returns a new list containing all elements that are contained in * both given lists. * * @param list1 the first list * @param list2 the second list * @return the intersection of those two lists * @throws NullPointerException if either list is null */ public static List intersection(final List list1, final List list2) { final ArrayList result = new ArrayList(); final Iterator iterator = list2.iterator(); while (iterator.hasNext()) { final Object o = iterator.next(); if (list1.contains(o)) { result.add(o); } } return result; } /** * Subtracts all elements in the second list from the first list, * placing the results in a new list. * This differs from {@link List#removeAll(Collection)} in that * cardinality is respected; if list1 contains two * occurrences of null and list2 only * contains one occurrence, then the returned list will still contain * one occurrence. * * @param list1 the list to subtract from * @param list2 the lsit to subtract * @return a new list containing the results * @throws NullPointerException if either list is null */ public static List subtract(final List list1, final List list2) { final ArrayList result = new ArrayList(list1); final Iterator iterator = list2.iterator(); while (iterator.hasNext()) { result.remove(iterator.next()); } return result; } /** * Returns the sum of the given lists. This is their intersection * subtracted from their union. * * @param list1 the first list * @param list2 the second list * @return a new list containing the sum of those lists * @throws NullPointerException if either list is null */ public static List sum(final List list1, final List list2) { return subtract(union(list1, list2), intersection(list1, list2)); } /** * Returns a new list containing the second list appended to the * first list. The {@link List#addAll(Collection)} operation is * used to append the two given lists into a new list. * * @param list1 the first list * @param list2 the second list * @return a new list containing the union of those lists * @throws NullPointerException if either list is null */ public static List union(final List list1, final List list2) { final ArrayList result = new ArrayList(list1); result.addAll(list2); return result; } static class ListIteratorWrapper implements ListIterator { final protected ListIterator iterator; public ListIteratorWrapper(ListIterator iterator) { this.iterator = iterator; } public boolean hasNext() { return iterator.hasNext(); } public Object next() { return iterator.next(); } public boolean hasPrevious() { return iterator.hasPrevious(); } public Object previous() { return iterator.previous(); } public int nextIndex() { return iterator.nextIndex(); } public int previousIndex() { return iterator.previousIndex(); } public void remove() { iterator.remove(); } public void set(Object o) { iterator.set(o); } public void add(Object o) { iterator.add(o); } } static class PredicatedList extends CollectionUtils.PredicatedCollection implements List { public PredicatedList(List list, Predicate p) { super(list, p); } public boolean addAll(int i, Collection c) { for (Iterator iter = c.iterator(); iter.hasNext(); ) { validate(iter.next()); } return getList().addAll(i, c); } public Object get(int i) { return getList().get(i); } public Object set(int i, Object o) { validate(o); return getList().set(i, o); } public void add(int i, Object o) { validate(o); getList().add(i, o); } public Object remove(int i) { return getList().remove(i); } public int indexOf(Object o) { return getList().indexOf(o); } public int lastIndexOf(Object o) { return getList().lastIndexOf(o); } public ListIterator listIterator() { return listIterator(0); } public ListIterator listIterator(int i) { return new ListIteratorWrapper(getList().listIterator(i)) { public void add(Object o) { validate(o); iterator.add(o); } public void set(Object o) { validate(o); iterator.set(o); } }; } public List subList(int i1, int i2) { List sub = getList().subList(i1, i2); return new PredicatedList(sub, predicate); } private List getList() { return (List)collection; } } static class FixedSizeList extends CollectionUtils.UnmodifiableCollection implements List { public FixedSizeList(List list) { super(list); } public boolean addAll(int i, Collection c) { throw new UnsupportedOperationException(); } public Object get(int i) { return getList().get(i); } public Object set(int i, Object o) { return getList().set(i, o); } public void add(int i, Object o) { throw new UnsupportedOperationException(); } public Object remove(int i) { throw new UnsupportedOperationException(); } public int indexOf(Object o) { return getList().indexOf(o); } public int lastIndexOf(Object o) { return getList().lastIndexOf(o); } public ListIterator listIterator() { return listIterator(0); } public ListIterator listIterator(int i) { return new ListIteratorWrapper(getList().listIterator(i)) { public void remove() { throw new UnsupportedOperationException(); } public void add(Object o) { throw new UnsupportedOperationException(); } public void remove(Object o) { throw new UnsupportedOperationException(); } }; } public List subList(int i1, int i2) { List sub = getList().subList(i1, i2); return new FixedSizeList(sub); } private List getList() { return (List)collection; } } static class LazyList extends CollectionUtils.CollectionWrapper implements List { protected final Factory factory; public LazyList(List list, Factory factory) { super(list); if (factory == null) { throw new IllegalArgumentException("Factory must not be null"); } this.factory = factory; } /* Proxy method to the impl's get method. With the exception that if it's out * of bounds, then the collection will grow, leaving place-holders in its * wake, so that an item can be set at any given index. Later the * place-holders are removed to return to a pure collection. * * If there's a place-holder at the index, then it's replaced with a proper * object to be used. */ public Object get(int index) { Object obj; if (index < (getList().size())) { /* within bounds, get the object */ obj = getList().get(index); if (obj == null) { /* item is a place holder, create new one, set and return */ obj = this.factory.create(); this.getList().set(index, obj); return obj; } else { /* good and ready to go */ return obj; } } else { /* we have to grow the list */ for (int i = getList().size(); i < index; i++) { getList().add(null); } /* create our last object, set and return */ obj = this.factory.create(); getList().add(obj); return obj; } } /* proxy the call to the provided list implementation. */ public List subList(int fromIndex, int toIndex) { /* wrap the returned sublist so it can continue the functionality */ return new LazyList(getList().subList(fromIndex, toIndex), factory); } public boolean addAll(int i, Collection c) { return getList().addAll(i, c); } public Object set(int i, Object o) { return getList().set(i, o); } public void add(int i, Object o) { getList().add(i, o); } public Object remove(int i) { return getList().remove(i); } public int indexOf(Object o) { return getList().indexOf(o); } public int lastIndexOf(Object o) { return getList().lastIndexOf(o); } public ListIterator listIterator() { return getList().listIterator(); } public ListIterator listIterator(int i) { return getList().listIterator(i); } private List getList() { return (List)collection; } } /** * Returns a predicated list backed by the given list. Only objects * that pass the test in the given predicate can be added to the list. * It is important not to use the original list after invoking this * method, as it is a backdoor for adding unvalidated objects. * * @param list the list to predicate, must not be null * @param predicate the predicate for the list, must not be null * @return a predicated list backed by the given list * @throws IllegalArgumentException if the List or Predicate is null */ public static List predicatedList(List list, Predicate predicate) { return new PredicatedList(list, predicate); } /** * Returns a "lazy" list whose elements will be created on demand.

*

* When the index passed to the returned list's {@link List#get(int) get} * method is greater than the list's size, then the factory will be used * to create a new object and that object will be inserted at that index. *

* For instance: * *

     * Factory factory = new Factory() {
     *     public Object create() {
     *         return new Date();
     *     }
     * }
     * List lazy = ListUtils.lazyList(new ArrayList(), factory);
     * Object obj = lazy.get(3);
     * 
* * After the above code is executed, obj will contain * a new Date instance. Furthermore, that Date * instance is the fourth element in the list. The first, second, * and third element are all set to null. * * @param list the list to make lazy, must not be null * @param factory the factory for creating new objects, must not be null * @return a lazy list backed by the given list * @throws IllegalArgumentException if the List or Factory is null */ public static List lazyList(List list, Factory factory) { return new LazyList(list, factory); } /** * Returns a fixed-sized list backed by the given list. * Elements may not be added or removed from the returned list, but * existing elements can be changed (for instance, via the * {@link List#set(int,Object)} method). * * @param list the list whose size to fix, must not be null * @return a fixed-size list backed by that list * @throws IllegalArgumentException if the List is null */ public static List fixedSizeList(List list) { return new FixedSizeList(list); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SequencedHashMap.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SequencedHashMap.jav0100644000175000017500000010010210055172400032121 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.io.Externalizable; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.AbstractCollection; import java.util.AbstractSet; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.NoSuchElementException; import java.util.ConcurrentModificationException; /** * A map of objects whose mapping entries are sequenced based on the order in * which they were added. This data structure has fast O(1) search * time, deletion time, and insertion time. * *

Although this map is sequenced, it cannot implement {@link * java.util.List} because of incompatible interface definitions. The remove * methods in List and Map have different return values (see: {@link * java.util.List#remove(Object)} and {@link java.util.Map#remove(Object)}). * *

This class is not thread safe. When a thread safe implementation is * required, use {@link Collections#synchronizedMap(Map)} as it is documented, * or use explicit synchronization controls. * * @since 2.0 * @author Michael A. Smith * @author Daniel Rall * @author Henning P. Schmiedehausen */ public class SequencedHashMap implements Map, Cloneable, Externalizable { /** * {@link java.util.Map.Entry} that doubles as a node in the linked list * of sequenced mappings. **/ private static class Entry implements Map.Entry { // Note: This class cannot easily be made clonable. While the actual // implementation of a clone would be simple, defining the semantics is // difficult. If a shallow clone is implemented, then entry.next.prev != // entry, which is unintuitive and probably breaks all sorts of assumptions // in code that uses this implementation. If a deep clone is // implementated, then what happens when the linked list is cyclical (as is // the case with SequencedHashMap)? It's impossible to know in the clone // when to stop cloning, and thus you end up in a recursive loop, // continuously cloning the "next" in the list. private final Object key; private Object value; // package private to allow the SequencedHashMap to access and manipulate // them. Entry next = null; Entry prev = null; public Entry(Object key, Object value) { this.key = key; this.value = value; } // per Map.Entry.getKey() public Object getKey() { return this.key; } // per Map.Entry.getValue() public Object getValue() { return this.value; } // per Map.Entry.setValue() public Object setValue(Object value) { Object oldValue = this.value; this.value = value; return oldValue; } public int hashCode() { // implemented per api docs for Map.Entry.hashCode() return ((getKey() == null ? 0 : getKey().hashCode()) ^ (getValue()==null ? 0 : getValue().hashCode())); } public boolean equals(Object obj) { if(obj == null) return false; if(obj == this) return true; if(!(obj instanceof Map.Entry)) return false; Map.Entry other = (Map.Entry)obj; // implemented per api docs for Map.Entry.equals(Object) return((getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) && (getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()))); } public String toString() { return "[" + getKey() + "=" + getValue() + "]"; } } /** * Construct an empty sentinel used to hold the head (sentinel.next) and the * tail (sentinel.prev) of the list. The sentinal has a null * key and value. **/ private static final Entry createSentinel() { Entry s = new Entry(null, null); s.prev = s; s.next = s; return s; } /** * Sentinel used to hold the head and tail of the list of entries. **/ private Entry sentinel; /** * Map of keys to entries **/ private HashMap entries; /** * Holds the number of modifications that have occurred to the map, * excluding modifications made through a collection view's iterator * (e.g. entrySet().iterator().remove()). This is used to create a * fail-fast behavior with the iterators. **/ private transient long modCount = 0; /** * Construct a new sequenced hash map with default initial size and load * factor. **/ public SequencedHashMap() { sentinel = createSentinel(); entries = new HashMap(); } /** * Construct a new sequenced hash map with the specified initial size and * default load factor. * * @param initialSize the initial size for the hash table * * @see HashMap#HashMap(int) **/ public SequencedHashMap(int initialSize) { sentinel = createSentinel(); entries = new HashMap(initialSize); } /** * Construct a new sequenced hash map with the specified initial size and * load factor. * * @param initialSize the initial size for the hash table * * @param loadFactor the load factor for the hash table. * * @see HashMap#HashMap(int,float) **/ public SequencedHashMap(int initialSize, float loadFactor) { sentinel = createSentinel(); entries = new HashMap(initialSize, loadFactor); } /** * Construct a new sequenced hash map and add all the elements in the * specified map. The order in which the mappings in the specified map are * added is defined by {@link #putAll(Map)}. **/ public SequencedHashMap(Map m) { this(); putAll(m); } /** * Removes an internal entry from the linked list. This does not remove * it from the underlying map. **/ private void removeEntry(Entry entry) { entry.next.prev = entry.prev; entry.prev.next = entry.next; } /** * Inserts a new internal entry to the tail of the linked list. This does * not add the entry to the underlying map. **/ private void insertEntry(Entry entry) { entry.next = sentinel; entry.prev = sentinel.prev; sentinel.prev.next = entry; sentinel.prev = entry; } // per Map.size() /** * Implements {@link Map#size()}. */ public int size() { // use the underlying Map's size since size is not maintained here. return entries.size(); } /** * Implements {@link Map#isEmpty()}. */ public boolean isEmpty() { // for quick check whether the map is entry, we can check the linked list // and see if there's anything in it. return sentinel.next == sentinel; } /** * Implements {@link Map#containsKey(Object)}. */ public boolean containsKey(Object key) { // pass on to underlying map implementation return entries.containsKey(key); } /** * Implements {@link Map#containsValue(Object)}. */ public boolean containsValue(Object value) { // unfortunately, we cannot just pass this call to the underlying map // because we are mapping keys to entries, not keys to values. The // underlying map doesn't have an efficient implementation anyway, so this // isn't a big deal. // do null comparison outside loop so we only need to do it once. This // provides a tighter, more efficient loop at the expense of slight // code duplication. if(value == null) { for(Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if(pos.getValue() == null) return true; } } else { for(Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if(value.equals(pos.getValue())) return true; } } return false; } /** * Implements {@link Map#get(Object)}. */ public Object get(Object o) { // find entry for the specified key object Entry entry = (Entry)entries.get(o); if(entry == null) return null; return entry.getValue(); } /** * Return the entry for the "oldest" mapping. That is, return the Map.Entry * for the key-value pair that was first put into the map when compared to * all the other pairings in the map. This behavior is equivalent to using * entrySet().iterator().next(), but this method provides an * optimized implementation. * * @return The first entry in the sequence, or null if the * map is empty. **/ public Map.Entry getFirst() { // sentinel.next points to the "first" element of the sequence -- the head // of the list, which is exactly the entry we need to return. We must test // for an empty list though because we don't want to return the sentinel! return (isEmpty()) ? null : sentinel.next; } /** * Return the key for the "oldest" mapping. That is, return the key for the * mapping that was first put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * getFirst().getKey(), but this method provides a slightly * optimized implementation. * * @return The first key in the sequence, or null if the * map is empty. **/ public Object getFirstKey() { // sentinel.next points to the "first" element of the sequence -- the head // of the list -- and the requisite key is returned from it. An empty list // does not need to be tested. In cases where the list is empty, // sentinel.next will point to the sentinel itself which has a null key, // which is exactly what we would want to return if the list is empty (a // nice convient way to avoid test for an empty list) return sentinel.next.getKey(); } /** * Return the value for the "oldest" mapping. That is, return the value for * the mapping that was first put into the map when compared to all the * other objects in the map. This behavior is equivalent to using * getFirst().getValue(), but this method provides a slightly * optimized implementation. * * @return The first value in the sequence, or null if the * map is empty. **/ public Object getFirstValue() { // sentinel.next points to the "first" element of the sequence -- the head // of the list -- and the requisite value is returned from it. An empty // list does not need to be tested. In cases where the list is empty, // sentinel.next will point to the sentinel itself which has a null value, // which is exactly what we would want to return if the list is empty (a // nice convient way to avoid test for an empty list) return sentinel.next.getValue(); } /** * Return the entry for the "newest" mapping. That is, return the Map.Entry * for the key-value pair that was first put into the map when compared to * all the other pairings in the map. The behavior is equivalent to: * *

   *    Object obj = null;
   *    Iterator iter = entrySet().iterator();
   *    while(iter.hasNext()) {
   *      obj = iter.next();
   *    }
   *    return (Map.Entry)obj;
   *  
* * However, the implementation of this method ensures an O(1) lookup of the * last key rather than O(n). * * @return The last entry in the sequence, or null if the map * is empty. **/ public Map.Entry getLast() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list, which is exactly the entry we need to return. We must test // for an empty list though because we don't want to return the sentinel! return (isEmpty()) ? null : sentinel.prev; } /** * Return the key for the "newest" mapping. That is, return the key for the * mapping that was last put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * getLast().getKey(), but this method provides a slightly * optimized implementation. * * @return The last key in the sequence, or null if the map is * empty. **/ public Object getLastKey() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list -- and the requisite key is returned from it. An empty list // does not need to be tested. In cases where the list is empty, // sentinel.prev will point to the sentinel itself which has a null key, // which is exactly what we would want to return if the list is empty (a // nice convient way to avoid test for an empty list) return sentinel.prev.getKey(); } /** * Return the value for the "newest" mapping. That is, return the value for * the mapping that was last put into the map when compared to all the other * objects in the map. This behavior is equivalent to using * getLast().getValue(), but this method provides a slightly * optimized implementation. * * @return The last value in the sequence, or null if the map * is empty. **/ public Object getLastValue() { // sentinel.prev points to the "last" element of the sequence -- the tail // of the list -- and the requisite value is returned from it. An empty // list does not need to be tested. In cases where the list is empty, // sentinel.prev will point to the sentinel itself which has a null value, // which is exactly what we would want to return if the list is empty (a // nice convient way to avoid test for an empty list) return sentinel.prev.getValue(); } /** * Implements {@link Map#put(Object, Object)}. */ public Object put(Object key, Object value) { modCount++; Object oldValue = null; // lookup the entry for the specified key Entry e = (Entry)entries.get(key); // check to see if it already exists if(e != null) { // remove from list so the entry gets "moved" to the end of list removeEntry(e); // update value in map oldValue = e.setValue(value); // Note: We do not update the key here because its unnecessary. We only // do comparisons using equals(Object) and we know the specified key and // that in the map are equal in that sense. This may cause a problem if // someone does not implement their hashCode() and/or equals(Object) // method properly and then use it as a key in this map. } else { // add new entry e = new Entry(key, value); entries.put(key, e); } // assert(entry in map, but not list) // add to list insertEntry(e); return oldValue; } /** * Implements {@link Map#remove(Object)}. */ public Object remove(Object key) { Entry e = removeImpl(key); return (e == null) ? null : e.getValue(); } /** * Fully remove an entry from the map, returning the old entry or null if * there was no such entry with the specified key. **/ private Entry removeImpl(Object key) { Entry e = (Entry)entries.remove(key); if(e == null) return null; modCount++; removeEntry(e); return e; } /** * Adds all the mappings in the specified map to this map, replacing any * mappings that already exist (as per {@link Map#putAll(Map)}). The order * in which the entries are added is determined by the iterator returned * from {@link Map#entrySet()} for the specified map. * * @param t the mappings that should be added to this map. * * @exception NullPointerException if t is null **/ public void putAll(Map t) { Iterator iter = t.entrySet().iterator(); while(iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); put(entry.getKey(), entry.getValue()); } } /** * Implements {@link Map#clear()}. */ public void clear() { modCount++; // remove all from the underlying map entries.clear(); // and the list sentinel.next = sentinel; sentinel.prev = sentinel; } /** * Implements {@link Map#equals(Object)}. */ public boolean equals(Object obj) { if(obj == null) return false; if(obj == this) return true; if(!(obj instanceof Map)) return false; return entrySet().equals(((Map)obj).entrySet()); } /** * Implements {@link Map#hashCode()}. */ public int hashCode() { return entrySet().hashCode(); } /** * Provides a string representation of the entries within the map. The * format of the returned string may change with different releases, so this * method is suitable for debugging purposes only. If a specific format is * required, use {@link #entrySet()}.{@link Set#iterator() iterator()} and * iterate over the entries in the map formatting them as appropriate. **/ public String toString() { StringBuffer buf = new StringBuffer(); buf.append('['); for(Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { buf.append(pos.getKey()); buf.append('='); buf.append(pos.getValue()); if(pos.next != sentinel) { buf.append(','); } } buf.append(']'); return buf.toString(); } /** * Implements {@link Map#keySet()}. */ public Set keySet() { return new AbstractSet() { // required impls public Iterator iterator() { return new OrderedIterator(KEY); } public boolean remove(Object o) { Entry e = SequencedHashMap.this.removeImpl(o); return (e != null); } // more efficient impls than abstract set public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return SequencedHashMap.this.containsKey(o); } }; } /** * Implements {@link Map#values()}. */ public Collection values() { return new AbstractCollection() { // required impl public Iterator iterator() { return new OrderedIterator(VALUE); } public boolean remove(Object value) { // do null comparison outside loop so we only need to do it once. This // provides a tighter, more efficient loop at the expense of slight // code duplication. if(value == null) { for(Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if(pos.getValue() == null) { SequencedHashMap.this.removeImpl(pos.getKey()); return true; } } } else { for(Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { if(value.equals(pos.getValue())) { SequencedHashMap.this.removeImpl(pos.getKey()); return true; } } } return false; } // more efficient impls than abstract collection public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return SequencedHashMap.this.containsValue(o); } }; } /** * Implements {@link Map#entrySet()}. */ public Set entrySet() { return new AbstractSet() { // helper private Entry findEntry(Object o) { if(o == null) return null; if(!(o instanceof Map.Entry)) return null; Map.Entry e = (Map.Entry)o; Entry entry = (Entry)entries.get(e.getKey()); if(entry != null && entry.equals(e)) return entry; else return null; } // required impl public Iterator iterator() { return new OrderedIterator(ENTRY); } public boolean remove(Object o) { Entry e = findEntry(o); if(e == null) return false; return SequencedHashMap.this.removeImpl(e.getKey()) != null; } // more efficient impls than abstract collection public void clear() { SequencedHashMap.this.clear(); } public int size() { return SequencedHashMap.this.size(); } public boolean isEmpty() { return SequencedHashMap.this.isEmpty(); } public boolean contains(Object o) { return findEntry(o) != null; } }; } // constants to define what the iterator should return on "next" private static final int KEY = 0; private static final int VALUE = 1; private static final int ENTRY = 2; private static final int REMOVED_MASK = 0x80000000; private class OrderedIterator implements Iterator { /** * Holds the type that should be returned from the iterator. The value * should be either {@link #KEY}, {@link #VALUE}, or {@link #ENTRY}. To * save a tiny bit of memory, this field is also used as a marker for when * remove has been called on the current object to prevent a second remove * on the same element. Essientially, if this value is negative (i.e. the * bit specified by {@link #REMOVED_MASK} is set), the current position * has been removed. If positive, remove can still be called. **/ private int returnType; /** * Holds the "current" position in the iterator. When pos.next is the * sentinel, we've reached the end of the list. **/ private Entry pos = sentinel; /** * Holds the expected modification count. If the actual modification * count of the map differs from this value, then a concurrent * modification has occurred. **/ private transient long expectedModCount = modCount; /** * Construct an iterator over the sequenced elements in the order in which * they were added. The {@link #next()} method returns the type specified * by returnType which must be either {@link #KEY}, {@link * #VALUE}, or {@link #ENTRY}. **/ public OrderedIterator(int returnType) { //// Since this is a private inner class, nothing else should have //// access to the constructor. Since we know the rest of the outer //// class uses the iterator correctly, we can leave of the following //// check: //if(returnType >= 0 && returnType <= 2) { // throw new IllegalArgumentException("Invalid iterator type"); //} // Set the "removed" bit so that the iterator starts in a state where // "next" must be called before "remove" will succeed. this.returnType = returnType | REMOVED_MASK; } /** * Returns whether there is any additional elements in the iterator to be * returned. * * @return true if there are more elements left to be * returned from the iterator; false otherwise. **/ public boolean hasNext() { return pos.next != sentinel; } /** * Returns the next element from the iterator. * * @return the next element from the iterator. * * @exception NoSuchElementException if there are no more elements in the * iterator. * * @exception ConcurrentModificationException if a modification occurs in * the underlying map. **/ public Object next() { if(modCount != expectedModCount) { throw new ConcurrentModificationException(); } if(pos.next == sentinel) { throw new NoSuchElementException(); } // clear the "removed" flag returnType = returnType & ~REMOVED_MASK; pos = pos.next; switch(returnType) { case KEY: return pos.getKey(); case VALUE: return pos.getValue(); case ENTRY: return pos; default: // should never happen throw new Error("bad iterator type: " + returnType); } } /** * Removes the last element returned from the {@link #next()} method from * the sequenced map. * * @exception IllegalStateException if there isn't a "last element" to be * removed. That is, if {@link #next()} has never been called, or if * {@link #remove()} was already called on the element. * * @exception ConcurrentModificationException if a modification occurs in * the underlying map. **/ public void remove() { if((returnType & REMOVED_MASK) != 0) { throw new IllegalStateException("remove() must follow next()"); } if(modCount != expectedModCount) { throw new ConcurrentModificationException(); } SequencedHashMap.this.removeImpl(pos.getKey()); // update the expected mod count for the remove operation expectedModCount++; // set the removed flag returnType = returnType | REMOVED_MASK; } } // APIs maintained from previous version of SequencedHashMap for backwards // compatibility /** * Creates a shallow copy of this object, preserving the internal structure * by copying only references. The keys and values themselves are not * clone()'d. The cloned object maintains the same sequence. * * @return A clone of this instance. * * @exception CloneNotSupportedException if clone is not supported by a * subclass. */ public Object clone () throws CloneNotSupportedException { // yes, calling super.clone() silly since we're just blowing away all // the stuff that super might be doing anyway, but for motivations on // this, see: // http://www.javaworld.com/javaworld/jw-01-1999/jw-01-object.html SequencedHashMap map = (SequencedHashMap)super.clone(); // create new, empty sentinel map.sentinel = createSentinel(); // create a new, empty entry map // note: this does not preserve the initial capacity and load factor. map.entries = new HashMap(); // add all the mappings map.putAll(this); // Note: We cannot just clone the hashmap and sentinel because we must // duplicate our internal structures. Cloning those two will not clone all // the other entries they reference, and so the cloned hash map will not be // able to maintain internal consistency because there are two objects with // the same entries. See discussion in the Entry implementation on why we // cannot implement a clone of the Entry (and thus why we need to recreate // everything). return map; } /** * Returns the Map.Entry at the specified index * * @exception ArrayIndexOutOfBoundsException if the specified index is * < 0 or > the size of the map. **/ private Map.Entry getEntry(int index) { Entry pos = sentinel; if(index < 0) { throw new ArrayIndexOutOfBoundsException(index + " < 0"); } // loop to one before the position int i = -1; while(i < (index-1) && pos.next != sentinel) { i++; pos = pos.next; } // pos.next is the requested position // if sentinel is next, past end of list if(pos.next == sentinel) { throw new ArrayIndexOutOfBoundsException(index + " >= " + (i + 1)); } return pos.next; } /** * Returns the key at the specified index. * * @exception ArrayIndexOutOfBoundsException if the index is * < 0 or > the size of the map. */ public Object get (int index) { return getEntry(index).getKey(); } /** * Returns the value at the specified index. * * @exception ArrayIndexOutOfBoundsException if the index is * < 0 or > the size of the map. */ public Object getValue (int index) { return getEntry(index).getValue(); } /** * Returns the index of the specified key. */ public int indexOf (Object key) { Entry e = (Entry)entries.get(key); int pos = 0; while(e.prev != sentinel) { pos++; e = e.prev; } return pos; } /** * Returns a key iterator. */ public Iterator iterator () { return keySet().iterator(); } /** * Returns the last index of the specified key. */ public int lastIndexOf (Object key) { // keys in a map are guarunteed to be unique return indexOf(key); } /** * Returns a List view of the keys rather than a set view. The returned * list is unmodifiable. This is required because changes to the values of * the list (using {@link java.util.ListIterator#set(Object)}) will * effectively remove the value from the list and reinsert that value at * the end of the list, which is an unexpected side effect of changing the * value of a list. This occurs because changing the key, changes when the * mapping is added to the map and thus where it appears in the list. * *

An alternative to this method is to use {@link #keySet()} * * @see #keySet() * @return The ordered list of keys. */ public List sequence() { List l = new ArrayList(size()); Iterator iter = keySet().iterator(); while(iter.hasNext()) { l.add(iter.next()); } return Collections.unmodifiableList(l); } /** * Removes the element at the specified index. * * @param index The index of the object to remove. * @return The previous value coressponding the key, or * null if none existed. * * @exception ArrayIndexOutOfBoundsException if the index is * < 0 or > the size of the map. */ public Object remove (int index) { return remove(get(index)); } // per Externalizable.readExternal(ObjectInput) /** * Deserializes this map from the given stream. * * @param in the stream to deserialize from * @throws IOException if the stream raises it * @throws ClassNotFoundException if the stream raises it */ public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException { int size = in.readInt(); for(int i = 0; i < size; i++) { Object key = in.readObject(); Object value = in.readObject(); put(key, value); } } /** * Serializes this map to the given stream. * * @param out the stream to serialize to * @throws IOException if the stream raises it */ public void writeExternal( ObjectOutput out ) throws IOException { out.writeInt(size()); for(Entry pos = sentinel.next; pos != sentinel; pos = pos.next) { out.writeObject(pos.getKey()); out.writeObject(pos.getValue()); } } // add a serial version uid, so that if we change things in the future // without changing the format, we can still deserialize properly. private static final long serialVersionUID = 3380552487888102930L; } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SortedBag.java0100644000175000017500000000232610055172400030767 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Comparator; /** * A type of {@link Bag} that maintains order among its unique * representative members. * * @since 2.0 * @author Chuck Burdick **/ public interface SortedBag extends Bag { /** * Returns the comparator associated with this sorted set, or null * if it uses its elements' natural ordering. **/ public Comparator comparator(); /** * Returns the first (lowest) member. **/ public Object first(); /** * Returns the last (highest) member. **/ public Object last(); } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BagUtils.java0100644000175000017500000002317310055172400030632 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Comparator; import java.util.Set; /** * Provides utility methods and decorators for {@link Bag} * and {@link SortedBag} instances.

* * @author Paul Jack * @author Stephen Colebourne * @version $Id: BagUtils.java,v 1.7.2.1 2004/05/22 12:14:01 scolebourne Exp $ * @since 2.1 */ public class BagUtils { /** * Prevents instantiation. */ private BagUtils() { } static class PredicatedBag extends CollectionUtils.PredicatedCollection implements Bag { public PredicatedBag(Bag b, Predicate p) { super(b, p); } public boolean add(Object o, int count) { validate(o); return getBag().add(o, count); } public boolean remove(Object o, int count) { return getBag().remove(o, count); } public Set uniqueSet() { return getBag().uniqueSet(); } public int getCount(Object o) { return getBag().getCount(o); } private Bag getBag() { return (Bag)collection; } } static class UnmodifiableBag extends CollectionUtils.UnmodifiableCollection implements Bag { public UnmodifiableBag(Bag bag) { super(bag); } private Bag getBag() { return (Bag)collection; } public boolean add(Object o, int count) { throw new UnsupportedOperationException(); } public boolean remove(Object o, int count) { throw new UnsupportedOperationException(); } public Set uniqueSet() { return ((Bag)collection).uniqueSet(); } public int getCount(Object o) { return ((Bag)collection).getCount(o); } } static class SynchronizedBag extends CollectionUtils.SynchronizedCollection implements Bag { public SynchronizedBag(Bag bag) { super(bag); } public synchronized boolean add(Object o, int count) { return getBag().add(o, count); } public synchronized boolean remove(Object o, int count) { return getBag().remove(o, count); } public synchronized Set uniqueSet() { return getBag().uniqueSet(); } public synchronized int getCount(Object o) { return getBag().getCount(o); } private Bag getBag() { return (Bag)collection; } } static class PredicatedSortedBag extends PredicatedBag implements SortedBag { public PredicatedSortedBag(SortedBag sb, Predicate p) { super(sb, p); } public Comparator comparator() { return getSortedBag().comparator(); } public Object first() { return getSortedBag().first(); } public Object last() { return getSortedBag().last(); } private SortedBag getSortedBag() { return (SortedBag)collection; } } static class SynchronizedSortedBag extends SynchronizedBag implements SortedBag { public SynchronizedSortedBag(SortedBag bag) { super(bag); } public synchronized Comparator comparator() { return getSortedBag().comparator(); } public synchronized Object first() { return getSortedBag().first(); } public synchronized Object last() { return getSortedBag().last(); } private SortedBag getSortedBag() { return (SortedBag)collection; } } static class UnmodifiableSortedBag extends UnmodifiableBag implements SortedBag { public UnmodifiableSortedBag(SortedBag bag) { super(bag); } public Comparator comparator() { return getSortedBag().comparator(); } public Object first() { return getSortedBag().first(); } public Object last() { return getSortedBag().last(); } private SortedBag getSortedBag() { return (SortedBag)collection; } } /** * Returns a predicated bag backed by the given bag. Only objects * that pass the test in the given predicate can be added to the bag. * It is important not to use the original bag after invoking this * method, as it is a backdoor for adding unvalidated objects. * * @param bag the bag to predicate, must not be null * @param predicate the predicate for the bag, must not be null * @return a predicated bag backed by the given bag * @throws IllegalArgumentException if the Bag or Predicate is null */ public static Bag predicatedBag(Bag bag, Predicate predicate) { return new PredicatedBag(bag, predicate); } /** * Returns an unmodifiable view of the given bag. Any modification * attempts to the returned bag will raise an * {@link UnsupportedOperationException}. * * @param bag the bag whose unmodifiable view is to be returned, must not be null * @return an unmodifiable view of that bag * @throws IllegalArgumentException if the Bag is null */ public static Bag unmodifiableBag(Bag bag) { return new UnmodifiableBag(bag); } /** * Returns a synchronized (thread-safe) bag backed by the given bag. * In order to guarantee serial access, it is critical that all * access to the backing bag is accomplished through the returned bag. *

* It is imperative that the user manually synchronize on the returned * bag when iterating over it: * *

     * Bag bag = BagUtils.synchronizedBag(new HashBag());
     * ...
     * synchronized(bag) {
     *     Iterator i = bag.iterator(); // Must be in synchronized block
     *     while (i.hasNext())
     *         foo(i.next());
     *     }
     * }
     * 
* * Failure to follow this advice may result in non-deterministic * behavior. * * @param bag the bag to synchronize, must not be null * @return a synchronized bag backed by that bag * @throws IllegalArgumentException if the Bag is null */ public static Bag synchronizedBag(Bag bag) { return new SynchronizedBag(bag); } /** * Returns a predicated sorted bag backed by the given sorted bag. * Only objects that pass the test in the given predicate can be * added to the bag. * It is important not to use the original bag after invoking this * method, as it is a backdoor for adding unvalidated objects. * * @param bag the sorted bag to predicate, must not be null * @param predicate the predicate for the bag, must not be null * @return a predicated bag backed by the given bag * @throws IllegalArgumentException if the SortedBag or Predicate is null */ public static SortedBag predicatedSortedBag(SortedBag bag, Predicate predicate) { return new PredicatedSortedBag(bag, predicate); } /** * Returns an unmodifiable view of the given sorted bag. Any modification * attempts to the returned bag will raise an * {@link UnsupportedOperationException}. * * @param bag the bag whose unmodifiable view is to be returned, must not be null * @return an unmodifiable view of that bag * @throws IllegalArgumentException if the SortedBag is null */ public static SortedBag unmodifiableSortedBag(SortedBag bag) { return new UnmodifiableSortedBag(bag); } /** * Returns a synchronized (thread-safe) sorted bag backed by the given * sorted bag. * In order to guarantee serial access, it is critical that all * access to the backing bag is accomplished through the returned bag. *

* It is imperative that the user manually synchronize on the returned * bag when iterating over it: * *

     * SortedBag bag = BagUtils.synchronizedSortedBag(new TreeBag());
     * ...
     * synchronized(bag) {
     *     Iterator i = bag.iterator(); // Must be in synchronized block
     *     while (i.hasNext())
     *         foo(i.next());
     *     }
     * }
     * 
* * Failure to follow this advice may result in non-deterministic * behavior. * * @param bag the bag to synchronize, must not be null * @return a synchronized bag backed by that bag * @throws IllegalArgumentException if the SortedBag is null */ public static SortedBag synchronizedSortedBag(SortedBag bag) { return new SynchronizedSortedBag(bag); } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ComparatorUtils.java0100644000175000017500000002045110055172376032260 0ustar toratora/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Collection; import java.util.Comparator; import org.apache.commons.collections.comparators.ComparableComparator; import org.apache.commons.collections.comparators.ComparatorChain; import org.apache.commons.collections.comparators.NullComparator; import org.apache.commons.collections.comparators.ReverseComparator; import org.apache.commons.collections.comparators.TransformingComparator; /** * Provides convenient static utility methods for Comparator * objects. *

* Most of the utility in this class can also be found in the * comparators package. This class merely provides a * convenient central place if you have use for more than one class * in the comparators subpackage. *

* Note that every method in this class allows you to specify * null instead of a comparator, in which case * {@link #NATURAL_COMPARATOR} will be used. * * @since 2.1 * @author Paul Jack * @author Stephen Colebourne * @version $Id: $ */ public class ComparatorUtils { /** * Restrictive constructor */ private ComparatorUtils() { } /** * Comparator for natural sort order. * * @see ComparableComparator#getInstance */ public static final Comparator NATURAL_COMPARATOR = ComparableComparator.getInstance(); /** * Gets a comparator that uses the natural order of the objects. * * @return a comparator which uses natural order */ public static Comparator naturalComparator() { return NATURAL_COMPARATOR; } /** * Gets a comparator that compares using two {@link Comparator}s. *

* The second comparator is used if the first comparator returns * that equal. * * @param comparator1 the first comparator to use, not null * @param comparator2 the first comparator to use, not null * @return a combination comparator over the comparators * @throws NullPointerException if either comparator is null */ public static Comparator chainedComparator(Comparator comparator1, Comparator comparator2) { return chainedComparator(new Comparator[] {comparator1, comparator2}); } /** * Gets a comparator that compares using an array of {@link Comparator}s. *

* The second comparator is used if the first comparator returns * that equal and so on. * * @param iterators the comparators to use, not null or empty or contain nulls * @return a combination comparator over the comparators * @throws NullPointerException if comparators array is null or contains a null */ public static Comparator chainedComparator(Comparator[] comparators) { ComparatorChain chain = new ComparatorChain(); for (int i = 0; i < comparators.length; i++) { if (comparators[i] == null) { throw new NullPointerException("Comparator cannot be null"); } chain.addComparator(comparators[i]); } return chain; } /** * Gets a comparator that compares using a collection of {@link Comparator}s. *

* The second comparator is used if the first comparator returns * that equal and so on. * * @param comparators the comparators to use, not null or empty or contain nulls * @return a combination comparator over the comparators * @throws NullPointerException if comparators collection is null or contains a null * @throws ClassCastException if the comparators collection contains the wrong object type */ public static Comparator chainedComparator(Collection comparators) { return chainedComparator( (Comparator[]) comparators.toArray(new Comparator[comparators.size()]) ); } /** * Gets a comparator that reverses the order of the given * comparator. * * @param comparator the comparator whose order to reverse * @return a comparator who reverses that order * @see ReverseComparator */ public static Comparator reversedComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new ReverseComparator(comparator); } /** * Gets a Comparator that controls the comparison of null values. *

* The returned comparator will consider a null value to be less than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator.

* * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ public static Comparator nullLowComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator(comparator, false); } /** * Gets a Comparator that controls the comparison of null values. *

* The returned comparator will consider a null value to be greater than * any nonnull value, and equal to any other null value. Two nonnull * values will be evaluated with the given comparator.

* * @param comparator the comparator that wants to allow nulls * @return a version of that comparator that allows nulls * @see NullComparator */ public static Comparator nullHighComparator(Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new NullComparator(comparator, true); } /** * Gets a Comparator that passes transformed objects to the given comparator. *

* Objects passed to the returned comparator will first be transformed * by the given transformer before they are compared by the given * comparator. * * @param comparator the sort order to use * @param transformer the transformer to use * @return a comparator that transforms its input objects before comparing them * @see TransformingComparator */ public static Comparator transformedComparator(Comparator comparator, Transformer transformer) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } return new TransformingComparator(transformer, comparator); } /** * Returns the smaller of the given objects according to the given * comparator. * * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the smaller of the two objects */ public static Object min(Object o1, Object o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } int c = comparator.compare(o1, o2); return (c < 0) ? o1 : o2; } /** * Returns the smaller of the given objects according to the given * comparator. * * @param o1 the first object to compare * @param o2 the second object to compare * @param comparator the sort order to use * @return the smaller of the two objects */ public static Object max(Object o1, Object o2, Comparator comparator) { if (comparator == null) { comparator = NATURAL_COMPARATOR; } int c = comparator.compare(o1, o2); return (c > 0) ? o1 : o2; } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SetUtils.java0100644000175000017500000000773110055172400030676 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Comparator; import java.util.Set; import java.util.SortedSet; /** * Provides static utility methods and decorators for {@link Set} * and {@link SortedSet} instances. * * @author Paul Jack * @author Stephen Colebourne * @version $Id: SetUtils.java,v 1.7.2.1 2004/05/22 12:14:02 scolebourne Exp $ * @since 2.1 */ public class SetUtils { /** * Prevents instantiation. */ private SetUtils() { } static class PredicatedSet extends CollectionUtils.PredicatedCollection implements Set { public PredicatedSet(Set set, Predicate predicate) { super(set, predicate); } } static class PredicatedSortedSet extends PredicatedSet implements SortedSet { public PredicatedSortedSet(SortedSet set, Predicate predicate) { super(set, predicate); } public SortedSet subSet(Object o1, Object o2) { SortedSet sub = getSortedSet().subSet(o1, o2); return new PredicatedSortedSet(sub, predicate); } public SortedSet headSet(Object o1) { SortedSet sub = getSortedSet().headSet(o1); return new PredicatedSortedSet(sub, predicate); } public SortedSet tailSet(Object o1) { SortedSet sub = getSortedSet().tailSet(o1); return new PredicatedSortedSet(sub, predicate); } public Object first() { return getSortedSet().first(); } public Object last() { return getSortedSet().last(); } public Comparator comparator() { return getSortedSet().comparator(); } private SortedSet getSortedSet() { return (SortedSet)collection; } } /** * Returns a predicated set backed by the given set. Only objects * that pass the test in the given predicate can be added to the set. * It is important not to use the original set after invoking this * method, as it is a backdoor for adding unvalidated objects. * * @param set the set to predicate, must not be null * @param predicate the predicate for the set, must not be null * @return a predicated set backed by the given set * @throws IllegalArgumentException if the Set or Predicate is null */ public static Set predicatedSet(Set set, Predicate predicate) { return new PredicatedSet(set, predicate); } /** * Returns a predicated sorted set backed by the given sorted set. * Only objects that pass the test in the given predicate can be added * to the sorted set. * It is important not to use the original sorted set after invoking this * method, as it is a backdoor for adding unvalidated objects. * * @param set the sorted set to predicate, must not be null * @param predicate the predicate for the sorted set, must not be null * @return a predicated sorted set backed by the given sorted set * @throws IllegalArgumentException if the Set or Predicate is null */ public static SortedSet predicatedSortedSet(SortedSet set, Predicate predicate) { return new PredicatedSortedSet(set, predicate); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ArrayEnumeration.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ArrayEnumeration.jav0100644000175000017500000000373010055172402032243 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.Enumeration; import java.util.List; import java.util.NoSuchElementException; /** * Enumeration wrapper for array. * * @since 1.0 * @author Peter Donald * @deprecated This class has significant overlap with ArrayIterator, * and Collections focuses mainly on Java2-style * collections. If you need to enumerate an array, * create an {@link ArrayIterator} and wrap it with an * {@link IteratorEnumeration} instead. */ public final class ArrayEnumeration implements Enumeration { protected Object[] m_elements; protected int m_index; public ArrayEnumeration( final List elements ) { m_elements = elements.toArray(); } public ArrayEnumeration( final Object[] elements ) { if(elements == null) { m_elements = new Object[0]; } else { m_elements = elements; } } public boolean hasMoreElements() { return ( m_index < m_elements.length ); } public Object nextElement() { if( !hasMoreElements() ) { throw new NoSuchElementException("No more elements exist"); } return m_elements[ m_index++ ]; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ProxyListIterator.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ProxyListIterator.ja0100644000175000017500000000333710055172376032274 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.util.ListIterator; /** * A proxy {@link ListIterator ListIterator} which delegates its * methods to a proxy instance. * * @since 2.0 * @see ProxyIterator * @version $Revision: 1.4.2.1 $ $Date: 2004/05/22 12:14:02 $ * @author Rodney Waldhoff * @deprecated this class has been moved to the iterators subpackage */ public class ProxyListIterator extends org.apache.commons.collections.iterators.ProxyListIterator { // Constructor //------------------------------------------------------------------------- /** * Constructs a new ProxyListIterator that will not * function until {@link #setListIterator(ListIterator) setListIterator} * is invoked. */ public ProxyListIterator() { super(); } /** * Constructs a new ProxyListIterator that will use the * given list iterator. * * @param iterator the list iterator to use */ public ProxyListIterator(ListIterator iterator) { super(iterator); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BufferUnderflowException.javalibcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BufferUnderflowExcep0100644000175000017500000000415110055172376032273 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; /** * The BufferUnderflowException is used when the buffer is already empty * * @author Avalon * @author Berin Loritsch * @author Jeff Turner * @author Paul Jack * @author Stephen Colebourne * @since 2.1 * @version $Id: BufferUnderflowException.java,v 1.5.2.1 2004/05/22 12:14:02 scolebourne Exp $ */ public class BufferUnderflowException extends RuntimeException { private final Throwable m_throwable; /** * Constructs a new BufferUnderflowException. */ public BufferUnderflowException() { super(); m_throwable = null; } /** * Construct a new BufferUnderflowException. * * @param message the detail message for this exception */ public BufferUnderflowException(String message) { this(message, null); } /** * Construct a new BufferUnderflowException. * * @param message the detail message for this exception * @param throwable the root cause of the exception */ public BufferUnderflowException(String message, Throwable exception) { super(message); m_throwable = exception; } /** * Gets the root cause of the exception. * * @return the root cause */ public final Throwable getCause() { return m_throwable; } } libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BeanMap.java0100644000175000017500000006576610055172400030441 0ustar toratora/* * Copyright 1999-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.collections; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.IntrospectionException; import java.beans.PropertyDescriptor; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Set; /** An implementation of Map for JavaBeans which uses introspection to * get and put properties in the bean. * * If an exception occurs during attempts to get or set a property then the * property is considered non existent in the Map * * @since 1.0 * @author James Strachan */ public class BeanMap extends AbstractMap implements Cloneable { private transient Object bean; private transient HashMap readMethods = new HashMap(); private transient HashMap writeMethods = new HashMap(); private transient HashMap types = new HashMap(); /** * An empty array. Used to invoke accessors via reflection. */ public static final Object[] NULL_ARGUMENTS = {}; /** * Maps primitive Class types to transformers. The transformer * transform strings into the appropriate primitive wrapper. */ public static HashMap defaultTransformers = new HashMap(); static { defaultTransformers.put( Boolean.TYPE, new Transformer() { public Object transform( Object input ) { return Boolean.valueOf( input.toString() ); } } ); defaultTransformers.put( Character.TYPE, new Transformer() { public Object transform( Object input ) { return new Character( input.toString().charAt( 0 ) ); } } ); defaultTransformers.put( Byte.TYPE, new Transformer() { public Object transform( Object input ) { return Byte.valueOf( input.toString() ); } } ); defaultTransformers.put( Short.TYPE, new Transformer() { public Object transform( Object input ) { return Short.valueOf( input.toString() ); } } ); defaultTransformers.put( Integer.TYPE, new Transformer() { public Object transform( Object input ) { return Integer.valueOf( input.toString() ); } } ); defaultTransformers.put( Long.TYPE, new Transformer() { public Object transform( Object input ) { return Long.valueOf( input.toString() ); } } ); defaultTransformers.put( Float.TYPE, new Transformer() { public Object transform( Object input ) { return Float.valueOf( input.toString() ); } } ); defaultTransformers.put( Double.TYPE, new Transformer() { public Object transform( Object input ) { return Double.valueOf( input.toString() ); } } ); } // Constructors //------------------------------------------------------------------------- /** * Constructs a new empty BeanMap. */ public BeanMap() { } /** * Constructs a new BeanMap that operates on the * specified bean. If the given bean is null, then * this map will be empty. * * @param bean the bean for this map to operate on */ public BeanMap(Object bean) { this.bean = bean; initialise(); } // Map interface //------------------------------------------------------------------------- /** * Clone this bean map using the following process: * *