libcommons-collections-java-2.1.1.orig/ 0040755 0001750 0001750 00000000000 10072641277 016555 5 ustar tora tora libcommons-collections-java-2.1.1.orig/src/ 0040755 0001750 0001750 00000000000 10055172376 017344 5 ustar tora tora libcommons-collections-java-2.1.1.orig/src/conf/ 0040755 0001750 0001750 00000000000 10072637470 020271 5 ustar tora tora libcommons-collections-java-2.1.1.orig/src/conf/MANIFEST.MF 0100644 0001750 0001750 00000000324 10055172376 021717 0 ustar tora tora Extension-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/ 0040755 0001750 0001750 00000000000 10055172376 020265 5 ustar tora tora libcommons-collections-java-2.1.1.orig/src/java/org/ 0040755 0001750 0001750 00000000000 10055172376 021054 5 ustar tora tora libcommons-collections-java-2.1.1.orig/src/java/org/apache/ 0040755 0001750 0001750 00000000000 10055172376 022275 5 ustar tora tora libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/ 0040755 0001750 0001750 00000000000 10055172376 023750 5 ustar tora tora libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ 0040755 0001750 0001750 00000000000 10072637466 026273 5 ustar tora tora ././@LongLink 0000000 0000000 0000000 00000000150 00000000000 011561 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/IteratorEnumeration.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/IteratorEnumeration. 0100644 0001750 0001750 00000003126 10055172400 032252 0 ustar tora tora /*
* 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.java 0100644 0001750 0001750 00000012030 10055172400 031442 0 ustar tora tora /*
* 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;
}
}
././@LongLink 0000000 0000000 0000000 00000000146 00000000000 011566 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BoundedFifoBuffer.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/BoundedFifoBuffer.ja 0100644 0001750 0001750 00000020461 10055172376 032120 0 ustar tora tora /*
* 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);
}
};
}
}
././@LongLink 0000000 0000000 0000000 00000000146 00000000000 011566 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SingletonIterator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/SingletonIterator.ja 0100644 0001750 0001750 00000002510 10055172400 032235 0 ustar tora tora /*
* 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.
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.java 0100644 0001750 0001750 00000004326 10055172402 030332 0 ustar tora tora /*
* 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.java 0100644 0001750 0001750 00000003740 10055172400 031744 0 ustar tora tora /*
* 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/ 0040755 0001750 0001750 00000000000 10072637465 030624 5 ustar tora tora ././@LongLink 0000000 0000000 0000000 00000000167 00000000000 011571 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/TransformingComparator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/Transfor 0100644 0001750 0001750 00000004415 10055172400 032326 0 ustar tora tora /*
* 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); } } ././@LongLink 0000000 0000000 0000000 00000000162 00000000000 011564 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ReverseComparator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ReverseC 0100644 0001750 0001750 00000004271 10055172400 032246 0 ustar tora tora /* * 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); } } ././@LongLink 0000000 0000000 0000000 00000000165 00000000000 011567 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ComparableComparator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/Comparab 0100644 0001750 0001750 00000007557 10055172400 032266 0 ustar tora tora /* * 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() ); } } } ././@LongLink 0000000 0000000 0000000 00000000160 00000000000 011562 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/ComparatorChain.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/Comparat 0100644 0001750 0001750 00000022734 10055172400 032302 0 ustar tora tora /* * 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; } } ././@LongLink 0000000 0000000 0000000 00000000157 00000000000 011570 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/NullComparator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/NullComp 0100644 0001750 0001750 00000015032 10055172400 032256 0 ustar tora tora /* * 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;
}
././@LongLink 0000000 0000000 0000000 00000000150 00000000000 011561 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/package.html libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/comparators/package. 0100644 0001750 0001750 00000000456 10055172376 032216 0 ustar tora tora
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.java 0100644 0001750 0001750 00000015350 10055172400 030216 0 ustar tora tora /*
* 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; } ././@LongLink 0000000 0000000 0000000 00000000150 00000000000 011561 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/UnboundedFifoBuffer.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/UnboundedFifoBuffer. 0100644 0001750 0001750 00000017625 10055172400 032144 0 ustar tora tora /* * 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);
}
};
}
}
././@LongLink 0000000 0000000 0000000 00000000147 00000000000 011567 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/FilterListIterator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/FilterListIterator.j 0100644 0001750 0001750 00000005324 10055172376 032235 0 ustar tora tora /*
* 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);
}
}
././@LongLink 0000000 0000000 0000000 00000000147 00000000000 011567 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ExtendedProperties.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/ExtendedProperties.j 0100644 0001750 0001750 00000160163 10055172376 032262 0 ustar tora tora /*
* 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: * *
key = value
* 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.java 0100644 0001750 0001750 00000014317 10055172376 031200 0 ustar tora tora /*
* 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.java 0100644 0001750 0001750 00000111157 10055172400 031650 0 ustar tora tora /*
* 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 ifclear()
* 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.
* 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.
* 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.java 0100644 0001750 0001750 00000021132 10055172400 031723 0 ustar tora tora /*
* 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.java 0100644 0001750 0001750 00000002235 10055172376 031030 0 ustar tora tora /* * 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.java 0100644 0001750 0001750 00000002100 10055172376 030526 0 ustar tora tora /* * 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.java 0100644 0001750 0001750 00000103130 10055172376 032240 0 ustar tora tora /* * 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 aCollectionUtils.
*/
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
* 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))));i
* 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.
*
* This iterator is a valid iterator object that will iterate over
* nothing.
*
* @return an iterator over nothing
* @deprecated Use
* This iterator is a valid list iterator object that will iterate
* over nothing.
*
* @return a list iterator over nothing
* @deprecated Use
* 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
* 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
* Given two ordered {@link Iterator}s
* 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
* 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
* 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
*
* 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
* 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
* 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
* 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:
*
*
* When you construct a
*
* 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
*
*
* 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
*
*
* As usual, this implementation is not synchronized. You
* can use {@link java.util.Collections#synchronizedMap} to
* provide synchronized access to a
*
* 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
* 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.java 0100644 0001750 0001750 00000010021 10055172400 030663 0 ustar tora tora /*
* 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 An example use case is where the wrapped 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 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 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
* 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 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
*
* 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
*
* 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
*
*
*
* 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 is the entry's hashCode, Hk is the key's hashCode, and n is
* the number of buckets.
*
* 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");
}
}
././@LongLink 0000000 0000000 0000000 00000000160 00000000000 011562 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/CollatingIterator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/CollatingI 0100644 0001750 0001750 00000030577 10055172400 032247 0 ustar tora tora /*
* 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 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.
*
*
*
* @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.java 0100644 0001750 0001750 00000056441 10055172376 031752 0 ustar tora tora /*
* 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.
* EmptyIterator.INSTANCE
*/
public static Iterator emptyIterator() {
return EMPTY_ITERATOR;
}
/**
* Gets an empty list iterator.
* EmptyListIterator.INSTANCE
*/
public static ListIterator emptyListIterator() {
return EMPTY_LIST_ITERATOR;
}
/**
* Gets a singleton iterator.
* new SingletonIterator(object)
*/
public static Iterator singletonIterator(Object object) {
return new SingletonIterator(object);
}
/**
* Gets a singleton list iterator.
* 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.
* A and B,
* the {@link Iterator#next()} method will return the lesser of
* A.next() and B.next().
* A and B,
* the {@link Iterator#next()} method will return the lesser of
* A.next() and B.next() and so on.
* A and B,
* the {@link Iterator#next()} method will return the lesser of
* A.next() and B.next() and so on.
*
*
*
* @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.java 0100644 0001750 0001750 00000014012 10055172400 031344 0 ustar tora tora /*
* 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.
* 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.java 0100644 0001750 0001750 00000037317 10055172400 031147 0 ustar tora tora /*
* 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}.
* 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.
* 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.java 0100644 0001750 0001750 00000002104 10055172400 031411 0 ustar tora tora /*
* 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);
}
././@LongLink 0000000 0000000 0000000 00000000151 00000000000 011562 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/CursorableLinkedList.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/CursorableLinkedList 0100644 0001750 0001750 00000132124 10055172400 032261 0 ustar tora tora /*
* 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.
*
* 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;iReferenceMap, 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}.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.NullPointerException.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.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.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).Map needs
* synchronization (to make it thread-safe), but the Map
* returned by Collections.synchronizedMap(map)
* hides part of map's public interface.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.java 0100644 0001750 0001750 00000016027 10055172376 027625 0 ustar tora tora /*
* 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}.
*
* 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()}.
*
* 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.
*
* 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.
*
* 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.
*
* 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.java 0100644 0001750 0001750 00000025307 10055172376 031571 0 ustar tora tora /*
* 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.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.java 0100644 0001750 0001750 00000047336 10055172400 032152 0 ustar tora tora /*
* 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)).
* 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.
* He = |Hk mod n|
*
*
*
* 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.java 0100644 0001750 0001750 00000014245 10055172376 031366 0 ustar tora tora /*
* 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.java 0100644 0001750 0001750 00000005723 10055172400 031711 0 ustar tora tora /*
* 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/ 0040755 0001750 0001750 00000000000 10072637465 030306 5 ustar tora tora ././@LongLink 0000000 0000000 0000000 00000000162 00000000000 011564 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/IteratorEnumeration.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/IteratorEn 0100644 0001750 0001750 00000005273 10055172376 032305 0 ustar tora tora /*
* 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;
}
}
././@LongLink 0000000 0000000 0000000 00000000160 00000000000 011562 L ustar root root libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/SingletonIterator.java libcommons-collections-java-2.1.1.orig/src/java/org/apache/commons/collections/iterators/SingletonI 0100644 0001750 0001750 00000004754 10055172402 032275 0 ustar tora tora /*
* 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.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.
* 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;itrue.
*/
private boolean anyValueSet(BitSet set) {
for(int i=0;i