code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
/**
* Interface for procedures that take two Object parameters.
* <p/>
* Created: Mon Nov 5 22:03:30 2001
*
* @author Eric D. Friedman
* @version $Id: TObjectObjectProcedure.java,v 1.1.2.1 2009/09/06 17:02:20 upholderoftruth Exp $
*/
public interface TObjectObjectProcedure<K, V> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a an <code>Object</code> value
* @param b an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( K a, V b );
}// TObjectObjectProcedure
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TObjectObjectProcedure.java | Java | asf20 | 1,755 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures with one int parameter.
*/
public interface TIntProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int value );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TIntProcedure.java | Java | asf20 | 1,600 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type Object and int.
*/
public interface TObjectIntProcedure<K> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a an <code>Object</code> value
* @param b a <code>int</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( K a, int b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TObjectIntProcedure.java | Java | asf20 | 1,668 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
/**
* Interface for procedures with one Object parameter.
*
* Created: Mon Nov 5 21:45:49 2001
*
* @author Eric D. Friedman
* @version $Id: TObjectProcedure.java,v 1.1.2.1 2009/09/02 21:52:33 upholderoftruth Exp $
*/
public interface TObjectProcedure<T> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param object an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(T object);
}// TObjectProcedure
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TObjectProcedure.java | Java | asf20 | 1,672 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type int and Object.
*/
public interface TIntObjectProcedure<T> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>int</code> value
* @param b an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int a, T b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TIntObjectProcedure.java | Java | asf20 | 1,668 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type long and Object.
*/
public interface TLongObjectProcedure<T> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>long</code> value
* @param b an <code>Object</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long a, T b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TLongObjectProcedure.java | Java | asf20 | 1,672 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure.array;
import gnu.trove.procedure.TObjectProcedure;
/**
* A procedure which stores each value it receives into a target array.
* <p/>
* Created: Sat Jan 12 10:13:42 2002
*
* @author Eric D. Friedman
* @version $Id: ToObjectArrayProceedure.java,v 1.1.2.1 2009/09/02 21:52:33 upholderoftruth Exp $
*/
public final class ToObjectArrayProceedure<T> implements TObjectProcedure<T> {
private final T[] target;
private int pos = 0;
public ToObjectArrayProceedure( final T[] target ) {
this.target = target;
}
public final boolean execute( T value ) {
target[pos++] = value;
return true;
}
} // ToObjectArrayProcedure | 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/array/ToObjectArrayProceedure.java | Java | asf20 | 1,706 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type int and int.
*/
public interface TIntIntProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a a <code>int</code> value
* @param b a <code>int</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( int a, int b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TIntIntProcedure.java | Java | asf20 | 1,657 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures that take two parameters of type Object and long.
*/
public interface TObjectLongProcedure<K> {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param a an <code>Object</code> value
* @param b a <code>long</code> value
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( K a, long b );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TObjectLongProcedure.java | Java | asf20 | 1,672 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.procedure;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for procedures with one long parameter.
*/
public interface TLongProcedure {
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>long</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute( long value );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/procedure/TLongProcedure.java | Java | asf20 | 1,604 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
// Copyright (c) 2011, Johan Parent All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.linked;
import gnu.trove.function.TIntFunction;
import gnu.trove.list.TIntList;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.TIntCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, double linked list of int primitives.
*/
public class TIntLinkedList implements TIntList, Externalizable {
int no_entry_value;
int size;
TIntLink head = null;
TIntLink tail = head;
public TIntLinkedList() {
}
public TIntLinkedList(int no_entry_value) {
this.no_entry_value = no_entry_value;
}
public TIntLinkedList(TIntList list) {
no_entry_value = list.getNoEntryValue();
//
for (TIntIterator iterator = list.iterator(); iterator.hasNext();) {
int next = iterator.next();
add(next);
}
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return size() == 0;
}
/** {@inheritDoc} */
public boolean add(int val) {
TIntLink l = new TIntLink(val);
if (no(head)) {
head = l;
tail = l;
} else {
l.setPrevious(tail);
tail.setNext(l);
//
tail = l;
}
size++;
return true;
}
/** {@inheritDoc} */
public void add(int[] vals) {
for (int val : vals) {
add(val);
}
}
/** {@inheritDoc} */
public void add(int[] vals, int offset, int length) {
for (int i = 0; i < length; i++) {
int val = vals[offset + i];
add(val);
}
}
/** {@inheritDoc} */
public void insert(int offset, int value) {
TIntLinkedList tmp = new TIntLinkedList();
tmp.add(value);
insert(offset, tmp);
}
/** {@inheritDoc} */
public void insert(int offset, int[] values) {
insert(offset, link(values, 0, values.length));
}
/** {@inheritDoc} */
public void insert(int offset, int[] values, int valOffset, int len) {
insert(offset, link(values, valOffset, len));
}
void insert(int offset, TIntLinkedList tmp) {
TIntLink l = getLinkAt(offset);
size = size + tmp.size;
//
if (l == head) {
// Add in front
tmp.tail.setNext(head);
head.setPrevious(tmp.tail);
head = tmp.head;
return;
}
if (no(l)) {
if (size == 0) {
// New empty list
head = tmp.head;
tail = tmp.tail;
} else {
// append
tail.setNext(tmp.head);
tmp.head.setPrevious(tail);
tail = tmp.tail;
}
} else {
TIntLink prev = l.getPrevious();
l.getPrevious().setNext(tmp.head);
// Link by behind tmp
tmp.tail.setNext(l);
l.setPrevious(tmp.tail);
tmp.head.setPrevious(prev);
}
}
static TIntLinkedList link(int[] values, int valOffset, int len) {
TIntLinkedList ret = new TIntLinkedList();
for (int i = 0; i < len; i++) {
ret.add(values[valOffset + i]);
}
return ret;
}
/** {@inheritDoc} */
public int get(int offset) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TIntLink l = getLinkAt(offset);
//
if (no(l))
return no_entry_value;
return l.getValue();
}
/**
* Returns the link at the given offset.
* <p/>
* A simple bisection criteria is used to keep the worst case complexity equal to
* O(n/2) where n = size(). Simply start from head of list or tail depending on offset
* and list size.
*
* @param offset of the link
* @return link or null if non-existent
*/
public TIntLink getLinkAt(int offset) {
if (offset >= size())
return null;
if (offset <= (size() >>> 1))
return getLink(head, 0, offset, true);
else
return getLink(tail, size() - 1, offset, false);
}
/**
* Returns the link at absolute offset starting from given the initial link 'l' at index 'idx'
*
* @param l
* @param idx
* @param offset
* @return
*/
private static TIntLink getLink(TIntLink l, int idx, int offset) {
return getLink(l, idx, offset, true);
}
/**
* Returns link at given absolute offset starting from link 'l' at index 'idx'
* @param l
* @param idx
* @param offset
* @param next
* @return
*/
private static TIntLink getLink(TIntLink l, int idx, int offset, boolean next) {
int i = idx;
//
while (got(l)) {
if (i == offset) {
return l;
}
i = i + (next ? 1 : -1);
l = next ? l.getNext() : l.getPrevious();
}
return null;
}
/** {@inheritDoc} */
public int set(int offset, int val) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TIntLink l = getLinkAt(offset);
//
if (no(l))
throw new IndexOutOfBoundsException("at offset " + offset);
int prev = l.getValue();
l.setValue(val);
return prev;
}
/** {@inheritDoc} */
public void set(int offset, int[] values) {
set(offset, values, 0, values.length);
}
/** {@inheritDoc} */
public void set(int offset, int[] values, int valOffset, int length) {
for (int i = 0; i < length; i++) {
int value = values[valOffset + i];
set(offset + i, value);
}
}
/** {@inheritDoc} */
public int replace(int offset, int val) {
return set(offset, val);
}
/** {@inheritDoc} */
public void clear() {
size = 0;
//
head = null;
tail = null;
}
/** {@inheritDoc} */
public boolean remove(int value) {
boolean changed = false;
for (TIntLink l = head; got(l); l = l.getNext()) {
//
if (l.getValue() == value) {
changed = true;
//
removeLink(l);
}
}
return changed;
}
/**
* unlinks the give TIntLink from the list
*
* @param l
*/
private void removeLink(TIntLink l) {
if (no(l))
return;
size--;
TIntLink prev = l.getPrevious();
TIntLink next = l.getNext();
if (got(prev)) {
prev.setNext(next);
} else {
// No previous we must be head
head = next;
}
if (got(next)) {
next.setPrevious(prev);
} else {
// No next so me must be tail
tail = prev;
}
// Unlink
l.setNext(null);
l.setPrevious(null);
}
/** {@inheritDoc} */
public boolean containsAll(Collection<?> collection) {
if (isEmpty())
return false;
for (Object o : collection) {
if (o instanceof Integer) {
Integer i = (Integer) o;
if (!(contains(i)))
return false;
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(TIntCollection collection) {
if (isEmpty())
return false;
for (TIntIterator it = collection.iterator(); it.hasNext();) {
int i = it.next();
if (!(contains(i)))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(int[] array) {
if (isEmpty())
return false;
for (int i : array) {
if (!contains(i))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean addAll(Collection<? extends Integer> collection) {
boolean ret = false;
for (Integer v : collection) {
if (add(v.intValue()))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(TIntCollection collection) {
boolean ret = false;
for (TIntIterator it = collection.iterator(); it.hasNext();) {
int i = it.next();
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(int[] array) {
boolean ret = false;
for (int i : array) {
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean retainAll(Collection<?> collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(Integer.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(TIntCollection collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(int[] array) {
Arrays.sort(array);
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) < 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(Collection<?> collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(Integer.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(TIntCollection collection) {
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(int[] array) {
Arrays.sort(array);
boolean modified = false;
TIntIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) >= 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public int removeAt(int offset) {
TIntLink l = getLinkAt(offset);
if (no(l))
throw new ArrayIndexOutOfBoundsException("no elemenet at " + offset);
int prev = l.getValue();
removeLink(l);
return prev;
}
/** {@inheritDoc} */
public void remove(int offset, int length) {
for (int i = 0; i < length; i++) {
removeAt(offset); // since the list shrinks we don't need to use offset+i to get the next entry ;)
}
}
/** {@inheritDoc} */
public void transformValues(TIntFunction function) {
for (TIntLink l = head; got(l);) {
//
l.setValue(function.execute(l.getValue()));
//
l = l.getNext();
}
}
/** {@inheritDoc} */
public void reverse() {
TIntLink h = head;
TIntLink t = tail;
TIntLink prev, next, tmp;
//
TIntLink l = head;
while (got(l)) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
//
head = t;
tail = h;
}
/** {@inheritDoc} */
public void reverse(int from, int to) {
if (from > to)
throw new IllegalArgumentException("from > to : " + from + ">" + to);
TIntLink start = getLinkAt(from);
TIntLink stop = getLinkAt(to);
TIntLink prev, next;
TIntLink tmp = null;
TIntLink tmpHead = start.getPrevious();
//
TIntLink l = start;
while (l != stop) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
// At this point l == stop and tmp is the but last element {
if (got(tmp)) {
tmpHead.setNext(tmp);
stop.setPrevious(tmpHead);
}
start.setNext(stop);
stop.setPrevious(start);
}
/** {@inheritDoc} */
public void shuffle(Random rand) {
for (int i = 0; i < size; i++) {
TIntLink l = getLinkAt(rand.nextInt(size()));
removeLink(l);
add(l.getValue());
}
}
/** {@inheritDoc} */
public TIntList subList(int begin, int end) {
if (end < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than end index " + end);
}
if (size < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than last index " + size);
}
if (begin < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (end > size) {
throw new IndexOutOfBoundsException("end index < " + size);
}
TIntLinkedList ret = new TIntLinkedList();
TIntLink tmp = getLinkAt(begin);
for (int i = begin; i < end; i++) {
ret.add(tmp.getValue()); // copy
tmp = tmp.getNext();
}
return ret;
}
/** {@inheritDoc} */
public int[] toArray() {
return toArray(new int[size], 0, size);
}
/** {@inheritDoc} */
public int[] toArray(int offset, int len) {
return toArray(new int[len], offset, 0, len);
}
/** {@inheritDoc} */
public int[] toArray(int[] dest) {
return toArray(dest, 0, size);
}
/** {@inheritDoc} */
public int[] toArray(int[] dest, int offset, int len) {
return toArray(dest, offset, 0, len);
}
/** {@inheritDoc} */
public int[] toArray(int[] dest, int source_pos, int dest_pos, int len) {
if (len == 0) {
return dest; // nothing to copy
}
if (source_pos < 0 || source_pos >= size()) {
throw new ArrayIndexOutOfBoundsException(source_pos);
}
TIntLink tmp = getLinkAt(source_pos);
for (int i = 0; i < len; i++) {
dest[dest_pos + i] = tmp.getValue(); // copy
tmp = tmp.getNext();
}
return dest;
}
/** {@inheritDoc} */
public boolean forEach(TIntProcedure procedure) {
for (TIntLink l = head; got(l); l = l.getNext()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending(TIntProcedure procedure) {
for (TIntLink l = tail; got(l); l = l.getPrevious()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public void sort() {
sort(0, size);
}
/** {@inheritDoc} */
public void sort(int fromIndex, int toIndex) {
TIntList tmp = subList(fromIndex, toIndex);
int[] vals = tmp.toArray();
Arrays.sort(vals);
set(fromIndex, vals);
}
/** {@inheritDoc} */
public void fill(int val) {
fill(0, size, val);
}
/** {@inheritDoc} */
public void fill(int fromIndex, int toIndex, int val) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
TIntLink l = getLinkAt(fromIndex);
if (toIndex > size) {
for (int i = fromIndex; i < size; i++) {
l.setValue(val);
l = l.getNext();
}
for (int i = size; i < toIndex; i++) {
add(val);
}
} else {
for (int i = fromIndex; i < toIndex; i++) {
l.setValue(val);
l = l.getNext();
}
}
}
/** {@inheritDoc} */
public int binarySearch(int value) {
return binarySearch(value, 0, size());
}
/** {@inheritDoc} */
public int binarySearch(int value, int fromIndex, int toIndex) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (toIndex > size) {
throw new IndexOutOfBoundsException("end index > size: " + toIndex + " > " + size);
}
if (toIndex < fromIndex) {
return -(fromIndex+1);
}
TIntLink middle;
int mid;
int from = fromIndex;
TIntLink fromLink = getLinkAt(fromIndex);
int to = toIndex;
while (from < to) {
mid = (from + to) >>> 1;
middle = getLink(fromLink, from, mid);
if (middle.getValue() == value)
return mid;
if (middle.getValue() < value) {
from = mid + 1;
fromLink = middle.next;
} else {
to = mid - 1;
}
}
return -(from + 1);
}
/** {@inheritDoc} */
public int indexOf(int value) {
return indexOf(0, value);
}
/** {@inheritDoc} */
public int indexOf(int offset, int value) {
int count = offset;
for (TIntLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
return count;
count++;
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf(int value) {
return lastIndexOf(0, value);
}
/** {@inheritDoc} */
public int lastIndexOf(int offset, int value) {
if (isEmpty())
return -1;
int last = -1;
int count = offset;
for (TIntLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
last = count;
count++;
}
return last;
}
/** {@inheritDoc} */
public boolean contains(int value) {
if (isEmpty())
return false;
for (TIntLink l = head; got(l); l = l.getNext()) {
if (l.getValue() == value)
return true;
}
return false;
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntIterator() {
TIntLink l = head;
TIntLink current;
public int next() {
if (no(l))
throw new NoSuchElementException();
int ret = l.getValue();
current = l;
l = l.getNext();
return ret;
}
public boolean hasNext() {
return got(l);
}
public void remove() {
if (current == null)
throw new IllegalStateException();
removeLink(current);
current = null;
}
};
}
/** {@inheritDoc} */
public TIntList grep(TIntProcedure condition) {
TIntList ret = new TIntLinkedList();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public TIntList inverseGrep(TIntProcedure condition) {
TIntList ret = new TIntLinkedList();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (!condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public int max() {
int ret = Integer.MIN_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (ret < l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public int min() {
int ret = Integer.MAX_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TIntLink l = head; got(l); l = l.getNext()) {
if (ret > l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public int sum() {
int sum = 0;
for (TIntLink l = head; got(l); l = l.getNext()) {
sum += l.getValue();
}
return sum;
}
//
//
//
static class TIntLink {
int value;
TIntLink previous;
TIntLink next;
TIntLink(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public TIntLink getPrevious() {
return previous;
}
public void setPrevious(TIntLink previous) {
this.previous = previous;
}
public TIntLink getNext() {
return next;
}
public void setNext(TIntLink next) {
this.next = next;
}
}
class RemoveProcedure implements TIntProcedure {
boolean changed = false;
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(int value) {
if (remove(value))
changed = true;
return true;
}
public boolean isChanged() {
return changed;
}
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(0);
// NO_ENTRY_VALUE
out.writeInt(no_entry_value);
// ENTRIES
out.writeInt(size);
for (TIntIterator iterator = iterator(); iterator.hasNext();) {
int next = iterator.next();
out.writeInt(next);
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
// ENTRIES
int len = in.readInt();
for (int i = 0; i < len; i++) {
add(in.readInt());
}
}
static boolean got(Object ref) {
return ref != null;
}
static boolean no(Object ref) {
return ref == null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TIntLinkedList that = (TIntLinkedList) o;
if (no_entry_value != that.no_entry_value) return false;
if (size != that.size) return false;
TIntIterator iterator = iterator();
TIntIterator thatIterator = that.iterator();
while (iterator.hasNext()) {
if (!thatIterator.hasNext())
return false;
if (iterator.next() != thatIterator.next())
return false;
}
return true;
}
@Override
public int hashCode() {
int result = HashFunctions.hash(no_entry_value);
result = 31 * result + size;
for (TIntIterator iterator = iterator(); iterator.hasNext();) {
result = 31 * result + HashFunctions.hash(iterator.next());
}
return result;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder("{");
TIntIterator it = iterator();
while (it.hasNext()) {
int next = it.next();
buf.append(next);
if (it.hasNext())
buf.append(", ");
}
buf.append("}");
return buf.toString();
}
} // TIntLinkedList
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/linked/TIntLinkedList.java | Java | asf20 | 26,971 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
// Copyright (c) 2011, Johan Parent All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.linked;
import gnu.trove.function.TLongFunction;
import gnu.trove.list.TLongList;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.TLongCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, double linked list of long primitives.
*/
public class TLongLinkedList implements TLongList, Externalizable {
long no_entry_value;
int size;
TLongLink head = null;
TLongLink tail = head;
public TLongLinkedList() {
}
public TLongLinkedList(long no_entry_value) {
this.no_entry_value = no_entry_value;
}
public TLongLinkedList(TLongList list) {
no_entry_value = list.getNoEntryValue();
//
for (TLongIterator iterator = list.iterator(); iterator.hasNext();) {
long next = iterator.next();
add(next);
}
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
/** {@inheritDoc} */
public int size() {
return size;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return size() == 0;
}
/** {@inheritDoc} */
public boolean add(long val) {
TLongLink l = new TLongLink(val);
if (no(head)) {
head = l;
tail = l;
} else {
l.setPrevious(tail);
tail.setNext(l);
//
tail = l;
}
size++;
return true;
}
/** {@inheritDoc} */
public void add(long[] vals) {
for (long val : vals) {
add(val);
}
}
/** {@inheritDoc} */
public void add(long[] vals, int offset, int length) {
for (int i = 0; i < length; i++) {
long val = vals[offset + i];
add(val);
}
}
/** {@inheritDoc} */
public void insert(int offset, long value) {
TLongLinkedList tmp = new TLongLinkedList();
tmp.add(value);
insert(offset, tmp);
}
/** {@inheritDoc} */
public void insert(int offset, long[] values) {
insert(offset, link(values, 0, values.length));
}
/** {@inheritDoc} */
public void insert(int offset, long[] values, int valOffset, int len) {
insert(offset, link(values, valOffset, len));
}
void insert(int offset, TLongLinkedList tmp) {
TLongLink l = getLinkAt(offset);
size = size + tmp.size;
//
if (l == head) {
// Add in front
tmp.tail.setNext(head);
head.setPrevious(tmp.tail);
head = tmp.head;
return;
}
if (no(l)) {
if (size == 0) {
// New empty list
head = tmp.head;
tail = tmp.tail;
} else {
// append
tail.setNext(tmp.head);
tmp.head.setPrevious(tail);
tail = tmp.tail;
}
} else {
TLongLink prev = l.getPrevious();
l.getPrevious().setNext(tmp.head);
// Link by behind tmp
tmp.tail.setNext(l);
l.setPrevious(tmp.tail);
tmp.head.setPrevious(prev);
}
}
static TLongLinkedList link(long[] values, int valOffset, int len) {
TLongLinkedList ret = new TLongLinkedList();
for (int i = 0; i < len; i++) {
ret.add(values[valOffset + i]);
}
return ret;
}
/** {@inheritDoc} */
public long get(int offset) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TLongLink l = getLinkAt(offset);
//
if (no(l))
return no_entry_value;
return l.getValue();
}
/**
* Returns the link at the given offset.
* <p/>
* A simple bisection criteria is used to keep the worst case complexity equal to
* O(n/2) where n = size(). Simply start from head of list or tail depending on offset
* and list size.
*
* @param offset of the link
* @return link or null if non-existent
*/
public TLongLink getLinkAt(int offset) {
if (offset >= size())
return null;
if (offset <= (size() >>> 1))
return getLink(head, 0, offset, true);
else
return getLink(tail, size() - 1, offset, false);
}
/**
* Returns the link at absolute offset starting from given the initial link 'l' at index 'idx'
*
* @param l
* @param idx
* @param offset
* @return
*/
private static TLongLink getLink(TLongLink l, int idx, int offset) {
return getLink(l, idx, offset, true);
}
/**
* Returns link at given absolute offset starting from link 'l' at index 'idx'
* @param l
* @param idx
* @param offset
* @param next
* @return
*/
private static TLongLink getLink(TLongLink l, int idx, int offset, boolean next) {
int i = idx;
//
while (got(l)) {
if (i == offset) {
return l;
}
i = i + (next ? 1 : -1);
l = next ? l.getNext() : l.getPrevious();
}
return null;
}
/** {@inheritDoc} */
public long set(int offset, long val) {
if (offset > size)
throw new IndexOutOfBoundsException("index " + offset + " exceeds size " + size);
TLongLink l = getLinkAt(offset);
//
if (no(l))
throw new IndexOutOfBoundsException("at offset " + offset);
long prev = l.getValue();
l.setValue(val);
return prev;
}
/** {@inheritDoc} */
public void set(int offset, long[] values) {
set(offset, values, 0, values.length);
}
/** {@inheritDoc} */
public void set(int offset, long[] values, int valOffset, int length) {
for (int i = 0; i < length; i++) {
long value = values[valOffset + i];
set(offset + i, value);
}
}
/** {@inheritDoc} */
public long replace(int offset, long val) {
return set(offset, val);
}
/** {@inheritDoc} */
public void clear() {
size = 0;
//
head = null;
tail = null;
}
/** {@inheritDoc} */
public boolean remove(long value) {
boolean changed = false;
for (TLongLink l = head; got(l); l = l.getNext()) {
//
if (l.getValue() == value) {
changed = true;
//
removeLink(l);
}
}
return changed;
}
/**
* unlinks the give TLongLink from the list
*
* @param l
*/
private void removeLink(TLongLink l) {
if (no(l))
return;
size--;
TLongLink prev = l.getPrevious();
TLongLink next = l.getNext();
if (got(prev)) {
prev.setNext(next);
} else {
// No previous we must be head
head = next;
}
if (got(next)) {
next.setPrevious(prev);
} else {
// No next so me must be tail
tail = prev;
}
// Unlink
l.setNext(null);
l.setPrevious(null);
}
/** {@inheritDoc} */
public boolean containsAll(Collection<?> collection) {
if (isEmpty())
return false;
for (Object o : collection) {
if (o instanceof Long) {
Long i = (Long) o;
if (!(contains(i)))
return false;
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(TLongCollection collection) {
if (isEmpty())
return false;
for (TLongIterator it = collection.iterator(); it.hasNext();) {
long i = it.next();
if (!(contains(i)))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll(long[] array) {
if (isEmpty())
return false;
for (long i : array) {
if (!contains(i))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean addAll(Collection<? extends Long> collection) {
boolean ret = false;
for (Long v : collection) {
if (add(v.longValue()))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(TLongCollection collection) {
boolean ret = false;
for (TLongIterator it = collection.iterator(); it.hasNext();) {
long i = it.next();
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean addAll(long[] array) {
boolean ret = false;
for (long i : array) {
if (add(i))
ret = true;
}
return ret;
}
/** {@inheritDoc} */
public boolean retainAll(Collection<?> collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(Long.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(TLongCollection collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (!collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll(long[] array) {
Arrays.sort(array);
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) < 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(Collection<?> collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(Long.valueOf(iter.next()))) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(TLongCollection collection) {
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (collection.contains(iter.next())) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean removeAll(long[] array) {
Arrays.sort(array);
boolean modified = false;
TLongIterator iter = iterator();
while (iter.hasNext()) {
if (Arrays.binarySearch(array, iter.next()) >= 0) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public long removeAt(int offset) {
TLongLink l = getLinkAt(offset);
if (no(l))
throw new ArrayIndexOutOfBoundsException("no elemenet at " + offset);
long prev = l.getValue();
removeLink(l);
return prev;
}
/** {@inheritDoc} */
public void remove(int offset, int length) {
for (int i = 0; i < length; i++) {
removeAt(offset); // since the list shrinks we don't need to use offset+i to get the next entry ;)
}
}
/** {@inheritDoc} */
public void transformValues(TLongFunction function) {
for (TLongLink l = head; got(l);) {
//
l.setValue(function.execute(l.getValue()));
//
l = l.getNext();
}
}
/** {@inheritDoc} */
public void reverse() {
TLongLink h = head;
TLongLink t = tail;
TLongLink prev, next, tmp;
//
TLongLink l = head;
while (got(l)) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
//
head = t;
tail = h;
}
/** {@inheritDoc} */
public void reverse(int from, int to) {
if (from > to)
throw new IllegalArgumentException("from > to : " + from + ">" + to);
TLongLink start = getLinkAt(from);
TLongLink stop = getLinkAt(to);
TLongLink prev, next;
TLongLink tmp = null;
TLongLink tmpHead = start.getPrevious();
//
TLongLink l = start;
while (l != stop) {
next = l.getNext();
prev = l.getPrevious();
//
tmp = l;
l = l.getNext();
//
tmp.setNext(prev);
tmp.setPrevious(next);
}
// At this point l == stop and tmp is the but last element {
if (got(tmp)) {
tmpHead.setNext(tmp);
stop.setPrevious(tmpHead);
}
start.setNext(stop);
stop.setPrevious(start);
}
/** {@inheritDoc} */
public void shuffle(Random rand) {
for (int i = 0; i < size; i++) {
TLongLink l = getLinkAt(rand.nextInt(size()));
removeLink(l);
add(l.getValue());
}
}
/** {@inheritDoc} */
public TLongList subList(int begin, int end) {
if (end < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than end index " + end);
}
if (size < begin) {
throw new IllegalArgumentException("begin index " + begin +
" greater than last index " + size);
}
if (begin < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (end > size) {
throw new IndexOutOfBoundsException("end index < " + size);
}
TLongLinkedList ret = new TLongLinkedList();
TLongLink tmp = getLinkAt(begin);
for (int i = begin; i < end; i++) {
ret.add(tmp.getValue()); // copy
tmp = tmp.getNext();
}
return ret;
}
/** {@inheritDoc} */
public long[] toArray() {
return toArray(new long[size], 0, size);
}
/** {@inheritDoc} */
public long[] toArray(int offset, int len) {
return toArray(new long[len], offset, 0, len);
}
/** {@inheritDoc} */
public long[] toArray(long[] dest) {
return toArray(dest, 0, size);
}
/** {@inheritDoc} */
public long[] toArray(long[] dest, int offset, int len) {
return toArray(dest, offset, 0, len);
}
/** {@inheritDoc} */
public long[] toArray(long[] dest, int source_pos, int dest_pos, int len) {
if (len == 0) {
return dest; // nothing to copy
}
if (source_pos < 0 || source_pos >= size()) {
throw new ArrayIndexOutOfBoundsException(source_pos);
}
TLongLink tmp = getLinkAt(source_pos);
for (int i = 0; i < len; i++) {
dest[dest_pos + i] = tmp.getValue(); // copy
tmp = tmp.getNext();
}
return dest;
}
/** {@inheritDoc} */
public boolean forEach(TLongProcedure procedure) {
for (TLongLink l = head; got(l); l = l.getNext()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending(TLongProcedure procedure) {
for (TLongLink l = tail; got(l); l = l.getPrevious()) {
if (!procedure.execute(l.getValue()))
return false;
}
return true;
}
/** {@inheritDoc} */
public void sort() {
sort(0, size);
}
/** {@inheritDoc} */
public void sort(int fromIndex, int toIndex) {
TLongList tmp = subList(fromIndex, toIndex);
long[] vals = tmp.toArray();
Arrays.sort(vals);
set(fromIndex, vals);
}
/** {@inheritDoc} */
public void fill(long val) {
fill(0, size, val);
}
/** {@inheritDoc} */
public void fill(int fromIndex, int toIndex, long val) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
TLongLink l = getLinkAt(fromIndex);
if (toIndex > size) {
for (int i = fromIndex; i < size; i++) {
l.setValue(val);
l = l.getNext();
}
for (int i = size; i < toIndex; i++) {
add(val);
}
} else {
for (int i = fromIndex; i < toIndex; i++) {
l.setValue(val);
l = l.getNext();
}
}
}
/** {@inheritDoc} */
public int binarySearch(long value) {
return binarySearch(value, 0, size());
}
/** {@inheritDoc} */
public int binarySearch(long value, int fromIndex, int toIndex) {
if (fromIndex < 0) {
throw new IndexOutOfBoundsException("begin index can not be < 0");
}
if (toIndex > size) {
throw new IndexOutOfBoundsException("end index > size: " + toIndex + " > " + size);
}
if (toIndex < fromIndex) {
return -(fromIndex+1);
}
TLongLink middle;
int mid;
int from = fromIndex;
TLongLink fromLink = getLinkAt(fromIndex);
int to = toIndex;
while (from < to) {
mid = (from + to) >>> 1;
middle = getLink(fromLink, from, mid);
if (middle.getValue() == value)
return mid;
if (middle.getValue() < value) {
from = mid + 1;
fromLink = middle.next;
} else {
to = mid - 1;
}
}
return -(from + 1);
}
/** {@inheritDoc} */
public int indexOf(long value) {
return indexOf(0, value);
}
/** {@inheritDoc} */
public int indexOf(int offset, long value) {
int count = offset;
for (TLongLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
return count;
count++;
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf(long value) {
return lastIndexOf(0, value);
}
/** {@inheritDoc} */
public int lastIndexOf(int offset, long value) {
if (isEmpty())
return -1;
int last = -1;
int count = offset;
for (TLongLink l = getLinkAt(offset); got(l.getNext()); l = l.getNext()) {
if (l.getValue() == value)
last = count;
count++;
}
return last;
}
/** {@inheritDoc} */
public boolean contains(long value) {
if (isEmpty())
return false;
for (TLongLink l = head; got(l); l = l.getNext()) {
if (l.getValue() == value)
return true;
}
return false;
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongIterator() {
TLongLink l = head;
TLongLink current;
public long next() {
if (no(l))
throw new NoSuchElementException();
long ret = l.getValue();
current = l;
l = l.getNext();
return ret;
}
public boolean hasNext() {
return got(l);
}
public void remove() {
if (current == null)
throw new IllegalStateException();
removeLink(current);
current = null;
}
};
}
/** {@inheritDoc} */
public TLongList grep(TLongProcedure condition) {
TLongList ret = new TLongLinkedList();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public TLongList inverseGrep(TLongProcedure condition) {
TLongList ret = new TLongLinkedList();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (!condition.execute(l.getValue()))
ret.add(l.getValue());
}
return ret;
}
/** {@inheritDoc} */
public long max() {
long ret = Long.MIN_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (ret < l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public long min() {
long ret = Long.MAX_VALUE;
if (isEmpty())
throw new IllegalStateException();
for (TLongLink l = head; got(l); l = l.getNext()) {
if (ret > l.getValue())
ret = l.getValue();
}
return ret;
}
/** {@inheritDoc} */
public long sum() {
long sum = 0;
for (TLongLink l = head; got(l); l = l.getNext()) {
sum += l.getValue();
}
return sum;
}
//
//
//
static class TLongLink {
long value;
TLongLink previous;
TLongLink next;
TLongLink(long value) {
this.value = value;
}
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
public TLongLink getPrevious() {
return previous;
}
public void setPrevious(TLongLink previous) {
this.previous = previous;
}
public TLongLink getNext() {
return next;
}
public void setNext(TLongLink next) {
this.next = next;
}
}
class RemoveProcedure implements TLongProcedure {
boolean changed = false;
/**
* Executes this procedure. A false return value indicates that
* the application executing this procedure should not invoke this
* procedure again.
*
* @param value a value of type <code>int</code>
* @return true if additional invocations of the procedure are
* allowed.
*/
public boolean execute(long value) {
if (remove(value))
changed = true;
return true;
}
public boolean isChanged() {
return changed;
}
}
/** {@inheritDoc} */
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(0);
// NO_ENTRY_VALUE
out.writeLong(no_entry_value);
// ENTRIES
out.writeInt(size);
for (TLongIterator iterator = iterator(); iterator.hasNext();) {
long next = iterator.next();
out.writeLong(next);
}
}
/** {@inheritDoc} */
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
// ENTRIES
int len = in.readInt();
for (int i = 0; i < len; i++) {
add(in.readLong());
}
}
static boolean got(Object ref) {
return ref != null;
}
static boolean no(Object ref) {
return ref == null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TLongLinkedList that = (TLongLinkedList) o;
if (no_entry_value != that.no_entry_value) return false;
if (size != that.size) return false;
TLongIterator iterator = iterator();
TLongIterator thatIterator = that.iterator();
while (iterator.hasNext()) {
if (!thatIterator.hasNext())
return false;
if (iterator.next() != thatIterator.next())
return false;
}
return true;
}
@Override
public int hashCode() {
int result = HashFunctions.hash(no_entry_value);
result = 31 * result + size;
for (TLongIterator iterator = iterator(); iterator.hasNext();) {
result = 31 * result + HashFunctions.hash(iterator.next());
}
return result;
}
@Override
public String toString() {
final StringBuilder buf = new StringBuilder("{");
TLongIterator it = iterator();
while (it.hasNext()) {
long next = it.next();
buf.append(next);
if (it.hasNext())
buf.append(", ");
}
buf.append("}");
return buf.toString();
}
} // TLongLinkedList
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/linked/TLongLinkedList.java | Java | asf20 | 27,130 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.linked;
import gnu.trove.list.TLinkable;
import gnu.trove.procedure.TObjectProcedure;
import java.io.*;
import java.util.AbstractSequentialList;
import java.util.ListIterator;
import java.util.NoSuchElementException;
import java.lang.reflect.Array;
/**
* <p>A LinkedList implementation which holds instances of type
* <tt>TLinkable</tt>.
* <p/>
* Using this implementation allows you to get java.util.LinkedList
* behavior (a doubly linked list, with Iterators that support insert
* and delete operations) without incurring the overhead of creating
* <tt>Node</tt> wrapper objects for every element in your list.
* <p/>
* The requirement to achieve this time/space gain is that the
* Objects stored in the List implement the <tt>TLinkable</tt>
* interface.
* <p/>
* The limitations are: <ul>
* <li>the same object cannot be put into more than one list at the same time.
* <li>the same object cannot be put into the same list more than once at the same time.
* <li>objects must only be removed from list they are in. That is,
* if you have an object A and lists l1 and l2, you must ensure that
* you invoke List.remove(A) on the correct list.
* <li> It is also forbidden to invoke List.remove() with an unaffiliated
* TLinkable (one that belongs to no list): this will destroy the list
* you invoke it on.
* </ul>
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: TLinkedList.java,v 1.1.2.3 2010/09/27 17:23:07 robeden Exp $
* @see gnu.trove.list.TLinkable
*/
public class TLinkedList<T extends TLinkable<T>> extends AbstractSequentialList<T>
implements Externalizable {
static final long serialVersionUID = 1L;
/** the head of the list */
protected T _head;
/** the tail of the list */
protected T _tail;
/** the number of elements in the list */
protected int _size = 0;
/** Creates a new <code>TLinkedList</code> instance. */
public TLinkedList() {
super();
}
/**
* Returns an iterator positioned at <tt>index</tt>. Assuming
* that the list has a value at that index, calling next() will
* retrieve and advance the iterator. Assuming that there is a
* value before <tt>index</tt> in the list, calling previous()
* will retrieve it (the value at index - 1) and move the iterator
* to that position. So, iterating from front to back starts at
* 0; iterating from back to front starts at <tt>size()</tt>.
*
* @param index an <code>int</code> value
* @return a <code>ListIterator</code> value
*/
public ListIterator<T> listIterator( int index ) {
return new IteratorImpl( index );
}
/**
* Returns the number of elements in the list.
*
* @return an <code>int</code> value
*/
public int size() {
return _size;
}
/**
* Inserts <tt>linkable</tt> at index <tt>index</tt> in the list.
* All values > index are shifted over one position to accommodate
* the new addition.
*
* @param index an <code>int</code> value
* @param linkable an object of type TLinkable
*/
public void add( int index, T linkable ) {
if ( index < 0 || index > size() ) {
throw new IndexOutOfBoundsException( "index:" + index );
}
insert( index, linkable );
}
/**
* Appends <tt>linkable</tt> to the end of the list.
*
* @param linkable an object of type TLinkable
* @return always true
*/
public boolean add( T linkable ) {
insert( _size, linkable );
return true;
}
/**
* Inserts <tt>linkable</tt> at the head of the list.
*
* @param linkable an object of type TLinkable
*/
public void addFirst( T linkable ) {
insert( 0, linkable );
}
/**
* Adds <tt>linkable</tt> to the end of the list.
*
* @param linkable an object of type TLinkable
*/
public void addLast( T linkable ) {
insert( size(), linkable );
}
/** Empties the list. */
public void clear() {
if ( null != _head ) {
for ( TLinkable<T> link = _head.getNext();
link != null;
link = link.getNext() ) {
TLinkable<T> prev = link.getPrevious();
prev.setNext( null );
link.setPrevious( null );
}
_head = _tail = null;
}
_size = 0;
}
/**
* Copies the list's contents into a native array. This will be a
* shallow copy: the Tlinkable instances in the Object[] array
* have links to one another: changing those will put this list
* into an unpredictable state. Holding a reference to one
* element in the list will prevent the others from being garbage
* collected unless you clear the next/previous links. <b>Caveat
* programmer!</b>
*
* @return an <code>Object[]</code> value
*/
public Object[] toArray() {
Object[] o = new Object[_size];
int i = 0;
for ( TLinkable link = _head; link != null; link = link.getNext() ) {
o[i++] = link;
}
return o;
}
/**
* Copies the list to a native array, destroying the next/previous
* links as the copy is made. This list will be emptied after the
* copy (as if clear() had been invoked). The Object[] array
* returned will contain TLinkables that do <b>not</b> hold
* references to one another and so are less likely to be the
* cause of memory leaks.
*
* @return an <code>Object[]</code> value
*/
public Object[] toUnlinkedArray() {
Object[] o = new Object[_size];
int i = 0;
for ( TLinkable<T> link = _head, tmp; link != null; i++ ) {
o[i] = link;
tmp = link;
link = link.getNext();
tmp.setNext( null ); // clear the links
tmp.setPrevious( null );
}
_size = 0; // clear the list
_head = _tail = null;
return o;
}
/**
* Returns a typed array of the objects in the set.
*
* @param a an <code>Object[]</code> value
* @return an <code>Object[]</code> value
*/
@SuppressWarnings({"unchecked"})
public T[] toUnlinkedArray( T[] a ) {
int size = size();
if ( a.length < size ) {
a = (T[]) Array.newInstance( a.getClass().getComponentType(), size );
}
int i = 0;
for ( T link = _head, tmp; link != null; i++ ) {
a[i] = link;
tmp = link;
link = link.getNext();
tmp.setNext( null ); // clear the links
tmp.setPrevious( null );
}
_size = 0; // clear the list
_head = _tail = null;
return a;
}
/**
* A linear search for <tt>o</tt> in the list.
*
* @param o an <code>Object</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( Object o ) {
for ( TLinkable<T> link = _head; link != null; link = link.getNext() ) {
if ( o.equals( link ) ) {
return true;
}
}
return false;
}
/** {@inheritDoc} */
@Override
@SuppressWarnings({"unchecked"})
public T get( int index ) {
// Blow out for bogus values
if ( index < 0 || index >= _size ) {
throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + _size );
}
// Determine if it's better to get there from the front or the back
if ( index > ( _size >> 1 ) ) {
int position = _size - 1;
T node = _tail;
while ( position > index ) {
node = node.getPrevious();
position--;
}
return node;
} else {
int position = 0;
T node = _head;
while ( position < index ) {
node = node.getNext();
position++;
}
return node;
}
}
/**
* Returns the head of the list
*
* @return an <code>Object</code> value
*/
public T getFirst() {
return _head;
}
/**
* Returns the tail of the list.
*
* @return an <code>Object</code> value
*/
public T getLast() {
return _tail;
}
/**
* Return the node following the given node. This method exists for two reasons:
* <ol>
* <li>It's really not recommended that the methods implemented by TLinkable be
* called directly since they're used internally by this class.</li>
* <li>This solves problems arising from generics when working with the linked
* objects directly.</li>
* </ol>
* <p/>
* NOTE: this should only be used with nodes contained in the list. The results are
* undefined with anything else.
*
* @param current The current node
* @return the node after the current node
*/
@SuppressWarnings({"unchecked"})
public T getNext( T current ) {
return current.getNext();
}
/**
* Return the node preceding the given node. This method exists for two reasons:
* <ol>
* <li>It's really not recommended that the methods implemented by TLinkable be
* called directly since they're used internally by this class.</li>
* <li>This solves problems arising from generics when working with the linked
* objects directly.</li>
* </ol>
* <p/>
* NOTE: this should only be used with nodes contained in the list. The results are
* undefined with anything else.
*
* @param current The current node
* @return the node after the current node
*/
@SuppressWarnings({"unchecked"})
public T getPrevious( T current ) {
return current.getPrevious();
}
/**
* Remove and return the first element in the list.
*
* @return an <code>Object</code> value
*/
@SuppressWarnings({"unchecked"})
public T removeFirst() {
T o = _head;
if ( o == null ) {
return null;
}
T n = o.getNext();
o.setNext( null );
if ( null != n ) {
n.setPrevious( null );
}
_head = n;
if ( --_size == 0 ) {
_tail = null;
}
return o;
}
/**
* Remove and return the last element in the list.
*
* @return an <code>Object</code> value
*/
@SuppressWarnings({"unchecked"})
public T removeLast() {
T o = _tail;
if ( o == null ) {
return null;
}
T prev = o.getPrevious();
o.setPrevious( null );
if ( null != prev ) {
prev.setNext( null );
}
_tail = prev;
if ( --_size == 0 ) {
_head = null;
}
return o;
}
/**
* Implementation of index-based list insertions.
*
* @param index an <code>int</code> value
* @param linkable an object of type TLinkable
*/
@SuppressWarnings({"unchecked"})
protected void insert( int index, T linkable ) {
if ( _size == 0 ) {
_head = _tail = linkable; // first insertion
} else if ( index == 0 ) {
linkable.setNext( _head ); // insert at front
_head.setPrevious( linkable );
_head = linkable;
} else if ( index == _size ) { // insert at back
_tail.setNext( linkable );
linkable.setPrevious( _tail );
_tail = linkable;
} else {
T node = get( index );
T before = node.getPrevious();
if ( before != null ) {
before.setNext( linkable );
}
linkable.setPrevious( before );
linkable.setNext( node );
node.setPrevious( linkable );
}
_size++;
}
/**
* Removes the specified element from the list. Note that
* it is the caller's responsibility to ensure that the
* element does, in fact, belong to this list and not another
* instance of TLinkedList.
*
* @param o a TLinkable element already inserted in this list.
* @return true if the element was a TLinkable and removed
*/
@SuppressWarnings({"unchecked"})
public boolean remove( Object o ) {
if ( o instanceof TLinkable ) {
T p, n;
TLinkable<T> link = (TLinkable<T>) o;
p = link.getPrevious();
n = link.getNext();
if ( n == null && p == null ) { // emptying the list
// It's possible this object is not something that's in the list. So,
// make sure it's the head if it doesn't point to anything. This solves
// problems caused by removing something multiple times.
if ( o != _head ) {
return false;
}
_head = _tail = null;
} else if ( n == null ) { // this is the tail
// make previous the new tail
link.setPrevious( null );
p.setNext( null );
_tail = p;
} else if ( p == null ) { // this is the head
// make next the new head
link.setNext( null );
n.setPrevious( null );
_head = n;
} else { // somewhere in the middle
p.setNext( n );
n.setPrevious( p );
link.setNext( null );
link.setPrevious( null );
}
_size--; // reduce size of list
return true;
} else {
return false;
}
}
/**
* Inserts newElement into the list immediately before current.
* All elements to the right of and including current are shifted
* over.
*
* @param current a <code>TLinkable</code> value currently in the list.
* @param newElement a <code>TLinkable</code> value to be added to
* the list.
*/
public void addBefore( T current, T newElement ) {
if ( current == _head ) {
addFirst( newElement );
} else if ( current == null ) {
addLast( newElement );
} else {
T p = current.getPrevious();
newElement.setNext( current );
p.setNext( newElement );
newElement.setPrevious( p );
current.setPrevious( newElement );
_size++;
}
}
/**
* Inserts newElement into the list immediately after current.
* All elements to the left of and including current are shifted
* over.
*
* @param current a <code>TLinkable</code> value currently in the list.
* @param newElement a <code>TLinkable</code> value to be added to
* the list.
*/
public void addAfter( T current, T newElement ) {
if ( current == _tail ) {
addLast( newElement );
} else if ( current == null ) {
addFirst( newElement );
} else {
T n = current.getNext();
newElement.setPrevious( current );
newElement.setNext( n );
current.setNext( newElement );
n.setPrevious( newElement );
_size++;
}
}
/**
* Executes <tt>procedure</tt> for each entry in the list.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the values terminated because
* the procedure returned false for some value.
*/
@SuppressWarnings({"unchecked"})
public boolean forEachValue( TObjectProcedure<T> procedure ) {
T node = _head;
while ( node != null ) {
boolean keep_going = procedure.execute( node );
if ( !keep_going ) {
return false;
}
node = node.getNext();
}
return true;
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// NUMBER OF ENTRIES
out.writeInt( _size );
// HEAD
out.writeObject( _head );
// TAIL
out.writeObject( _tail );
}
@SuppressWarnings({"unchecked"})
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// NUMBER OF ENTRIED
_size = in.readInt();
// HEAD
_head = (T) in.readObject();
// TAIL
_tail = (T) in.readObject();
}
/** A ListIterator that supports additions and deletions. */
protected final class IteratorImpl implements ListIterator<T> {
private int _nextIndex = 0;
private T _next;
private T _lastReturned;
/**
* Creates a new <code>Iterator</code> instance positioned at
* <tt>index</tt>.
*
* @param position an <code>int</code> value
*/
@SuppressWarnings({"unchecked"})
IteratorImpl( int position ) {
if ( position < 0 || position > _size ) {
throw new IndexOutOfBoundsException();
}
_nextIndex = position;
if ( position == 0 ) {
_next = _head;
} else if ( position == _size ) {
_next = null;
} else if ( position < ( _size >> 1 ) ) {
int pos = 0;
for ( _next = _head; pos < position; pos++ ) {
_next = _next.getNext();
}
} else {
int pos = _size - 1;
for ( _next = _tail; pos > position; pos-- ) {
_next = _next.getPrevious();
}
}
}
/**
* Insert <tt>linkable</tt> at the current position of the iterator.
* Calling next() after add() will return the added object.
*
* @param linkable an object of type TLinkable
*/
public final void add( T linkable ) {
_lastReturned = null;
_nextIndex++;
if ( _size == 0 ) {
TLinkedList.this.add( linkable );
} else {
TLinkedList.this.addBefore( _next, linkable );
}
}
/**
* True if a call to next() will return an object.
*
* @return a <code>boolean</code> value
*/
public final boolean hasNext() {
return _nextIndex != _size;
}
/**
* True if a call to previous() will return a value.
*
* @return a <code>boolean</code> value
*/
public final boolean hasPrevious() {
return _nextIndex != 0;
}
/**
* Returns the value at the Iterator's index and advances the
* iterator.
*
* @return an <code>Object</code> value
* @throws NoSuchElementException if there is no next element
*/
@SuppressWarnings({"unchecked"})
public final T next() {
if ( _nextIndex == _size ) {
throw new NoSuchElementException();
}
_lastReturned = _next;
_next = _next.getNext();
_nextIndex++;
return _lastReturned;
}
/**
* returns the index of the next node in the list (the
* one that would be returned by a call to next()).
*
* @return an <code>int</code> value
*/
public final int nextIndex() {
return _nextIndex;
}
/**
* Returns the value before the Iterator's index and moves the
* iterator back one index.
*
* @return an <code>Object</code> value
* @throws NoSuchElementException if there is no previous element.
*/
@SuppressWarnings({"unchecked"})
public final T previous() {
if ( _nextIndex == 0 ) {
throw new NoSuchElementException();
}
if ( _nextIndex == _size ) {
_lastReturned = _next = _tail;
} else {
_lastReturned = _next = _next.getPrevious();
}
_nextIndex--;
return _lastReturned;
}
/**
* Returns the previous element's index.
*
* @return an <code>int</code> value
*/
public final int previousIndex() {
return _nextIndex - 1;
}
/**
* Removes the current element in the list and shrinks its
* size accordingly.
*
* @throws IllegalStateException neither next nor previous
* have been invoked, or remove or add have been invoked after
* the last invocation of next or previous.
*/
@SuppressWarnings({"unchecked"})
public final void remove() {
if ( _lastReturned == null ) {
throw new IllegalStateException( "must invoke next or previous before invoking remove" );
}
if ( _lastReturned != _next ) {
_nextIndex--;
}
_next = _lastReturned.getNext();
TLinkedList.this.remove( _lastReturned );
_lastReturned = null;
}
/**
* Replaces the current element in the list with
* <tt>linkable</tt>
*
* @param linkable an object of type TLinkable
*/
public final void set( T linkable ) {
if ( _lastReturned == null ) {
throw new IllegalStateException();
}
swap( _lastReturned, linkable );
_lastReturned = linkable;
}
/**
* Replace from with to in the list.
*
* @param from a <code>TLinkable</code> value
* @param to a <code>TLinkable</code> value
*/
private void swap( T from, T to ) {
T from_p = from.getPrevious();
T from_n = from.getNext();
T to_p = to.getPrevious();
T to_n = to.getNext();
// NOTE: 'to' cannot be null at this point
if ( from_n == to ) {
if ( from_p != null ) from_p.setNext( to );
to.setPrevious( from_p );
to.setNext( from );
from.setPrevious( to );
from.setNext( to_n );
if ( to_n != null ) to_n.setPrevious( from );
}
// NOTE: 'from' cannot be null at this point
else if ( to_n == from ) {
if ( to_p != null ) to_p.setNext( to );
to.setPrevious( from );
to.setNext( from_n );
from.setPrevious( to_p );
from.setNext( to );
if ( from_n != null ) from_n.setPrevious( to );
}
else {
from.setNext( to_n );
from.setPrevious( to_p );
if ( to_p != null ) to_p.setNext( from );
if ( to_n != null ) to_n.setPrevious( from );
to.setNext( from_n );
to.setPrevious( from_p );
if ( from_p != null ) from_p.setNext( to );
if ( from_n != null ) from_n.setPrevious( to );
}
if ( _head == from ) _head = to;
else if ( _head == to ) _head = from;
if ( _tail == from ) _tail = to;
else if ( _tail == to ) _tail = from;
if ( _lastReturned == from ) _lastReturned = to;
else if ( _lastReturned == to ) _lastReturned = from;
if ( _next == from ) _next = to;
else if ( _next == to ) _next = from;
}
}
} // TLinkedList
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/linked/TLinkedList.java | Java | asf20 | 25,873 |
package gnu.trove.list;
/**
* Simple adapter class implementing {@link TLinkable}, so you don't have to. Example:
* <pre>
private class MyObject extends TLinkableAdapter<MyObject> {
private final String value;
MyObject( String value ) {
this.value = value;
}
public String getValue() {
return value;
}
}
* </pre>
*/
public abstract class TLinkableAdapter<T extends TLinkable> implements TLinkable<T> {
private volatile T next;
private volatile T prev;
@Override
public T getNext() {
return next;
}
@Override
public void setNext( T next ) {
this.next = next;
}
@Override
public T getPrevious() {
return prev;
}
@Override
public void setPrevious( T prev ) {
this.prev = prev;
}
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/TLinkableAdapter.java | Java | asf20 | 731 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.procedure.*;
import gnu.trove.TIntCollection;
import java.io.Serializable;
import java.util.Random;
/**
* Interface for Trove list implementations.
*/
public interface TIntList extends TIntCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue();
/**
* Returns the number of values in the list.
*
* @return the number of values in the list.
*/
public int size();
/**
* Tests whether this list contains any values.
*
* @return true if the list is empty.
*/
public boolean isEmpty();
/**
* Adds <tt>val</tt> to the end of the list, growing as needed.
*
* @param val an <code>int</code> value
* @return true if the list was modified by the add operation
*/
public boolean add(int val);
/**
* Adds the values in the array <tt>vals</tt> to the end of the
* list, in order.
*
* @param vals an <code>int[]</code> value
*/
public void add( int[] vals );
/**
* Adds a subset of the values in the array <tt>vals</tt> to the
* end of the list, in order.
*
* @param vals an <code>int[]</code> value
* @param offset the offset at which to start copying
* @param length the number of values to copy.
*/
public void add( int[] vals, int offset, int length );
/**
* Inserts <tt>value</tt> into the list at <tt>offset</tt>. All
* values including and to the right of <tt>offset</tt> are shifted
* to the right.
*
* @param offset an <code>int</code> value
* @param value an <code>int</code> value
*/
public void insert( int offset, int value );
/**
* Inserts the array of <tt>values</tt> into the list at
* <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>int[]</code> value
*/
public void insert( int offset, int[] values );
/**
* Inserts a slice of the array of <tt>values</tt> into the list
* at <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>int[]</code> value
* @param valOffset the offset in the values array at which to
* start copying.
* @param len the number of values to copy from the values array
*/
public void insert( int offset, int[] values, int valOffset, int len );
/**
* Returns the value at the specified offset.
*
* @param offset an <code>int</code> value
* @return an <code>int</code> value
*/
public int get( int offset );
/**
* Sets the value at the specified offset.
*
* @param offset an <code>int</code> value
* @param val an <code>int</code> value
*
* @return The value previously at the given index.
*/
public int set( int offset, int val );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* the contents of the <tt>values</tt> array.
*
* @param offset the first offset to replace
* @param values the source of the new values
*/
public void set( int offset, int[] values );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* <tt>length</tt> values from the <tt>values</tt> array, starting
* at valOffset.
*
* @param offset the first offset to replace
* @param values the source of the new values
* @param valOffset the first value to copy from the values array
* @param length the number of values to copy
*/
public void set( int offset, int[] values, int valOffset, int length );
/**
* Sets the value at the specified offset and returns the
* previously stored value.
*
* @param offset an <code>int</code> value
* @param val an <code>int</code> value
* @return the value previously stored at offset.
*/
public int replace( int offset, int val );
/**
* Flushes the internal state of the list, resetting the capacity
* to the default.
*/
public void clear();
/**
* Removes <tt>value</tt> from the list.
*
* @param value an <code>int</code> value
* @return true if the list was modified by the remove operation.
*/
public boolean remove( int value );
/**
* Removes <tt>value</tt> at a given offset from the list.
*
* @param offset an <code>int</code> value that represents
* the offset to the element to be removed
* @return an <tt>int</tt> that is the value removed.
*/
public int removeAt( int offset );
/**
* Removes <tt>length</tt> values from the list, starting at
* <tt>offset</tt>
*
* @param offset an <code>int</code> value
* @param length an <code>int</code> value
*/
public void remove( int offset, int length );
/**
* Transform each value in the list using the specified function.
*
* @param function a <code>TIntFunction</code> value
*/
public void transformValues( TIntFunction function );
/**
* Reverse the order of the elements in the list.
*/
public void reverse();
/**
* Reverse the order of the elements in the range of the list.
*
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
public void reverse( int from, int to );
/**
* Shuffle the elements of the list using the specified random
* number generator.
*
* @param rand a <code>Random</code> value
*/
public void shuffle( Random rand );
/**
* Returns a sublist of this list.
*
* @param begin low endpoint (inclusive) of the subList.
* @param end high endpoint (exclusive) of the subList.
* @return sublist of this list from begin, inclusive to end, exclusive.
* @throws IndexOutOfBoundsException - endpoint out of range
* @throws IllegalArgumentException - endpoints out of order (end > begin)
*/
public TIntList subList( int begin, int end );
/**
* Copies the contents of the list into a native array.
*
* @return an <code>int[]</code> value
*/
public int[] toArray();
/**
* Copies a slice of the list into a native array.
*
* @param offset the offset at which to start copying
* @param len the number of values to copy.
* @return an <code>int[]</code> value
*/
public int[] toArray( int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to
* <tt>{@link #getNoEntryValue()}</tt>.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any "null" elements.)
*
* <p>NOTE: Trove does not allocate a new array if the array passed in is
* not large enough to hold all of the data elements. It will instead fill
* the array passed in.
*
* @param dest the array to copy into.
* @return the array passed in.
*/
public int[] toArray( int[] dest );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param offset the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public int[] toArray( int[] dest, int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param source_pos the offset of the first value to copy
* @param dest_pos the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public int[] toArray( int[] dest, int source_pos, int dest_pos, int len );
/**
* Applies the procedure to each value in the list in ascending
* (front to back) order.
*
* @param procedure a <code>TIntProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEach( TIntProcedure procedure );
/**
* Applies the procedure to each value in the list in descending
* (back to front) order.
*
* @param procedure a <code>TIntProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEachDescending( TIntProcedure procedure );
/**
* Sort the values in the list (ascending) using the Sun quicksort
* implementation.
*
* @see java.util.Arrays#sort
*/
public void sort();
/**
* Sort a slice of the list (ascending) using the Sun quicksort
* implementation.
*
* @param fromIndex the index at which to start sorting (inclusive)
* @param toIndex the index at which to stop sorting (exclusive)
* @see java.util.Arrays#sort
*/
public void sort( int fromIndex, int toIndex );
/**
* Fills every slot in the list with the specified value.
*
* @param val the value to use when filling
*/
public void fill( int val );
/**
* Fills a range in the list with the specified value.
*
* @param fromIndex the offset at which to start filling (inclusive)
* @param toIndex the offset at which to stop filling (exclusive)
* @param val the value to use when filling
*/
public void fill( int fromIndex, int toIndex, int val );
/**
* Performs a binary search for <tt>value</tt> in the entire list.
* Note that you <b>must</b> @{link #sort sort} the list before
* doing a search.
*
* @param value the value to search for
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( int value );
/**
* Performs a binary search for <tt>value</tt> in the specified
* range. Note that you <b>must</b> @{link #sort sort} the list
* or the range before doing a search.
*
* @param value the value to search for
* @param fromIndex the lower boundary of the range (inclusive)
* @param toIndex the upper boundary of the range (exclusive)
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( int value, int fromIndex, int toIndex );
/**
* Searches the list front to back for the index of
* <tt>value</tt>.
*
* @param value an <code>int</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( int value );
/**
* Searches the list front to back for the index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (inclusive)
* @param value an <code>int</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( int offset, int value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>.
*
* @param value an <code>int</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( int value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (exclusive)
* @param value an <code>int</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( int offset, int value );
/**
* Searches the list for <tt>value</tt>
*
* @param value an <code>int</code> value
* @return true if value is in the list.
*/
public boolean contains( int value );
/**
* Searches the list for values satisfying <tt>condition</tt> in
* the manner of the *nix <tt>grep</tt> utility.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which match the condition.
*/
public TIntList grep( TIntProcedure condition );
/**
* Searches the list for values which do <b>not</b> satisfy
* <tt>condition</tt>. This is akin to *nix <code>grep -v</code>.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which do not match the condition.
*/
public TIntList inverseGrep( TIntProcedure condition );
/**
* Finds the maximum value in the list.
*
* @return the largest value in the list.
* @exception IllegalStateException if the list is empty
*/
public int max();
/**
* Finds the minimum value in the list.
*
* @return the smallest value in the list.
* @exception IllegalStateException if the list is empty
*/
public int min();
/**
* Calculates the sum of all the values in the list.
*
* @return the sum of the values in the list (zero if the list is empty).
*/
public int sum();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/TIntList.java | Java | asf20 | 15,413 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list;
import java.io.Serializable;
/**
* Interface for Objects which can be inserted into a TLinkedList.
*
* @author Eric D. Friedman
* @version $Id: TLinkable.java,v 1.1.2.2 2009/09/04 12:32:33 upholderoftruth Exp $
* @see gnu.trove.list.linked.TLinkedList
*/
public interface TLinkable<T extends TLinkable> extends Serializable {
static final long serialVersionUID = 997545054865482562L;
/**
* Returns the linked list node after this one.
*
* @return a <code>TLinkable</code> value
*/
public T getNext();
/**
* Returns the linked list node before this one.
*
* @return a <code>TLinkable</code> value
*/
public T getPrevious();
/**
* Sets the linked list node after this one.
*
* @param linkable a <code>TLinkable</code> value
*/
public void setNext( T linkable );
/**
* Sets the linked list node before this one.
*
* @param linkable a <code>TLinkable</code> value
*/
public void setPrevious( T linkable );
}// TLinkable
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/TLinkable.java | Java | asf20 | 2,093 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.function.*;
import gnu.trove.procedure.*;
import gnu.trove.TLongCollection;
import java.io.Serializable;
import java.util.Random;
/**
* Interface for Trove list implementations.
*/
public interface TLongList extends TLongCollection {
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue();
/**
* Returns the number of values in the list.
*
* @return the number of values in the list.
*/
public int size();
/**
* Tests whether this list contains any values.
*
* @return true if the list is empty.
*/
public boolean isEmpty();
/**
* Adds <tt>val</tt> to the end of the list, growing as needed.
*
* @param val an <code>long</code> value
* @return true if the list was modified by the add operation
*/
public boolean add(long val);
/**
* Adds the values in the array <tt>vals</tt> to the end of the
* list, in order.
*
* @param vals an <code>long[]</code> value
*/
public void add( long[] vals );
/**
* Adds a subset of the values in the array <tt>vals</tt> to the
* end of the list, in order.
*
* @param vals an <code>long[]</code> value
* @param offset the offset at which to start copying
* @param length the number of values to copy.
*/
public void add( long[] vals, int offset, int length );
/**
* Inserts <tt>value</tt> into the list at <tt>offset</tt>. All
* values including and to the right of <tt>offset</tt> are shifted
* to the right.
*
* @param offset an <code>int</code> value
* @param value an <code>long</code> value
*/
public void insert( int offset, long value );
/**
* Inserts the array of <tt>values</tt> into the list at
* <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>long[]</code> value
*/
public void insert( int offset, long[] values );
/**
* Inserts a slice of the array of <tt>values</tt> into the list
* at <tt>offset</tt>. All values including and to the right of
* <tt>offset</tt> are shifted to the right.
*
* @param offset an <code>int</code> value
* @param values an <code>long[]</code> value
* @param valOffset the offset in the values array at which to
* start copying.
* @param len the number of values to copy from the values array
*/
public void insert( int offset, long[] values, int valOffset, int len );
/**
* Returns the value at the specified offset.
*
* @param offset an <code>int</code> value
* @return an <code>long</code> value
*/
public long get( int offset );
/**
* Sets the value at the specified offset.
*
* @param offset an <code>int</code> value
* @param val an <code>long</code> value
*
* @return The value previously at the given index.
*/
public long set( int offset, long val );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* the contents of the <tt>values</tt> array.
*
* @param offset the first offset to replace
* @param values the source of the new values
*/
public void set( int offset, long[] values );
/**
* Replace the values in the list starting at <tt>offset</tt> with
* <tt>length</tt> values from the <tt>values</tt> array, starting
* at valOffset.
*
* @param offset the first offset to replace
* @param values the source of the new values
* @param valOffset the first value to copy from the values array
* @param length the number of values to copy
*/
public void set( int offset, long[] values, int valOffset, int length );
/**
* Sets the value at the specified offset and returns the
* previously stored value.
*
* @param offset an <code>int</code> value
* @param val an <code>long</code> value
* @return the value previously stored at offset.
*/
public long replace( int offset, long val );
/**
* Flushes the internal state of the list, resetting the capacity
* to the default.
*/
public void clear();
/**
* Removes <tt>value</tt> from the list.
*
* @param value an <code>long</code> value
* @return true if the list was modified by the remove operation.
*/
public boolean remove( long value );
/**
* Removes <tt>value</tt> at a given offset from the list.
*
* @param offset an <code>int</code> value that represents
* the offset to the element to be removed
* @return an <tt>long</tt> that is the value removed.
*/
public long removeAt( int offset );
/**
* Removes <tt>length</tt> values from the list, starting at
* <tt>offset</tt>
*
* @param offset an <code>int</code> value
* @param length an <code>int</code> value
*/
public void remove( int offset, int length );
/**
* Transform each value in the list using the specified function.
*
* @param function a <code>TLongFunction</code> value
*/
public void transformValues( TLongFunction function );
/**
* Reverse the order of the elements in the list.
*/
public void reverse();
/**
* Reverse the order of the elements in the range of the list.
*
* @param from the inclusive index at which to start reversing
* @param to the exclusive index at which to stop reversing
*/
public void reverse( int from, int to );
/**
* Shuffle the elements of the list using the specified random
* number generator.
*
* @param rand a <code>Random</code> value
*/
public void shuffle( Random rand );
/**
* Returns a sublist of this list.
*
* @param begin low endpoint (inclusive) of the subList.
* @param end high endpoint (exclusive) of the subList.
* @return sublist of this list from begin, inclusive to end, exclusive.
* @throws IndexOutOfBoundsException - endpoint out of range
* @throws IllegalArgumentException - endpoints out of order (end > begin)
*/
public TLongList subList( int begin, int end );
/**
* Copies the contents of the list into a native array.
*
* @return an <code>long[]</code> value
*/
public long[] toArray();
/**
* Copies a slice of the list into a native array.
*
* @param offset the offset at which to start copying
* @param len the number of values to copy.
* @return an <code>long[]</code> value
*/
public long[] toArray( int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* <p>If the list fits in the specified array with room to spare (i.e.,
* the array has more elements than the list), the element in the array
* immediately following the end of the list is set to
* <tt>{@link #getNoEntryValue()}</tt>.
* (This is useful in determining the length of the list <i>only</i> if
* the caller knows that the list does not contain any "null" elements.)
*
* <p>NOTE: Trove does not allocate a new array if the array passed in is
* not large enough to hold all of the data elements. It will instead fill
* the array passed in.
*
* @param dest the array to copy into.
* @return the array passed in.
*/
public long[] toArray( long[] dest );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param offset the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public long[] toArray( long[] dest, int offset, int len );
/**
* Copies a slice of the list into a native array.
*
* @param dest the array to copy into.
* @param source_pos the offset of the first value to copy
* @param dest_pos the offset where the first value should be copied
* @param len the number of values to copy.
* @return the array passed in.
*/
public long[] toArray( long[] dest, int source_pos, int dest_pos, int len );
/**
* Applies the procedure to each value in the list in ascending
* (front to back) order.
*
* @param procedure a <code>TLongProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEach( TLongProcedure procedure );
/**
* Applies the procedure to each value in the list in descending
* (back to front) order.
*
* @param procedure a <code>TLongProcedure</code> value
* @return true if the procedure did not terminate prematurely.
*/
public boolean forEachDescending( TLongProcedure procedure );
/**
* Sort the values in the list (ascending) using the Sun quicksort
* implementation.
*
* @see java.util.Arrays#sort
*/
public void sort();
/**
* Sort a slice of the list (ascending) using the Sun quicksort
* implementation.
*
* @param fromIndex the index at which to start sorting (inclusive)
* @param toIndex the index at which to stop sorting (exclusive)
* @see java.util.Arrays#sort
*/
public void sort( int fromIndex, int toIndex );
/**
* Fills every slot in the list with the specified value.
*
* @param val the value to use when filling
*/
public void fill( long val );
/**
* Fills a range in the list with the specified value.
*
* @param fromIndex the offset at which to start filling (inclusive)
* @param toIndex the offset at which to stop filling (exclusive)
* @param val the value to use when filling
*/
public void fill( int fromIndex, int toIndex, long val );
/**
* Performs a binary search for <tt>value</tt> in the entire list.
* Note that you <b>must</b> @{link #sort sort} the list before
* doing a search.
*
* @param value the value to search for
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( long value );
/**
* Performs a binary search for <tt>value</tt> in the specified
* range. Note that you <b>must</b> @{link #sort sort} the list
* or the range before doing a search.
*
* @param value the value to search for
* @param fromIndex the lower boundary of the range (inclusive)
* @param toIndex the upper boundary of the range (exclusive)
* @return the absolute offset in the list of the value, or its
* negative insertion point into the sorted list.
*/
public int binarySearch( long value, int fromIndex, int toIndex );
/**
* Searches the list front to back for the index of
* <tt>value</tt>.
*
* @param value an <code>long</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( long value );
/**
* Searches the list front to back for the index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (inclusive)
* @param value an <code>long</code> value
* @return the first offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int indexOf( int offset, long value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>.
*
* @param value an <code>long</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( long value );
/**
* Searches the list back to front for the last index of
* <tt>value</tt>, starting at <tt>offset</tt>.
*
* @param offset the offset at which to start the linear search
* (exclusive)
* @param value an <code>long</code> value
* @return the last offset of the value, or -1 if it is not in
* the list.
* @see #binarySearch for faster searches on sorted lists
*/
public int lastIndexOf( int offset, long value );
/**
* Searches the list for <tt>value</tt>
*
* @param value an <code>long</code> value
* @return true if value is in the list.
*/
public boolean contains( long value );
/**
* Searches the list for values satisfying <tt>condition</tt> in
* the manner of the *nix <tt>grep</tt> utility.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which match the condition.
*/
public TLongList grep( TLongProcedure condition );
/**
* Searches the list for values which do <b>not</b> satisfy
* <tt>condition</tt>. This is akin to *nix <code>grep -v</code>.
*
* @param condition a condition to apply to each element in the list
* @return a list of values which do not match the condition.
*/
public TLongList inverseGrep( TLongProcedure condition );
/**
* Finds the maximum value in the list.
*
* @return the largest value in the list.
* @exception IllegalStateException if the list is empty
*/
public long max();
/**
* Finds the minimum value in the list.
*
* @return the smallest value in the list.
* @exception IllegalStateException if the list is empty
*/
public long min();
/**
* Calculates the sum of all the values in the list.
*
* @return the sum of the values in the list (zero if the list is empty).
*/
public long sum();
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/TLongList.java | Java | asf20 | 15,481 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.array;
import gnu.trove.function.TLongFunction;
import gnu.trove.list.TLongList;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.iterator.TLongIterator;
import gnu.trove.TLongCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, array-backed list of long primitives.
*/
public class TLongArrayList implements TLongList, Externalizable {
static final long serialVersionUID = 1L;
/** the data of the list */
protected long[] _data;
/** the index after the last entry in the list */
protected int _pos;
/** the default capacity for new lists */
protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/** the long value that represents null */
protected long no_entry_value;
/**
* Creates a new <code>TLongArrayList</code> instance with the
* default capacity.
*/
@SuppressWarnings({"RedundantCast"})
public TLongArrayList() {
this( DEFAULT_CAPACITY, ( long ) 0 );
}
/**
* Creates a new <code>TLongArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
*/
@SuppressWarnings({"RedundantCast"})
public TLongArrayList( int capacity ) {
this( capacity, ( long ) 0 );
}
/**
* Creates a new <code>TLongArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
* @param no_entry_value an <code>long</code> value that represents null.
*/
public TLongArrayList( int capacity, long no_entry_value ) {
_data = new long[ capacity ];
_pos = 0;
this.no_entry_value = no_entry_value;
}
/**
* Creates a new <code>TLongArrayList</code> instance that contains
* a copy of the collection passed to us.
*
* @param collection the collection to copy
*/
public TLongArrayList ( TLongCollection collection ) {
this( collection.size() );
addAll( collection );
}
/**
* Creates a new <code>TLongArrayList</code> instance whose
* capacity is the length of <tt>values</tt> array and whose
* initial contents are the specified values.
* <p>
* A defensive copy of the given values is held by the new instance.
*
* @param values an <code>long[]</code> value
*/
public TLongArrayList( long[] values ) {
this( values.length );
add( values );
}
protected TLongArrayList(long[] values, long no_entry_value, boolean wrap) {
if (!wrap)
throw new IllegalStateException("Wrong call");
if (values == null)
throw new IllegalArgumentException("values can not be null");
_data = values;
_pos = values.length;
this.no_entry_value = no_entry_value;
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @return
*/
public static TLongArrayList wrap(long[] values) {
return wrap(values, ( long ) 0);
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @param no_entry_value
* @return
*/
public static TLongArrayList wrap(long[] values, long no_entry_value) {
return new TLongArrayList(values, no_entry_value, true) {
/**
* Growing the wrapped external array is not allow
*/
@Override
public void ensureCapacity(int capacity) {
if (capacity > _data.length)
throw new IllegalStateException("Can not grow ArrayList wrapped external array");
}
};
}
/** {@inheritDoc} */
public long getNoEntryValue() {
return no_entry_value;
}
// sizing
/**
* Grow the internal array as needed to accommodate the specified number of elements.
* The size of the array bytes on each resize unless capacity requires more than twice
* the current capacity.
*/
public void ensureCapacity( int capacity ) {
if ( capacity > _data.length ) {
int newCap = Math.max( _data.length << 1, capacity );
long[] tmp = new long[ newCap ];
System.arraycopy( _data, 0, tmp, 0, _data.length );
_data = tmp;
}
}
/** {@inheritDoc} */
public int size() {
return _pos;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _pos == 0;
}
/**
* Sheds any excess capacity above and beyond the current size of the list.
*/
public void trimToSize() {
if ( _data.length > size() ) {
long[] tmp = new long[ size() ];
toArray( tmp, 0, tmp.length );
_data = tmp;
}
}
// modifying
/** {@inheritDoc} */
public boolean add( long val ) {
ensureCapacity( _pos + 1 );
_data[ _pos++ ] = val;
return true;
}
/** {@inheritDoc} */
public void add( long[] vals ) {
add( vals, 0, vals.length );
}
/** {@inheritDoc} */
public void add( long[] vals, int offset, int length ) {
ensureCapacity( _pos + length );
System.arraycopy( vals, offset, _data, _pos, length );
_pos += length;
}
/** {@inheritDoc} */
public void insert( int offset, long value ) {
if ( offset == _pos ) {
add( value );
return;
}
ensureCapacity( _pos + 1 );
// shift right
System.arraycopy( _data, offset, _data, offset + 1, _pos - offset );
// insert
_data[ offset ] = value;
_pos++;
}
/** {@inheritDoc} */
public void insert( int offset, long[] values ) {
insert( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void insert( int offset, long[] values, int valOffset, int len ) {
if ( offset == _pos ) {
add( values, valOffset, len );
return;
}
ensureCapacity( _pos + len );
// shift right
System.arraycopy( _data, offset, _data, offset + len, _pos - offset );
// insert
System.arraycopy( values, valOffset, _data, offset, len );
_pos += len;
}
/** {@inheritDoc} */
public long get( int offset ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
return _data[ offset ];
}
/**
* Returns the value at the specified offset without doing any bounds checking.
*/
public long getQuick( int offset ) {
return _data[ offset ];
}
/** {@inheritDoc} */
public long set( int offset, long val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
long prev_val = _data[ offset ];
_data[ offset ] = val;
return prev_val;
}
/** {@inheritDoc} */
public long replace( int offset, long val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
long old = _data[ offset ];
_data[ offset ] = val;
return old;
}
/** {@inheritDoc} */
public void set( int offset, long[] values ) {
set( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void set( int offset, long[] values, int valOffset, int length ) {
if ( offset < 0 || offset + length > _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( values, valOffset, _data, offset, length );
}
/**
* Sets the value at the specified offset without doing any bounds checking.
*/
public void setQuick( int offset, long val ) {
_data[ offset ] = val;
}
/** {@inheritDoc} */
public void clear() {
clear( DEFAULT_CAPACITY );
}
/**
* Flushes the internal state of the list, setting the capacity of the empty list to
* <tt>capacity</tt>.
*/
public void clear( int capacity ) {
_data = new long[ capacity ];
_pos = 0;
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays.
*/
public void reset() {
_pos = 0;
Arrays.fill( _data, no_entry_value );
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays. This method differs from
* {@link #reset()} in that it does not clear the old values in the backing array.
* Thus, it is possible for getQuick to return stale data if this method is used and
* the caller is careless about bounds checking.
*/
public void resetQuick() {
_pos = 0;
}
/** {@inheritDoc} */
public boolean remove( long value ) {
for ( int index = 0; index < _pos; index++ ) {
if ( value == _data[index] ) {
remove( index, 1 );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public long removeAt( int offset ) {
long old = get( offset );
remove( offset, 1 );
return old;
}
/** {@inheritDoc} */
public void remove( int offset, int length ) {
if ( length == 0 ) return;
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException(offset);
}
if ( offset == 0 ) {
// data at the front
System.arraycopy( _data, length, _data, 0, _pos - length );
}
else if ( _pos - length == offset ) {
// no copy to make, decrementing pos "deletes" values at
// the end
}
else {
// data in the middle
System.arraycopy( _data, offset + length, _data, offset,
_pos - ( offset + length ) );
}
_pos -= length;
// no need to clear old values beyond _pos, because this is a
// primitive collection and 0 takes as much room as any other
// value
}
/** {@inheritDoc} */
public TLongIterator iterator() {
return new TLongArrayIterator( 0 );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TLongCollection collection ) {
if ( this == collection ) {
return true;
}
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( long[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Long> collection ) {
boolean changed = false;
for ( Long element : collection ) {
long e = element.longValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TLongCollection collection ) {
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( long[] array ) {
boolean changed = false;
for ( long element : array ) {
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Long.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TLongCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TLongIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( long[] array ) {
boolean changed = false;
Arrays.sort( array );
long[] data = _data;
for ( int i = data.length; i-- > 0; ) {
if ( Arrays.binarySearch( array, data[i] ) < 0 ) {
remove( i, 1 );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Long ) {
long c = ( ( Long ) element ).longValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TLongCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TLongIterator iter = collection.iterator();
while ( iter.hasNext() ) {
long element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( long[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void transformValues( TLongFunction function ) {
for ( int i = _pos; i-- > 0; ) {
_data[ i ] = function.execute( _data[ i ] );
}
}
/** {@inheritDoc} */
public void reverse() {
reverse( 0, _pos );
}
/** {@inheritDoc} */
public void reverse( int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( i, j );
}
}
/** {@inheritDoc} */
public void shuffle( Random rand ) {
for ( int i = _pos; i-- > 1; ) {
swap( i, rand.nextInt( i ) );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( int i, int j ) {
long tmp = _data[ i ];
_data[ i ] = _data[ j ];
_data[ j ] = tmp;
}
// copying
/** {@inheritDoc} */
public TLongList subList( int begin, int end ) {
if ( end < begin ) {
throw new IllegalArgumentException( "end index " + end +
" greater than begin index " + begin );
}
if ( begin < 0 ) {
throw new IndexOutOfBoundsException( "begin index can not be < 0" );
}
if ( end > _data.length ) {
throw new IndexOutOfBoundsException( "end index < " + _data.length );
}
TLongArrayList list = new TLongArrayList( end - begin );
for ( int i = begin; i < end; i++ ) {
list.add( _data[ i ] );
}
return list;
}
/** {@inheritDoc} */
public long[] toArray() {
return toArray( 0, _pos );
}
/** {@inheritDoc} */
public long[] toArray( int offset, int len ) {
long[] rv = new long[ len ];
toArray( rv, offset, len );
return rv;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest ) {
int len = dest.length;
if ( dest.length > _pos ) {
len = _pos;
dest[len] = no_entry_value;
}
toArray( dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest, int offset, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( _data, offset, dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public long[] toArray( long[] dest, int source_pos, int dest_pos, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( source_pos < 0 || source_pos >= _pos ) {
throw new ArrayIndexOutOfBoundsException( source_pos );
}
System.arraycopy( _data, source_pos, dest, dest_pos, len );
return dest;
}
// comparing
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( other == this ) {
return true;
}
else if ( other instanceof TLongArrayList ) {
TLongArrayList that = ( TLongArrayList )other;
if ( that.size() != this.size() ) return false;
else {
for ( int i = _pos; i-- > 0; ) {
if ( this._data[ i ] != that._data[ i ] ) {
return false;
}
}
return true;
}
}
else return false;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int h = 0;
for ( int i = _pos; i-- > 0; ) {
h += HashFunctions.hash( _data[ i ] );
}
return h;
}
// procedures
/** {@inheritDoc} */
public boolean forEach( TLongProcedure procedure ) {
for ( int i = 0; i < _pos; i++ ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending( TLongProcedure procedure ) {
for ( int i = _pos; i-- > 0; ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
// sorting
/** {@inheritDoc} */
public void sort() {
Arrays.sort( _data, 0, _pos );
}
/** {@inheritDoc} */
public void sort( int fromIndex, int toIndex ) {
Arrays.sort( _data, fromIndex, toIndex );
}
// filling
/** {@inheritDoc} */
public void fill( long val ) {
Arrays.fill( _data, 0, _pos, val );
}
/** {@inheritDoc} */
public void fill( int fromIndex, int toIndex, long val ) {
if ( toIndex > _pos ) {
ensureCapacity( toIndex );
_pos = toIndex;
}
Arrays.fill( _data, fromIndex, toIndex, val );
}
// searching
/** {@inheritDoc} */
public int binarySearch( long value ) {
return binarySearch( value, 0, _pos );
}
/** {@inheritDoc} */
public int binarySearch(long value, int fromIndex, int toIndex) {
if ( fromIndex < 0 ) {
throw new ArrayIndexOutOfBoundsException( fromIndex );
}
if ( toIndex > _pos ) {
throw new ArrayIndexOutOfBoundsException( toIndex );
}
int low = fromIndex;
int high = toIndex - 1;
while ( low <= high ) {
int mid = ( low + high ) >>> 1;
long midVal = _data[ mid ];
if ( midVal < value ) {
low = mid + 1;
}
else if ( midVal > value ) {
high = mid - 1;
}
else {
return mid; // value found
}
}
return -( low + 1 ); // value not found.
}
/** {@inheritDoc} */
public int indexOf( long value ) {
return indexOf( 0, value );
}
/** {@inheritDoc} */
public int indexOf( int offset, long value ) {
for ( int i = offset; i < _pos; i++ ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf( long value ) {
return lastIndexOf( _pos, value );
}
/** {@inheritDoc} */
public int lastIndexOf( int offset, long value ) {
for ( int i = offset; i-- > 0; ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public boolean contains( long value ) {
return lastIndexOf( value ) >= 0;
}
/** {@inheritDoc} */
public TLongList grep( TLongProcedure condition ) {
TLongArrayList list = new TLongArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public TLongList inverseGrep( TLongProcedure condition ) {
TLongArrayList list = new TLongArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( !condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public long max() {
if ( size() == 0 ) {
throw new IllegalStateException("cannot find maximum of an empty list");
}
long max = Long.MIN_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[ i ] > max ) {
max = _data[ i ];
}
}
return max;
}
/** {@inheritDoc} */
public long min() {
if ( size() == 0 ) {
throw new IllegalStateException( "cannot find minimum of an empty list" );
}
long min = Long.MAX_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[i] < min ) {
min = _data[i];
}
}
return min;
}
/** {@inheritDoc} */
public long sum() {
long sum = 0;
for ( int i = 0; i < _pos; i++ ) {
sum += _data[ i ];
}
return sum;
}
// stringification
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = 0, end = _pos - 1; i < end; i++ ) {
buf.append( _data[ i ] );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _data[ _pos - 1 ] );
}
buf.append( "}" );
return buf.toString();
}
/** TLongArrayList iterator */
class TLongArrayIterator implements TLongIterator {
/** Index of element to be returned by subsequent call to next. */
private int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
TLongArrayIterator( int index ) {
cursor = index;
}
/** {@inheritDoc} */
public boolean hasNext() {
return cursor < size();
}
/** {@inheritDoc} */
public long next() {
try {
long next = get( cursor );
lastRet = cursor++;
return next;
} catch ( IndexOutOfBoundsException e ) {
throw new NoSuchElementException();
}
}
/** {@inheritDoc} */
public void remove() {
if ( lastRet == -1 )
throw new IllegalStateException();
try {
TLongArrayList.this.remove( lastRet, 1);
if ( lastRet < cursor )
cursor--;
lastRet = -1;
} catch ( IndexOutOfBoundsException e ) {
throw new ConcurrentModificationException();
}
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// POSITION
out.writeInt( _pos );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
// ENTRIES
int len = _data.length;
out.writeInt( len );
for( int i = 0; i < len; i++ ) {
out.writeLong( _data[ i ] );
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// POSITION
_pos = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
// ENTRIES
int len = in.readInt();
_data = new long[ len ];
for( int i = 0; i < len; i++ ) {
_data[ i ] = in.readLong();
}
}
} // TLongArrayList
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/array/TLongArrayList.java | Java | asf20 | 27,813 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.list.array;
import gnu.trove.function.TIntFunction;
import gnu.trove.list.TIntList;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.TIntCollection;
import gnu.trove.impl.*;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.*;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* A resizable, array-backed list of int primitives.
*/
public class TIntArrayList implements TIntList, Externalizable {
static final long serialVersionUID = 1L;
/** the data of the list */
protected int[] _data;
/** the index after the last entry in the list */
protected int _pos;
/** the default capacity for new lists */
protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/** the int value that represents null */
protected int no_entry_value;
/**
* Creates a new <code>TIntArrayList</code> instance with the
* default capacity.
*/
@SuppressWarnings({"RedundantCast"})
public TIntArrayList() {
this( DEFAULT_CAPACITY, ( int ) 0 );
}
/**
* Creates a new <code>TIntArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
*/
@SuppressWarnings({"RedundantCast"})
public TIntArrayList( int capacity ) {
this( capacity, ( int ) 0 );
}
/**
* Creates a new <code>TIntArrayList</code> instance with the
* specified capacity.
*
* @param capacity an <code>int</code> value
* @param no_entry_value an <code>int</code> value that represents null.
*/
public TIntArrayList( int capacity, int no_entry_value ) {
_data = new int[ capacity ];
_pos = 0;
this.no_entry_value = no_entry_value;
}
/**
* Creates a new <code>TIntArrayList</code> instance that contains
* a copy of the collection passed to us.
*
* @param collection the collection to copy
*/
public TIntArrayList ( TIntCollection collection ) {
this( collection.size() );
addAll( collection );
}
/**
* Creates a new <code>TIntArrayList</code> instance whose
* capacity is the length of <tt>values</tt> array and whose
* initial contents are the specified values.
* <p>
* A defensive copy of the given values is held by the new instance.
*
* @param values an <code>int[]</code> value
*/
public TIntArrayList( int[] values ) {
this( values.length );
add( values );
}
protected TIntArrayList(int[] values, int no_entry_value, boolean wrap) {
if (!wrap)
throw new IllegalStateException("Wrong call");
if (values == null)
throw new IllegalArgumentException("values can not be null");
_data = values;
_pos = values.length;
this.no_entry_value = no_entry_value;
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @return
*/
public static TIntArrayList wrap(int[] values) {
return wrap(values, ( int ) 0);
}
/**
* Returns a primitive List implementation that wraps around the given primitive array.
* <p/>
* NOTE: mutating operation are allowed as long as the List does not grow. In that case
* an IllegalStateException will be thrown
*
* @param values
* @param no_entry_value
* @return
*/
public static TIntArrayList wrap(int[] values, int no_entry_value) {
return new TIntArrayList(values, no_entry_value, true) {
/**
* Growing the wrapped external array is not allow
*/
@Override
public void ensureCapacity(int capacity) {
if (capacity > _data.length)
throw new IllegalStateException("Can not grow ArrayList wrapped external array");
}
};
}
/** {@inheritDoc} */
public int getNoEntryValue() {
return no_entry_value;
}
// sizing
/**
* Grow the internal array as needed to accommodate the specified number of elements.
* The size of the array bytes on each resize unless capacity requires more than twice
* the current capacity.
*/
public void ensureCapacity( int capacity ) {
if ( capacity > _data.length ) {
int newCap = Math.max( _data.length << 1, capacity );
int[] tmp = new int[ newCap ];
System.arraycopy( _data, 0, tmp, 0, _data.length );
_data = tmp;
}
}
/** {@inheritDoc} */
public int size() {
return _pos;
}
/** {@inheritDoc} */
public boolean isEmpty() {
return _pos == 0;
}
/**
* Sheds any excess capacity above and beyond the current size of the list.
*/
public void trimToSize() {
if ( _data.length > size() ) {
int[] tmp = new int[ size() ];
toArray( tmp, 0, tmp.length );
_data = tmp;
}
}
// modifying
/** {@inheritDoc} */
public boolean add( int val ) {
ensureCapacity( _pos + 1 );
_data[ _pos++ ] = val;
return true;
}
/** {@inheritDoc} */
public void add( int[] vals ) {
add( vals, 0, vals.length );
}
/** {@inheritDoc} */
public void add( int[] vals, int offset, int length ) {
ensureCapacity( _pos + length );
System.arraycopy( vals, offset, _data, _pos, length );
_pos += length;
}
/** {@inheritDoc} */
public void insert( int offset, int value ) {
if ( offset == _pos ) {
add( value );
return;
}
ensureCapacity( _pos + 1 );
// shift right
System.arraycopy( _data, offset, _data, offset + 1, _pos - offset );
// insert
_data[ offset ] = value;
_pos++;
}
/** {@inheritDoc} */
public void insert( int offset, int[] values ) {
insert( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void insert( int offset, int[] values, int valOffset, int len ) {
if ( offset == _pos ) {
add( values, valOffset, len );
return;
}
ensureCapacity( _pos + len );
// shift right
System.arraycopy( _data, offset, _data, offset + len, _pos - offset );
// insert
System.arraycopy( values, valOffset, _data, offset, len );
_pos += len;
}
/** {@inheritDoc} */
public int get( int offset ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
return _data[ offset ];
}
/**
* Returns the value at the specified offset without doing any bounds checking.
*/
public int getQuick( int offset ) {
return _data[ offset ];
}
/** {@inheritDoc} */
public int set( int offset, int val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
int prev_val = _data[ offset ];
_data[ offset ] = val;
return prev_val;
}
/** {@inheritDoc} */
public int replace( int offset, int val ) {
if ( offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
int old = _data[ offset ];
_data[ offset ] = val;
return old;
}
/** {@inheritDoc} */
public void set( int offset, int[] values ) {
set( offset, values, 0, values.length );
}
/** {@inheritDoc} */
public void set( int offset, int[] values, int valOffset, int length ) {
if ( offset < 0 || offset + length > _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( values, valOffset, _data, offset, length );
}
/**
* Sets the value at the specified offset without doing any bounds checking.
*/
public void setQuick( int offset, int val ) {
_data[ offset ] = val;
}
/** {@inheritDoc} */
public void clear() {
clear( DEFAULT_CAPACITY );
}
/**
* Flushes the internal state of the list, setting the capacity of the empty list to
* <tt>capacity</tt>.
*/
public void clear( int capacity ) {
_data = new int[ capacity ];
_pos = 0;
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays.
*/
public void reset() {
_pos = 0;
Arrays.fill( _data, no_entry_value );
}
/**
* Sets the size of the list to 0, but does not change its capacity. This method can
* be used as an alternative to the {@link #clear()} method if you want to recycle a
* list without allocating new backing arrays. This method differs from
* {@link #reset()} in that it does not clear the old values in the backing array.
* Thus, it is possible for getQuick to return stale data if this method is used and
* the caller is careless about bounds checking.
*/
public void resetQuick() {
_pos = 0;
}
/** {@inheritDoc} */
public boolean remove( int value ) {
for ( int index = 0; index < _pos; index++ ) {
if ( value == _data[index] ) {
remove( index, 1 );
return true;
}
}
return false;
}
/** {@inheritDoc} */
public int removeAt( int offset ) {
int old = get( offset );
remove( offset, 1 );
return old;
}
/** {@inheritDoc} */
public void remove( int offset, int length ) {
if ( length == 0 ) return;
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException(offset);
}
if ( offset == 0 ) {
// data at the front
System.arraycopy( _data, length, _data, 0, _pos - length );
}
else if ( _pos - length == offset ) {
// no copy to make, decrementing pos "deletes" values at
// the end
}
else {
// data in the middle
System.arraycopy( _data, offset + length, _data, offset,
_pos - ( offset + length ) );
}
_pos -= length;
// no need to clear old values beyond _pos, because this is a
// primitive collection and 0 takes as much room as any other
// value
}
/** {@inheritDoc} */
public TIntIterator iterator() {
return new TIntArrayIterator( 0 );
}
/** {@inheritDoc} */
public boolean containsAll( Collection<?> collection ) {
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( ! contains( c ) ) {
return false;
}
} else {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( TIntCollection collection ) {
if ( this == collection ) {
return true;
}
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( ! contains( element ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean containsAll( int[] array ) {
for ( int i = array.length; i-- > 0; ) {
if ( ! contains( array[i] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean addAll( Collection<? extends Integer> collection ) {
boolean changed = false;
for ( Integer element : collection ) {
int e = element.intValue();
if ( add( e ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( TIntCollection collection ) {
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean addAll( int[] array ) {
boolean changed = false;
for ( int element : array ) {
if ( add( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
@SuppressWarnings({"SuspiciousMethodCalls"})
public boolean retainAll( Collection<?> collection ) {
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( Integer.valueOf ( iter.next() ) ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( TIntCollection collection ) {
if ( this == collection ) {
return false;
}
boolean modified = false;
TIntIterator iter = iterator();
while ( iter.hasNext() ) {
if ( ! collection.contains( iter.next() ) ) {
iter.remove();
modified = true;
}
}
return modified;
}
/** {@inheritDoc} */
public boolean retainAll( int[] array ) {
boolean changed = false;
Arrays.sort( array );
int[] data = _data;
for ( int i = data.length; i-- > 0; ) {
if ( Arrays.binarySearch( array, data[i] ) < 0 ) {
remove( i, 1 );
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( Collection<?> collection ) {
boolean changed = false;
for ( Object element : collection ) {
if ( element instanceof Integer ) {
int c = ( ( Integer ) element ).intValue();
if ( remove( c ) ) {
changed = true;
}
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( TIntCollection collection ) {
if ( collection == this ) {
clear();
return true;
}
boolean changed = false;
TIntIterator iter = collection.iterator();
while ( iter.hasNext() ) {
int element = iter.next();
if ( remove( element ) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public boolean removeAll( int[] array ) {
boolean changed = false;
for ( int i = array.length; i-- > 0; ) {
if ( remove(array[i]) ) {
changed = true;
}
}
return changed;
}
/** {@inheritDoc} */
public void transformValues( TIntFunction function ) {
for ( int i = _pos; i-- > 0; ) {
_data[ i ] = function.execute( _data[ i ] );
}
}
/** {@inheritDoc} */
public void reverse() {
reverse( 0, _pos );
}
/** {@inheritDoc} */
public void reverse( int from, int to ) {
if ( from == to ) {
return; // nothing to do
}
if ( from > to ) {
throw new IllegalArgumentException( "from cannot be greater than to" );
}
for ( int i = from, j = to - 1; i < j; i++, j-- ) {
swap( i, j );
}
}
/** {@inheritDoc} */
public void shuffle( Random rand ) {
for ( int i = _pos; i-- > 1; ) {
swap( i, rand.nextInt( i ) );
}
}
/**
* Swap the values at offsets <tt>i</tt> and <tt>j</tt>.
*
* @param i an offset into the data array
* @param j an offset into the data array
*/
private void swap( int i, int j ) {
int tmp = _data[ i ];
_data[ i ] = _data[ j ];
_data[ j ] = tmp;
}
// copying
/** {@inheritDoc} */
public TIntList subList( int begin, int end ) {
if ( end < begin ) {
throw new IllegalArgumentException( "end index " + end +
" greater than begin index " + begin );
}
if ( begin < 0 ) {
throw new IndexOutOfBoundsException( "begin index can not be < 0" );
}
if ( end > _data.length ) {
throw new IndexOutOfBoundsException( "end index < " + _data.length );
}
TIntArrayList list = new TIntArrayList( end - begin );
for ( int i = begin; i < end; i++ ) {
list.add( _data[ i ] );
}
return list;
}
/** {@inheritDoc} */
public int[] toArray() {
return toArray( 0, _pos );
}
/** {@inheritDoc} */
public int[] toArray( int offset, int len ) {
int[] rv = new int[ len ];
toArray( rv, offset, len );
return rv;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest ) {
int len = dest.length;
if ( dest.length > _pos ) {
len = _pos;
dest[len] = no_entry_value;
}
toArray( dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest, int offset, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( offset < 0 || offset >= _pos ) {
throw new ArrayIndexOutOfBoundsException( offset );
}
System.arraycopy( _data, offset, dest, 0, len );
return dest;
}
/** {@inheritDoc} */
public int[] toArray( int[] dest, int source_pos, int dest_pos, int len ) {
if ( len == 0 ) {
return dest; // nothing to copy
}
if ( source_pos < 0 || source_pos >= _pos ) {
throw new ArrayIndexOutOfBoundsException( source_pos );
}
System.arraycopy( _data, source_pos, dest, dest_pos, len );
return dest;
}
// comparing
/** {@inheritDoc} */
@Override
public boolean equals( Object other ) {
if ( other == this ) {
return true;
}
else if ( other instanceof TIntArrayList ) {
TIntArrayList that = ( TIntArrayList )other;
if ( that.size() != this.size() ) return false;
else {
for ( int i = _pos; i-- > 0; ) {
if ( this._data[ i ] != that._data[ i ] ) {
return false;
}
}
return true;
}
}
else return false;
}
/** {@inheritDoc} */
@Override
public int hashCode() {
int h = 0;
for ( int i = _pos; i-- > 0; ) {
h += HashFunctions.hash( _data[ i ] );
}
return h;
}
// procedures
/** {@inheritDoc} */
public boolean forEach( TIntProcedure procedure ) {
for ( int i = 0; i < _pos; i++ ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
/** {@inheritDoc} */
public boolean forEachDescending( TIntProcedure procedure ) {
for ( int i = _pos; i-- > 0; ) {
if ( !procedure.execute( _data[ i ] ) ) {
return false;
}
}
return true;
}
// sorting
/** {@inheritDoc} */
public void sort() {
Arrays.sort( _data, 0, _pos );
}
/** {@inheritDoc} */
public void sort( int fromIndex, int toIndex ) {
Arrays.sort( _data, fromIndex, toIndex );
}
// filling
/** {@inheritDoc} */
public void fill( int val ) {
Arrays.fill( _data, 0, _pos, val );
}
/** {@inheritDoc} */
public void fill( int fromIndex, int toIndex, int val ) {
if ( toIndex > _pos ) {
ensureCapacity( toIndex );
_pos = toIndex;
}
Arrays.fill( _data, fromIndex, toIndex, val );
}
// searching
/** {@inheritDoc} */
public int binarySearch( int value ) {
return binarySearch( value, 0, _pos );
}
/** {@inheritDoc} */
public int binarySearch(int value, int fromIndex, int toIndex) {
if ( fromIndex < 0 ) {
throw new ArrayIndexOutOfBoundsException( fromIndex );
}
if ( toIndex > _pos ) {
throw new ArrayIndexOutOfBoundsException( toIndex );
}
int low = fromIndex;
int high = toIndex - 1;
while ( low <= high ) {
int mid = ( low + high ) >>> 1;
int midVal = _data[ mid ];
if ( midVal < value ) {
low = mid + 1;
}
else if ( midVal > value ) {
high = mid - 1;
}
else {
return mid; // value found
}
}
return -( low + 1 ); // value not found.
}
/** {@inheritDoc} */
public int indexOf( int value ) {
return indexOf( 0, value );
}
/** {@inheritDoc} */
public int indexOf( int offset, int value ) {
for ( int i = offset; i < _pos; i++ ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public int lastIndexOf( int value ) {
return lastIndexOf( _pos, value );
}
/** {@inheritDoc} */
public int lastIndexOf( int offset, int value ) {
for ( int i = offset; i-- > 0; ) {
if ( _data[ i ] == value ) {
return i;
}
}
return -1;
}
/** {@inheritDoc} */
public boolean contains( int value ) {
return lastIndexOf( value ) >= 0;
}
/** {@inheritDoc} */
public TIntList grep( TIntProcedure condition ) {
TIntArrayList list = new TIntArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public TIntList inverseGrep( TIntProcedure condition ) {
TIntArrayList list = new TIntArrayList();
for ( int i = 0; i < _pos; i++ ) {
if ( !condition.execute( _data[ i ] ) ) {
list.add( _data[ i ] );
}
}
return list;
}
/** {@inheritDoc} */
public int max() {
if ( size() == 0 ) {
throw new IllegalStateException("cannot find maximum of an empty list");
}
int max = Integer.MIN_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[ i ] > max ) {
max = _data[ i ];
}
}
return max;
}
/** {@inheritDoc} */
public int min() {
if ( size() == 0 ) {
throw new IllegalStateException( "cannot find minimum of an empty list" );
}
int min = Integer.MAX_VALUE;
for ( int i = 0; i < _pos; i++ ) {
if ( _data[i] < min ) {
min = _data[i];
}
}
return min;
}
/** {@inheritDoc} */
public int sum() {
int sum = 0;
for ( int i = 0; i < _pos; i++ ) {
sum += _data[ i ];
}
return sum;
}
// stringification
/** {@inheritDoc} */
@Override
public String toString() {
final StringBuilder buf = new StringBuilder( "{" );
for ( int i = 0, end = _pos - 1; i < end; i++ ) {
buf.append( _data[ i ] );
buf.append( ", " );
}
if ( size() > 0 ) {
buf.append( _data[ _pos - 1 ] );
}
buf.append( "}" );
return buf.toString();
}
/** TIntArrayList iterator */
class TIntArrayIterator implements TIntIterator {
/** Index of element to be returned by subsequent call to next. */
private int cursor = 0;
/**
* Index of element returned by most recent call to next or
* previous. Reset to -1 if this element is deleted by a call
* to remove.
*/
int lastRet = -1;
TIntArrayIterator( int index ) {
cursor = index;
}
/** {@inheritDoc} */
public boolean hasNext() {
return cursor < size();
}
/** {@inheritDoc} */
public int next() {
try {
int next = get( cursor );
lastRet = cursor++;
return next;
} catch ( IndexOutOfBoundsException e ) {
throw new NoSuchElementException();
}
}
/** {@inheritDoc} */
public void remove() {
if ( lastRet == -1 )
throw new IllegalStateException();
try {
TIntArrayList.this.remove( lastRet, 1);
if ( lastRet < cursor )
cursor--;
lastRet = -1;
} catch ( IndexOutOfBoundsException e ) {
throw new ConcurrentModificationException();
}
}
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// POSITION
out.writeInt( _pos );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
// ENTRIES
int len = _data.length;
out.writeInt( len );
for( int i = 0; i < len; i++ ) {
out.writeInt( _data[ i ] );
}
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// POSITION
_pos = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
// ENTRIES
int len = in.readInt();
_data = new int[ len ];
for( int i = 0; i < len; i++ ) {
_data[ i ] = in.readInt();
}
}
} // TIntArrayList
| 04146814d-23 | SimpleTrove/src/gnu/trove/list/array/TIntArrayList.java | Java | asf20 | 27,692 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.function;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for functions that accept and return one long primitive.
*/
public interface TLongFunction {
/**
* Execute this function with <tt>value</tt>
*
* @param value a <code>long</code> input
* @return a <code>long</code> result
*/
public long execute( long value );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/function/TLongFunction.java | Java | asf20 | 1,452 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.function;
/**
* Interface for functions that accept and return one Object reference.
* <p/>
* Created: Mon Nov 5 22:19:36 2001
*
* @author Eric D. Friedman
* @version $Id: TObjectFunction.java,v 1.1.2.1 2009/09/06 17:02:19 upholderoftruth Exp $
*/
public interface TObjectFunction<T, R> {
/**
* Execute this function with <tt>value</tt>
*
* @param value an <code>Object</code> input
* @return an <code>Object</code> result
*/
public R execute( T value );
}// TObjectFunction
| 04146814d-23 | SimpleTrove/src/gnu/trove/function/TObjectFunction.java | Java | asf20 | 1,532 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.function;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* Interface for functions that accept and return one int primitive.
*/
public interface TIntFunction {
/**
* Execute this function with <tt>value</tt>
*
* @param value a <code>int</code> input
* @return a <code>int</code> result
*/
public int execute( int value );
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/function/TIntFunction.java | Java | asf20 | 1,446 |
<!--
~ ///////////////////////////////////////////////////////////////////////////////
~ // Copyright (c) 2009, Rob Eden All Rights Reserved.
~ //
~ // This library is free software; you can redistribute it and/or
~ // modify it under the terms of the GNU Lesser General Public
~ // License as published by the Free Software Foundation; either
~ // version 2.1 of the License, or (at your option) any later version.
~ //
~ // This library is distributed in the hope that it will be useful,
~ // but WITHOUT ANY WARRANTY; without even the implied warranty of
~ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
~ // GNU General Public License for more details.
~ //
~ // You should have received a copy of the GNU Lesser General Public
~ // License along with this program; if not, write to the Free Software
~ // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
~ ///////////////////////////////////////////////////////////////////////////////
-->
<html>
This package (and its sub-packages) contain internal implementations used in Trove. These
classes should <strong>not</strong> be accessed directly (treat them like <tt>com.sun</tt>
classes.
</html> | 04146814d-23 | SimpleTrove/src/gnu/trove/impl/package.html | HTML | asf20 | 1,253 |
// Copyright (c) 1999 CERN - European Organization for Nuclear Research.
// Permission to use, copy, modify, distribute and sell this software and
// its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and that
// both that copyright notice and this permission notice appear in
// supporting documentation. CERN makes no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without expressed or implied warranty.
package gnu.trove.impl;
/**
* Provides various hash functions.
*
* @author wolfgang.hoschek@cern.ch
* @version 1.0, 09/24/99
*/
public final class HashFunctions {
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(double value) {
assert !Double.isNaN(value) : "Values of NaN are not supported.";
long bits = Double.doubleToLongBits(value);
return (int)(bits ^ (bits >>> 32));
//return (int) Double.doubleToLongBits(value*663608941.737);
//this avoids excessive hashCollisions in the case values are
//of the form (1.0, 2.0, 3.0, ...)
}
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(float value) {
assert !Float.isNaN(value) : "Values of NaN are not supported.";
return Float.floatToIntBits(value*663608941.737f);
// this avoids excessive hashCollisions in the case values are
// of the form (1.0, 2.0, 3.0, ...)
}
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(int value) {
return value;
}
/**
* Returns a hashcode for the specified value.
*
* @return a hash code value for the specified value.
*/
public static int hash(long value) {
return ((int)(value ^ (value >>> 32)));
}
/**
* Returns a hashcode for the specified object.
*
* @return a hash code value for the specified object.
*/
public static int hash(Object object) {
return object==null ? 0 : object.hashCode();
}
/**
* In profiling, it has been found to be faster to have our own local implementation
* of "ceil" rather than to call to {@link Math#ceil(double)}.
*/
public static int fastCeil( float v ) {
int possible_result = ( int ) v;
if ( v - possible_result > 0 ) possible_result++;
return possible_result;
}
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/HashFunctions.java | Java | asf20 | 2,781 |
// Copyright (c) 1999 CERN - European Organization for Nuclear Research.
// Permission to use, copy, modify, distribute and sell this software
// and its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appear in all copies and
// that both that copyright notice and this permission notice appear in
// supporting documentation. CERN makes no representations about the
// suitability of this software for any purpose. It is provided "as is"
// without expressed or implied warranty.
package gnu.trove.impl;
import java.util.Arrays;
/*
* Modified for Trove to use the java.util.Arrays sort/search
* algorithms instead of those provided with colt.
*/
/**
* Used to keep hash table capacities prime numbers.
* Not of interest for users; only for implementors of hashtables.
*
* <p>Choosing prime numbers as hash table capacities is a good idea
* to keep them working fast, particularly under hash table
* expansions.
*
* <p>However, JDK 1.2, JGL 3.1 and many other toolkits do nothing to
* keep capacities prime. This class provides efficient means to
* choose prime capacities.
*
* <p>Choosing a prime is <tt>O(log 300)</tt> (binary search in a list
* of 300 ints). Memory requirements: 1 KB static memory.
*
* @author wolfgang.hoschek@cern.ch
* @version 1.0, 09/24/99
*/
public final class PrimeFinder {
/**
* The largest prime this class can generate; currently equal to
* <tt>Integer.MAX_VALUE</tt>.
*/
public static final int largestPrime = Integer.MAX_VALUE; //yes, it is prime.
/**
* The prime number list consists of 11 chunks.
*
* Each chunk contains prime numbers.
*
* A chunk starts with a prime P1. The next element is a prime
* P2. P2 is the smallest prime for which holds: P2 >= 2*P1.
*
* The next element is P3, for which the same holds with respect
* to P2, and so on.
*
* Chunks are chosen such that for any desired capacity >= 1000
* the list includes a prime number <= desired capacity * 1.11.
*
* Therefore, primes can be retrieved which are quite close to any
* desired capacity, which in turn avoids wasting memory.
*
* For example, the list includes
* 1039,1117,1201,1277,1361,1439,1523,1597,1759,1907,2081.
*
* So if you need a prime >= 1040, you will find a prime <=
* 1040*1.11=1154.
*
* Chunks are chosen such that they are optimized for a hashtable
* growthfactor of 2.0;
*
* If your hashtable has such a growthfactor then, after initially
* "rounding to a prime" upon hashtable construction, it will
* later expand to prime capacities such that there exist no
* better primes.
*
* In total these are about 32*10=320 numbers -> 1 KB of static
* memory needed.
*
* If you are stingy, then delete every second or fourth chunk.
*/
private static final int[] primeCapacities = {
//chunk #0
largestPrime,
//chunk #1
5,11,23,47,97,197,397,797,1597,3203,6421,12853,25717,51437,102877,205759,
411527,823117,1646237,3292489,6584983,13169977,26339969,52679969,105359939,
210719881,421439783,842879579,1685759167,
//chunk #2
433,877,1759,3527,7057,14143,28289,56591,113189,226379,452759,905551,1811107,
3622219,7244441,14488931,28977863,57955739,115911563,231823147,463646329,927292699,
1854585413,
//chunk #3
953,1907,3821,7643,15287,30577,61169,122347,244703,489407,978821,1957651,3915341,
7830701,15661423,31322867,62645741,125291483,250582987,501165979,1002331963,
2004663929,
//chunk #4
1039,2081,4177,8363,16729,33461,66923,133853,267713,535481,1070981,2141977,4283963,
8567929,17135863,34271747,68543509,137087021,274174111,548348231,1096696463,
//chunk #5
31,67,137,277,557,1117,2237,4481,8963,17929,35863,71741,143483,286973,573953,
1147921,2295859,4591721,9183457,18366923,36733847,73467739,146935499,293871013,
587742049,1175484103,
//chunk #6
599,1201,2411,4831,9677,19373,38747,77509,155027,310081,620171,1240361,2480729,
4961459,9922933,19845871,39691759,79383533,158767069,317534141,635068283,1270136683,
//chunk #7
311,631,1277,2557,5119,10243,20507,41017,82037,164089,328213,656429,1312867,
2625761,5251529,10503061,21006137,42012281,84024581,168049163,336098327,672196673,
1344393353,
//chunk #8
3,7,17,37,79,163,331,673,1361,2729,5471,10949,21911,43853,87719,175447,350899,
701819,1403641,2807303,5614657,11229331,22458671,44917381,89834777,179669557,
359339171,718678369,1437356741,
//chunk #9
43,89,179,359,719,1439,2879,5779,11579,23159,46327,92657,185323,370661,741337,
1482707,2965421,5930887,11861791,23723597,47447201,94894427,189788857,379577741,
759155483,1518310967,
//chunk #10
379,761,1523,3049,6101,12203,24407,48817,97649,195311,390647,781301,1562611,
3125257,6250537,12501169,25002389,50004791,100009607,200019221,400038451,800076929,
1600153859
};
static { //initializer
// The above prime numbers are formatted for human readability.
// To find numbers fast, we sort them once and for all.
Arrays.sort(primeCapacities);
}
/**
* Returns a prime number which is <code>>= desiredCapacity</code>
* and very close to <code>desiredCapacity</code> (within 11% if
* <code>desiredCapacity >= 1000</code>).
*
* @param desiredCapacity the capacity desired by the user.
* @return the capacity which should be used for a hashtable.
*/
public static final int nextPrime(int desiredCapacity) {
int i = Arrays.binarySearch(primeCapacities, desiredCapacity);
if (i<0) {
// desired capacity not found, choose next prime greater
// than desired capacity
i = -i -1; // remember the semantics of binarySearch...
}
return primeCapacities[i];
}
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/PrimeFinder.java | Java | asf20 | 6,328 |
// ////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl;
/**
* Central location for constants needed by various implementations.
*/
public class Constants {
private static final boolean VERBOSE =
System.getProperty( "gnu.trove.verbose", null ) != null;
/** the default capacity for new collections */
public static final int DEFAULT_CAPACITY = 10;
/** the load above which rehashing occurs. */
public static final float DEFAULT_LOAD_FACTOR = 0.5f;
/** the default value that represents for <tt>byte</tt> types. */
public static final byte DEFAULT_BYTE_NO_ENTRY_VALUE;
static {
byte value;
String property = System.getProperty( "gnu.trove.no_entry.byte", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Byte.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Byte.MIN_VALUE;
else value = Byte.valueOf( property );
if ( value > Byte.MAX_VALUE ) value = Byte.MAX_VALUE;
else if ( value < Byte.MIN_VALUE ) value = Byte.MIN_VALUE;
DEFAULT_BYTE_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_BYTE_NO_ENTRY_VALUE: " +
DEFAULT_BYTE_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>short</tt> types. */
public static final short DEFAULT_SHORT_NO_ENTRY_VALUE;
static {
short value;
String property = System.getProperty( "gnu.trove.no_entry.short", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Short.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Short.MIN_VALUE;
else value = Short.valueOf( property );
if ( value > Short.MAX_VALUE ) value = Short.MAX_VALUE;
else if ( value < Short.MIN_VALUE ) value = Short.MIN_VALUE;
DEFAULT_SHORT_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_SHORT_NO_ENTRY_VALUE: " +
DEFAULT_SHORT_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>char</tt> types. */
public static final char DEFAULT_CHAR_NO_ENTRY_VALUE;
static {
char value;
String property = System.getProperty( "gnu.trove.no_entry.char", "\0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Character.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Character.MIN_VALUE;
else value = property.toCharArray()[0];
if ( value > Character.MAX_VALUE ) value = Character.MAX_VALUE;
else if ( value < Character.MIN_VALUE ) value = Character.MIN_VALUE;
DEFAULT_CHAR_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_CHAR_NO_ENTRY_VALUE: " +
Integer.valueOf( value ) );
}
}
/** the default value that represents for <tt>int</tt> types. */
public static final int DEFAULT_INT_NO_ENTRY_VALUE;
static {
int value;
String property = System.getProperty( "gnu.trove.no_entry.int", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Integer.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Integer.MIN_VALUE;
else value = Integer.valueOf( property );
DEFAULT_INT_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_INT_NO_ENTRY_VALUE: " +
DEFAULT_INT_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>long</tt> types. */
public static final long DEFAULT_LONG_NO_ENTRY_VALUE;
static {
long value;
String property = System.getProperty( "gnu.trove.no_entry.long", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Long.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Long.MIN_VALUE;
else value = Long.valueOf( property );
DEFAULT_LONG_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_LONG_NO_ENTRY_VALUE: " +
DEFAULT_LONG_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>float</tt> types. */
public static final float DEFAULT_FLOAT_NO_ENTRY_VALUE;
static {
float value;
String property = System.getProperty( "gnu.trove.no_entry.float", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Float.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Float.MIN_VALUE;
// Value from Float.MIN_NORMAL (introduced in 1.6)
else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-126f;
else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.NEGATIVE_INFINITY;
else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Float.POSITIVE_INFINITY;
// else if ( "NaN".equalsIgnoreCase( property ) ) value = Float.NaN;
else value = Float.valueOf( property );
DEFAULT_FLOAT_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_FLOAT_NO_ENTRY_VALUE: " +
DEFAULT_FLOAT_NO_ENTRY_VALUE );
}
}
/** the default value that represents for <tt>double</tt> types. */
public static final double DEFAULT_DOUBLE_NO_ENTRY_VALUE;
static {
double value;
String property = System.getProperty( "gnu.trove.no_entry.double", "0" );
if ( "MAX_VALUE".equalsIgnoreCase( property ) ) value = Double.MAX_VALUE;
else if ( "MIN_VALUE".equalsIgnoreCase( property ) ) value = Double.MIN_VALUE;
// Value from Double.MIN_NORMAL (introduced in 1.6)
else if ( "MIN_NORMAL".equalsIgnoreCase( property ) ) value = 0x1.0p-1022;
else if ( "NEGATIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.NEGATIVE_INFINITY;
else if ( "POSITIVE_INFINITY".equalsIgnoreCase( property ) ) value = Double.POSITIVE_INFINITY;
// else if ( "NaN".equalsIgnoreCase( property ) ) value = Double.NaN;
else value = Double.valueOf( property );
DEFAULT_DOUBLE_NO_ENTRY_VALUE = value;
if ( VERBOSE ) {
System.out.println( "DEFAULT_DOUBLE_NO_ENTRY_VALUE: " +
DEFAULT_DOUBLE_NO_ENTRY_VALUE );
}
}
}
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/Constants.java | Java | asf20 | 7,631 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.iterator.TIterator;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
/**
* Implements all iterator functions for the hashed object set.
* Subclasses may override objectAtIndex to vary the object
* returned by calls to next() (e.g. for values, and Map.Entry
* objects).
* <p/>
* <p> Note that iteration is fastest if you forego the calls to
* <tt>hasNext</tt> in favor of checking the size of the structure
* yourself and then call next() that many times:
* <p/>
* <pre>
* Iterator i = collection.iterator();
* for (int size = collection.size(); size-- > 0;) {
* Object o = i.next();
* }
* </pre>
* <p/>
* <p>You may, of course, use the hasNext(), next() idiom too if
* you aren't in a performance critical spot.</p>
*/
public abstract class THashIterator<V> implements TIterator, Iterator<V> {
private final TObjectHash<V> _object_hash;
/** the data structure this iterator traverses */
protected final THash _hash;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/**
* Create an instance of THashIterator over the values of the TObjectHash
*
* @param hash the object
*/
protected THashIterator( TObjectHash<V> hash ) {
_hash = hash;
_expectedSize = _hash.size();
_index = _hash.capacity();
_object_hash = hash;
}
/**
* Moves the iterator to the next Object and returns it.
*
* @return an <code>Object</code> value
* @throws ConcurrentModificationException
* if the structure
* was changed using a method that isn't on this iterator.
* @throws NoSuchElementException if this is called on an
* exhausted iterator.
*/
public V next() {
moveToNextIndex();
return objectAtIndex( _index );
}
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext() {
return nextIndex() >= 0;
}
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt( _index );
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws ConcurrentModificationException
* if the underlying
* collection's size has been modified since the iterator was
* created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
Object[] set = _object_hash._set;
int i = _index;
while ( i-- > 0 && ( set[i] == TObjectHash.FREE || set[i] == TObjectHash.REMOVED ) ) {
;
}
return i;
}
/**
* Returns the object at the specified index. Subclasses should
* implement this to return the appropriate object for the given
* index.
*
* @param index the index of the value to return.
* @return an <code>Object</code> value
*/
abstract protected V objectAtIndex( int index );
} // THashIterator
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/THashIterator.java | Java | asf20 | 5,594 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.TIntProcedure;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.Constants;
import java.util.Arrays;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for int primitives.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TIntHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of ints */
public transient int[] _set;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>TIntHash</code> instance with the default
* capacity and load factor.
*/
public TIntHash() {
super();
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntHash( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_value = Constants.DEFAULT_INT_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TIntHash( int initialCapacity, float loadFactor, int no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_value = no_entry_value;
//noinspection RedundantCast
if ( no_entry_value != ( int ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new int[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( int val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TIntProcedure procedure ) {
byte[] states = _states;
int[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_value;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param val an <code>int</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( int val ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( val ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == val)
return index;
return indexRehashed(val, index, hash, state);
}
int indexRehashed(int key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param val an <code>int</code> value
* @return an <code>int</code> value
*/
protected int insertKey( int val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, int val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
} // TIntHash
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TIntHash.java | Java | asf20 | 10,053 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.impl.HashFunctions;
/**
* The base class for hashtables of primitive values. Since there is
* no notion of object equality for primitives, it isn't possible to
* use a `REMOVED' object to track deletions in an open-addressed table.
* So, we have to resort to using a parallel `bookkeeping' array of bytes,
* in which flags can be set to indicate that a particular slot in the
* hash table is FREE, FULL, or REMOVED.
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: TPrimitiveHash.java,v 1.1.2.6 2010/03/01 23:39:07 robeden Exp $
*/
abstract public class TPrimitiveHash extends THash {
@SuppressWarnings( { "UnusedDeclaration" } )
static final long serialVersionUID = 1L;
/**
* flags indicating whether each position in the hash is
* FREE, FULL, or REMOVED
*/
public transient byte[] _states;
/* constants used for state flags */
/** flag indicating that a slot in the hashtable is available */
public static final byte FREE = 0;
/** flag indicating that a slot in the hashtable is occupied */
public static final byte FULL = 1;
/**
* flag indicating that the value of a slot in the hashtable
* was deleted
*/
public static final byte REMOVED = 2;
/**
* Creates a new <code>THash</code> instance with the default
* capacity and load factor.
*/
public TPrimitiveHash() {
super();
}
/**
* Creates a new <code>TPrimitiveHash</code> instance with a prime
* capacity at or near the specified capacity and with the default
* load factor.
*
* @param initialCapacity an <code>int</code> value
*/
public TPrimitiveHash( int initialCapacity ) {
this( initialCapacity, DEFAULT_LOAD_FACTOR );
}
/**
* Creates a new <code>TPrimitiveHash</code> instance with a prime
* capacity at or near the minimum needed to hold
* <tt>initialCapacity<tt> elements with load factor
* <tt>loadFactor</tt> without triggering a rehash.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public TPrimitiveHash( int initialCapacity, float loadFactor ) {
super();
initialCapacity = Math.max( 1, initialCapacity );
_loadFactor = loadFactor;
setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) );
}
/**
* Returns the capacity of the hash table. This is the true
* physical capacity, without adjusting for the load factor.
*
* @return the physical capacity of the hash table.
*/
public int capacity() {
return _states.length;
}
/**
* Delete the record at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_states[index] = REMOVED;
super.removeAt( index );
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_states = new byte[capacity];
return capacity;
}
} // TPrimitiveHash | 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TPrimitiveHash.java | Java | asf20 | 4,603 |
// ////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009, Rob Eden All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// ////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.iterator.TPrimitiveIterator;
import java.util.ConcurrentModificationException;
import java.util.NoSuchElementException;
/**
* Implements all iterator functions for the hashed object set.
* Subclasses may override objectAtIndex to vary the object
* returned by calls to next() (e.g. for values, and Map.Entry
* objects).
* <p/>
* <p> Note that iteration is fastest if you forego the calls to
* <tt>hasNext</tt> in favor of checking the size of the structure
* yourself and then call next() that many times:
* <p/>
* <pre>
* Iterator i = collection.iterator();
* for (int size = collection.size(); size-- > 0;) {
* Object o = i.next();
* }
* </pre>
* <p/>
* <p>You may, of course, use the hasNext(), next() idiom too if
* you aren't in a performance critical spot.</p>
*/
public abstract class THashPrimitiveIterator implements TPrimitiveIterator {
/** the data structure this iterator traverses */
protected final TPrimitiveHash _hash;
/**
* the number of elements this iterator believes are in the
* data structure it accesses.
*/
protected int _expectedSize;
/** the index used for iteration. */
protected int _index;
/**
* Creates a <tt>TPrimitiveIterator</tt> for the specified collection.
*
* @param hash the <tt>TPrimitiveHash</tt> we want to iterate over.
*/
public THashPrimitiveIterator( TPrimitiveHash hash ) {
_hash = hash;
_expectedSize = _hash.size();
_index = _hash.capacity();
}
/**
* Returns the index of the next value in the data structure
* or a negative value if the iterator is exhausted.
*
* @return an <code>int</code> value
* @throws java.util.ConcurrentModificationException
* if the underlying collection's
* size has been modified since the iterator was created.
*/
protected final int nextIndex() {
if ( _expectedSize != _hash.size() ) {
throw new ConcurrentModificationException();
}
byte[] states = _hash._states;
int i = _index;
while ( i-- > 0 && ( states[i] != TPrimitiveHash.FULL ) ) {
;
}
return i;
}
/**
* Returns true if the iterator can be advanced past its current
* location.
*
* @return a <code>boolean</code> value
*/
public boolean hasNext() {
return nextIndex() >= 0;
}
/**
* Removes the last entry returned by the iterator.
* Invoking this method more than once for a single entry
* will leave the underlying data structure in a confused
* state.
*/
public void remove() {
if (_expectedSize != _hash.size()) {
throw new ConcurrentModificationException();
}
// Disable auto compaction during the remove. This is a workaround for bug 1642768.
try {
_hash.tempDisableAutoCompaction();
_hash.removeAt(_index);
}
finally {
_hash.reenableAutoCompaction( false );
}
_expectedSize--;
}
/**
* Sets the internal <tt>index</tt> so that the `next' object
* can be returned.
*/
protected final void moveToNextIndex() {
// doing the assignment && < 0 in one line shaves
// 3 opcodes...
if ( ( _index = nextIndex() ) < 0 ) {
throw new NoSuchElementException();
}
}
} // TPrimitiveIterator | 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/THashPrimitiveIterator.java | Java | asf20 | 4,604 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for int/int primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TIntIntHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of ints */
public transient int[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TIntIntHash() {
super();
no_entry_key = ( int ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntIntHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( int ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TIntIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntIntHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( int ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TIntIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TIntIntHash( int initialCapacity, float loadFactor,
int no_entry_key, int no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new int[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( int val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TIntProcedure procedure ) {
byte[] states = _states;
int[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>int</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(int key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>int</code> value
* @return an <code>int</code> value
*/
protected int insertKey( int val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, int val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
}
} // TIntIntHash
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TIntIntHash.java | Java | asf20 | 14,087 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.impl.Constants;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.PrimeFinder;
import java.io.Externalizable;
import java.io.ObjectOutput;
import java.io.IOException;
import java.io.ObjectInput;
/**
* Base class for hashtables that use open addressing to resolve
* collisions.
*
* Created: Wed Nov 28 21:11:16 2001
*
* @author Eric D. Friedman
* @author Rob Eden (auto-compaction)
* @author Jeff Randall
*
* @version $Id: THash.java,v 1.1.2.4 2010/03/02 00:55:34 robeden Exp $
*/
abstract public class THash implements Externalizable {
@SuppressWarnings( { "UnusedDeclaration" } )
static final long serialVersionUID = -1792948471915530295L;
/** the load above which rehashing occurs. */
protected static final float DEFAULT_LOAD_FACTOR = Constants.DEFAULT_LOAD_FACTOR;
/**
* the default initial capacity for the hash table. This is one
* less than a prime value because one is added to it when
* searching for a prime capacity to account for the free slot
* required by open addressing. Thus, the real default capacity is
* 11.
*/
protected static final int DEFAULT_CAPACITY = Constants.DEFAULT_CAPACITY;
/** the current number of occupied slots in the hash. */
protected transient int _size;
/** the current number of free slots in the hash. */
protected transient int _free;
/**
* Determines how full the internal table can become before
* rehashing is required. This must be a value in the range: 0.0 <
* loadFactor < 1.0. The default value is 0.5, which is about as
* large as you can get in open addressing without hurting
* performance. Cf. Knuth, Volume 3., Chapter 6.
*/
protected float _loadFactor;
/**
* The maximum number of elements allowed without allocating more
* space.
*/
protected int _maxSize;
/** The number of removes that should be performed before an auto-compaction occurs. */
protected int _autoCompactRemovesRemaining;
/**
* The auto-compaction factor for the table.
*
* @see #setAutoCompactionFactor
*/
protected float _autoCompactionFactor;
/** @see #tempDisableAutoCompaction */
protected transient boolean _autoCompactTemporaryDisable = false;
/**
* Creates a new <code>THash</code> instance with the default
* capacity and load factor.
*/
public THash() {
this( DEFAULT_CAPACITY, DEFAULT_LOAD_FACTOR );
}
/**
* Creates a new <code>THash</code> instance with a prime capacity
* at or near the specified capacity and with the default load
* factor.
*
* @param initialCapacity an <code>int</code> value
*/
public THash( int initialCapacity ) {
this( initialCapacity, DEFAULT_LOAD_FACTOR );
}
/**
* Creates a new <code>THash</code> instance with a prime capacity
* at or near the minimum needed to hold <tt>initialCapacity</tt>
* elements with load factor <tt>loadFactor</tt> without triggering
* a rehash.
*
* @param initialCapacity an <code>int</code> value
* @param loadFactor a <code>float</code> value
*/
public THash( int initialCapacity, float loadFactor ) {
super();
_loadFactor = loadFactor;
// Through testing, the load factor (especially the default load factor) has been
// found to be a pretty good starting auto-compaction factor.
_autoCompactionFactor = loadFactor;
setUp( HashFunctions.fastCeil( initialCapacity / loadFactor ) );
}
/**
* Tells whether this set is currently holding any elements.
*
* @return a <code>boolean</code> value
*/
public boolean isEmpty() {
return 0 == _size;
}
/**
* Returns the number of distinct elements in this collection.
*
* @return an <code>int</code> value
*/
public int size() {
return _size;
}
/** @return the current physical capacity of the hash table. */
abstract public int capacity();
/**
* Ensure that this hashtable has sufficient capacity to hold
* <tt>desiredCapacity<tt> <b>additional</b> elements without
* requiring a rehash. This is a tuning method you can call
* before doing a large insert.
*
* @param desiredCapacity an <code>int</code> value
*/
public void ensureCapacity( int desiredCapacity ) {
if ( desiredCapacity > ( _maxSize - size() ) ) {
rehash( PrimeFinder.nextPrime( Math.max( size() + 1,
HashFunctions.fastCeil( ( desiredCapacity + size() ) / _loadFactor ) + 1 ) ) );
computeMaxSize( capacity() );
}
}
/**
* Compresses the hashtable to the minimum prime size (as defined
* by PrimeFinder) that will hold all of the elements currently in
* the table. If you have done a lot of <tt>remove</tt>
* operations and plan to do a lot of queries or insertions or
* iteration, it is a good idea to invoke this method. Doing so
* will accomplish two things:
* <p/>
* <ol>
* <li> You'll free memory allocated to the table but no
* longer needed because of the remove()s.</li>
* <p/>
* <li> You'll get better query/insert/iterator performance
* because there won't be any <tt>REMOVED</tt> slots to skip
* over when probing for indices in the table.</li>
* </ol>
*/
public void compact() {
// need at least one free spot for open addressing
rehash( PrimeFinder.nextPrime( Math.max( _size + 1,
HashFunctions.fastCeil( size() / _loadFactor ) + 1 ) ) );
computeMaxSize( capacity() );
// If auto-compaction is enabled, re-determine the compaction interval
if ( _autoCompactionFactor != 0 ) {
computeNextAutoCompactionAmount( size() );
}
}
/**
* The auto-compaction factor controls whether and when a table performs a
* {@link #compact} automatically after a certain number of remove operations.
* If the value is non-zero, the number of removes that need to occur for
* auto-compaction is the size of table at the time of the previous compaction
* (or the initial capacity) multiplied by this factor.
* <p/>
* Setting this value to zero will disable auto-compaction.
*
* @param factor a <tt>float</tt> that indicates the auto-compaction factor
*/
public void setAutoCompactionFactor( float factor ) {
if ( factor < 0 ) {
throw new IllegalArgumentException( "Factor must be >= 0: " + factor );
}
_autoCompactionFactor = factor;
}
/**
* @see #setAutoCompactionFactor
*
* @return a <<tt>float</tt> that represents the auto-compaction factor.
*/
public float getAutoCompactionFactor() {
return _autoCompactionFactor;
}
/**
* This simply calls {@link #compact compact}. It is included for
* symmetry with other collection classes. Note that the name of this
* method is somewhat misleading (which is why we prefer
* <tt>compact</tt>) as the load factor may require capacity above
* and beyond the size of this collection.
*
* @see #compact
*/
public final void trimToSize() {
compact();
}
/**
* Delete the record at <tt>index</tt>. Reduces the size of the
* collection by one.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_size--;
// If auto-compaction is enabled, see if we need to compact
if ( _autoCompactionFactor != 0 ) {
_autoCompactRemovesRemaining--;
if ( !_autoCompactTemporaryDisable && _autoCompactRemovesRemaining <= 0 ) {
// Do the compact
// NOTE: this will cause the next compaction interval to be calculated
compact();
}
}
}
/** Empties the collection. */
public void clear() {
_size = 0;
_free = capacity();
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = PrimeFinder.nextPrime( initialCapacity );
computeMaxSize( capacity );
computeNextAutoCompactionAmount( initialCapacity );
return capacity;
}
/**
* Rehashes the set.
*
* @param newCapacity an <code>int</code> value
*/
protected abstract void rehash( int newCapacity );
/**
* Temporarily disables auto-compaction. MUST be followed by calling
* {@link #reenableAutoCompaction}.
*/
public void tempDisableAutoCompaction() {
_autoCompactTemporaryDisable = true;
}
/**
* Re-enable auto-compaction after it was disabled via
* {@link #tempDisableAutoCompaction()}.
*
* @param check_for_compaction True if compaction should be performed if needed
* before returning. If false, no compaction will be
* performed.
*/
public void reenableAutoCompaction( boolean check_for_compaction ) {
_autoCompactTemporaryDisable = false;
if ( check_for_compaction && _autoCompactRemovesRemaining <= 0 &&
_autoCompactionFactor != 0 ) {
// Do the compact
// NOTE: this will cause the next compaction interval to be calculated
compact();
}
}
/**
* Computes the values of maxSize. There will always be at least
* one free slot required.
*
* @param capacity an <code>int</code> value
*/
protected void computeMaxSize( int capacity ) {
// need at least one free slot for open addressing
_maxSize = Math.min( capacity - 1, (int) ( capacity * _loadFactor ) );
_free = capacity - _size; // reset the free element count
}
/**
* Computes the number of removes that need to happen before the next auto-compaction
* will occur.
*
* @param size an <tt>int</tt> that sets the auto-compaction limit.
*/
protected void computeNextAutoCompactionAmount( int size ) {
if ( _autoCompactionFactor != 0 ) {
// NOTE: doing the round ourselves has been found to be faster than using
// Math.round.
_autoCompactRemovesRemaining =
(int) ( ( size * _autoCompactionFactor ) + 0.5f );
}
}
/**
* After an insert, this hook is called to adjust the size/free
* values of the set and to perform rehashing if necessary.
*
* @param usedFreeSlot the slot
*/
protected final void postInsertHook( boolean usedFreeSlot ) {
if ( usedFreeSlot ) {
_free--;
}
// rehash whenever we exhaust the available space in the table
if ( ++_size > _maxSize || _free == 0 ) {
// choose a new capacity suited to the new state of the table
// if we've grown beyond our maximum size, double capacity;
// if we've exhausted the free spots, rehash to the same capacity,
// which will free up any stale removed slots for reuse.
int newCapacity = _size > _maxSize ? PrimeFinder.nextPrime( capacity() << 1 ) : capacity();
rehash( newCapacity );
computeMaxSize( capacity() );
}
}
protected int calculateGrownCapacity() {
return capacity() << 1;
}
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// LOAD FACTOR
out.writeFloat( _loadFactor );
// AUTO COMPACTION LOAD FACTOR
out.writeFloat( _autoCompactionFactor );
}
public void readExternal( ObjectInput in )
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// LOAD FACTOR
float old_factor = _loadFactor;
_loadFactor = in.readFloat();
// AUTO COMPACTION LOAD FACTOR
_autoCompactionFactor = in.readFloat();
// If we change the laod factor from the default, re-setup
if ( old_factor != _loadFactor ) {
setUp( (int) Math.ceil( DEFAULT_CAPACITY / _loadFactor ) );
}
}
}// THash | 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/THash.java | Java | asf20 | 14,099 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for int/long primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TIntLongHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of ints */
public transient int[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TIntLongHash() {
super();
no_entry_key = ( int ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TIntLongHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( int ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TIntLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TIntLongHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( int ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TIntLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TIntLongHash( int initialCapacity, float loadFactor,
int no_entry_key, long no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new int[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>int</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( int val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TIntProcedure procedure ) {
byte[] states = _states;
int[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>int</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(int key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>int</code> value
* @return an <code>int</code> value
*/
protected int insertKey( int val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(int val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, int val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( int key ) {
int hash, probe, index, length;
final byte[] states = _states;
final int[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeInt( no_entry_key );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readInt();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
}
} // TIntLongHash
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TIntLongHash.java | Java | asf20 | 14,104 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for long/long primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TLongLongHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of longs */
public transient long[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TLongLongHash() {
super();
no_entry_key = ( long ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongLongHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( long ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TLongLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongLongHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( long ) 0;
no_entry_value = ( long ) 0;
}
/**
* Creates a new <code>TLongLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TLongLongHash( int initialCapacity, float loadFactor,
long no_entry_key, long no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new long[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( long val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TLongProcedure procedure ) {
byte[] states = _states;
long[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>long</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(long key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>long</code> value
* @return an <code>int</code> value
*/
protected int insertKey( long val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(long val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, long val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeLong( no_entry_key );
// NO_ENTRY_VALUE
out.writeLong( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readLong();
// NO_ENTRY_VALUE
no_entry_value = in.readLong();
}
} // TLongLongHash
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TLongLongHash.java | Java | asf20 | 14,139 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.TObjectProcedure;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* An open addressed hashing implementation for Object types.
* <p/>
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: TObjectHash.java,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TObjectHash<T> extends THash {
@SuppressWarnings({"UnusedDeclaration"})
static final long serialVersionUID = -3461112548087185871L;
/**
* the set of Objects
*/
public transient Object[] _set;
public static final Object REMOVED = new Object(), FREE = new Object();
/**
* Indicates whether the last insertKey() call used a FREE slot. This field
* should be inspected right after call insertKey()
*/
protected boolean consumeFreeSlot;
/**
* Creates a new <code>TObjectHash</code> instance with the
* default capacity and load factor.
*/
public TObjectHash() {
super();
}
/**
* Creates a new <code>TObjectHash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TObjectHash(int initialCapacity) {
super(initialCapacity);
}
/**
* Creates a new <code>TObjectHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TObjectHash(int initialCapacity, float loadFactor) {
super(initialCapacity, loadFactor);
}
public int capacity() {
return _set.length;
}
protected void removeAt(int index) {
_set[index] = REMOVED;
super.removeAt(index);
}
/**
* initializes the Object set of this hash table.
*
* @param initialCapacity an <code>int</code> value
* @return an <code>int</code> value
*/
public int setUp(int initialCapacity) {
int capacity;
capacity = super.setUp(initialCapacity);
_set = new Object[capacity];
Arrays.fill(_set, FREE);
return capacity;
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
@SuppressWarnings({"unchecked"})
public boolean forEach(TObjectProcedure<? super T> procedure) {
Object[] set = _set;
for (int i = set.length; i-- > 0;) {
if (set[i] != FREE
&& set[i] != REMOVED
&& !procedure.execute((T) set[i])) {
return false;
}
}
return true;
}
/**
* Searches the set for <tt>obj</tt>
*
* @param obj an <code>Object</code> value
* @return a <code>boolean</code> value
*/
@SuppressWarnings({"unchecked"})
public boolean contains(Object obj) {
return index(obj) >= 0;
}
/**
* Locates the index of <tt>obj</tt>.
*
* @param obj an <code>Object</code> value
* @return the index of <tt>obj</tt> or -1 if it isn't in the set.
*/
protected int index(Object obj) {
if (obj == null)
return indexForNull();
// From here on we know obj to be non-null
final int hash = hash(obj) & 0x7fffffff;
int index = hash % _set.length;
Object cur = _set[index];
if (cur == FREE) {
return -1;
}
if (cur == obj || equals(obj, cur)) {
return index;
}
return indexRehashed(obj, index, hash, cur);
}
/**
* Locates the index of non-null <tt>obj</tt>.
*
* @param obj target key, know to be non-null
* @param index we start from
* @param hash
* @param cur
* @return
*/
private int indexRehashed(Object obj, int index, int hash, Object cur) {
final Object[] set = _set;
final int length = set.length;
// NOTE: here it has to be REMOVED or FULL (some user-given value)
// see Knuth, p. 529
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
cur = set[index];
//
if (cur == FREE)
return -1;
//
if ((cur == obj || equals(obj, cur)))
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index <tt>null</tt>.
* <p/>
* null specific loop exploiting several properties to simplify the iteration logic
* - the null value hashes to 0 we so we can iterate from the beginning.
* - the probe value is 1 for this case
* - object identity can be used to match this case
* <p/>
* --> this result a simpler loop
*
* @return
*/
private int indexForNull() {
int index = 0;
for (Object o : _set) {
if (o == null)
return index;
if (o == FREE)
return -1;
index++;
}
return -1;
}
/**
* Alias introduced to avoid breaking the API. The new method name insertKey() reflects the
* changes made to the logic.
*
* @param obj
* @return
* @deprecated use {@link #insertKey} instead
*/
@Deprecated
protected int insertionIndex(T obj) {
return insertKey(obj);
}
/**
* Locates the index at which <tt>key</tt> can be inserted. if
* there is already a value equal()ing <tt>key</tt> in the set,
* returns that value's index as <tt>-index - 1</tt>.
* <p/>
* If a slot is found the value is inserted. When a FREE slot is used the consumeFreeSlot field is
* set to true. This field should be used in the method invoking insertKey() to pass to postInsertHook()
*
* @param key an <code>Object</code> value
* @return the index of a FREE slot at which key can be inserted
* or, if key is already stored in the hash, the negative value of
* that index, minus 1: -index -1.
*/
protected int insertKey(T key) {
consumeFreeSlot = false;
if (key == null)
return insertKeyForNull();
final int hash = hash(key) & 0x7fffffff;
int index = hash % _set.length;
Object cur = _set[index];
if (cur == FREE) {
consumeFreeSlot = true;
_set[index] = key; // insert value
return index; // empty, all done
}
if (cur == key || equals(key, cur)) {
return -index - 1; // already stored
}
return insertKeyRehash(key, index, hash, cur);
}
/**
* Looks for a slot using double hashing for a non-null key values and inserts the value
* in the slot
*
* @param key non-null key value
* @param index natural index
* @param hash
* @param cur value of first matched slot
* @return
*/
private int insertKeyRehash(T key, int index, int hash, Object cur) {
final Object[] set = _set;
final int length = set.length;
// already FULL or REMOVED, must probe
// compute the double hash
final int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (cur == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
cur = set[index];
// A FREE slot stops the search
if (cur == FREE) {
if (firstRemoved != -1) {
_set[firstRemoved] = key;
return firstRemoved;
} else {
consumeFreeSlot = true;
_set[index] = key; // insert value
return index;
}
}
if (cur == key || equals(key, cur)) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
_set[firstRemoved] = key;
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
/**
* Looks for a slot using double hashing for a null key value and inserts the value.
* <p/>
* null specific loop exploiting several properties to simplify the iteration logic
* - the null value hashes to 0 we so we can iterate from the beginning.
* - the probe value is 1 for this case
* - object identity can be used to match this case
*
* @return
*/
private int insertKeyForNull() {
int index = 0;
int firstRemoved = -1;
// Look for a slot containing the 'null' value as key
for (Object o : _set) {
// Locate first removed
if (o == REMOVED && firstRemoved == -1)
firstRemoved = index;
if (o == FREE) {
if (firstRemoved != -1) {
_set[firstRemoved] = null;
return firstRemoved;
} else {
consumeFreeSlot = true;
_set[index] = null; // insert value
return index;
}
}
if (o == null) {
return -index - 1;
}
index++;
}
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
_set[firstRemoved] = null;
return firstRemoved;
}
// We scanned the entire key set and found nothing, is set full?
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("Could not find insertion index for null key. Key set full!?!!");
}
/**
* Convenience methods for subclasses to use in throwing exceptions about
* badly behaved user objects employed as keys. We have to throw an
* IllegalArgumentException with a rather verbose message telling the
* user that they need to fix their object implementation to conform
* to the general contract for java.lang.Object.
*
*
* @param o1 the first of the equal elements with unequal hash codes.
* @param o2 the second of the equal elements with unequal hash codes.
* @throws IllegalArgumentException the whole point of this method.
*/
protected final void throwObjectContractViolation(Object o1, Object o2)
throws IllegalArgumentException {
throw buildObjectContractViolation(o1, o2, "");
}
/**
* Convenience methods for subclasses to use in throwing exceptions about
* badly behaved user objects employed as keys. We have to throw an
* IllegalArgumentException with a rather verbose message telling the
* user that they need to fix their object implementation to conform
* to the general contract for java.lang.Object.
*
*
* @param o1 the first of the equal elements with unequal hash codes.
* @param o2 the second of the equal elements with unequal hash codes.
* @param size
*@param oldSize
* @param oldKeys @throws IllegalArgumentException the whole point of this method.
*/
protected final void throwObjectContractViolation(Object o1, Object o2, int size, int oldSize, Object[] oldKeys)
throws IllegalArgumentException {
String extra = dumpExtraInfo(o1, o2, size(), oldSize, oldKeys);
throw buildObjectContractViolation(o1, o2, extra);
}
/**
* Convenience methods for subclasses to use in throwing exceptions about
* badly behaved user objects employed as keys. We have to throw an
* IllegalArgumentException with a rather verbose message telling the
* user that they need to fix their object implementation to conform
* to the general contract for java.lang.Object.
*
*
* @param o1 the first of the equal elements with unequal hash codes.
* @param o2 the second of the equal elements with unequal hash codes.
* @throws IllegalArgumentException the whole point of this method.
*/
protected final IllegalArgumentException buildObjectContractViolation(Object o1, Object o2, String extra ) {
return new IllegalArgumentException("Equal objects must have equal hashcodes. " +
"During rehashing, Trove discovered that the following two objects claim " +
"to be equal (as in java.lang.Object.equals()) but their hashCodes (or " +
"those calculated by your TObjectHashingStrategy) are not equal." +
"This violates the general contract of java.lang.Object.hashCode(). See " +
"bullet point two in that method's documentation. object #1 =" + objectInfo(o1) +
"; object #2 =" + objectInfo(o2) + "\n" + extra);
}
protected boolean equals(Object notnull, Object two) {
if (two == null || two == REMOVED)
return false;
return notnull.equals(two);
}
protected int hash(Object notnull) {
return notnull.hashCode();
}
protected static String reportPotentialConcurrentMod(int newSize, int oldSize) {
// Note that we would not be able to detect concurrent paired of put()-remove()
// operations with this simple check
if (newSize != oldSize)
return "[Warning] apparent concurrent modification of the key set. " +
"Size before and after rehash() do not match " + oldSize + " vs " + newSize;
return "";
}
/**
*
* @param newVal the key being inserted
* @param oldVal the key already stored at that position
* @param currentSize size of the key set during rehashing
* @param oldSize size of the key set before rehashing
* @param oldKeys the old key set
*/
protected String dumpExtraInfo(Object newVal, Object oldVal, int currentSize, int oldSize, Object[] oldKeys) {
StringBuilder b = new StringBuilder();
//
b.append(dumpKeyTypes(newVal, oldVal));
b.append(reportPotentialConcurrentMod(currentSize, oldSize));
b.append(detectKeyLoss(oldKeys, oldSize));
// Is de same object already present? Double insert?
if (newVal == oldVal) {
b.append("Inserting same object twice, rehashing bug. Object= ").append(oldVal);
}
return b.toString();
}
/**
* Detect inconsistent hashCode() and/or equals() methods
*
* @param keys
* @param oldSize
* @return
*/
private static String detectKeyLoss(Object[] keys, int oldSize) {
StringBuilder buf = new StringBuilder();
Set<Object> k = makeKeySet(keys);
if (k.size() != oldSize) {
buf.append("\nhashCode() and/or equals() have inconsistent implementation");
buf.append("\nKey set lost entries, now got ").append(k.size()).append(" instead of ").append(oldSize);
buf.append(". This can manifest itself as an apparent duplicate key.");
}
return buf.toString();
}
private static Set<Object> makeKeySet(Object[] keys) {
Set<Object> types = new HashSet<Object>();
for (Object o : keys) {
if (o != FREE && o != REMOVED) {
types.add(o);
}
}
return types;
}
private static String equalsSymmetryInfo(Object a, Object b) {
StringBuilder buf = new StringBuilder();
if (a == b) {
return "a == b";
}
if (a.getClass() != b.getClass()) {
buf.append("Class of objects differ a=").append(a.getClass()).append(" vs b=").append(b.getClass());
boolean aEb = a.equals(b);
boolean bEa = b.equals(a);
if (aEb != bEa) {
buf.append("\nequals() of a or b object are asymmetric");
buf.append("\na.equals(b) =").append(aEb);
buf.append("\nb.equals(a) =").append(bEa);
}
}
return buf.toString();
}
protected static String objectInfo(Object o) {
return (o == null ? "class null" : o.getClass()) + " id= " + System.identityHashCode(o)
+ " hashCode= " + (o == null ? 0 : o.hashCode()) + " toString= " + String.valueOf(o);
}
private String dumpKeyTypes(Object newVal, Object oldVal) {
StringBuilder buf = new StringBuilder();
Set<Class<?>> types = new HashSet<Class<?>>();
for (Object o : _set) {
if (o != FREE && o != REMOVED) {
if (o != null)
types.add(o.getClass());
else
types.add(null);
}
}
if (types.size() > 1) {
buf.append("\nMore than one type used for keys. Watch out for asymmetric equals(). " +
"Read about the 'Liskov substitution principle' and the implications for equals() in java.");
buf.append("\nKey types: ").append(types);
buf.append(equalsSymmetryInfo(newVal, oldVal));
}
return buf.toString();
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
// VERSION
out.writeByte(0);
// SUPER
super.writeExternal(out);
}
@Override
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal(in);
}
} // TObjectHash
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TObjectHash.java | Java | asf20 | 20,561 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.TLongProcedure;
import gnu.trove.impl.HashFunctions;
import gnu.trove.impl.Constants;
import java.util.Arrays;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for long primitives.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman, Rob Eden, Jeff Randall
* @version $Id: _E_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TLongHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of longs */
public transient long[] _set;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>TLongHash</code> instance with the default
* capacity and load factor.
*/
public TLongHash() {
super();
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongHash( int initialCapacity ) {
super( initialCapacity );
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_value = Constants.DEFAULT_LONG_NO_ENTRY_VALUE;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Creates a new <code>TLongHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TLongHash( int initialCapacity, float loadFactor, long no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_value = no_entry_value;
//noinspection RedundantCast
if ( no_entry_value != ( long ) 0 ) {
Arrays.fill( _set, no_entry_value );
}
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new long[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( long val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each element in the set.
*
* @param procedure a <code>TObjectProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TLongProcedure procedure ) {
byte[] states = _states;
long[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_value;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param val an <code>long</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( long val ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( val ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == val)
return index;
return indexRehashed(val, index, hash, state);
}
int indexRehashed(long key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param val an <code>long</code> value
* @return an <code>int</code> value
*/
protected int insertKey( long val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(long val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, long val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
} // TLongHash
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TLongHash.java | Java | asf20 | 10,090 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove.impl.hash;
import gnu.trove.procedure.*;
import gnu.trove.impl.HashFunctions;
import java.io.ObjectOutput;
import java.io.ObjectInput;
import java.io.IOException;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
/**
* An open addressed hashing implementation for long/int primitive entries.
*
* Created: Sun Nov 4 08:56:06 2001
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _K__V_Hash.template,v 1.1.2.6 2009/11/07 03:36:44 robeden Exp $
*/
abstract public class TLongIntHash extends TPrimitiveHash {
static final long serialVersionUID = 1L;
/** the set of longs */
public transient long[] _set;
/**
* key that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected long no_entry_key;
/**
* value that represents null
*
* NOTE: should not be modified after the Hash is created, but is
* not final because of Externalization
*
*/
protected int no_entry_value;
protected boolean consumeFreeSlot;
/**
* Creates a new <code>T#E#Hash</code> instance with the default
* capacity and load factor.
*/
public TLongIntHash() {
super();
no_entry_key = ( long ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>T#E#Hash</code> instance whose capacity
* is the next highest prime above <tt>initialCapacity + 1</tt>
* unless that value is already prime.
*
* @param initialCapacity an <code>int</code> value
*/
public TLongIntHash( int initialCapacity ) {
super( initialCapacity );
no_entry_key = ( long ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TLongIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
*/
public TLongIntHash( int initialCapacity, float loadFactor ) {
super(initialCapacity, loadFactor);
no_entry_key = ( long ) 0;
no_entry_value = ( int ) 0;
}
/**
* Creates a new <code>TLongIntHash</code> instance with a prime
* value at or near the specified capacity and load factor.
*
* @param initialCapacity used to find a prime capacity for the table.
* @param loadFactor used to calculate the threshold over which
* rehashing takes place.
* @param no_entry_value value that represents null
*/
public TLongIntHash( int initialCapacity, float loadFactor,
long no_entry_key, int no_entry_value ) {
super(initialCapacity, loadFactor);
this.no_entry_key = no_entry_key;
this.no_entry_value = no_entry_value;
}
/**
* Returns the value that is used to represent null as a key. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public long getNoEntryKey() {
return no_entry_key;
}
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
public int getNoEntryValue() {
return no_entry_value;
}
/**
* initializes the hashtable to a prime capacity which is at least
* <tt>initialCapacity + 1</tt>.
*
* @param initialCapacity an <code>int</code> value
* @return the actual capacity chosen
*/
protected int setUp( int initialCapacity ) {
int capacity;
capacity = super.setUp( initialCapacity );
_set = new long[capacity];
return capacity;
}
/**
* Searches the set for <tt>val</tt>
*
* @param val an <code>long</code> value
* @return a <code>boolean</code> value
*/
public boolean contains( long val ) {
return index(val) >= 0;
}
/**
* Executes <tt>procedure</tt> for each key in the map.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the set terminated because
* the procedure returned false for some value.
*/
public boolean forEach( TLongProcedure procedure ) {
byte[] states = _states;
long[] set = _set;
for ( int i = set.length; i-- > 0; ) {
if ( states[i] == FULL && ! procedure.execute( set[i] ) ) {
return false;
}
}
return true;
}
/**
* Releases the element currently stored at <tt>index</tt>.
*
* @param index an <code>int</code> value
*/
protected void removeAt( int index ) {
_set[index] = no_entry_key;
super.removeAt( index );
}
/**
* Locates the index of <tt>val</tt>.
*
* @param key an <code>long</code> value
* @return the index of <tt>val</tt> or -1 if it isn't in the set.
*/
protected int index( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
if (state == FREE)
return -1;
if (state == FULL && set[index] == key)
return index;
return indexRehashed(key, index, hash, state);
}
int indexRehashed(long key, int index, int hash, byte state) {
// see Knuth, p. 529
int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
do {
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
//
if (state == FREE)
return -1;
//
if (key == _set[index])
return index;
} while (index != loopIndex);
return -1;
}
/**
* Locates the index at which <tt>val</tt> can be inserted. if
* there is already a value equal()ing <tt>val</tt> in the set,
* returns that value as a negative integer.
*
* @param key an <code>long</code> value
* @return an <code>int</code> value
*/
protected int insertKey( long val ) {
int hash, index;
hash = HashFunctions.hash(val) & 0x7fffffff;
index = hash % _states.length;
byte state = _states[index];
consumeFreeSlot = false;
if (state == FREE) {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index; // empty, all done
}
if (state == FULL && _set[index] == val) {
return -index - 1; // already stored
}
// already FULL or REMOVED, must probe
return insertKeyRehash(val, index, hash, state);
}
int insertKeyRehash(long val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
}
void insertKeyAt(int index, long val) {
_set[index] = val; // insert value
_states[index] = FULL;
}
protected int XinsertKey( long key ) {
int hash, probe, index, length;
final byte[] states = _states;
final long[] set = _set;
length = states.length;
hash = HashFunctions.hash( key ) & 0x7fffffff;
index = hash % length;
byte state = states[index];
consumeFreeSlot = false;
if ( state == FREE ) {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index; // empty, all done
} else if ( state == FULL && set[index] == key ) {
return -index -1; // already stored
} else { // already FULL or REMOVED, must probe
// compute the double hash
probe = 1 + ( hash % ( length - 2 ) );
// if the slot we landed on is FULL (but not removed), probe
// until we find an empty slot, a REMOVED slot, or an element
// equal to the one we are trying to insert.
// finding an empty slot means that the value is not present
// and that we should use that slot as the insertion point;
// finding a REMOVED slot means that we need to keep searching,
// however we want to remember the offset of that REMOVED slot
// so we can reuse it in case a "new" insertion (i.e. not an update)
// is possible.
// finding a matching value means that we've found that our desired
// key is already in the table
if ( state != REMOVED ) {
// starting at the natural offset, probe until we find an
// offset that isn't full.
do {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
} while ( state == FULL && set[index] != key );
}
// if the index we found was removed: continue probing until we
// locate a free location or an element which equal()s the
// one we have.
if ( state == REMOVED) {
int firstRemoved = index;
while ( state != FREE && ( state == REMOVED || set[index] != key ) ) {
index -= probe;
if (index < 0) {
index += length;
}
state = states[index];
}
if (state == FULL) {
return -index -1;
} else {
set[index] = key;
states[index] = FULL;
return firstRemoved;
}
}
// if it's full, the key is already stored
if (state == FULL) {
return -index -1;
} else {
consumeFreeSlot = true;
set[index] = key;
states[index] = FULL;
return index;
}
}
}
/** {@inheritDoc} */
public void writeExternal( ObjectOutput out ) throws IOException {
// VERSION
out.writeByte( 0 );
// SUPER
super.writeExternal( out );
// NO_ENTRY_KEY
out.writeLong( no_entry_key );
// NO_ENTRY_VALUE
out.writeInt( no_entry_value );
}
/** {@inheritDoc} */
public void readExternal( ObjectInput in ) throws IOException, ClassNotFoundException {
// VERSION
in.readByte();
// SUPER
super.readExternal( in );
// NO_ENTRY_KEY
no_entry_key = in.readLong();
// NO_ENTRY_VALUE
no_entry_value = in.readInt();
}
} // TLongIntHash
| 04146814d-23 | SimpleTrove/src/gnu/trove/impl/hash/TLongIntHash.java | Java | asf20 | 14,122 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TIntIterator;
import gnu.trove.procedure.TIntProcedure;
import java.util.Collection;
import java.io.Serializable;
/**
* An interface that mimics the <tt>Collection</tt> interface.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $
*/
public interface TIntCollection {
static final long serialVersionUID = 1L;
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
int getNoEntryValue();
/**
* Returns the number of elements in this collection (its cardinality). If this
* collection contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this collection (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this collection contains no elements.
*
* @return <tt>true</tt> if this collection contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this collection contains the specified element.
*
* @param entry an <code>int</code> value
* @return true if the collection contains the specified element.
*/
boolean contains( int entry );
/**
* Creates an iterator over the values of the collection. The iterator
* supports element deletion.
*
* @return an <code>TIntIterator</code> value
*/
TIntIterator iterator();
/**
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this collection. (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this collection
*/
int[] toArray();
/**
* Returns an array containing elements in this collection.
*
* <p>If this collection fits in the specified array with room to spare
* (i.e., the array has more elements than this collection), the element in
* the array immediately following the end of the collection is collection to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this collection <i>only</i> if the caller knows that this
* collection does not contain any elements representing null.)
*
* <p>If the native array is smaller than the collection size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this collection are to be
* stored.
* @return an <tt>int[]</tt> containing all the elements in this collection
* @throws NullPointerException if the specified array is null
*/
int[] toArray( int[] dest );
/**
* Inserts a value into the collection.
*
* @param entry a <code>int</code> value
* @return true if the collection was modified by the add operation
*/
boolean add( int entry );
/**
* Removes <tt>entry</tt> from the collection.
*
* @param entry an <code>int</code> value
* @return true if the collection was modified by the remove operation.
*/
boolean remove( int entry );
/**
* Tests the collection to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>TIntCollection</tt> are present.
*
* @param collection a <code>TIntCollection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( TIntCollection collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of int primitives.
* @return true if all elements were present in the collection.
*/
boolean containsAll( int[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( Collection<? extends Integer> collection );
/**
* Adds all of the elements in the <tt>TIntCollection</tt> to the collection.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( TIntCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the collection.
*
* @param array a <code>array</code> of int primitives.
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( int[] array );
/**
* Removes any values in the collection which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the collection which are not contained in
* <tt>TIntCollection</tt>.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( TIntCollection collection );
/**
* Removes any values in the collection which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of int primitives.
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( int[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TIntCollection</tt> from the collection.
*
* @param collection a <code>TIntCollection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( TIntCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the collection.
*
* @param array an <code>array</code> of int primitives.
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( int[] array );
/**
* Empties the collection.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the collection.
*
* @param procedure a <code>TIntProcedure</code> value
* @return false if the loop over the collection terminated because
* the procedure returned false for some value.
*/
boolean forEach( TIntProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this collection for equality. Returns
* <tt>true</tt> if the specified object is also a collection, the two collection
* have the same size, and every member of the specified collection is
* contained in this collection (or equivalently, every member of this collection is
* contained in the specified collection). This definition ensures that the
* equals method works properly across different implementations of the
* collection interface.
*
* @param o object to be compared for equality with this collection
* @return <tt>true</tt> if the specified object is equal to this collection
*/
boolean equals( Object o );
/**
* Returns the hash code value for this collection. The hash code of a collection is
* defined to be the sum of the hash codes of the elements in the collection.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two collection <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this collection
* @see Object#equals(Object)
* @see Collection#equals(Object)
*/
int hashCode();
} // TIntCollection
| 04146814d-23 | SimpleTrove/src/gnu/trove/TIntCollection.java | Java | asf20 | 10,699 |
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2001, Eric D. Friedman All Rights Reserved.
// Copyright (c) 2009, Rob Eden All Rights Reserved.
// Copyright (c) 2009, Jeff Randall All Rights Reserved.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
///////////////////////////////////////////////////////////////////////////////
package gnu.trove;
//////////////////////////////////////////////////
// THIS IS A GENERATED CLASS. DO NOT HAND EDIT! //
//////////////////////////////////////////////////
import gnu.trove.iterator.TLongIterator;
import gnu.trove.procedure.TLongProcedure;
import java.util.Collection;
import java.io.Serializable;
/**
* An interface that mimics the <tt>Collection</tt> interface.
*
* @author Eric D. Friedman
* @author Rob Eden
* @author Jeff Randall
* @version $Id: _E_Collection.template,v 1.1.2.2 2009/09/15 02:38:30 upholderoftruth Exp $
*/
public interface TLongCollection {
static final long serialVersionUID = 1L;
/**
* Returns the value that is used to represent null. The default
* value is generally zero, but can be changed during construction
* of the collection.
*
* @return the value that represents null
*/
long getNoEntryValue();
/**
* Returns the number of elements in this collection (its cardinality). If this
* collection contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
* <tt>Integer.MAX_VALUE</tt>.
*
* @return the number of elements in this collection (its cardinality)
*/
int size();
/**
* Returns <tt>true</tt> if this collection contains no elements.
*
* @return <tt>true</tt> if this collection contains no elements
*/
boolean isEmpty();
/**
* Returns <tt>true</tt> if this collection contains the specified element.
*
* @param entry an <code>long</code> value
* @return true if the collection contains the specified element.
*/
boolean contains( long entry );
/**
* Creates an iterator over the values of the collection. The iterator
* supports element deletion.
*
* @return an <code>TLongIterator</code> value
*/
TLongIterator iterator();
/**
* Returns an array containing all of the elements in this collection.
* If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the
* elements in the same order.
*
* <p>The returned array will be "safe" in that no references to it
* are maintained by this collection. (In other words, this method must
* allocate a new array even if this collection is backed by an array).
* The caller is thus free to modify the returned array.
*
* <p>This method acts as bridge between array-based and collection-based
* APIs.
*
* @return an array containing all the elements in this collection
*/
long[] toArray();
/**
* Returns an array containing elements in this collection.
*
* <p>If this collection fits in the specified array with room to spare
* (i.e., the array has more elements than this collection), the element in
* the array immediately following the end of the collection is collection to
* <tt>{@link #getNoEntryValue()}</tt>. (This is useful in determining
* the length of this collection <i>only</i> if the caller knows that this
* collection does not contain any elements representing null.)
*
* <p>If the native array is smaller than the collection size,
* the array will be filled with elements in Iterator order
* until it is full and exclude the remainder.
*
* <p>If this collection makes any guarantees as to what order its elements
* are returned by its iterator, this method must return the elements
* in the same order.
*
* @param dest the array into which the elements of this collection are to be
* stored.
* @return an <tt>long[]</tt> containing all the elements in this collection
* @throws NullPointerException if the specified array is null
*/
long[] toArray( long[] dest );
/**
* Inserts a value into the collection.
*
* @param entry a <code>long</code> value
* @return true if the collection was modified by the add operation
*/
boolean add( long entry );
/**
* Removes <tt>entry</tt> from the collection.
*
* @param entry an <code>long</code> value
* @return true if the collection was modified by the remove operation.
*/
boolean remove( long entry );
/**
* Tests the collection to determine if all of the elements in
* <tt>collection</tt> are present.
*
* @param collection a <code>Collection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( Collection<?> collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>TLongCollection</tt> are present.
*
* @param collection a <code>TLongCollection</code> value
* @return true if all elements were present in the collection.
*/
boolean containsAll( TLongCollection collection );
/**
* Tests the collection to determine if all of the elements in
* <tt>array</tt> are present.
*
* @param array as <code>array</code> of long primitives.
* @return true if all elements were present in the collection.
*/
boolean containsAll( long[] array );
/**
* Adds all of the elements in <tt>collection</tt> to the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( Collection<? extends Long> collection );
/**
* Adds all of the elements in the <tt>TLongCollection</tt> to the collection.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( TLongCollection collection );
/**
* Adds all of the elements in the <tt>array</tt> to the collection.
*
* @param array a <code>array</code> of long primitives.
* @return true if the collection was modified by the add all operation.
*/
boolean addAll( long[] array );
/**
* Removes any values in the collection which are not contained in
* <tt>collection</tt>.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( Collection<?> collection );
/**
* Removes any values in the collection which are not contained in
* <tt>TLongCollection</tt>.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( TLongCollection collection );
/**
* Removes any values in the collection which are not contained in
* <tt>array</tt>.
*
* @param array an <code>array</code> of long primitives.
* @return true if the collection was modified by the retain all operation
*/
boolean retainAll( long[] array );
/**
* Removes all of the elements in <tt>collection</tt> from the collection.
*
* @param collection a <code>Collection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( Collection<?> collection );
/**
* Removes all of the elements in <tt>TLongCollection</tt> from the collection.
*
* @param collection a <code>TLongCollection</code> value
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( TLongCollection collection );
/**
* Removes all of the elements in <tt>array</tt> from the collection.
*
* @param array an <code>array</code> of long primitives.
* @return true if the collection was modified by the remove all operation.
*/
boolean removeAll( long[] array );
/**
* Empties the collection.
*/
void clear();
/**
* Executes <tt>procedure</tt> for each element in the collection.
*
* @param procedure a <code>TLongProcedure</code> value
* @return false if the loop over the collection terminated because
* the procedure returned false for some value.
*/
boolean forEach( TLongProcedure procedure );
// Comparison and hashing
/**
* Compares the specified object with this collection for equality. Returns
* <tt>true</tt> if the specified object is also a collection, the two collection
* have the same size, and every member of the specified collection is
* contained in this collection (or equivalently, every member of this collection is
* contained in the specified collection). This definition ensures that the
* equals method works properly across different implementations of the
* collection interface.
*
* @param o object to be compared for equality with this collection
* @return <tt>true</tt> if the specified object is equal to this collection
*/
boolean equals( Object o );
/**
* Returns the hash code value for this collection. The hash code of a collection is
* defined to be the sum of the hash codes of the elements in the collection.
* This ensures that <tt>s1.equals(s2)</tt> implies that
* <tt>s1.hashCode()==s2.hashCode()</tt> for any two collection <tt>s1</tt>
* and <tt>s2</tt>, as required by the general contract of
* {@link Object#hashCode}.
*
* @return the hash code value for this collection
* @see Object#equals(Object)
* @see Collection#equals(Object)
*/
int hashCode();
} // TLongCollection
| 04146814d-23 | SimpleTrove/src/gnu/trove/TLongCollection.java | Java | asf20 | 10,735 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing;
import java.util.LinkedList;
import static net.robotmedia.billing.BillingRequest.*;
import net.robotmedia.billing.utils.Compatibility;
import com.android.vending.billing.IMarketBillingService;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class BillingService extends Service implements ServiceConnection {
private static enum Action {
CHECK_BILLING_SUPPORTED, CONFIRM_NOTIFICATIONS, GET_PURCHASE_INFORMATION, REQUEST_PURCHASE, RESTORE_TRANSACTIONS,
}
private static final String ACTION_MARKET_BILLING_SERVICE = "com.android.vending.billing.MarketBillingService.BIND";
private static final String EXTRA_DEVELOPER_PAYLOAD = "DEVELOPER_PAYLOAD";
private static final String EXTRA_ITEM_ID = "ITEM_ID";
private static final String EXTRA_NONCE = "EXTRA_NONCE";
private static final String EXTRA_NOTIFY_IDS = "NOTIFY_IDS";
private static LinkedList<BillingRequest> mPendingRequests = new LinkedList<BillingRequest>();
private static IMarketBillingService mService;
public static void checkBillingSupported(Context context) {
final Intent intent = createIntent(context, Action.CHECK_BILLING_SUPPORTED);
context.startService(intent);
}
public static void confirmNotifications(Context context, String[] notifyIds) {
final Intent intent = createIntent(context, Action.CONFIRM_NOTIFICATIONS);
intent.putExtra(EXTRA_NOTIFY_IDS, notifyIds);
context.startService(intent);
}
private static Intent createIntent(Context context, Action action) {
final String actionString = getActionForIntent(context, action);
final Intent intent = new Intent(actionString);
intent.setClass(context, BillingService.class);
return intent;
}
private static final String getActionForIntent(Context context, Action action) {
return context.getPackageName() + "." + action.toString();
}
public static void getPurchaseInformation(Context context, String[] notifyIds, long nonce) {
final Intent intent = createIntent(context, Action.GET_PURCHASE_INFORMATION);
intent.putExtra(EXTRA_NOTIFY_IDS, notifyIds);
intent.putExtra(EXTRA_NONCE, nonce);
context.startService(intent);
}
public static void requestPurchase(Context context, String itemId, String developerPayload) {
final Intent intent = createIntent(context, Action.REQUEST_PURCHASE);
intent.putExtra(EXTRA_ITEM_ID, itemId);
intent.putExtra(EXTRA_DEVELOPER_PAYLOAD, developerPayload);
context.startService(intent);
}
public static void restoreTransations(Context context, long nonce) {
final Intent intent = createIntent(context, Action.RESTORE_TRANSACTIONS);
intent.setClass(context, BillingService.class);
intent.putExtra(EXTRA_NONCE, nonce);
context.startService(intent);
}
private void bindMarketBillingService() {
try {
final boolean bindResult = bindService(new Intent(ACTION_MARKET_BILLING_SERVICE), this, Context.BIND_AUTO_CREATE);
if (!bindResult) {
Log.e(this.getClass().getSimpleName(), "Could not bind to MarketBillingService");
}
} catch (SecurityException e) {
Log.e(this.getClass().getSimpleName(), "Could not bind to MarketBillingService", e);
}
}
private void checkBillingSupported(int startId) {
final String packageName = getPackageName();
final CheckBillingSupported request = new CheckBillingSupported(packageName, startId);
runRequestOrQueue(request);
}
private void confirmNotifications(Intent intent, int startId) {
final String packageName = getPackageName();
final String[] notifyIds = intent.getStringArrayExtra(EXTRA_NOTIFY_IDS);
final ConfirmNotifications request = new ConfirmNotifications(packageName, startId, notifyIds);
runRequestOrQueue(request);
}
private Action getActionFromIntent(Intent intent) {
final String actionString = intent.getAction();
if (actionString == null) {
return null;
}
final String[] split = actionString.split("\\.");
if (split.length <= 0) {
return null;
}
return Action.valueOf(split[split.length - 1]);
}
private void getPurchaseInformation(Intent intent, int startId) {
final String packageName = getPackageName();
final long nonce = intent.getLongExtra(EXTRA_NONCE, 0);
final String[] notifyIds = intent.getStringArrayExtra(EXTRA_NOTIFY_IDS);
final GetPurchaseInformation request = new GetPurchaseInformation(packageName, startId, notifyIds);
request.setNonce(nonce);
runRequestOrQueue(request);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IMarketBillingService.Stub.asInterface(service);
runPendingRequests();
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
// This is the old onStart method that will be called on the pre-2.0
// platform. On 2.0 or later we override onStartCommand() so this
// method will not be called.
@Override
public void onStart(Intent intent, int startId) {
handleCommand(intent, startId);
}
// @Override // Avoid compile errors on pre-2.0
public int onStartCommand(Intent intent, int flags, int startId) {
handleCommand(intent, startId);
return Compatibility.START_NOT_STICKY;
}
private void handleCommand(Intent intent, int startId) {
final Action action = getActionFromIntent(intent);
if (action == null) {
return;
}
switch (action) {
case CHECK_BILLING_SUPPORTED:
checkBillingSupported(startId);
break;
case REQUEST_PURCHASE:
requestPurchase(intent, startId);
break;
case GET_PURCHASE_INFORMATION:
getPurchaseInformation(intent, startId);
break;
case CONFIRM_NOTIFICATIONS:
confirmNotifications(intent, startId);
break;
case RESTORE_TRANSACTIONS:
restoreTransactions(intent, startId);
}
}
private void requestPurchase(Intent intent, int startId) {
final String packageName = getPackageName();
final String itemId = intent.getStringExtra(EXTRA_ITEM_ID);
final String developerPayload = intent.getStringExtra(EXTRA_DEVELOPER_PAYLOAD);
final RequestPurchase request = new RequestPurchase(packageName, startId, itemId, developerPayload);
runRequestOrQueue(request);
}
private void restoreTransactions(Intent intent, int startId) {
final String packageName = getPackageName();
final long nonce = intent.getLongExtra(EXTRA_NONCE, 0);
final RestoreTransactions request = new RestoreTransactions(packageName, startId);
request.setNonce(nonce);
runRequestOrQueue(request);
}
private void runPendingRequests() {
BillingRequest request;
int maxStartId = -1;
while ((request = mPendingRequests.peek()) != null) {
if (mService != null) {
runRequest(request);
mPendingRequests.remove();
if (maxStartId < request.getStartId()) {
maxStartId = request.getStartId();
}
} else {
bindMarketBillingService();
return;
}
}
if (maxStartId >= 0) {
stopSelf(maxStartId);
}
}
private void runRequest(BillingRequest request) {
try {
final long requestId = request.run(mService);
BillingController.onRequestSent(requestId, request);
} catch (RemoteException e) {
Log.w(this.getClass().getSimpleName(), "Remote billing service crashed");
// TODO: Retry?
}
}
private void runRequestOrQueue(BillingRequest request) {
mPendingRequests.add(request);
if (mService == null) {
bindMarketBillingService();
} else {
runPendingRequests();
}
}
@Override
public void onDestroy() {
super.onDestroy();
// Ensure we're not leaking Android Market billing service
if (mService != null) {
try {
unbindService(this);
} catch (IllegalArgumentException e) {
// This might happen if the service was disconnected
}
}
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/BillingService.java | Java | asf20 | 8,541 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class BillingReceiver extends BroadcastReceiver {
static final String ACTION_NOTIFY = "com.android.vending.billing.IN_APP_NOTIFY";
static final String ACTION_RESPONSE_CODE =
"com.android.vending.billing.RESPONSE_CODE";
static final String ACTION_PURCHASE_STATE_CHANGED =
"com.android.vending.billing.PURCHASE_STATE_CHANGED";
static final String EXTRA_NOTIFICATION_ID = "notification_id";
static final String EXTRA_INAPP_SIGNED_DATA = "inapp_signed_data";
static final String EXTRA_INAPP_SIGNATURE = "inapp_signature";
static final String EXTRA_REQUEST_ID = "request_id";
static final String EXTRA_RESPONSE_CODE = "response_code";
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
BillingController.debug("Received " + action);
if (ACTION_PURCHASE_STATE_CHANGED.equals(action)) {
purchaseStateChanged(context, intent);
} else if (ACTION_NOTIFY.equals(action)) {
notify(context, intent);
} else if (ACTION_RESPONSE_CODE.equals(action)) {
responseCode(context, intent);
} else {
Log.w(this.getClass().getSimpleName(), "Unexpected action: " + action);
}
}
private void purchaseStateChanged(Context context, Intent intent) {
final String signedData = intent.getStringExtra(EXTRA_INAPP_SIGNED_DATA);
final String signature = intent.getStringExtra(EXTRA_INAPP_SIGNATURE);
BillingController.onPurchaseStateChanged(context, signedData, signature);
}
private void notify(Context context, Intent intent) {
String notifyId = intent.getStringExtra(EXTRA_NOTIFICATION_ID);
BillingController.onNotify(context, notifyId);
}
private void responseCode(Context context, Intent intent) {
final long requestId = intent.getLongExtra(EXTRA_REQUEST_ID, -1);
final int responseCode = intent.getIntExtra(EXTRA_RESPONSE_CODE, 0);
BillingController.onResponseCode(context, requestId, responseCode);
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/BillingReceiver.java | Java | asf20 | 2,887 |
// Copyright 2002, Google, Inc.
//
// 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 net.robotmedia.billing.utils;
/**
* Exception thrown when encountering an invalid Base64 input character.
*
* @author nelson
*/
public class Base64DecoderException extends Exception {
public Base64DecoderException() {
super();
}
public Base64DecoderException(String s) {
super(s);
}
private static final long serialVersionUID = 1L;
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/utils/Base64DecoderException.java | Java | asf20 | 958 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.utils;
import java.security.SecureRandom;
import java.util.HashSet;
import net.robotmedia.billing.utils.AESObfuscator.ValidationException;
import android.content.Context;
import android.provider.Settings;
import android.util.Log;
public class Security {
private static HashSet<Long> knownNonces = new HashSet<Long>();
private static final SecureRandom RANDOM = new SecureRandom();
private static final String TAG = Security.class.getSimpleName();
/** Generates a nonce (a random number used once). */
public static long generateNonce() {
long nonce = RANDOM.nextLong();
knownNonces.add(nonce);
return nonce;
}
public static boolean isNonceKnown(long nonce) {
return knownNonces.contains(nonce);
}
public static void removeNonce(long nonce) {
knownNonces.remove(nonce);
}
public static String obfuscate(Context context, byte[] salt, String original) {
final AESObfuscator obfuscator = getObfuscator(context, salt);
return obfuscator.obfuscate(original);
}
private static AESObfuscator _obfuscator = null;
private static AESObfuscator getObfuscator(Context context, byte[] salt) {
if (_obfuscator == null) {
final String installationId = Installation.id(context);
final String deviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
final String password = installationId + deviceId + context.getPackageName();
_obfuscator = new AESObfuscator(salt, password);
}
return _obfuscator;
}
public static String unobfuscate(Context context, byte[] salt, String obfuscated) {
final AESObfuscator obfuscator = getObfuscator(context, salt);
try {
return obfuscator.unobfuscate(obfuscated);
} catch (ValidationException e) {
Log.w(TAG, "Invalid obfuscated data or key");
}
return null;
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/utils/Security.java | Java | asf20 | 2,462 |
// Portions copyright 2002, Google, Inc.
//
// 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 net.robotmedia.billing.utils;
// This code was converted from code at http://iharder.sourceforge.net/base64/
// Lots of extraneous features were removed.
/* The original code said:
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit
* <a href="http://iharder.net/xmlizable">http://iharder.net/xmlizable</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rharder@usa.net
* @version 1.3
*/
/**
* Base64 converter class. This code is not a complete MIME encoder;
* it simply converts binary data to base64 data and back.
*
* <p>Note {@link CharBase64} is a GWT-compatible implementation of this
* class.
*/
public class Base64 {
/** Specify encoding (value is {@code true}). */
public final static boolean ENCODE = true;
/** Specify decoding (value is {@code false}). */
public final static boolean DECODE = false;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte) '=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte) '\n';
/**
* The 64 valid Base64 values.
*/
private final static byte[] ALPHABET =
{(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
(byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
(byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
(byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
(byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
(byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
(byte) '9', (byte) '+', (byte) '/'};
/**
* The 64 valid web safe Base64 values.
*/
private final static byte[] WEBSAFE_ALPHABET =
{(byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F',
(byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K',
(byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P',
(byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U',
(byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z',
(byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e',
(byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j',
(byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o',
(byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't',
(byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y',
(byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3',
(byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8',
(byte) '9', (byte) '-', (byte) '_'};
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] DECODABET = {-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9, -9, -9, // Decimal 44 - 46
63, // Slash at decimal 47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
-9, -9, -9, -9, -9, -9, // Decimal 91 - 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
/* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
/** The web safe decodabet */
private final static byte[] WEBSAFE_DECODABET =
{-9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8
-5, -5, // Whitespace: Tab and Linefeed
-9, -9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26
-9, -9, -9, -9, -9, // Decimal 27 - 31
-5, // Whitespace: Space
-9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 44
62, // Dash '-' sign at decimal 45
-9, -9, // Decimal 46-47
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine
-9, -9, -9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9, -9, -9, // Decimal 62 - 64
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N'
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z'
-9, -9, -9, -9, // Decimal 91-94
63, // Underscore '_' at decimal 95
-9, // Decimal 96
26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm'
39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z'
-9, -9, -9, -9, -9 // Decimal 123 - 127
/* ,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 128 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
// Indicates white space in encoding
private final static byte WHITE_SPACE_ENC = -5;
// Indicates equals sign in encoding
private final static byte EQUALS_SIGN_ENC = -1;
/** Defeats instantiation. */
private Base64() {
}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accommodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param alphabet is the encoding alphabet
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(byte[] source, int srcOffset,
int numSigBytes, byte[] destination, int destOffset, byte[] alphabet) {
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index alphabet
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff =
(numSigBytes > 0 ? ((source[srcOffset] << 24) >>> 8) : 0)
| (numSigBytes > 1 ? ((source[srcOffset + 1] << 24) >>> 16) : 0)
| (numSigBytes > 2 ? ((source[srcOffset + 2] << 24) >>> 24) : 0);
switch (numSigBytes) {
case 3:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = alphabet[(inBuff) & 0x3f];
return destination;
case 2:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = alphabet[(inBuff >>> 6) & 0x3f];
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
case 1:
destination[destOffset] = alphabet[(inBuff >>> 18)];
destination[destOffset + 1] = alphabet[(inBuff >>> 12) & 0x3f];
destination[destOffset + 2] = EQUALS_SIGN;
destination[destOffset + 3] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Encodes a byte array into Base64 notation.
* Equivalent to calling
* {@code encodeBytes(source, 0, source.length)}
*
* @param source The data to convert
* @since 1.4
*/
public static String encode(byte[] source) {
return encode(source, 0, source.length, ALPHABET, true);
}
/**
* Encodes a byte array into web safe Base64 notation.
*
* @param source The data to convert
* @param doPadding is {@code true} to pad result with '=' chars
* if it does not fall on 3 byte boundaries
*/
public static String encodeWebSafe(byte[] source, boolean doPadding) {
return encode(source, 0, source.length, WEBSAFE_ALPHABET, doPadding);
}
/**
* Encodes a byte array into Base64 notation.
*
* @param source the data to convert
* @param off offset in array where conversion should begin
* @param len length of data to convert
* @param alphabet the encoding alphabet
* @param doPadding is {@code true} to pad result with '=' chars
* if it does not fall on 3 byte boundaries
* @since 1.4
*/
public static String encode(byte[] source, int off, int len, byte[] alphabet,
boolean doPadding) {
byte[] outBuff = encode(source, off, len, alphabet, Integer.MAX_VALUE);
int outLen = outBuff.length;
// If doPadding is false, set length to truncate '='
// padding characters
while (doPadding == false && outLen > 0) {
if (outBuff[outLen - 1] != '=') {
break;
}
outLen -= 1;
}
return new String(outBuff, 0, outLen);
}
/**
* Encodes a byte array into Base64 notation.
*
* @param source the data to convert
* @param off offset in array where conversion should begin
* @param len length of data to convert
* @param alphabet is the encoding alphabet
* @param maxLineLength maximum length of one line.
* @return the BASE64-encoded byte array
*/
public static byte[] encode(byte[] source, int off, int len, byte[] alphabet,
int maxLineLength) {
int lenDiv3 = (len + 2) / 3; // ceil(len / 3)
int len43 = lenDiv3 * 4;
byte[] outBuff = new byte[len43 // Main 4:3
+ (len43 / maxLineLength)]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for (; d < len2; d += 3, e += 4) {
// The following block of code is the same as
// encode3to4( source, d + off, 3, outBuff, e, alphabet );
// but inlined for faster encoding (~20% improvement)
int inBuff =
((source[d + off] << 24) >>> 8)
| ((source[d + 1 + off] << 24) >>> 16)
| ((source[d + 2 + off] << 24) >>> 24);
outBuff[e] = alphabet[(inBuff >>> 18)];
outBuff[e + 1] = alphabet[(inBuff >>> 12) & 0x3f];
outBuff[e + 2] = alphabet[(inBuff >>> 6) & 0x3f];
outBuff[e + 3] = alphabet[(inBuff) & 0x3f];
lineLength += 4;
if (lineLength == maxLineLength) {
outBuff[e + 4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // end for: each piece of array
if (d < len) {
encode3to4(source, d + off, len - d, outBuff, e, alphabet);
lineLength += 4;
if (lineLength == maxLineLength) {
// Add a last newline
outBuff[e + 4] = NEW_LINE;
e++;
}
e += 4;
}
assert (e == outBuff.length);
return outBuff;
}
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accommodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @param decodabet the decodabet for decoding Base64 content
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3(byte[] source, int srcOffset,
byte[] destination, int destOffset, byte[] decodabet) {
// Example: Dk==
if (source[srcOffset + 2] == EQUALS_SIGN) {
int outBuff =
((decodabet[source[srcOffset]] << 24) >>> 6)
| ((decodabet[source[srcOffset + 1]] << 24) >>> 12);
destination[destOffset] = (byte) (outBuff >>> 16);
return 1;
} else if (source[srcOffset + 3] == EQUALS_SIGN) {
// Example: DkL=
int outBuff =
((decodabet[source[srcOffset]] << 24) >>> 6)
| ((decodabet[source[srcOffset + 1]] << 24) >>> 12)
| ((decodabet[source[srcOffset + 2]] << 24) >>> 18);
destination[destOffset] = (byte) (outBuff >>> 16);
destination[destOffset + 1] = (byte) (outBuff >>> 8);
return 2;
} else {
// Example: DkLE
int outBuff =
((decodabet[source[srcOffset]] << 24) >>> 6)
| ((decodabet[source[srcOffset + 1]] << 24) >>> 12)
| ((decodabet[source[srcOffset + 2]] << 24) >>> 18)
| ((decodabet[source[srcOffset + 3]] << 24) >>> 24);
destination[destOffset] = (byte) (outBuff >> 16);
destination[destOffset + 1] = (byte) (outBuff >> 8);
destination[destOffset + 2] = (byte) (outBuff);
return 3;
}
} // end decodeToBytes
/**
* Decodes data from Base64 notation.
*
* @param s the string to decode (decoded in default encoding)
* @return the decoded data
* @since 1.4
*/
public static byte[] decode(String s) throws Base64DecoderException {
byte[] bytes = s.getBytes();
return decode(bytes, 0, bytes.length);
}
/**
* Decodes data from web safe Base64 notation.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
*
* @param s the string to decode (decoded in default encoding)
* @return the decoded data
*/
public static byte[] decodeWebSafe(String s) throws Base64DecoderException {
byte[] bytes = s.getBytes();
return decodeWebSafe(bytes, 0, bytes.length);
}
/**
* Decodes Base64 content in byte array format and returns
* the decoded byte array.
*
* @param source The Base64 encoded data
* @return decoded data
* @since 1.3
* @throws Base64DecoderException
*/
public static byte[] decode(byte[] source) throws Base64DecoderException {
return decode(source, 0, source.length);
}
/**
* Decodes web safe Base64 content in byte array format and returns
* the decoded data.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
*
* @param source the string to decode (decoded in default encoding)
* @return the decoded data
*/
public static byte[] decodeWebSafe(byte[] source)
throws Base64DecoderException {
return decodeWebSafe(source, 0, source.length);
}
/**
* Decodes Base64 content in byte array format and returns
* the decoded byte array.
*
* @param source the Base64 encoded data
* @param off the offset of where to begin decoding
* @param len the length of characters to decode
* @return decoded data
* @since 1.3
* @throws Base64DecoderException
*/
public static byte[] decode(byte[] source, int off, int len)
throws Base64DecoderException {
return decode(source, off, len, DECODABET);
}
/**
* Decodes web safe Base64 content in byte array format and returns
* the decoded byte array.
* Web safe encoding uses '-' instead of '+', '_' instead of '/'
*
* @param source the Base64 encoded data
* @param off the offset of where to begin decoding
* @param len the length of characters to decode
* @return decoded data
*/
public static byte[] decodeWebSafe(byte[] source, int off, int len)
throws Base64DecoderException {
return decode(source, off, len, WEBSAFE_DECODABET);
}
/**
* Decodes Base64 content using the supplied decodabet and returns
* the decoded byte array.
*
* @param source the Base64 encoded data
* @param off the offset of where to begin decoding
* @param len the length of characters to decode
* @param decodabet the decodabet for decoding Base64 content
* @return decoded data
*/
public static byte[] decode(byte[] source, int off, int len, byte[] decodabet)
throws Base64DecoderException {
int len34 = len * 3 / 4;
byte[] outBuff = new byte[2 + len34]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for (i = 0; i < len; i++) {
sbiCrop = (byte) (source[i + off] & 0x7f); // Only the low seven bits
sbiDecode = decodabet[sbiCrop];
if (sbiDecode >= WHITE_SPACE_ENC) { // White space Equals sign or better
if (sbiDecode >= EQUALS_SIGN_ENC) {
// An equals sign (for padding) must not occur at position 0 or 1
// and must be the last byte[s] in the encoded value
if (sbiCrop == EQUALS_SIGN) {
int bytesLeft = len - i;
byte lastByte = (byte) (source[len - 1 + off] & 0x7f);
if (b4Posn == 0 || b4Posn == 1) {
throw new Base64DecoderException(
"invalid padding byte '=' at byte offset " + i);
} else if ((b4Posn == 3 && bytesLeft > 2)
|| (b4Posn == 4 && bytesLeft > 1)) {
throw new Base64DecoderException(
"padding byte '=' falsely signals end of encoded value "
+ "at offset " + i);
} else if (lastByte != EQUALS_SIGN && lastByte != NEW_LINE) {
throw new Base64DecoderException(
"encoded value has invalid trailing byte");
}
break;
}
b4[b4Posn++] = sbiCrop;
if (b4Posn == 4) {
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
b4Posn = 0;
}
}
} else {
throw new Base64DecoderException("Bad Base64 input character at " + i
+ ": " + source[i + off] + "(decimal)");
}
}
// Because web safe encoding allows non padding base64 encodes, we
// need to pad the rest of the b4 buffer with equal signs when
// b4Posn != 0. There can be at most 2 equal signs at the end of
// four characters, so the b4 buffer must have two or three
// characters. This also catches the case where the input is
// padded with EQUALS_SIGN
if (b4Posn != 0) {
if (b4Posn == 1) {
throw new Base64DecoderException("single trailing character at offset "
+ (len - 1));
}
b4[b4Posn++] = EQUALS_SIGN;
outBuffPosn += decode4to3(b4, 0, outBuff, outBuffPosn, decodabet);
}
byte[] out = new byte[outBuffPosn];
System.arraycopy(outBuff, 0, out, 0, outBuffPosn);
return out;
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/utils/Base64.java | Java | asf20 | 22,625 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 net.robotmedia.billing.utils;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
/**
* An obfuscator that uses AES to encrypt data.
*/
public class AESObfuscator {
private static final String UTF8 = "UTF-8";
private static final String KEYGEN_ALGORITHM = "PBEWITHSHAAND256BITAES-CBC-BC";
private static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
private static final byte[] IV =
{ 16, 74, 71, -80, 32, 101, -47, 72, 117, -14, 0, -29, 70, 65, -12, 74 };
private static final String header = "net.robotmedia.billing.utils.AESObfuscator-1|";
private Cipher mEncryptor;
private Cipher mDecryptor;
public AESObfuscator(byte[] salt, String password) {
try {
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEYGEN_ALGORITHM);
KeySpec keySpec =
new PBEKeySpec(password.toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(keySpec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
mEncryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mEncryptor.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(IV));
mDecryptor = Cipher.getInstance(CIPHER_ALGORITHM);
mDecryptor.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(IV));
} catch (GeneralSecurityException e) {
// This can't happen on a compatible Android device.
throw new RuntimeException("Invalid environment", e);
}
}
public String obfuscate(String original) {
if (original == null) {
return null;
}
try {
// Header is appended as an integrity check
return Base64.encode(mEncryptor.doFinal((header + original).getBytes(UTF8)));
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Invalid environment", e);
} catch (GeneralSecurityException e) {
throw new RuntimeException("Invalid environment", e);
}
}
public String unobfuscate(String obfuscated) throws ValidationException {
if (obfuscated == null) {
return null;
}
try {
String result = new String(mDecryptor.doFinal(Base64.decode(obfuscated)), UTF8);
// Check for presence of header. This serves as a final integrity check, for cases
// where the block size is correct during decryption.
int headerIndex = result.indexOf(header);
if (headerIndex != 0) {
throw new ValidationException("Header not found (invalid data or key)" + ":" +
obfuscated);
}
return result.substring(header.length(), result.length());
} catch (Base64DecoderException e) {
throw new ValidationException(e.getMessage() + ":" + obfuscated);
} catch (IllegalBlockSizeException e) {
throw new ValidationException(e.getMessage() + ":" + obfuscated);
} catch (BadPaddingException e) {
throw new ValidationException(e.getMessage() + ":" + obfuscated);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Invalid environment", e);
}
}
public class ValidationException extends Exception {
public ValidationException() {
super();
}
public ValidationException(String s) {
super(s);
}
private static final long serialVersionUID = 1L;
}
} | 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/utils/AESObfuscator.java | Java | asf20 | 4,565 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.utils;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import android.app.Activity;
import android.app.Service;
import android.content.Intent;
import android.content.IntentSender;
import android.util.Log;
public class Compatibility {
private static Method startIntentSender;
public static int START_NOT_STICKY;
@SuppressWarnings("rawtypes")
private static final Class[] START_INTENT_SENDER_SIG = new Class[] {
IntentSender.class, Intent.class, int.class, int.class, int.class
};
static {
initCompatibility();
};
private static void initCompatibility() {
try {
final Field field = Service.class.getField("START_NOT_STICKY");
START_NOT_STICKY = field.getInt(null);
} catch (Exception e) {
START_NOT_STICKY = 2;
}
try {
startIntentSender = Activity.class.getMethod("startIntentSender",
START_INTENT_SENDER_SIG);
} catch (SecurityException e) {
startIntentSender = null;
} catch (NoSuchMethodException e) {
startIntentSender = null;
}
}
public static void startIntentSender(Activity activity, IntentSender intentSender, Intent intent) {
if (startIntentSender != null) {
final Object[] args = new Object[5];
args[0] = intentSender;
args[1] = intent;
args[2] = Integer.valueOf(0);
args[3] = Integer.valueOf(0);
args[4] = Integer.valueOf(0);
try {
startIntentSender.invoke(activity, args);
} catch (Exception e) {
Log.e(Compatibility.class.getSimpleName(), "startIntentSender", e);
}
}
}
public static boolean isStartIntentSenderSupported() {
return startIntentSender != null;
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/utils/Compatibility.java | Java | asf20 | 2,397 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.utils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.UUID;
import android.content.Context;
public class Installation {
private static final String INSTALLATION = "INSTALLATION";
private static String sID = null;
public synchronized static String id(Context context) {
if (sID == null) {
File installation = new File(context.getFilesDir(), INSTALLATION);
try {
if (!installation.exists()) {
writeInstallationFile(installation);
}
sID = readInstallationFile(installation);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return sID;
}
private static String readInstallationFile(File installation) throws IOException {
RandomAccessFile f = new RandomAccessFile(installation, "r");
byte[] bytes = new byte[(int) f.length()];
f.readFully(bytes);
f.close();
return new String(bytes);
}
private static void writeInstallationFile(File installation) throws IOException {
FileOutputStream out = new FileOutputStream(installation);
String id = UUID.randomUUID().toString();
out.write(id.getBytes());
out.close();
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/utils/Installation.java | Java | asf20 | 1,836 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing;
import android.app.PendingIntent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import com.android.vending.billing.IMarketBillingService;
public abstract class BillingRequest {
public static class CheckBillingSupported extends BillingRequest {
public CheckBillingSupported(String packageName, int startId) {
super(packageName, startId);
}
@Override
public String getRequestType() {
return "CHECK_BILLING_SUPPORTED";
}
@Override
protected void processOkResponse(Bundle response) {
final boolean supported = this.isSuccess();
BillingController.onBillingChecked(supported);
}
}
public static class ConfirmNotifications extends BillingRequest {
private String[] notifyIds;
private static final String KEY_NOTIFY_IDS = "NOTIFY_IDS";
public ConfirmNotifications(String packageName, int startId, String[] notifyIds) {
super(packageName, startId);
this.notifyIds = notifyIds;
}
@Override
protected void addParams(Bundle request) {
request.putStringArray(KEY_NOTIFY_IDS, notifyIds);
}
@Override
public String getRequestType() {
return "CONFIRM_NOTIFICATIONS";
}
}
public static class GetPurchaseInformation extends BillingRequest {
private String[] notifyIds;
private static final String KEY_NOTIFY_IDS = "NOTIFY_IDS";
public GetPurchaseInformation(String packageName, int startId, String[] notifyIds) {
super(packageName,startId);
this.notifyIds = notifyIds;
}
@Override
protected void addParams(Bundle request) {
request.putStringArray(KEY_NOTIFY_IDS, notifyIds);
}
@Override
public String getRequestType() {
return "GET_PURCHASE_INFORMATION";
}
@Override public boolean hasNonce() { return true; }
}
public static class RequestPurchase extends BillingRequest {
private String itemId;
private String developerPayload;
private static final String KEY_ITEM_ID = "ITEM_ID";
private static final String KEY_DEVELOPER_PAYLOAD = "DEVELOPER_PAYLOAD";
private static final String KEY_PURCHASE_INTENT = "PURCHASE_INTENT";
public RequestPurchase(String packageName, int startId, String itemId, String developerPayload) {
super(packageName, startId);
this.itemId = itemId;
this.developerPayload = developerPayload;
}
@Override
protected void addParams(Bundle request) {
request.putString(KEY_ITEM_ID, itemId);
if (developerPayload != null) {
request.putString(KEY_DEVELOPER_PAYLOAD, developerPayload);
}
}
@Override
public String getRequestType() {
return "REQUEST_PURCHASE";
}
@Override
public void onResponseCode(ResponseCode response) {
super.onResponseCode(response);
BillingController.onRequestPurchaseResponse(itemId, response);
}
@Override
protected void processOkResponse(Bundle response) {
final PendingIntent purchaseIntent = response.getParcelable(KEY_PURCHASE_INTENT);
BillingController.onPurchaseIntent(itemId, purchaseIntent);
}
}
public static enum ResponseCode {
RESULT_OK, // 0
RESULT_USER_CANCELED, // 1
RESULT_SERVICE_UNAVAILABLE, // 2
RESULT_BILLING_UNAVAILABLE, // 3
RESULT_ITEM_UNAVAILABLE, // 4
RESULT_DEVELOPER_ERROR, // 5
RESULT_ERROR; // 6
public static boolean isResponseOk(int response) {
return ResponseCode.RESULT_OK.ordinal() == response;
}
// Converts from an ordinal value to the ResponseCode
public static ResponseCode valueOf(int index) {
ResponseCode[] values = ResponseCode.values();
if (index < 0 || index >= values.length) {
return RESULT_ERROR;
}
return values[index];
}
}
public static class RestoreTransactions extends BillingRequest {
public RestoreTransactions(String packageName, int startId) {
super(packageName, startId);
}
@Override
public String getRequestType() {
return "RESTORE_TRANSACTIONS";
}
@Override public boolean hasNonce() { return true; }
@Override
public void onResponseCode(ResponseCode response) {
super.onResponseCode(response);
if (response == ResponseCode.RESULT_OK) {
BillingController.onTransactionsRestored();
}
}
}
private static final String KEY_BILLING_REQUEST = "BILLING_REQUEST";
private static final String KEY_API_VERSION = "API_VERSION";
private static final String KEY_PACKAGE_NAME = "PACKAGE_NAME";
private static final String KEY_RESPONSE_CODE = "RESPONSE_CODE";
protected static final String KEY_REQUEST_ID = "REQUEST_ID";
private static final String KEY_NONCE = "NONCE";
public static final long IGNORE_REQUEST_ID = -1;
private String packageName;
private int startId;
private boolean success;
private long nonce;
public BillingRequest(String packageName,int startId) {
this.packageName = packageName;
this.startId=startId;
}
protected void addParams(Bundle request) {
// Do nothing by default
}
public long getNonce() {
return nonce;
}
public abstract String getRequestType();
public boolean hasNonce() {
return false;
}
public boolean isSuccess() {
return success;
}
protected Bundle makeRequestBundle() {
final Bundle request = new Bundle();
request.putString(KEY_BILLING_REQUEST, getRequestType());
request.putInt(KEY_API_VERSION, 1);
request.putString(KEY_PACKAGE_NAME, packageName);
if (hasNonce()) {
request.putLong(KEY_NONCE, nonce);
}
return request;
}
public void onResponseCode(ResponseCode responde) {
// Do nothing by default
}
protected void processOkResponse(Bundle response) {
// Do nothing by default
}
public long run(IMarketBillingService mService) throws RemoteException {
final Bundle request = makeRequestBundle();
addParams(request);
final Bundle response = mService.sendBillingRequest(request);
if (validateResponse(response)) {
processOkResponse(response);
return response.getLong(KEY_REQUEST_ID, IGNORE_REQUEST_ID);
} else {
return IGNORE_REQUEST_ID;
}
}
public void setNonce(long nonce) {
this.nonce = nonce;
}
protected boolean validateResponse(Bundle response) {
final int responseCode = response.getInt(KEY_RESPONSE_CODE);
success = ResponseCode.isResponseOk(responseCode);
if (!success) {
Log.w(this.getClass().getSimpleName(), "Error with response code " + ResponseCode.valueOf(responseCode));
}
return success;
}
public int getStartId() {
return startId;
}
} | 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/BillingRequest.java | Java | asf20 | 7,708 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing;
import net.robotmedia.billing.BillingRequest.ResponseCode;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.app.PendingIntent;
public interface IBillingObserver {
/**
* Called only once after determining if in-app billing is supported or not.
*
* @param supported
* if true, in-app billing is supported. Otherwise, it isn't.
* @see BillingController#checkBillingSupported(android.content.Context)
*/
public void onBillingChecked(boolean supported);
/**
* Called after requesting the purchase of the specified item.
*
* @param itemId
* id of the item whose purchase was requested.
* @param purchaseIntent
* a purchase pending intent for the specified item.
* @see BillingController#requestPurchase(android.content.Context, String,
* boolean)
*/
public void onPurchaseIntent(String itemId, PendingIntent purchaseIntent);
/**
* Called when the specified item is purchased, cancelled or refunded.
*
* @param itemId
* id of the item whose purchase state has changed.
* @param state
* purchase state of the specified item.
*/
public void onPurchaseStateChanged(String itemId, PurchaseState state);
/**
* Called with the response for the purchase request of the specified item.
* This is used for reporting various errors, or if the user backed out and
* didn't purchase the item.
*
* @param itemId
* id of the item whose purchase was requested
* @param response
* response of the purchase request
*/
public void onRequestPurchaseResponse(String itemId, ResponseCode response);
/**
* Called when a restore transactions request has been successfully
* received by the server.
*/
public void onTransactionsRestored();
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/IBillingObserver.java | Java | asf20 | 2,488 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import net.robotmedia.billing.model.Transaction;
import net.robotmedia.billing.model.TransactionManager;
import net.robotmedia.billing.security.DefaultSignatureValidator;
import net.robotmedia.billing.security.ISignatureValidator;
import net.robotmedia.billing.utils.Compatibility;
import net.robotmedia.billing.utils.Security;
import android.app.Activity;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;
import android.util.Log;
public class BillingController {
public static enum BillingStatus {
UNKNOWN, SUPPORTED, UNSUPPORTED
}
/**
* Used to provide on-demand values to the billing controller.
*/
public interface IConfiguration {
/**
* Returns a salt for the obfuscation of purchases in local memory.
*
* @return array of 20 random bytes.
*/
public byte[] getObfuscationSalt();
/**
* Returns the public key used to verify the signature of responses of
* the Market Billing service.
*
* @return Base64 encoded public key.
*/
public String getPublicKey();
}
private static BillingStatus status = BillingStatus.UNKNOWN;
private static Set<String> automaticConfirmations = new HashSet<String>();
private static IConfiguration configuration = null;
private static boolean debug = false;
private static ISignatureValidator validator = null;
private static final String JSON_NONCE = "nonce";
private static final String JSON_ORDERS = "orders";
private static HashMap<String, Set<String>> manualConfirmations = new HashMap<String, Set<String>>();
private static Set<IBillingObserver> observers = new HashSet<IBillingObserver>();
public static final String LOG_TAG = "Billing";
private static HashMap<Long, BillingRequest> pendingRequests = new HashMap<Long, BillingRequest>();
/**
* Adds the specified notification to the set of manual confirmations of the
* specified item.
*
* @param itemId
* id of the item.
* @param notificationId
* id of the notification.
*/
private static final void addManualConfirmation(String itemId, String notificationId) {
Set<String> notifications = manualConfirmations.get(itemId);
if (notifications == null) {
notifications = new HashSet<String>();
manualConfirmations.put(itemId, notifications);
}
notifications.add(notificationId);
}
/**
* Returns the billing status. If it is currently unknown, checks the billing
* status asynchronously, in which case observers will eventually receive
* a {@link IBillingObserver#onBillingChecked(boolean)} notification.
*
* @param context
* @return the current billing status (unknown, supported or unsupported).
* @see IBillingObserver#onBillingChecked(boolean)
*/
public static BillingStatus checkBillingSupported(Context context) {
if (status == BillingStatus.UNKNOWN) {
BillingService.checkBillingSupported(context);
}
return status;
}
/**
* Requests to confirm all pending notifications for the specified item.
*
* @param context
* @param itemId
* id of the item whose purchase must be confirmed.
* @return true if pending notifications for this item were found, false
* otherwise.
*/
public static boolean confirmNotifications(Context context, String itemId) {
final Set<String> notifications = manualConfirmations.get(itemId);
if (notifications != null) {
confirmNotifications(context, notifications.toArray(new String[] {}));
return true;
} else {
return false;
}
}
/**
* Requests to confirm all specified notifications.
*
* @param context
* @param notifyIds
* array with the ids of all the notifications to confirm.
*/
private static void confirmNotifications(Context context, String[] notifyIds) {
BillingService.confirmNotifications(context, notifyIds);
}
/**
* Returns the number of purchases for the specified item. Refunded and
* cancelled purchases are not subtracted. See
* {@link #countPurchasesNet(Context, String)} if they need to be.
*
* @param context
* @param itemId
* id of the item whose purchases will be counted.
* @return number of purchases for the specified item.
*/
public static int countPurchases(Context context, String itemId) {
final byte[] salt = getSalt();
itemId = salt != null ? Security.obfuscate(context, salt, itemId) : itemId;
return TransactionManager.countPurchases(context, itemId);
}
protected static void debug(String message) {
if (debug) {
Log.d(LOG_TAG, message);
}
}
/**
* Requests purchase information for the specified notification. Immediately
* followed by a call to
* {@link #onPurchaseInformationResponse(long, boolean)} and later to
* {@link #onPurchaseStateChanged(Context, String, String)}, if the request
* is successful.
*
* @param context
* @param notifyId
* id of the notification whose purchase information is
* requested.
*/
private static void getPurchaseInformation(Context context, String notifyId) {
final long nonce = Security.generateNonce();
BillingService.getPurchaseInformation(context, new String[] { notifyId }, nonce);
}
/**
* Gets the salt from the configuration and logs a warning if it's null.
*
* @return salt.
*/
private static byte[] getSalt() {
byte[] salt = null;
if (configuration == null || ((salt = configuration.getObfuscationSalt()) == null)) {
Log.w(LOG_TAG, "Can't (un)obfuscate purchases without salt");
}
return salt;
}
/**
* Lists all transactions stored locally, including cancellations and
* refunds.
*
* @param context
* @return list of transactions.
*/
public static List<Transaction> getTransactions(Context context) {
List<Transaction> transactions = TransactionManager.getTransactions(context);
unobfuscate(context, transactions);
return transactions;
}
/**
* Lists all transactions of the specified item, stored locally.
*
* @param context
* @param itemId
* id of the item whose transactions will be returned.
* @return list of transactions.
*/
public static List<Transaction> getTransactions(Context context, String itemId) {
final byte[] salt = getSalt();
itemId = salt != null ? Security.obfuscate(context, salt, itemId) : itemId;
List<Transaction> transactions = TransactionManager.getTransactions(context, itemId);
unobfuscate(context, transactions);
return transactions;
}
/**
* Returns true if the specified item has been registered as purchased in
* local memory. Note that if the item was later canceled or refunded this
* will still return true. Also note that the item might have been purchased
* in another installation, but not yet registered in this one.
*
* @param context
* @param itemId
* item id.
* @return true if the specified item is purchased, false otherwise.
*/
public static boolean isPurchased(Context context, String itemId) {
final byte[] salt = getSalt();
itemId = salt != null ? Security.obfuscate(context, salt, itemId) : itemId;
return TransactionManager.isPurchased(context, itemId);
}
/**
* Notifies observers of the purchase state change of the specified item.
*
* @param itemId
* id of the item whose purchase state has changed.
* @param state
* new purchase state of the item.
*/
private static void notifyPurchaseStateChange(String itemId, Transaction.PurchaseState state) {
for (IBillingObserver o : observers) {
o.onPurchaseStateChanged(itemId, state);
}
}
/**
* Obfuscates the specified purchase. Only the order id, product id and
* developer payload are obfuscated.
*
* @param context
* @param purchase
* purchase to be obfuscated.
* @see #unobfuscate(Context, Transaction)
*/
static void obfuscate(Context context, Transaction purchase) {
final byte[] salt = getSalt();
if (salt == null) {
return;
}
purchase.orderId = Security.obfuscate(context, salt, purchase.orderId);
purchase.productId = Security.obfuscate(context, salt, purchase.productId);
purchase.developerPayload = Security.obfuscate(context, salt, purchase.developerPayload);
}
/**
* Called after the response to a
* {@link net.robotmedia.billing.request.CheckBillingSupported} request is
* received.
*
* @param supported
*/
protected static void onBillingChecked(boolean supported) {
status = supported ? BillingStatus.SUPPORTED : BillingStatus.UNSUPPORTED;
for (IBillingObserver o : observers) {
o.onBillingChecked(supported);
}
}
/**
* Called when an IN_APP_NOTIFY message is received.
*
* @param context
* @param notifyId
* notification id.
*/
protected static void onNotify(Context context, String notifyId) {
debug("Notification " + notifyId + " available");
getPurchaseInformation(context, notifyId);
}
/**
* Called after the response to a
* {@link net.robotmedia.billing.request.RequestPurchase} request is
* received.
*
* @param itemId
* id of the item whose purchase was requested.
* @param purchaseIntent
* intent to purchase the item.
*/
protected static void onPurchaseIntent(String itemId, PendingIntent purchaseIntent) {
for (IBillingObserver o : observers) {
o.onPurchaseIntent(itemId, purchaseIntent);
}
}
/**
* Called after the response to a
* {@link net.robotmedia.billing.request.GetPurchaseInformation} request is
* received. Registers all transactions in local memory and confirms those
* who can be confirmed automatically.
*
* @param context
* @param signedData
* signed JSON data received from the Market Billing service.
* @param signature
* data signature.
*/
protected static void onPurchaseStateChanged(Context context, String signedData, String signature) {
debug("Purchase state changed");
if (TextUtils.isEmpty(signedData)) {
Log.w(LOG_TAG, "Signed data is empty");
return;
}
if (!debug) {
if (TextUtils.isEmpty(signature)) {
Log.w(LOG_TAG, "Empty signature requires debug mode");
return;
}
final ISignatureValidator validator = BillingController.validator != null ? BillingController.validator
: new DefaultSignatureValidator(BillingController.configuration);
if (!validator.validate(signedData, signature)) {
Log.w(LOG_TAG, "Signature does not match data.");
return;
}
}
List<Transaction> purchases;
try {
JSONObject jObject = new JSONObject(signedData);
if (!verifyNonce(jObject)) {
Log.w(LOG_TAG, "Invalid nonce");
return;
}
purchases = parsePurchases(jObject);
} catch (JSONException e) {
Log.e(LOG_TAG, "JSON exception: ", e);
return;
}
ArrayList<String> confirmations = new ArrayList<String>();
for (Transaction p : purchases) {
if (p.notificationId != null && automaticConfirmations.contains(p.productId)) {
confirmations.add(p.notificationId);
} else {
// TODO: Discriminate between purchases, cancellations and
// refunds.
addManualConfirmation(p.productId, p.notificationId);
}
storeTransaction(context, p);
notifyPurchaseStateChange(p.productId, p.purchaseState);
}
if (!confirmations.isEmpty()) {
final String[] notifyIds = confirmations.toArray(new String[confirmations.size()]);
confirmNotifications(context, notifyIds);
}
}
/**
* Called after a {@link net.robotmedia.billing.BillingRequest} is
* sent.
*
* @param requestId
* the id the request.
* @param request
* the billing request.
*/
protected static void onRequestSent(long requestId, BillingRequest request) {
debug("Request " + requestId + " of type " + request.getRequestType() + " sent");
if (request.isSuccess()) {
pendingRequests.put(requestId, request);
} else if (request.hasNonce()) {
Security.removeNonce(request.getNonce());
}
}
/**
* Called after a {@link net.robotmedia.billing.BillingRequest} is
* sent.
*
* @param context
* @param requestId
* the id of the request.
* @param responseCode
* the response code.
* @see net.robotmedia.billing.request.ResponseCode
*/
protected static void onResponseCode(Context context, long requestId, int responseCode) {
final BillingRequest.ResponseCode response = BillingRequest.ResponseCode.valueOf(responseCode);
debug("Request " + requestId + " received response " + response);
final BillingRequest request = pendingRequests.get(requestId);
if (request != null) {
pendingRequests.remove(requestId);
request.onResponseCode(response);
}
}
protected static void onTransactionsRestored() {
for (IBillingObserver o : observers) {
o.onTransactionsRestored();
}
}
/**
* Parse all purchases from the JSON data received from the Market Billing
* service.
*
* @param data
* JSON data received from the Market Billing service.
* @return list of purchases.
* @throws JSONException
* if the data couldn't be properly parsed.
*/
private static List<Transaction> parsePurchases(JSONObject data) throws JSONException {
ArrayList<Transaction> purchases = new ArrayList<Transaction>();
JSONArray orders = data.optJSONArray(JSON_ORDERS);
int numTransactions = 0;
if (orders != null) {
numTransactions = orders.length();
}
for (int i = 0; i < numTransactions; i++) {
JSONObject jElement = orders.getJSONObject(i);
Transaction p = Transaction.parse(jElement);
purchases.add(p);
}
return purchases;
}
/**
* Registers the specified billing observer.
*
* @param observer
* the billing observer to add.
* @return true if the observer wasn't previously registered, false
* otherwise.
* @see #unregisterObserver(IBillingObserver)
*/
public static boolean registerObserver(IBillingObserver observer) {
return observers.add(observer);
}
/**
* Requests the purchase of the specified item. The transaction will not be
* confirmed automatically.
*
* @param context
* @param itemId
* id of the item to be purchased.
* @see #requestPurchase(Context, String, boolean)
*/
public static void requestPurchase(Context context, String itemId) {
requestPurchase(context, itemId, false);
}
/**
* Requests the purchase of the specified item with optional automatic
* confirmation.
*
* @param context
* @param itemId
* id of the item to be purchased.
* @param confirm
* if true, the transaction will be confirmed automatically. If
* false, the transaction will have to be confirmed with a call
* to {@link #confirmNotifications(Context, String)}.
* @see IBillingObserver#onPurchaseIntent(String, PendingIntent)
*/
public static void requestPurchase(Context context, String itemId, boolean confirm) {
if (confirm) {
automaticConfirmations.add(itemId);
}
BillingService.requestPurchase(context, itemId, null);
}
/**
* Requests to restore all transactions.
*
* @param context
*/
public static void restoreTransactions(Context context) {
final long nonce = Security.generateNonce();
BillingService.restoreTransations(context, nonce);
}
/**
* Sets the configuration instance of the controller.
*
* @param config
* configuration instance.
*/
public static void setConfiguration(IConfiguration config) {
configuration = config;
}
/**
* Sets debug mode.
*
* @param value
*/
public static final void setDebug(boolean value) {
debug = value;
}
/**
* Sets a custom signature validator. If no custom signature validator is
* provided,
* {@link net.robotmedia.billing.signature.DefaultSignatureValidator} will
* be used.
*
* @param validator
* signature validator instance.
*/
public static void setSignatureValidator(ISignatureValidator validator) {
BillingController.validator = validator;
}
/**
* Starts the specified purchase intent with the specified activity.
*
* @param activity
* @param purchaseIntent
* purchase intent.
* @param intent
*/
public static void startPurchaseIntent(Activity activity, PendingIntent purchaseIntent, Intent intent) {
if (Compatibility.isStartIntentSenderSupported()) {
// This is on Android 2.0 and beyond. The in-app buy page activity
// must be on the activity stack of the application.
Compatibility.startIntentSender(activity, purchaseIntent.getIntentSender(), intent);
} else {
// This is on Android version 1.6. The in-app buy page activity must
// be on its own separate activity stack instead of on the activity
// stack of the application.
try {
purchaseIntent.send(activity, 0 /* code */, intent);
} catch (CanceledException e) {
Log.e(LOG_TAG, "Error starting purchase intent", e);
}
}
}
static void storeTransaction(Context context, Transaction t) {
final Transaction t2 = t.clone();
obfuscate(context, t2);
TransactionManager.addTransaction(context, t2);
}
static void unobfuscate(Context context, List<Transaction> transactions) {
for (Transaction p : transactions) {
unobfuscate(context, p);
}
}
/**
* Unobfuscate the specified purchase.
*
* @param context
* @param purchase
* purchase to unobfuscate.
* @see #obfuscate(Context, Transaction)
*/
static void unobfuscate(Context context, Transaction purchase) {
final byte[] salt = getSalt();
if (salt == null) {
return;
}
purchase.orderId = Security.unobfuscate(context, salt, purchase.orderId);
purchase.productId = Security.unobfuscate(context, salt, purchase.productId);
purchase.developerPayload = Security.unobfuscate(context, salt, purchase.developerPayload);
}
/**
* Unregisters the specified billing observer.
*
* @param observer
* the billing observer to unregister.
* @return true if the billing observer was unregistered, false otherwise.
* @see #registerObserver(IBillingObserver)
*/
public static boolean unregisterObserver(IBillingObserver observer) {
return observers.remove(observer);
}
private static boolean verifyNonce(JSONObject data) {
long nonce = data.optLong(JSON_NONCE);
if (Security.isNonceKnown(nonce)) {
Security.removeNonce(nonce);
return true;
} else {
return false;
}
}
protected static void onRequestPurchaseResponse(String itemId, BillingRequest.ResponseCode response) {
for (IBillingObserver o : observers) {
o.onRequestPurchaseResponse(itemId, response);
}
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/BillingController.java | Java | asf20 | 19,520 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.model;
import java.util.ArrayList;
import java.util.List;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.content.Context;
import android.database.Cursor;
public class TransactionManager {
public synchronized static void addTransaction(Context context, Transaction transaction) {
BillingDB db = new BillingDB(context);
db.insert(transaction);
db.close();
}
public synchronized static boolean isPurchased(Context context, String itemId) {
return countPurchases(context, itemId) > 0;
}
public synchronized static int countPurchases(Context context, String itemId) {
BillingDB db = new BillingDB(context);
final Cursor c = db.queryTransactions(itemId, PurchaseState.PURCHASED);
int count = 0;
if (c != null) {
count = c.getCount();
c.close();
}
db.close();
return count;
}
public synchronized static List<Transaction> getTransactions(Context context) {
BillingDB db = new BillingDB(context);
final Cursor c = db.queryTransactions();
final List<Transaction> transactions = cursorToList(c);
db.close();
return transactions;
}
private static List<Transaction> cursorToList(final Cursor c) {
final List<Transaction> transactions = new ArrayList<Transaction>();
if (c != null) {
while (c.moveToNext()) {
final Transaction purchase = BillingDB.createTransaction(c);
transactions.add(purchase);
}
c.close();
}
return transactions;
}
public synchronized static List<Transaction> getTransactions(Context context, String itemId) {
BillingDB db = new BillingDB(context);
final Cursor c = db.queryTransactions(itemId);
final List<Transaction> transactions = cursorToList(c);
db.close();
return transactions;
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/model/TransactionManager.java | Java | asf20 | 2,456 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.model;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class BillingDB {
static final String DATABASE_NAME = "billing.db";
static final int DATABASE_VERSION = 1;
static final String TABLE_TRANSACTIONS = "purchases";
public static final String COLUMN__ID = "_id";
public static final String COLUMN_STATE = "state";
public static final String COLUMN_PRODUCT_ID = "productId";
public static final String COLUMN_PURCHASE_TIME = "purchaseTime";
public static final String COLUMN_DEVELOPER_PAYLOAD = "developerPayload";
private static final String[] TABLE_TRANSACTIONS_COLUMNS = {
COLUMN__ID, COLUMN_PRODUCT_ID, COLUMN_STATE,
COLUMN_PURCHASE_TIME, COLUMN_DEVELOPER_PAYLOAD
};
SQLiteDatabase mDb;
private DatabaseHelper mDatabaseHelper;
public BillingDB(Context context) {
mDatabaseHelper = new DatabaseHelper(context);
mDb = mDatabaseHelper.getWritableDatabase();
}
public void close() {
mDatabaseHelper.close();
}
public void insert(Transaction transaction) {
ContentValues values = new ContentValues();
values.put(COLUMN__ID, transaction.orderId);
values.put(COLUMN_PRODUCT_ID, transaction.productId);
values.put(COLUMN_STATE, transaction.purchaseState.ordinal());
values.put(COLUMN_PURCHASE_TIME, transaction.purchaseTime);
values.put(COLUMN_DEVELOPER_PAYLOAD, transaction.developerPayload);
mDb.replace(TABLE_TRANSACTIONS, null /* nullColumnHack */, values);
}
public Cursor queryTransactions() {
return mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, null,
null, null, null, null);
}
public Cursor queryTransactions(String productId) {
return mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, COLUMN_PRODUCT_ID + " = ?",
new String[] {productId}, null, null, null);
}
public Cursor queryTransactions(String productId, PurchaseState state) {
return mDb.query(TABLE_TRANSACTIONS, TABLE_TRANSACTIONS_COLUMNS, COLUMN_PRODUCT_ID + " = ? AND " + COLUMN_STATE + " = ?",
new String[] {productId, String.valueOf(state.ordinal())}, null, null, null);
}
protected static final Transaction createTransaction(Cursor cursor) {
final Transaction purchase = new Transaction();
purchase.orderId = cursor.getString(0);
purchase.productId = cursor.getString(1);
purchase.purchaseState = PurchaseState.valueOf(cursor.getInt(2));
purchase.purchaseTime = cursor.getLong(3);
purchase.developerPayload = cursor.getString(4);
return purchase;
}
private class DatabaseHelper extends SQLiteOpenHelper {
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
createTransactionsTable(db);
}
private void createTransactionsTable(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_TRANSACTIONS + "(" +
COLUMN__ID + " TEXT PRIMARY KEY, " +
COLUMN_PRODUCT_ID + " INTEGER, " +
COLUMN_STATE + " TEXT, " +
COLUMN_PURCHASE_TIME + " TEXT, " +
COLUMN_DEVELOPER_PAYLOAD + " INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/model/BillingDB.java | Java | asf20 | 4,346 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.model;
import org.json.JSONException;
import org.json.JSONObject;
public class Transaction {
public enum PurchaseState {
// Responses to requestPurchase or restoreTransactions.
PURCHASED, // 0: User was charged for the order.
CANCELLED, // 1: The charge failed on the server.
REFUNDED; // 2: User received a refund for the order.
// Converts from an ordinal value to the PurchaseState
public static PurchaseState valueOf(int index) {
PurchaseState[] values = PurchaseState.values();
if (index < 0 || index >= values.length) {
return CANCELLED;
}
return values[index];
}
}
static final String DEVELOPER_PAYLOAD = "developerPayload";
static final String NOTIFICATION_ID = "notificationId";
static final String ORDER_ID = "orderId";
static final String PACKAGE_NAME = "packageName";
static final String PRODUCT_ID = "productId";
static final String PURCHASE_STATE = "purchaseState";
static final String PURCHASE_TIME = "purchaseTime";
public static Transaction parse(JSONObject json) throws JSONException {
final Transaction transaction = new Transaction();
final int response = json.getInt(PURCHASE_STATE);
transaction.purchaseState = PurchaseState.valueOf(response);
transaction.productId = json.getString(PRODUCT_ID);
transaction.packageName = json.getString(PACKAGE_NAME);
transaction.purchaseTime = json.getLong(PURCHASE_TIME);
transaction.orderId = json.optString(ORDER_ID, null);
transaction.notificationId = json.optString(NOTIFICATION_ID, null);
transaction.developerPayload = json.optString(DEVELOPER_PAYLOAD, null);
return transaction;
}
public String developerPayload;
public String notificationId;
public String orderId;
public String packageName;
public String productId;
public PurchaseState purchaseState;
public long purchaseTime;
public Transaction() {}
public Transaction(String orderId, String productId, String packageName, PurchaseState purchaseState,
String notificationId, long purchaseTime, String developerPayload) {
this.orderId = orderId;
this.productId = productId;
this.packageName = packageName;
this.purchaseState = purchaseState;
this.notificationId = notificationId;
this.purchaseTime = purchaseTime;
this.developerPayload = developerPayload;
}
public Transaction clone() {
return new Transaction(orderId, productId, packageName, purchaseState, notificationId, purchaseTime, developerPayload);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Transaction other = (Transaction) obj;
if (developerPayload == null) {
if (other.developerPayload != null)
return false;
} else if (!developerPayload.equals(other.developerPayload))
return false;
if (notificationId == null) {
if (other.notificationId != null)
return false;
} else if (!notificationId.equals(other.notificationId))
return false;
if (orderId == null) {
if (other.orderId != null)
return false;
} else if (!orderId.equals(other.orderId))
return false;
if (packageName == null) {
if (other.packageName != null)
return false;
} else if (!packageName.equals(other.packageName))
return false;
if (productId == null) {
if (other.productId != null)
return false;
} else if (!productId.equals(other.productId))
return false;
if (purchaseState != other.purchaseState)
return false;
if (purchaseTime != other.purchaseTime)
return false;
return true;
}
@Override
public String toString() {
return String.valueOf(orderId);
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/model/Transaction.java | Java | asf20 | 4,489 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.helper;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.BillingController.BillingStatus;
import net.robotmedia.billing.BillingRequest.ResponseCode;
import net.robotmedia.billing.model.Transaction.PurchaseState;
import android.app.Activity;
public abstract class AbstractBillingActivity extends Activity implements BillingController.IConfiguration {
protected AbstractBillingObserver mBillingObserver;
/**
* Returns the billing status. If it's currently unknown, requests to check
* if billing is supported and
* {@link AbstractBillingActivity#onBillingChecked(boolean)} should be
* called later with the result.
*
* @return the current billing status (unknown, supported or unsupported).
* @see AbstractBillingActivity#onBillingChecked(boolean)
*/
public BillingStatus checkBillingSupported() {
return BillingController.checkBillingSupported(this);
}
public abstract void onBillingChecked(boolean supported);
@Override
protected void onCreate(android.os.Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBillingObserver = new AbstractBillingObserver(this) {
@Override
public void onBillingChecked(boolean supported) {
AbstractBillingActivity.this.onBillingChecked(supported);
}
@Override
public void onPurchaseStateChanged(String itemId, PurchaseState state) {
AbstractBillingActivity.this.onPurchaseStateChanged(itemId, state);
}
@Override
public void onRequestPurchaseResponse(String itemId, ResponseCode response) {
AbstractBillingActivity.this.onRequestPurchaseResponse(itemId, response);
}
};
BillingController.registerObserver(mBillingObserver);
BillingController.setConfiguration(this); // This activity will provide
// the public key and salt
this.checkBillingSupported();
if (!mBillingObserver.isTransactionsRestored()) {
BillingController.restoreTransactions(this);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
BillingController.unregisterObserver(mBillingObserver); // Avoid
// receiving
// notifications after
// destroy
BillingController.setConfiguration(null);
}
public abstract void onPurchaseStateChanged(String itemId, PurchaseState state);;
public abstract void onRequestPurchaseResponse(String itemId, ResponseCode response);
/**
* Requests the purchase of the specified item. The transaction will not be
* confirmed automatically; such confirmation could be handled in
* {@link AbstractBillingActivity#onPurchaseExecuted(String)}. If automatic
* confirmation is preferred use
* {@link BillingController#requestPurchase(android.content.Context, String, boolean)}
* instead.
*
* @param itemId
* id of the item to be purchased.
*/
public void requestPurchase(String itemId) {
BillingController.requestPurchase(this, itemId);
}
/**
* Requests to restore all transactions.
*/
public void restoreTransactions() {
BillingController.restoreTransactions(this);
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/helper/AbstractBillingActivity.java | Java | asf20 | 3,695 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.helper;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.IBillingObserver;
/**
* Abstract subclass of IBillingObserver that provides default implementations
* for {@link IBillingObserver#onPurchaseIntent(String, PendingIntent)} and
* {@link IBillingObserver#onTransactionsRestored()}.
*
*/
public abstract class AbstractBillingObserver implements IBillingObserver {
protected static final String KEY_TRANSACTIONS_RESTORED = "net.robotmedia.billing.transactionsRestored";
protected Activity activity;
public AbstractBillingObserver(Activity activity) {
this.activity = activity;
}
public boolean isTransactionsRestored() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
return preferences.getBoolean(KEY_TRANSACTIONS_RESTORED, false);
}
/**
* Called after requesting the purchase of the specified item. The default
* implementation simply starts the pending intent.
*
* @param itemId
* id of the item whose purchase was requested.
* @param purchaseIntent
* a purchase pending intent for the specified item.
*/
@Override
public void onPurchaseIntent(String itemId, PendingIntent purchaseIntent) {
BillingController.startPurchaseIntent(activity, purchaseIntent, null);
}
@Override
public void onTransactionsRestored() {
final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(activity);
final Editor editor = preferences.edit();
editor.putBoolean(KEY_TRANSACTIONS_RESTORED, true);
editor.commit();
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/helper/AbstractBillingObserver.java | Java | asf20 | 2,462 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.security;
public interface ISignatureValidator {
/**
* Validates that the specified signature matches the computed signature on
* the specified signed data. Returns true if the data is correctly signed.
*
* @param signedData
* signed data
* @param signature
* signature
* @return true if the data and signature match, false otherwise.
*/
public boolean validate(String signedData, String signature);
} | 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/security/ISignatureValidator.java | Java | asf20 | 1,122 |
/* Copyright 2011 Robot Media SL (http://www.robotmedia.net)
*
* 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 net.robotmedia.billing.security;
import java.security.InvalidKeyException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.X509EncodedKeySpec;
import android.text.TextUtils;
import android.util.Log;
import net.robotmedia.billing.BillingController;
import net.robotmedia.billing.utils.Base64;
import net.robotmedia.billing.utils.Base64DecoderException;
public class DefaultSignatureValidator implements ISignatureValidator {
protected static final String KEY_FACTORY_ALGORITHM = "RSA";
protected static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
/**
* Generates a PublicKey instance from a string containing the
* Base64-encoded public key.
*
* @param encodedPublicKey
* Base64-encoded public key
* @throws IllegalArgumentException
* if encodedPublicKey is invalid
*/
protected PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(BillingController.LOG_TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
} catch (Base64DecoderException e) {
Log.e(BillingController.LOG_TAG, "Base64 decoding failed.");
throw new IllegalArgumentException(e);
}
}
private BillingController.IConfiguration configuration;
public DefaultSignatureValidator(BillingController.IConfiguration configuration) {
this.configuration = configuration;
}
protected boolean validate(PublicKey publicKey, String signedData, String signature) {
Signature sig;
try {
sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(Base64.decode(signature))) {
Log.e(BillingController.LOG_TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(BillingController.LOG_TAG, "NoSuchAlgorithmException");
} catch (InvalidKeyException e) {
Log.e(BillingController.LOG_TAG, "Invalid key specification");
} catch (SignatureException e) {
Log.e(BillingController.LOG_TAG, "Signature exception");
} catch (Base64DecoderException e) {
Log.e(BillingController.LOG_TAG, "Base64 decoding failed");
}
return false;
}
@Override
public boolean validate(String signedData, String signature) {
final String publicKey;
if (configuration == null || TextUtils.isEmpty(publicKey = configuration.getPublicKey())) {
Log.w(BillingController.LOG_TAG, "Please set the public key or turn on debug mode");
return false;
}
if (signedData == null) {
Log.e(BillingController.LOG_TAG, "Data is null");
return false;
}
PublicKey key = generatePublicKey(publicKey);
return validate(key, signedData, signature);
}
}
| 04146814d-23 | AndroidBillingLibrary/src/net/robotmedia/billing/security/DefaultSignatureValidator.java | Java | asf20 | 3,855 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 com.android.vending.billing;
import android.os.Bundle;
interface IMarketBillingService {
/** Given the arguments in bundle form, returns a bundle for results. */
Bundle sendBillingRequest(in Bundle bundle);
}
| 04146814d-23 | AndroidBillingLibrary/src/com/android/vending/billing/IMarketBillingService.aidl | AIDL | asf20 | 848 |
package yuku.atree.demo;
import android.app.*;
import android.os.*;
import android.view.*;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import java.io.*;
import yuku.atree.*;
import yuku.atree.nodes.*;
public class MainActivity extends Activity {
private ListView tree;
private TreeAdapter adapter;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tree = (ListView) findViewById(R.id.aTree);
TreeNode root = getDemoTree();
root = new FileTreeNode("Choose a folder", new File[] {
Environment.getExternalStorageDirectory(),
new File("/"),
});
root.setExpanded(true);
adapter = new TreeAdapter();
adapter.setRoot(root);
adapter.setRootVisible(false);
tree.setAdapter(adapter);
adapter.setTreeListener(tree_listener);
tree.setOnItemClickListener(tree_itemClick);
}
private DemoTreeNode getDemoTree() {
DemoTreeNode root = new DemoTreeNode("root");
root.add(new DemoTreeNode("child 1") {{
add(new DemoTreeNode("grand child 1"));
add(new DemoTreeNode("grand child 2"));
add(new DemoTreeNode("grand child 3"));
setExpanded(true);
}});
root.add(new DemoTreeNode("child 2"));
root.add(new DemoTreeNode("child 3") {{
add(new DemoTreeNode("grand child 4"));
}});
return root;
}
private TreeListener tree_listener = new BaseTreeListener() {
};
private OnItemClickListener tree_itemClick = new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TreeNode node = adapter.getItem(position);
node.setExpanded(!node.getExpanded());
adapter.notifyDataSetChanged();
};
};
class DemoTreeNode extends BaseMutableTreeNode {
private final String text;
public DemoTreeNode(String text) {
this.text = text;
}
@Override public View getView(int position, View convertView, ViewGroup parent, int level, TreeNodeIconType iconType, int[] lines) {
View res = convertView != null? convertView: getLayoutInflater().inflate(R.layout.item_node, null);
TextView lText = (TextView) res.findViewById(R.id.lText);
ImageView imgNodeIcon = (ImageView) res.findViewById(R.id.imgNodeIcon);
lText.setText("" + level + " " + text);
MarginLayoutParams lp = (MarginLayoutParams) imgNodeIcon.getLayoutParams();
lp.leftMargin = 20 * level;
return res;
}
}
class FileTreeNode extends BaseFileTreeNode {
private String label;
public FileTreeNode(File file) {
super(file);
}
public FileTreeNode(String label, File[] virtualChildren) {
super(virtualChildren);
this.label = label;
}
@Override public View getView(int position, View convertView, ViewGroup parent, int level, TreeNodeIconType iconType, int[] lines) {
View res = convertView != null ? convertView : getLayoutInflater().inflate(R.layout.item_node, null);
TextView lText = (TextView) res.findViewById(R.id.lText);
ImageView imgNodeIcon = (ImageView) res.findViewById(R.id.imgNodeIcon);
lText.setText(label != null? label: file.getName());
MarginLayoutParams lp = (MarginLayoutParams) imgNodeIcon.getLayoutParams();
lp.leftMargin = (int) (getResources().getDisplayMetrics().density * 20) * (level - 1);
imgNodeIcon.setImageResource(file.isDirectory() ? android.R.drawable.presence_online : android.R.drawable.presence_offline);
return res;
}
@Override protected BaseFileTreeNode generateForFile(File file) {
return new FileTreeNode(file);
}
@Override protected boolean showHidden() {
return false;
}
@Override protected boolean showDirectoriesOnly() {
return true;
}
}
}
| 04146814d-23 | ATreeDemo/src/yuku/atree/demo/MainActivity.java | Java | asf20 | 3,773 |
package yuku.atree;
public interface MutableTreeNode extends TreeNode {
void insert(MutableTreeNode child, int index);
void remove(int index);
void remove(MutableTreeNode node);
void setUserObject(Object object);
<T> T getUserObject();
void removeFromParent();
void setParent(MutableTreeNode parent);
} | 04146814d-23 | ATree/src/yuku/atree/MutableTreeNode.java | Java | asf20 | 331 |
package yuku.atree;
import java.util.*;
public abstract class BaseMutableTreeNode implements MutableTreeNode {
protected MutableTreeNode parent;
protected List<TreeNode> children;
protected transient Object userObject;
private boolean expanded;
public BaseMutableTreeNode() {
this(null);
}
public BaseMutableTreeNode(final Object userObject) {
setUserObject(userObject);
}
@Override public void insert(final MutableTreeNode child, final int childIndex) {
if (child == null || isNodeAncestor(child)) {
throw new IllegalArgumentException("invalid child to insert"); //$NON-NLS-1$
}
if (child.getParent() instanceof MutableTreeNode) {
child.<MutableTreeNode> getParent().remove(child);
}
child.setParent(this);
getChildren().add(childIndex, child);
}
@Override public void remove(final int childIndex) {
MutableTreeNode child = (MutableTreeNode) getChildren().remove(childIndex);
child.setParent(null);
}
@Override public void setParent(final MutableTreeNode parent) {
this.parent = parent;
}
@SuppressWarnings("unchecked") @Override public <T extends TreeNode> T getParent() {
return (T) parent;
}
@SuppressWarnings("unchecked") @Override public <T extends TreeNode> T getChildAt(final int index) {
return (T) getChildren().get(index);
}
@Override public int getChildCount() {
return children != null ? children.size() : 0;
}
@Override public int getIndex(final TreeNode child) {
return children != null ? children.indexOf(child) : -1;
}
public List<TreeNode> children() {
return children;
}
@Override public void setUserObject(final Object userObject) {
this.userObject = userObject;
}
@SuppressWarnings("unchecked") @Override public <T> T getUserObject() {
return (T) userObject;
}
@Override public void removeFromParent() {
if (parent != null) {
parent.remove(this);
}
}
@Override public void remove(final MutableTreeNode child) {
int index = -1;
if (child == null || children == null || (index = children.indexOf(child)) == -1) {
throw new IllegalArgumentException("child null or not found"); //$NON-NLS-1$
}
remove(index);
}
public void removeAllChildren() {
if (children == null) {
return;
}
for (Iterator<TreeNode> it = children.iterator(); it.hasNext();) {
MutableTreeNode child = (MutableTreeNode) it.next();
child.setParent(null);
it.remove();
}
}
public void add(final MutableTreeNode child) {
insert(child, getChildCount() - (isNodeChild(child) ? 1 : 0));
}
public boolean isNodeAncestor(final TreeNode anotherNode) {
if (anotherNode == null) {
return false;
}
TreeNode currentParent = this;
while (currentParent != null) {
if (currentParent == anotherNode) {
return true;
}
currentParent = currentParent.getParent();
}
return false;
}
public boolean isNodeDescendant(final BaseMutableTreeNode anotherNode) {
return anotherNode != null ? anotherNode.isNodeAncestor(this) : false;
}
public TreeNode getSharedAncestor(final BaseMutableTreeNode anotherNode) {
TreeNode currentParent = anotherNode;
while (currentParent != null) {
if (isNodeAncestor(currentParent)) {
return currentParent;
}
currentParent = currentParent.getParent();
}
return null;
}
public boolean isNodeRelated(final BaseMutableTreeNode node) {
return getSharedAncestor(node) != null;
}
@Override public int getDepth() {
if (children == null || children.size() == 0) {
return 0;
}
int childrenDepth = 0;
for (Iterator<TreeNode> it = children.iterator(); it.hasNext();) {
TreeNode child = it.next();
int childDepth = child.getDepth();
if (childDepth > childrenDepth) {
childrenDepth = childDepth;
}
}
return childrenDepth + 1;
}
@Override public int getLevel() {
int result = 0;
TreeNode currentParent = getParent();
while (currentParent != null) {
currentParent = currentParent.getParent();
result++;
}
return result;
}
public TreeNode[] getPath() {
return getPathToRoot(this, 0);
}
public Object[] getUserObjectPath() {
TreeNode[] path = getPath();
Object[] result = new Object[path.length];
for (int i = 0; i < path.length; i++) {
result[i] = ((BaseMutableTreeNode) path[i]).getUserObject();
}
return result;
}
public TreeNode getRoot() {
TreeNode currentNode = this;
while (currentNode.getParent() != null) {
currentNode = currentNode.getParent();
}
return currentNode;
}
public boolean isRoot() {
return getParent() == null;
}
public boolean isNodeChild(final TreeNode child) {
return child != null && children != null ? children.contains(child) : false;
}
@Override public boolean isLeaf() {
return children == null || children.isEmpty();
}
@Override public String toString() {
return getUserObject() != null ? getUserObject().toString() : null;
}
protected TreeNode[] getPathToRoot(final TreeNode node, final int depth) {
if (node == null) {
return new TreeNode[depth];
}
TreeNode[] result = getPathToRoot(node.getParent(), depth + 1);
result[result.length - 1 - depth] = node;
return result;
}
private List<TreeNode> getChildren() {
if (children == null) {
children = new ArrayList<TreeNode>();
}
return children;
}
// including me
@Override public int getRowCount() {
if (!expanded) {
return 1;
}
int res = 1;
for (TreeNode node: getChildren()) {
res += node.getRowCount();
}
return res;
}
@Override public boolean getExpanded() {
return expanded;
}
@Override public void setExpanded(boolean expanded) {
this.expanded = expanded;
}
}
| 04146814d-23 | ATree/src/yuku/atree/BaseMutableTreeNode.java | Java | asf20 | 5,600 |
package yuku.atree;
public class BaseTreeListener implements TreeListener {
public static final String TAG = BaseTreeListener.class.getSimpleName();
@Override public void onTreeNodesChanged(TreeEvent e) {
}
@Override public void onTreeNodesInserted(TreeEvent e) {
}
@Override public void onTreeNodesRemoved(TreeEvent e) {
}
@Override public void onTreeStructureChanged(TreeEvent e) {
}
}
| 04146814d-23 | ATree/src/yuku/atree/BaseTreeListener.java | Java | asf20 | 402 |
package yuku.atree;
/**
* Storage of the utility methods for tree-related calculations.
*
*/
public class TreeCommons {
/**
* Returns tree path from the specified ancestor to a node.
*
* @param node
* TreeNode which is the path end
* @param ancestor
* TreeNode which is the path top
*
* @return path from an ancestor to a node
*/
public static TreeNode[] getPathToAncestor(final TreeNode node, final TreeNode ancestor) {
return getPathToAncestor(node, ancestor, 0);
}
/**
* Returns tree path from the specified ancestor to a node limited by the depth.
*
* @param node
* TreeNode which is the path end
* @param ancestor
* TreeNode which is the path top
* @param depth
* int value representing the maximum path length
*
* @return path from an ancestor to a node
*/
public static TreeNode[] getPathToAncestor(final TreeNode node, final TreeNode ancestor, final int depth) {
if (node == null) {
return new TreeNode[depth];
}
if (node == ancestor) {
TreeNode[] result = new TreeNode[depth + 1];
result[0] = ancestor;
return result;
}
TreeNode[] result = getPathToAncestor(node.getParent(), ancestor, depth + 1);
result[result.length - depth - 1] = node;
return result;
}
} | 04146814d-23 | ATree/src/yuku/atree/TreeCommons.java | Java | asf20 | 1,309 |
package yuku.atree;
public enum TreeNodeIconType {
none, // -
up, // '-
both, // |-
}
| 04146814d-23 | ATree/src/yuku/atree/TreeNodeIconType.java | Java | asf20 | 90 |
package yuku.atree;
import java.io.*;
public class TreePath implements Serializable {
private TreeNode[] elements;
private TreePath parent;
private final int pathCount;
public TreePath(final TreeNode[] path) {
pathCount = path.length;
elements = new TreeNode[pathCount];
System.arraycopy(path, 0, elements, 0, pathCount);
parent = null;
}
public TreePath(final TreeNode singlePath) {
elements = new TreeNode[] {singlePath};
pathCount = 1;
parent = null;
}
protected TreePath() {
elements = new TreeNode[] {null};
pathCount = 1;
parent = null;
}
protected TreePath(final TreeNode[] path, final int length) {
pathCount = length;
elements = new TreeNode[pathCount];
System.arraycopy(path, 0, elements, 0, pathCount);
parent = null;
}
protected TreePath(final TreePath parentPath, final TreeNode lastElement) {
elements = new TreeNode[] {lastElement};
parent = parentPath;
pathCount = (parent != null) ? parent.getPathCount() + 1 : 1;
}
@Override public boolean equals(final Object o) {
if (!(o instanceof TreePath)) {
return false;
}
TreePath path = (TreePath)o;
final int numPathComponents = getPathCount();
if (path.getPathCount() != numPathComponents) {
return false;
}
for (int i = 0; i < numPathComponents; i++) {
if (!path.getPathComponent(i).equals(getPathComponent(i))) {
return false;
}
}
return true;
}
public TreeNode getLastPathComponent() {
return elements[elements.length - 1];
}
public TreePath getParentPath() {
if (parent != null) {
return parent;
}
int numParentPaths = getPathCount() - 1;
if (numParentPaths <= 0) {
return null;
}
return new TreePath(getPath(), numParentPaths);
}
public TreeNode[] getPath() {
if (parent == null) {
return elements;
}
TreeNode[] parentPath = parent.getPath();
TreeNode[] result = new TreeNode[parentPath.length + 1];
System.arraycopy(parentPath, 0, result, 0, parentPath.length);
result[result.length - 1] = getLastPathComponent();
elements = result.clone();
parent = null;
return result;
}
public TreeNode getPathComponent(final int element) {
final int pathCount = getPathCount();
if (element < 0 || element >= pathCount) {
throw new IllegalArgumentException("element index out of bounds"); //$NON-NLS-1$
}
if (parent == null) {
return elements[element];
}
return (element < pathCount - 1) ? parent.getPathComponent(element) :
getLastPathComponent();
}
public int getPathCount() {
return pathCount;
}
public boolean isDescendant(final TreePath child) {
if (child == null) {
return false;
}
final int numPathComponents = getPathCount();
if (child.getPathCount() < numPathComponents) {
return false;
}
for (int i = 0; i < numPathComponents; i++) {
if (!child.getPathComponent(i).equals(getPathComponent(i))) {
return false;
}
}
return true;
}
public TreePath pathByAddingChild(final TreeNode child) {
return new TreePath(this, child);
}
@Override public int hashCode() {
return getLastPathComponent().hashCode();
}
@Override public String toString() {
String result = null;
final int numPathComponents = getPathCount();
for (int i = 0; i < numPathComponents; i++) {
if (result != null) {
result += ", ";
} else {
result = "";
}
result += getPathComponent(i);
}
return "[" + result + "]";
}
}
| 04146814d-23 | ATree/src/yuku/atree/TreePath.java | Java | asf20 | 4,125 |
package yuku.atree;
import android.view.*;
import android.widget.*;
public class TreeAdapter extends BaseAdapter {
public static final String TAG = TreeAdapter.class.getSimpleName();
private TreeNode root;
private boolean rootVisible = true;
private TreeListener listener;
@Override public int getCount() {
if (root == null) {
return 0;
} else {
return root.getRowCount() - (rootVisible? 0: 1);
}
}
@Override public TreeNode getItem(int position) {
if (rootVisible && position == 0) return root;
return searchItem(root, rootVisible? 0: -1, position);
}
private static TreeNode searchItem(TreeNode cur, int base, int target) {
if (base == target) return cur;
int pos = base + 1; // first child is always one row after
for (int i = 0, len = cur.getChildCount(); i < len; i++) {
TreeNode child = cur.getChildAt(i);
int max = pos + child.getRowCount();
// range covered is pos..<max
if (target >= pos && target < max) {
return searchItem(child, pos, target);
}
pos = max;
}
throw new RuntimeException("invalid target: " + target);
}
@Override public long getItemId(int position) {
return position;
}
@Override public View getView(int position, View convertView, ViewGroup parent) {
TreeNode node = getItem(position);
return node.getView(position, convertView, parent, node.getLevel(), TreeNodeIconType.up, null);
}
public void setRoot(TreeNode root) {
this.root = root;
notifyDataSetChanged();
if (root != null) {
dispatchNodeStructureChanged(root);
} else {
notifyRootChangedToNull(this);
}
}
public boolean getRootVisible() {
return rootVisible;
}
public void setRootVisible(boolean visible) {
this.rootVisible = visible;
notifyDataSetChanged();
}
public void setTreeListener(final TreeListener l) {
listener = l;
}
@SuppressWarnings("unchecked") public <T extends TreeNode> T getRoot() {
return (T) root;
}
public int getIndexOfChild(TreeNode parent, TreeNode child) {
if (parent == null || child == null) {
return -1;
}
int numChildren = parent.getChildCount();
for (int i = 0; i < numChildren; i++) {
if (child.equals(parent.getChildAt(i))) {
return i;
}
}
return -1;
}
public void reload() {
reload(root);
}
public void reload(final TreeNode node) {
dispatchNodeStructureChanged(node);
}
public void insertNodeInto(final MutableTreeNode newChild, final MutableTreeNode parent, final int index) {
parent.insert(newChild, index);
dispatchNodesWereInserted(parent, new int[] { index });
}
public void removeNodeFromParent(final MutableTreeNode node) {
MutableTreeNode parent = node.getParent();
int index = parent.getIndex(node);
parent.remove(node);
dispatchNodesWereRemoved(parent, new int[] { index }, new TreeNode[] { node });
}
public void dispatchNodeChanged(final TreeNode node) {
if (node == root) {
dispatchNodesChanged(node, null);
return;
}
if (node == null) {
return;
}
final TreeNode parent = node.getParent();
if (parent == null) {
return;
}
dispatchNodesChanged(parent, new int[] { getIndexOfChild(parent, node) });
}
public void dispatchNodesChanged(final TreeNode node, final int[] childIndices) {
if (node == null || node != root || childIndices == null || childIndices.length == 0) {
return;
}
notifyTreeNodesChanged(getPathToRoot(node), childIndices, getNodeChildren(node, childIndices));
}
public void dispatchNodesWereInserted(final TreeNode node, final int[] childIndices) {
if (node == null || childIndices == null || childIndices.length == 0) {
return;
}
notifyTreeNodesInserted(this, getPathToRoot(node), childIndices, getNodeChildren(node, childIndices));
}
public void dispatchNodesWereRemoved(final TreeNode node, final int[] childIndices, final TreeNode[] removedChildren) {
if (node == null || childIndices == null || childIndices.length == 0) {
return;
}
notifyTreeNodesRemoved(this, getPathToRoot(node), childIndices, removedChildren);
}
public void dispatchNodeStructureChanged(final TreeNode node) {
if (node == null) {
return;
}
notifyTreeStructureChanged(this, getPathToRoot(node), null, null);
}
public TreeNode[] getPathToRoot(final TreeNode aNode) {
if (aNode == null) {
return new TreeNode[0];
}
return getPathToRoot(aNode, 0);
}
protected TreeNode[] getPathToRoot(final TreeNode aNode, final int depth) {
return TreeCommons.getPathToAncestor(aNode, root, depth);
}
protected void notifyTreeNodesChanged(final TreeNode[] path, final int[] childIndices, final TreeNode[] children) {
if (listener == null) return;
TreeEvent event = new TreeEvent(path, childIndices, children);
listener.onTreeNodesChanged(event);
}
protected void notifyTreeNodesInserted(final Object source, final TreeNode[] path, final int[] childIndices, final TreeNode[] children) {
if (listener == null) return;
TreeEvent event = new TreeEvent(path, childIndices, children);
listener.onTreeNodesInserted(event);
}
protected void notifyTreeNodesRemoved(final Object source, final TreeNode[] path, final int[] childIndices, final TreeNode[] children) {
if (listener == null) return;
TreeEvent event = new TreeEvent(path, childIndices, children);
listener.onTreeNodesRemoved(event);
}
protected void notifyTreeStructureChanged(final Object source, final TreeNode[] path, final int[] childIndices, final TreeNode[] children) {
if (listener == null) return;
TreeEvent event = new TreeEvent(path, childIndices, children);
listener.onTreeStructureChanged(event);
}
private void notifyRootChangedToNull(final Object source) {
TreeEvent event = new TreeEvent((TreePath) null);
listener.onTreeStructureChanged(event);
}
private TreeNode[] getNodeChildren(final TreeNode node, final int[] childIndices) {
if (childIndices == null) {
return null;
}
TreeNode[] result = new TreeNode[childIndices.length];
for (int i = 0; i < result.length; i++) {
result[i] = node.getChildAt(childIndices[i]);
}
return result;
}
}
| 04146814d-23 | ATree/src/yuku/atree/TreeAdapter.java | Java | asf20 | 6,082 |
package yuku.atree.nodes;
import java.io.*;
import java.util.*;
import yuku.atree.*;
public abstract class BaseFileTreeNode extends BaseMutableTreeNode implements Comparable<BaseFileTreeNode> {
public static final String TAG = BaseFileTreeNode.class.getSimpleName();
protected final File file;
protected final File[] virtualChildren;
public BaseFileTreeNode(File file) {
this.file = file;
this.virtualChildren = null;
}
public BaseFileTreeNode(File[] virtualChildren) {
this.file = null;
this.virtualChildren = virtualChildren;
}
@Override public void setExpanded(boolean expanded) {
super.setExpanded(expanded);
if (expanded) {
File[] files;
if (file != null && file.isDirectory()) {
files = file.listFiles(fileFilter);
if (files != null) Arrays.sort(files, fileComparator);
} else if (virtualChildren != null) {
files = virtualChildren;
} else {
files = null;
}
if (files == null) {
this.removeAllChildren();
} else {
HashMap<String, BaseFileTreeNode> existing = new HashMap<String, BaseFileTreeNode>();
for (int i = 0; i < this.getChildCount(); i++) {
BaseFileTreeNode child = this.getChildAt(i);
existing.put(child.file.getName(), child);
}
this.removeAllChildren();
for (File file : files) {
BaseFileTreeNode existingNode = existing.get(file.getName());
if (existingNode != null) {
this.add(existingNode);
} else {
this.add(generateForFile(file));
}
}
}
}
}
private FileFilter fileFilter = new FileFilter() {
@Override public boolean accept(File pathname) {
if (showDirectoriesOnly()) {
if (!pathname.isDirectory()) {
return false;
}
}
if (!showHidden()) {
if (pathname.isHidden()) {
return false;
}
}
return true;
}
};
static Comparator<File> fileComparator = new Comparator<File>() {
@Override public int compare(File a, File b) {
// virtual first
if (a == null) {
return -1;
} else if (b == null) {
return +1;
}
if (a.isDirectory() && !b.isDirectory()) {
return -1;
} else if (!a.isDirectory() && b.isDirectory()) {
return +1;
}
// both files or both dirs
String aname = a.getName();
String bname = b.getName();
// dot-files are later
if (aname.startsWith(".") && !bname.startsWith(".")) { //$NON-NLS-1$ //$NON-NLS-2$
return +1;
} else if (!aname.startsWith(".") && bname.startsWith(".")) { //$NON-NLS-1$ //$NON-NLS-2$
return -1;
}
return aname.compareToIgnoreCase(bname);
}
};
@Override public int compareTo(BaseFileTreeNode another) {
File a = this.file;
File b = another.file;
return fileComparator.compare(a, b);
}
protected abstract BaseFileTreeNode generateForFile(File file);
protected boolean showDirectoriesOnly() {
return false;
}
protected boolean showHidden() {
return true;
}
public File getFile() {
return file;
}
public File[] getVirtualChildren() {
return virtualChildren;
}
}
| 04146814d-23 | ATree/src/yuku/atree/nodes/BaseFileTreeNode.java | Java | asf20 | 3,043 |
package yuku.atree;
public interface TreeListener {
void onTreeNodesChanged(TreeEvent e);
void onTreeNodesInserted(TreeEvent e);
void onTreeNodesRemoved(TreeEvent e);
void onTreeStructureChanged(TreeEvent e);
}
| 04146814d-23 | ATree/src/yuku/atree/TreeListener.java | Java | asf20 | 228 |
package yuku.atree;
import android.view.*;
public interface TreeNode {
<T extends TreeNode> T getChildAt(int childIndex);
int getChildCount();
<T extends TreeNode> T getParent();
int getIndex(TreeNode node);
boolean isLeaf();
// yuku's additions
int getDepth();
int getLevel();
// for converting to list
int getRowCount();
boolean getExpanded();
void setExpanded(boolean expanded);
View getView(int position, View convertView, ViewGroup parent, int level, TreeNodeIconType iconType, int[] lines);
}
| 04146814d-23 | ATree/src/yuku/atree/TreeNode.java | Java | asf20 | 564 |
package yuku.atree;
public class TreeEvent {
protected TreePath path;
protected int[] childIndices;
protected TreeNode[] children;
public TreeEvent(final TreeNode[] path) {
this(path, new int[0], null);
}
public TreeEvent(final TreePath path) {
this(path, new int[0], null);
}
public TreeEvent(final TreeNode[] path, final int[] childIndices, final TreeNode[] children) {
this(new TreePath(path), childIndices, children);
}
public TreeEvent(final TreePath path, final int[] childIndices, final TreeNode[] children) {
this.path = path;
this.childIndices = childIndices;
this.children = children;
}
public TreePath getTreePath() {
return path;
}
public TreeNode[] getPath() {
return path != null ? path.getPath() : null;
}
public TreeNode[] getChildren() {
return children != null ? children.clone() : null;
}
public int[] getChildIndices() {
return childIndices != null ? (int[]) childIndices.clone() : null;
}
}
| 04146814d-23 | ATree/src/yuku/atree/TreeEvent.java | Java | asf20 | 961 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 yuku.androidsdk.android.util;
import java.io.*;
/**
* Utilities for encoding and decoding the Base64 representation of
* binary data. See RFCs <a
* href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and <a
* href="http://www.ietf.org/rfc/rfc3548.txt">3548</a>.
*/
public class Base64 {
/**
* Default values for encoder/decoder flags.
*/
public static final int DEFAULT = 0;
/**
* Encoder flag bit to omit the padding '=' characters at the end
* of the output (if any).
*/
public static final int NO_PADDING = 1;
/**
* Encoder flag bit to omit all line terminators (i.e., the output
* will be on one long line).
*/
public static final int NO_WRAP = 2;
/**
* Encoder flag bit to indicate lines should be terminated with a
* CRLF pair instead of just an LF. Has no effect if {@code
* NO_WRAP} is specified as well.
*/
public static final int CRLF = 4;
/**
* Encoder/decoder flag bit to indicate using the "URL and
* filename safe" variant of Base64 (see RFC 3548 section 4) where
* {@code -} and {@code _} are used in place of {@code +} and
* {@code /}.
*/
public static final int URL_SAFE = 8;
/**
* Flag to pass to {@link Base64OutputStream} to indicate that it
* should not close the output stream it is wrapping when it
* itself is closed.
*/
public static final int NO_CLOSE = 16;
// --------------------------------------------------------
// shared code
// --------------------------------------------------------
/* package */ static abstract class Coder {
public byte[] output;
public int op;
/**
* Encode/decode another block of input data. this.output is
* provided by the caller, and must be big enough to hold all
* the coded data. On exit, this.opwill be set to the length
* of the coded data.
*
* @param finish true if this is the final call to process for
* this object. Will finalize the coder state and
* include any final bytes in the output.
*
* @return true if the input so far is good; false if some
* error has been detected in the input stream..
*/
public abstract boolean process(byte[] input, int offset, int len, boolean finish);
/**
* @return the maximum number of bytes a call to process()
* could produce for the given number of input bytes. This may
* be an overestimate.
*/
public abstract int maxOutputSize(int len);
}
// --------------------------------------------------------
// decoding
// --------------------------------------------------------
/**
* Decode the Base64-encoded data in input and return the data in
* a new byte array.
*
* <p>The padding '=' characters at the end are considered optional, but
* if any are present, there must be the correct number of them.
*
* @param str the input String to decode, which is converted to
* bytes using the default charset
* @param flags controls certain features of the decoded output.
* Pass {@code DEFAULT} to decode standard Base64.
*
* @throws IllegalArgumentException if the input contains
* incorrect padding
*/
public static byte[] decode(String str, int flags) {
return decode(str.getBytes(), flags);
}
/**
* Decode the Base64-encoded data in input and return the data in
* a new byte array.
*
* <p>The padding '=' characters at the end are considered optional, but
* if any are present, there must be the correct number of them.
*
* @param input the input array to decode
* @param flags controls certain features of the decoded output.
* Pass {@code DEFAULT} to decode standard Base64.
*
* @throws IllegalArgumentException if the input contains
* incorrect padding
*/
public static byte[] decode(byte[] input, int flags) {
return decode(input, 0, input.length, flags);
}
/**
* Decode the Base64-encoded data in input and return the data in
* a new byte array.
*
* <p>The padding '=' characters at the end are considered optional, but
* if any are present, there must be the correct number of them.
*
* @param input the data to decode
* @param offset the position within the input array at which to start
* @param len the number of bytes of input to decode
* @param flags controls certain features of the decoded output.
* Pass {@code DEFAULT} to decode standard Base64.
*
* @throws IllegalArgumentException if the input contains
* incorrect padding
*/
public static byte[] decode(byte[] input, int offset, int len, int flags) {
// Allocate space for the most data the input could represent.
// (It could contain less if it contains whitespace, etc.)
Decoder decoder = new Decoder(flags, new byte[len*3/4]);
if (!decoder.process(input, offset, len, true)) {
throw new IllegalArgumentException("bad base-64"); //$NON-NLS-1$
}
// Maybe we got lucky and allocated exactly enough output space.
if (decoder.op == decoder.output.length) {
return decoder.output;
}
// Need to shorten the array, so allocate a new one of the
// right size and copy.
byte[] temp = new byte[decoder.op];
System.arraycopy(decoder.output, 0, temp, 0, decoder.op);
return temp;
}
/* package */ static class Decoder extends Coder {
/**
* Lookup table for turning bytes into their position in the
* Base64 alphabet.
*/
private static final int DECODE[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
/**
* Decode lookup table for the "web safe" variant (RFC 3548
* sec. 4) where - and _ replace + and /.
*/
private static final int DECODE_WEBSAFE[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1,
52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -2, -1, -1,
-1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, 63,
-1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
};
/** Non-data values in the DECODE arrays. */
private static final int SKIP = -1;
private static final int EQUALS = -2;
/**
* States 0-3 are reading through the next input tuple.
* State 4 is having read one '=' and expecting exactly
* one more.
* State 5 is expecting no more data or padding characters
* in the input.
* State 6 is the error state; an error has been detected
* in the input and no future input can "fix" it.
*/
private int state; // state number (0 to 6)
private int value;
final private int[] alphabet;
public Decoder(int flags, byte[] output) {
this.output = output;
alphabet = ((flags & URL_SAFE) == 0) ? DECODE : DECODE_WEBSAFE;
state = 0;
value = 0;
}
/**
* @return an overestimate for the number of bytes {@code
* len} bytes could decode to.
*/
@Override public int maxOutputSize(int len) {
return len * 3/4 + 10;
}
/**
* Decode another block of input data.
*
* @return true if the state machine is still healthy. false if
* bad base-64 data has been detected in the input stream.
*/
@Override public boolean process(byte[] input, int offset, int len, boolean finish) {
if (this.state == 6) return false;
int p = offset;
len += offset;
// Using local variables makes the decoder about 12%
// faster than if we manipulate the member variables in
// the loop. (Even alphabet makes a measurable
// difference, which is somewhat surprising to me since
// the member variable is final.)
int state = this.state;
int value = this.value;
int op = 0;
final byte[] output = this.output;
final int[] alphabet = this.alphabet;
while (p < len) {
// Try the fast path: we're starting a new tuple and the
// next four bytes of the input stream are all data
// bytes. This corresponds to going through states
// 0-1-2-3-0. We expect to use this method for most of
// the data.
//
// If any of the next four bytes of input are non-data
// (whitespace, etc.), value will end up negative. (All
// the non-data values in decode are small negative
// numbers, so shifting any of them up and or'ing them
// together will result in a value with its top bit set.)
//
// You can remove this whole block and the output should
// be the same, just slower.
if (state == 0) {
while (p+4 <= len &&
(value = ((alphabet[input[p] & 0xff] << 18) |
(alphabet[input[p+1] & 0xff] << 12) |
(alphabet[input[p+2] & 0xff] << 6) |
(alphabet[input[p+3] & 0xff]))) >= 0) {
output[op+2] = (byte) value;
output[op+1] = (byte) (value >> 8);
output[op] = (byte) (value >> 16);
op += 3;
p += 4;
}
if (p >= len) break;
}
// The fast path isn't available -- either we've read a
// partial tuple, or the next four input bytes aren't all
// data, or whatever. Fall back to the slower state
// machine implementation.
int d = alphabet[input[p++] & 0xff];
switch (state) {
case 0:
if (d >= 0) {
value = d;
++state;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 1:
if (d >= 0) {
value = (value << 6) | d;
++state;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 2:
if (d >= 0) {
value = (value << 6) | d;
++state;
} else if (d == EQUALS) {
// Emit the last (partial) output tuple;
// expect exactly one more padding character.
output[op++] = (byte) (value >> 4);
state = 4;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 3:
if (d >= 0) {
// Emit the output triple and return to state 0.
value = (value << 6) | d;
output[op+2] = (byte) value;
output[op+1] = (byte) (value >> 8);
output[op] = (byte) (value >> 16);
op += 3;
state = 0;
} else if (d == EQUALS) {
// Emit the last (partial) output tuple;
// expect no further data or padding characters.
output[op+1] = (byte) (value >> 2);
output[op] = (byte) (value >> 10);
op += 2;
state = 5;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 4:
if (d == EQUALS) {
++state;
} else if (d != SKIP) {
this.state = 6;
return false;
}
break;
case 5:
if (d != SKIP) {
this.state = 6;
return false;
}
break;
}
}
if (!finish) {
// We're out of input, but a future call could provide
// more.
this.state = state;
this.value = value;
this.op = op;
return true;
}
// Done reading input. Now figure out where we are left in
// the state machine and finish up.
switch (state) {
case 0:
// Output length is a multiple of three. Fine.
break;
case 1:
// Read one extra input byte, which isn't enough to
// make another output byte. Illegal.
this.state = 6;
return false;
case 2:
// Read two extra input bytes, enough to emit 1 more
// output byte. Fine.
output[op++] = (byte) (value >> 4);
break;
case 3:
// Read three extra input bytes, enough to emit 2 more
// output bytes. Fine.
output[op++] = (byte) (value >> 10);
output[op++] = (byte) (value >> 2);
break;
case 4:
// Read one padding '=' when we expected 2. Illegal.
this.state = 6;
return false;
case 5:
// Read all the padding '='s we expected and no more.
// Fine.
break;
}
this.state = state;
this.op = op;
return true;
}
}
// --------------------------------------------------------
// encoding
// --------------------------------------------------------
/**
* Base64-encode the given data and return a newly allocated
* String with the result.
*
* @param input the data to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static String encodeToString(byte[] input, int flags) {
try {
return new String(encode(input, flags), "US-ASCII"); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
// US-ASCII is guaranteed to be available.
throw new AssertionError(e);
}
}
/**
* Base64-encode the given data and return a newly allocated
* String with the result.
*
* @param input the data to encode
* @param offset the position within the input array at which to
* start
* @param len the number of bytes of input to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static String encodeToString(byte[] input, int offset, int len, int flags) {
try {
return new String(encode(input, offset, len, flags), "US-ASCII"); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
// US-ASCII is guaranteed to be available.
throw new AssertionError(e);
}
}
/**
* Base64-encode the given data and return a newly allocated
* byte[] with the result.
*
* @param input the data to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static byte[] encode(byte[] input, int flags) {
return encode(input, 0, input.length, flags);
}
/**
* Base64-encode the given data and return a newly allocated
* byte[] with the result.
*
* @param input the data to encode
* @param offset the position within the input array at which to
* start
* @param len the number of bytes of input to encode
* @param flags controls certain features of the encoded output.
* Passing {@code DEFAULT} results in output that
* adheres to RFC 2045.
*/
public static byte[] encode(byte[] input, int offset, int len, int flags) {
Encoder encoder = new Encoder(flags, null);
// Compute the exact length of the array we will produce.
int output_len = len / 3 * 4;
// Account for the tail of the data and the padding bytes, if any.
if (encoder.do_padding) {
if (len % 3 > 0) {
output_len += 4;
}
} else {
switch (len % 3) {
case 0: break;
case 1: output_len += 2; break;
case 2: output_len += 3; break;
}
}
// Account for the newlines, if any.
if (encoder.do_newline && len > 0) {
output_len += (((len-1) / (3 * Encoder.LINE_GROUPS)) + 1) *
(encoder.do_cr ? 2 : 1);
}
encoder.output = new byte[output_len];
encoder.process(input, offset, len, true);
assert encoder.op == output_len;
return encoder.output;
}
/* package */ static class Encoder extends Coder {
/**
* Emit a new line every this many output tuples. Corresponds to
* a 76-character line length (the maximum allowable according to
* <a href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>).
*/
public static final int LINE_GROUPS = 19;
/**
* Lookup table for turning Base64 alphabet positions (6 bits)
* into output bytes.
*/
private static final byte ENCODE[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/',
};
/**
* Lookup table for turning Base64 alphabet positions (6 bits)
* into output bytes.
*/
private static final byte ENCODE_WEBSAFE[] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '_',
};
final private byte[] tail;
/* package */ int tailLen;
private int count;
final public boolean do_padding;
final public boolean do_newline;
final public boolean do_cr;
final private byte[] alphabet;
public Encoder(int flags, byte[] output) {
this.output = output;
do_padding = (flags & NO_PADDING) == 0;
do_newline = (flags & NO_WRAP) == 0;
do_cr = (flags & CRLF) != 0;
alphabet = ((flags & URL_SAFE) == 0) ? ENCODE : ENCODE_WEBSAFE;
tail = new byte[2];
tailLen = 0;
count = do_newline ? LINE_GROUPS : -1;
}
/**
* @return an overestimate for the number of bytes {@code
* len} bytes could encode to.
*/
@Override public int maxOutputSize(int len) {
return len * 8/5 + 10;
}
@Override public boolean process(byte[] input, int offset, int len, boolean finish) {
// Using local variables makes the encoder about 9% faster.
final byte[] alphabet = this.alphabet;
final byte[] output = this.output;
int op = 0;
int count = this.count;
int p = offset;
len += offset;
int v = -1;
// First we need to concatenate the tail of the previous call
// with any input bytes available now and see if we can empty
// the tail.
switch (tailLen) {
case 0:
// There was no tail.
break;
case 1:
if (p+2 <= len) {
// A 1-byte tail with at least 2 bytes of
// input available now.
v = ((tail[0] & 0xff) << 16) |
((input[p++] & 0xff) << 8) |
(input[p++] & 0xff);
tailLen = 0;
};
break;
case 2:
if (p+1 <= len) {
// A 2-byte tail with at least 1 byte of input.
v = ((tail[0] & 0xff) << 16) |
((tail[1] & 0xff) << 8) |
(input[p++] & 0xff);
tailLen = 0;
}
break;
}
if (v != -1) {
output[op++] = alphabet[(v >> 18) & 0x3f];
output[op++] = alphabet[(v >> 12) & 0x3f];
output[op++] = alphabet[(v >> 6) & 0x3f];
output[op++] = alphabet[v & 0x3f];
if (--count == 0) {
if (do_cr) output[op++] = '\r';
output[op++] = '\n';
count = LINE_GROUPS;
}
}
// At this point either there is no tail, or there are fewer
// than 3 bytes of input available.
// The main loop, turning 3 input bytes into 4 output bytes on
// each iteration.
while (p+3 <= len) {
v = ((input[p] & 0xff) << 16) |
((input[p+1] & 0xff) << 8) |
(input[p+2] & 0xff);
output[op] = alphabet[(v >> 18) & 0x3f];
output[op+1] = alphabet[(v >> 12) & 0x3f];
output[op+2] = alphabet[(v >> 6) & 0x3f];
output[op+3] = alphabet[v & 0x3f];
p += 3;
op += 4;
if (--count == 0) {
if (do_cr) output[op++] = '\r';
output[op++] = '\n';
count = LINE_GROUPS;
}
}
if (finish) {
// Finish up the tail of the input. Note that we need to
// consume any bytes in tail before any bytes
// remaining in input; there should be at most two bytes
// total.
if (p-tailLen == len-1) {
int t = 0;
v = ((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 4;
tailLen -= t;
output[op++] = alphabet[(v >> 6) & 0x3f];
output[op++] = alphabet[v & 0x3f];
if (do_padding) {
output[op++] = '=';
output[op++] = '=';
}
if (do_newline) {
if (do_cr) output[op++] = '\r';
output[op++] = '\n';
}
} else if (p-tailLen == len-2) {
int t = 0;
v = (((tailLen > 1 ? tail[t++] : input[p++]) & 0xff) << 10) |
(((tailLen > 0 ? tail[t++] : input[p++]) & 0xff) << 2);
tailLen -= t;
output[op++] = alphabet[(v >> 12) & 0x3f];
output[op++] = alphabet[(v >> 6) & 0x3f];
output[op++] = alphabet[v & 0x3f];
if (do_padding) {
output[op++] = '=';
}
if (do_newline) {
if (do_cr) output[op++] = '\r';
output[op++] = '\n';
}
} else if (do_newline && op > 0 && count != LINE_GROUPS) {
if (do_cr) output[op++] = '\r';
output[op++] = '\n';
}
assert tailLen == 0;
assert p == len;
} else {
// Save the leftovers in tail to be consumed on the next
// call to encodeInternal.
if (p == len-1) {
tail[tailLen++] = input[p];
} else if (p == len-2) {
tail[tailLen++] = input[p];
tail[tailLen++] = input[p+1];
}
}
this.op = op;
this.count = count;
return true;
}
}
private Base64() { } // don't instantiate
} | 04146814d-23 | AndroidCrypto/src/yuku/androidsdk/android/util/Base64.java | Java | asf20 | 28,669 |
package yuku.androidcrypto;
import java.io.*;
import java.security.*;
public class Digester {
public static byte[] digest(DigestType type, byte[] data) {
MessageDigest md = type.getMessageDigest();
md.update(data);
return md.digest();
}
/**
* String encoded in utf8 first
*/
public static byte[] digest(DigestType type, String data) {
return digest(type, utf8Encode(data));
}
public static byte[] digestFile(DigestType type, File file) {
BufferedInputStream is = null;
try {
is = new BufferedInputStream(new FileInputStream(file), 64*1024);
byte[] buf = new byte[8192];
MessageDigest md = type.getMessageDigest();
while (true) {
int read = is.read(buf);
if (read < 0) break;
md.update(buf, 0, read);
}
return md.digest();
} catch (IOException e) {
return null;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
}
public static byte[] utf8Encode(String s) {
try {
return s.getBytes("utf-8"); //$NON-NLS-1$
} catch (UnsupportedEncodingException e) {
return null;
}
}
public static String toHex(byte[] a) {
char[] d = new char[a.length * 2];
int pos = 0;
for (byte b: a) {
int h = (b & 0xf0) >> 4;
int l = b & 0x0f;
d[pos++] = (char) (h < 10? ('0' + h): ('a' + h - 10));
d[pos++] = (char) (l < 10? ('0' + l): ('a' + l - 10));
}
return new String(d);
}
}
| 04146814d-23 | AndroidCrypto/src/yuku/androidcrypto/Digester.java | Java | asf20 | 1,427 |
package yuku.androidcrypto;
import android.util.*;
import java.security.*;
public enum DigestType {
MD5("MD5"), //$NON-NLS-1$
SHA1("SHA1"), //$NON-NLS-1$
SHA256("SHA256"), //$NON-NLS-1$
SHA512("SHA512"); //$NON-NLS-1$
private static final String TAG = MessageDigest.class.getSimpleName();
private final String algo;
DigestType(String algo) {
this.algo = algo;
}
public MessageDigest getMessageDigest() {
try {
return MessageDigest.getInstance(algo);
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "NoSuchAlgorithmException: " + algo, e); //$NON-NLS-1$
return null;
}
}
}
| 04146814d-23 | AndroidCrypto/src/yuku/androidcrypto/DigestType.java | Java | asf20 | 610 |
package yuku.iconcontextmenu.test;
import yuku.iconcontextmenu.*;
import yuku.iconcontextmenu.IconContextMenu.IconContextItemSelectedListener;
import android.app.Activity;
import android.content.*;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnDismissListener;
import android.os.Bundle;
import android.view.*;
import android.widget.Toast;
public class IconContextMenuDicobaActivity extends Activity implements IconContextItemSelectedListener, OnCancelListener, OnDismissListener {
private IconContextMenu iconContextMenu = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void bDemo1_click(View v) {
initContextMenu();
iconContextMenu.setInfo(v);
iconContextMenu.show();
}
private void initContextMenu() {
if (iconContextMenu == null) {
iconContextMenu = new IconContextMenu(this, R.menu.demo);
iconContextMenu.setTitle("See the icons?! Nice?");
iconContextMenu.setOnIconContextItemSelectedListener(this);
iconContextMenu.setOnCancelListener(this);
iconContextMenu.setOnDismissListener(this);
}
}
@Override
public void onIconContextItemSelected(MenuItem item, Object info) {
Toast.makeText(this, "menuItem: " + item + " info: " + info, Toast.LENGTH_SHORT).show();
}
@Override
public void onDismiss(DialogInterface dialog) {
Toast.makeText(this, "onDismiss", Toast.LENGTH_SHORT).show();
}
@Override
public void onCancel(DialogInterface dialog) {
Toast.makeText(this, "onCancel", Toast.LENGTH_SHORT).show();
}
} | 04146814d-23 | IconContextMenuDicoba/src/yuku/iconcontextmenu/test/IconContextMenuDicobaActivity.java | Java | asf20 | 1,672 |
package yuku.filechooser;
import android.os.*;
public class FolderChooserResult implements Parcelable {
public static final String TAG = FolderChooserResult.class.getSimpleName();
public String selectedFolder;
@Override public int describeContents() {
return 0;
}
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(selectedFolder);
}
public static final Parcelable.Creator<FolderChooserResult> CREATOR = new Parcelable.Creator<FolderChooserResult>() {
@Override public FolderChooserResult[] newArray(int size) {
return new FolderChooserResult[size];
}
@Override public FolderChooserResult createFromParcel(Parcel in) {
FolderChooserResult res = new FolderChooserResult();
res.selectedFolder = in.readString();
return res;
}
};
}
| 04146814d-23 | FileChooser/src/yuku/filechooser/FolderChooserResult.java | Java | asf20 | 796 |
package yuku.filechooser;
import android.os.*;
public class FileChooserConfig implements Parcelable {
public static final String TAG = FileChooserConfig.class.getSimpleName();
public enum Mode {
Open,
Save,
}
public Mode mode;
public String pattern;
public String title;
public String initialDir;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mode.ordinal());
dest.writeString(pattern);
dest.writeString(title);
dest.writeString(initialDir);
}
public static final Parcelable.Creator<FileChooserConfig> CREATOR = new Parcelable.Creator<FileChooserConfig>() {
@Override
public FileChooserConfig[] newArray(int size) {
return new FileChooserConfig[size];
}
@Override
public FileChooserConfig createFromParcel(Parcel in) {
FileChooserConfig res = new FileChooserConfig();
int mode_i = in.readInt(); if (mode_i >= 0 || mode_i < Mode.values().length) res.mode = Mode.values()[mode_i]; else res.mode = Mode.Open;
res.pattern = in.readString();
res.title = in.readString();
res.initialDir = in.readString();
return res;
}
};
}
| 04146814d-23 | FileChooser/src/yuku/filechooser/FileChooserConfig.java | Java | asf20 | 1,178 |
package yuku.filechooser;
import android.os.*;
public class FileChooserResult implements Parcelable {
public static final String TAG = FileChooserResult.class.getSimpleName();
public String currentDir;
public String firstFilename;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(currentDir);
dest.writeString(firstFilename);
}
public static final Parcelable.Creator<FileChooserResult> CREATOR = new Parcelable.Creator<FileChooserResult>() {
@Override
public FileChooserResult[] newArray(int size) {
return new FileChooserResult[size];
}
@Override
public FileChooserResult createFromParcel(Parcel in) {
FileChooserResult res = new FileChooserResult();
res.currentDir = in.readString();
res.firstFilename = in.readString();
return res;
}
};
}
| 04146814d-23 | FileChooser/src/yuku/filechooser/FileChooserResult.java | Java | asf20 | 881 |
package yuku.filechooser;
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
import java.util.List;
public class FolderChooserConfig implements Parcelable {
public static final String TAG = FolderChooserConfig.class.getSimpleName();
public String title;
public List<String> roots;
public boolean showHidden;
public boolean mustBeWritable;
@Override public int describeContents() {
return 0;
}
@Override public void writeToParcel(Parcel dest, int flags) {
dest.writeString(title);
dest.writeStringList(roots);
dest.writeByte((byte) (showHidden? 1: 0));
dest.writeByte((byte) (mustBeWritable? 1: 0));
}
public static final Parcelable.Creator<FolderChooserConfig> CREATOR = new Parcelable.Creator<FolderChooserConfig>() {
@Override public FolderChooserConfig[] newArray(int size) {
return new FolderChooserConfig[size];
}
@Override public FolderChooserConfig createFromParcel(Parcel in) {
FolderChooserConfig res = new FolderChooserConfig();
res.title = in.readString();
res.roots = new ArrayList<String>(); in.readStringList(res.roots);
res.showHidden = in.readByte() != 0;
res.mustBeWritable = in.readByte() != 0;
return res;
}
};
}
| 04146814d-23 | FileChooser/src/yuku/filechooser/FolderChooserConfig.java | Java | asf20 | 1,223 |
package yuku.filechooser;
import android.app.*;
import android.content.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import java.io.*;
import java.util.*;
import java.util.regex.*;
public class FileChooserActivity extends Activity {
static final String EXTRA_config = "config"; //$NON-NLS-1$
static final String EXTRA_result = null;
public static Intent createIntent(Context context, FileChooserConfig config) {
Intent res = new Intent(context, FileChooserActivity.class);
res.putExtra(EXTRA_config, config);
return res;
}
public static FileChooserResult obtainResult(Intent data) {
if (data == null) return null;
return data.getParcelableExtra(EXTRA_result);
}
ListView lsFile;
FileChooserConfig config;
FileAdapter adapter;
File cd;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
config = getIntent().getParcelableExtra(EXTRA_config);
if (config.title == null) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
} else {
setTitle(config.title);
}
setContentView(R.layout.filechooser_activity_filechooser);
lsFile = (ListView) findViewById(R.id.filechooser_lsFile);
lsFile.setAdapter(adapter = new FileAdapter());
lsFile.setOnItemClickListener(lsFile_itemClick);
init();
}
private OnItemClickListener lsFile_itemClick = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
File file = adapter.getItem(position);
if (file != null) {
if (file.isDirectory()) {
cd = file;
ls();
} else {
FileChooserResult result = new FileChooserResult();
result.currentDir = cd.getAbsolutePath();
result.firstFilename = file.getAbsolutePath();
Intent data = new Intent();
data.putExtra(EXTRA_result, result);
setResult(RESULT_OK, data);
finish();
}
}
}
};
private void init() {
if (config.initialDir != null) {
cd = new File(config.initialDir);
} else {
cd = Environment.getExternalStorageDirectory();
}
ls();
}
void ls() {
File[] files = cd.listFiles(new FileFilter() {
Matcher m;
@Override
public boolean accept(File pathname) {
if (config.pattern == null) {
return true;
}
if (pathname.isDirectory()) {
return true;
}
if (m == null) {
m = Pattern.compile(config.pattern).matcher(""); //$NON-NLS-1$
}
m.reset(pathname.getName());
return m.matches();
}
});
if (files == null) {
files = new File[0];
}
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File a, File b) {
if (a.isDirectory() && !b.isDirectory()) {
return -1;
} else if (!a.isDirectory() && b.isDirectory()) {
return +1;
}
// both files or both dirs
String aname = a.getName();
String bname = b.getName();
// dot-files are later
if (aname.startsWith(".") && !bname.startsWith(".")) { //$NON-NLS-1$ //$NON-NLS-2$
return +1;
} else if (!aname.startsWith(".") && bname.startsWith(".")) { //$NON-NLS-1$ //$NON-NLS-2$
return -1;
}
return aname.compareToIgnoreCase(bname);
}
});
adapter.setNewData(files);
lsFile.setSelection(0);
}
class FileAdapter extends BaseAdapter {
File[] files;
@Override
public int getCount() {
return (files == null? 0: files.length) + 1;
}
public void setNewData(File[] files) {
this.files = files;
notifyDataSetChanged();
}
@Override
public File getItem(int position) {
if (files == null) return null;
if (position == 0) return cd.getParentFile();
return files[position - 1];
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView res = (TextView) (convertView != null? convertView: LayoutInflater.from(getApplicationContext()).inflate(android.R.layout.simple_list_item_1, null));
if (position == 0) {
res.setText(R.string.filechooser_parent_folder);
res.setCompoundDrawablesWithIntrinsicBounds(R.drawable.filechooser_up, 0, 0, 0);
} else {
File file = getItem(position);
res.setText(file.getName());
res.setCompoundDrawablesWithIntrinsicBounds(file.isDirectory()? R.drawable.filechooser_folder: R.drawable.filechooser_file, 0, 0, 0);
}
return res;
}
}
}
| 04146814d-23 | FileChooser/src/yuku/filechooser/FileChooserActivity.java | Java | asf20 | 4,636 |
package yuku.filechooser;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.Environment;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextWatcher;
import android.text.style.StyleSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import java.io.File;
import java.util.Arrays;
import yuku.atree.TreeAdapter;
import yuku.atree.TreeNodeIconType;
import yuku.atree.nodes.BaseFileTreeNode;
public class FolderChooserActivity extends Activity {
static final String EXTRA_config = "config"; //$NON-NLS-1$
static final String EXTRA_result = null;
public static Intent createIntent(Context context, FolderChooserConfig config) {
Intent res = new Intent(context, FolderChooserActivity.class);
res.putExtra(EXTRA_config, config);
return res;
}
public static FolderChooserResult obtainResult(Intent data) {
if (data == null) return null;
return data.getParcelableExtra(EXTRA_result);
}
ListView tree;
Button bOk;
TextView lPath;
FolderChooserConfig config;
TreeAdapter adapter;
File selectedDir;
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
config = getIntent().getParcelableExtra(EXTRA_config);
if (config.title == null) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
} else {
setTitle(config.title);
}
setContentView(R.layout.filechooser_activity_folderchooser);
tree = (ListView) findViewById(R.id.filechooser_tree);
bOk = (Button) findViewById(R.id.filechooser_bOk);
lPath = (TextView) findViewById(R.id.filechooser_lPath);
adapter = new TreeAdapter();
tree.setAdapter(adapter);
tree.setOnItemClickListener(tree_itemClick);
perm_writeExt = checkCallingOrSelfPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (perm_writeExt == PackageManager.PERMISSION_GRANTED) {
tree.setOnItemLongClickListener(tree_itemLongClick);
}
bOk.setOnClickListener(bOk_click);
setSelectedDir(null);
if (config.roots == null || config.roots.size() == 0) {
config.roots = Arrays.asList(Environment.getExternalStorageDirectory().getAbsolutePath());
}
File[] children = new File[config.roots.size()];
for (int i = 0; i < config.roots.size(); i++) {
children[i] = new File(config.roots.get(i));
}
FileTreeNode root = new FileTreeNode("root", children);
adapter.setRootVisible(false);
root.setExpanded(true);
adapter.setRoot(root);
}
private OnItemClickListener tree_itemClick = new OnItemClickListener() {
@Override public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
FileTreeNode node = (FileTreeNode) adapter.getItem(position);
node.setExpanded(!node.getExpanded());
adapter.notifyDataSetChanged();
setSelectedDir(node.getFile());
}
};
private OnItemLongClickListener tree_itemLongClick = new OnItemLongClickListener() {
@Override public boolean onItemLongClick(AdapterView<?> parent, View v, final int position, long id) {
final FileTreeNode node = (FileTreeNode) adapter.getItem(position);
final File file = node.getFile();
if (!file.isDirectory()) return false;
new AlertDialog.Builder(FolderChooserActivity.this)
.setItems(new String[] {"New folder"}, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface _unused_, int which) {
final Button[] bOk = {null};
final EditText tFolderName = new EditText(FolderChooserActivity.this);
MarginLayoutParams lp = new MarginLayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
lp.leftMargin = lp.topMargin = lp.rightMargin = lp.bottomMargin = (int) (6 * getResources().getDisplayMetrics().density);
tFolderName.setLayoutParams(lp);
tFolderName.setHint("Folder name");
tFolderName.addTextChangedListener(new TextWatcher() {
@Override public void afterTextChanged(Editable s) {
bOk[0].setEnabled(s.toString().trim().length() > 0);
}
@Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
final AlertDialog dialog = new AlertDialog.Builder(FolderChooserActivity.this)
.setTitle("New folder")
.setView(tFolderName)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override public void onClick(DialogInterface dialog, int which) {
String folderName = tFolderName.getText().toString().trim();
File newDir = new File(file, folderName);
boolean ok = newDir.mkdirs();
if (ok) {
if (node.getExpanded()) {
node.setExpanded(false);
}
node.setExpanded(true);
}
}})
.show();
bOk[0] = dialog.getButton(DialogInterface.BUTTON_POSITIVE);
bOk[0].setEnabled(false);
}
})
.show();
return true;
}
};
OnClickListener bOk_click = new OnClickListener() {
@Override public void onClick(View v) {
if (selectedDir == null) return;
FolderChooserResult result = new FolderChooserResult();
result.selectedFolder = selectedDir.getAbsolutePath();
Intent data = new Intent();
data.putExtra(EXTRA_result, result);
setResult(RESULT_OK, data);
finish();
}
};
private int perm_writeExt;
class FileTreeNode extends BaseFileTreeNode {
private String label;
public FileTreeNode(File file) {
super(file);
}
public FileTreeNode(String label, File[] virtualChildren) {
super(virtualChildren);
this.label = label;
}
@Override public View getView(int position, View convertView, ViewGroup parent, int level, TreeNodeIconType iconType, int[] lines) {
TextView res = (TextView) (convertView != null? convertView: LayoutInflater.from(getApplicationContext()).inflate(android.R.layout.simple_list_item_1, null));
res.setPadding((int) ((getResources().getDisplayMetrics().density) * (20 * (level - 1) + 6)), 0, 0, 0);
res.setText(label != null? label: file.getName());
res.setCompoundDrawablesWithIntrinsicBounds(file.isDirectory()? R.drawable.filechooser_folder: R.drawable.filechooser_file, 0, 0, 0);
return res;
}
@Override protected BaseFileTreeNode generateForFile(File file) {
return new FileTreeNode(file);
}
@Override protected boolean showDirectoriesOnly() {
return true;
}
@Override protected boolean showHidden() {
return config.showHidden;
}
}
protected void setSelectedDir(File dir) {
this.selectedDir = dir;
bOk.setEnabled(dir != null);
if (dir != null) {
// display complete path
SpannableStringBuilder sb = new SpannableStringBuilder();
String parent = dir.getParent();
sb.append(parent == null? "": parent + "/");
int sb_len = sb.length();
sb.append(dir.getName());
sb.setSpan(new StyleSpan(Typeface.BOLD), sb_len, sb.length(), 0);
lPath.setText(sb, BufferType.SPANNABLE);
// disable button if not writable
if (config.mustBeWritable && !dir.canWrite()) {
bOk.setEnabled(false);
}
} else {
lPath.setText("");
}
}
}
| 04146814d-23 | FileChooser/src/yuku/filechooser/FolderChooserActivity.java | Java | asf20 | 7,862 |
package yuku.androidsdk.searchbar;
import android.content.Context;
import android.text.Editable;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TextView.BufferType;
import android.widget.TextView.OnEditorActionListener;
public class SearchBar extends LinearLayout {
public static final String TAG = SearchBar.class.getSimpleName();
public interface OnSearchListener {
void onSearch(SearchBar searchBar, Editable text);
}
TextView lBadge;
EditText tSearch;
Button bSearch;
Button bExtra1;
LinearLayout root;
OnSearchListener onSearchListener;
public SearchBar(Context context) {
super(context);
init();
}
public SearchBar(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
LayoutInflater.from(getContext()).inflate(R.layout.search_bar, this);
lBadge = (TextView) findViewById(R.id.search_badge);
tSearch = (EditText) findViewById(R.id.search_src_text);
bSearch = (Button) findViewById(R.id.search_go_btn);
bExtra1 = (Button) findViewById(R.id.search_extra1_btn);
root = (LinearLayout) findViewById(R.id.search_bar);
if (isInEditMode()) return;
tSearch.setOnEditorActionListener(new OnEditorActionListener() {
@Override public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
if (onSearchListener != null) {
onSearchListener.onSearch(SearchBar.this, tSearch.getText());
}
return true;
}
return false;
}
});
bSearch.setOnClickListener(new OnClickListener() {
@Override public void onClick(View v) {
if (onSearchListener != null) {
onSearchListener.onSearch(SearchBar.this, tSearch.getText());
}
}
});
lBadge.setVisibility(View.GONE);
}
public Editable getText() {
return tSearch.getText();
}
public void setText(CharSequence text, BufferType type) {
tSearch.setText(text, type);
}
public final void setText(CharSequence text) {
tSearch.setText(text);
}
public void setOnSearchListener(OnSearchListener l) {
this.onSearchListener = l;
}
public EditText getSearchField() {
return tSearch;
}
public Button getSearchButton() {
return bSearch;
}
public Button getSearchExtra1() {
return bExtra1;
}
public void setBottomView(View v) {
// note that the root has 1 child already. So we need to add/replace the second child and so on.
if (root.getChildCount() > 1) {
root.removeViews(1, root.getChildCount() - 1);
}
v.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
root.addView(v);
}
@SuppressWarnings("unchecked") public <T extends View> T getBottomView() {
if (root.getChildCount() <= 1) {
return null;
}
return (T) root.getChildAt(1);
}
}
| 04146814d-23 | SdkSearchBar/src/yuku/androidsdk/searchbar/SearchBar.java | Java | asf20 | 3,155 |
package yuku.iconcontextmenu;
import yuku.androidsdk.com.android.internal.view.menu.MenuBuilder;
import android.app.AlertDialog;
import android.content.*;
import android.view.*;
public class IconContextMenu {
public interface IconContextItemSelectedListener {
void onIconContextItemSelected(MenuItem item, Object info);
}
private final AlertDialog dialog;
private final Menu menu;
private IconContextItemSelectedListener iconContextItemSelectedListener;
private Object info;
public IconContextMenu(Context context, int menuId) {
this(context, newMenu(context, menuId));
}
public static Menu newMenu(Context context, int menuId) {
Menu menu = new MenuBuilder(context);
new MenuInflater(context).inflate(menuId, menu);
return menu;
}
public IconContextMenu(Context context, Menu menu) {
this.menu = menu;
final IconContextMenuAdapter adapter = new IconContextMenuAdapter(context, menu);
this.dialog = new AlertDialog.Builder(context)
.setAdapter(adapter, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (iconContextItemSelectedListener != null) {
iconContextItemSelectedListener.onIconContextItemSelected(adapter.getItem(which), info);
}
}
})
.setInverseBackgroundForced(true)
.create();
}
public void setInfo(Object info) {
this.info = info;
}
public Object getInfo() {
return info;
}
public Menu getMenu() {
return menu;
}
public void setOnIconContextItemSelectedListener(IconContextItemSelectedListener iconContextItemSelectedListener) {
this.iconContextItemSelectedListener = iconContextItemSelectedListener;
}
public void setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) {
dialog.setOnCancelListener(onCancelListener);
}
public void setOnDismissListener(DialogInterface.OnDismissListener onDismissListener) {
dialog.setOnDismissListener(onDismissListener);
}
public void setTitle(CharSequence title) {
dialog.setTitle(title);
}
public void setTitle(int titleId) {
dialog.setTitle(titleId);
}
public void show() {
dialog.show();
}
public void dismiss() {
dialog.dismiss();
}
public void cancel() {
dialog.cancel();
}
public AlertDialog getDialog() {
return dialog;
}
} | 04146814d-23 | IconContextMenu/src/yuku/iconcontextmenu/IconContextMenu.java | Java | asf20 | 2,510 |
package yuku.iconcontextmenu;
import android.content.Context;
import android.view.*;
import android.widget.*;
public class IconContextMenuAdapter extends BaseAdapter {
private Context context;
private Menu menu;
public IconContextMenuAdapter(Context context, Menu menu) {
this.context = context;
this.menu = menu;
}
@Override
public int getCount() {
return menu.size();
}
@Override
public MenuItem getItem(int position) {
return menu.getItem(position);
}
@Override
public long getItemId(int position) {
return getItem(position).getItemId();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
MenuItem item = getItem(position);
TextView res = (TextView) convertView;
if (res == null) {
res = (TextView) LayoutInflater.from(context).inflate(android.R.layout.select_dialog_item, null);
}
res.setTag(item);
res.setText(item.getTitle());
res.setCompoundDrawablesWithIntrinsicBounds(item.getIcon(), null, null, null);
return res;
}
}
| 04146814d-23 | IconContextMenu/src/yuku/iconcontextmenu/IconContextMenuAdapter.java | Java | asf20 | 1,116 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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 yuku.androidsdk.com.android.internal.view.menu;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.*;
/**
* @hide
*/
public final class MenuItemImpl implements MenuItem {
private final int mId;
private final int mGroup;
private final int mCategoryOrder;
private final int mOrdering;
private CharSequence mTitle;
private CharSequence mTitleCondensed;
private Intent mIntent;
private char mShortcutNumericChar;
private char mShortcutAlphabeticChar;
/** The icon's drawable which is only created as needed */
private Drawable mIconDrawable;
/**
* The icon's resource ID which is used to get the Drawable when it is
* needed (if the Drawable isn't already obtained--only one of the two is
* needed).
*/
private int mIconResId = NO_ICON;
/** The menu to which this item belongs */
private MenuBuilder mMenu;
private Runnable mItemCallback;
private int mFlags = ENABLED;
private static final int CHECKABLE = 0x00000001;
private static final int CHECKED = 0x00000002;
private static final int EXCLUSIVE = 0x00000004;
private static final int HIDDEN = 0x00000008;
private static final int ENABLED = 0x00000010;
/** Used for the icon resource ID if this item does not have an icon */
static final int NO_ICON = 0;
/**
* Current use case is for context menu: Extra information linked to the
* View that added this item to the context menu.
*/
private ContextMenuInfo mMenuInfo;
private static String sPrependShortcutLabel;
private static String sEnterShortcutLabel;
private static String sDeleteShortcutLabel;
private static String sSpaceShortcutLabel;
/**
* Instantiates this menu item. The constructor {@link #MenuItemData(MenuBuilder, int, int, int, CharSequence, int)} is
* preferred due to lazy loading of the icon Drawable.
*
* @param menu
* @param group
* Item ordering grouping control. The item will be added after
* all other items whose order is <= this number, and before any
* that are larger than it. This can also be used to define
* groups of items for batch state changes. Normally use 0.
* @param id
* Unique item ID. Use 0 if you do not need a unique ID.
* @param categoryOrder
* The ordering for this item.
* @param title
* The text to display for the item.
*/
MenuItemImpl(MenuBuilder menu, int group, int id, int categoryOrder, int ordering, CharSequence title) {
mMenu = menu;
mId = id;
mGroup = group;
mCategoryOrder = categoryOrder;
mOrdering = ordering;
mTitle = title;
}
@Override
public boolean isEnabled() {
return (mFlags & ENABLED) != 0;
}
@Override
public MenuItem setEnabled(boolean enabled) {
if (enabled) {
mFlags |= ENABLED;
} else {
mFlags &= ~ENABLED;
}
return this;
}
@Override
public int getGroupId() {
return mGroup;
}
@Override
@ViewDebug.CapturedViewProperty
public int getItemId() {
return mId;
}
@Override
public int getOrder() {
return mCategoryOrder;
}
public int getOrdering() {
return mOrdering;
}
@Override
public Intent getIntent() {
return mIntent;
}
@Override
public MenuItem setIntent(Intent intent) {
mIntent = intent;
return this;
}
Runnable getCallback() {
return mItemCallback;
}
public MenuItem setCallback(Runnable callback) {
mItemCallback = callback;
return this;
}
@Override
public char getAlphabeticShortcut() {
return mShortcutAlphabeticChar;
}
@Override
public MenuItem setAlphabeticShortcut(char alphaChar) {
if (mShortcutAlphabeticChar == alphaChar) return this;
mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
return this;
}
@Override
public char getNumericShortcut() {
return mShortcutNumericChar;
}
@Override
public MenuItem setNumericShortcut(char numericChar) {
if (mShortcutNumericChar == numericChar) return this;
mShortcutNumericChar = numericChar;
return this;
}
@Override
public MenuItem setShortcut(char numericChar, char alphaChar) {
mShortcutNumericChar = numericChar;
mShortcutAlphabeticChar = Character.toLowerCase(alphaChar);
return this;
}
/**
* @return The active shortcut (based on QWERTY-mode of the menu).
*/
char getShortcut() {
return (mMenu.isQwertyMode() ? mShortcutAlphabeticChar : mShortcutNumericChar);
}
/**
* @return The label to show for the shortcut. This includes the chording
* key (for example 'Menu+a'). Also, any non-human readable
* characters should be human readable (for example 'Menu+enter').
*/
String getShortcutLabel() {
char shortcut = getShortcut();
if (shortcut == 0) {
return "";
}
StringBuilder sb = new StringBuilder(sPrependShortcutLabel);
switch (shortcut) {
case '\n':
sb.append(sEnterShortcutLabel);
break;
case '\b':
sb.append(sDeleteShortcutLabel);
break;
case ' ':
sb.append(sSpaceShortcutLabel);
break;
default:
sb.append(shortcut);
break;
}
return sb.toString();
}
@Override
@ViewDebug.CapturedViewProperty
public CharSequence getTitle() {
return mTitle;
}
@Override
public MenuItem setTitle(CharSequence title) {
mTitle = title;
return this;
}
@Override
public MenuItem setTitle(int title) {
return setTitle(mMenu.getContext().getString(title));
}
@Override
public CharSequence getTitleCondensed() {
return mTitleCondensed != null ? mTitleCondensed : mTitle;
}
@Override
public MenuItem setTitleCondensed(CharSequence title) {
mTitleCondensed = title;
// Could use getTitle() in the loop below, but just cache what it would do here
if (title == null) {
title = mTitle;
}
return this;
}
@Override
public Drawable getIcon() {
if (mIconDrawable != null) {
return mIconDrawable;
}
if (mIconResId != NO_ICON) {
return mMenu.getResources().getDrawable(mIconResId);
}
return null;
}
@Override
public MenuItem setIcon(Drawable icon) {
mIconResId = NO_ICON;
mIconDrawable = icon;
return this;
}
@Override
public MenuItem setIcon(int iconResId) {
mIconDrawable = null;
mIconResId = iconResId;
return this;
}
@Override
public boolean isCheckable() {
return (mFlags & CHECKABLE) == CHECKABLE;
}
@Override
public MenuItem setCheckable(boolean checkable) {
mFlags = (mFlags & ~CHECKABLE) | (checkable ? CHECKABLE : 0);
return this;
}
public void setExclusiveCheckable(boolean exclusive) {
mFlags = (mFlags & ~EXCLUSIVE) | (exclusive ? EXCLUSIVE : 0);
}
public boolean isExclusiveCheckable() {
return (mFlags & EXCLUSIVE) != 0;
}
@Override
public boolean isChecked() {
return (mFlags & CHECKED) == CHECKED;
}
@Override
public MenuItem setChecked(boolean checked) {
if ((mFlags & EXCLUSIVE) != 0) {
// Call the method on the Menu since it knows about the others in this
// exclusive checkable group
mMenu.setExclusiveItemChecked(this);
} else {
setCheckedInt(checked);
}
return this;
}
void setCheckedInt(boolean checked) {
mFlags = (mFlags & ~CHECKED) | (checked ? CHECKED : 0);
}
@Override
public boolean isVisible() {
return (mFlags & HIDDEN) == 0;
}
/**
* Changes the visibility of the item. This method DOES NOT notify the
* parent menu of a change in this item, so this should only be called from
* methods that will eventually trigger this change. If unsure, use {@link #setVisible(boolean)} instead.
*
* @param shown
* Whether to show (true) or hide (false).
* @return Whether the item's shown state was changed
*/
boolean setVisibleInt(boolean shown) {
final int oldFlags = mFlags;
mFlags = (mFlags & ~HIDDEN) | (shown ? 0 : HIDDEN);
return oldFlags != mFlags;
}
@Override
public MenuItem setVisible(boolean shown) {
// Try to set the shown state to the given state. If the shown state was changed
// (i.e. the previous state isn't the same as given state), notify the parent menu that
// the shown state has changed for this item
if (setVisibleInt(shown)) mMenu.onItemVisibleChanged(this);
return this;
}
@Override
public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener clickListener) {
return this;
}
@Override
public String toString() {
return mTitle.toString();
}
void setMenuInfo(ContextMenuInfo menuInfo) {
mMenuInfo = menuInfo;
}
@Override
public ContextMenuInfo getMenuInfo() {
return mMenuInfo;
}
@Override
public SubMenu getSubMenu() {
return null;
}
@Override
public boolean hasSubMenu() {
return false;
}
// ERROR REPORT 2010-01-08 don't know from where.
//java.lang.AbstractMethodError: abstract method not implemented
//at yuku.androidsdk.com.android.internal.view.menu.MenuItemImpl.setShortcutLabel(MenuItemImpl.java)
// so, dummy implementation:
public void setShortcutLabel(String whatever) {}
}
| 04146814d-23 | IconContextMenu/src/yuku/androidsdk/com/android/internal/view/menu/MenuItemImpl.java | Java | asf20 | 9,529 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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 yuku.androidsdk.com.android.internal.view.menu;
import java.util.*;
import android.content.*;
import android.content.pm.*;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.*;
/**
* Implementation of the {@link android.view.Menu} interface for creating a
* standard menu UI.
*/
public class MenuBuilder implements Menu {
/** The number of different menu types */
public static final int NUM_TYPES = 3;
/** The menu type that represents the icon menu view */
public static final int TYPE_ICON = 0;
/** The menu type that represents the expanded menu view */
public static final int TYPE_EXPANDED = 1;
/**
* The menu type that represents a menu dialog. Examples are context and sub
* menus. This menu type will not have a corresponding MenuView, but it will
* have an ItemView.
*/
public static final int TYPE_DIALOG = 2;
private static final int[] sCategoryToOrder = new int[] {
1, /* No category */
4, /* CONTAINER */
5, /* SYSTEM */
3, /* SECONDARY */
2, /* ALTERNATIVE */
0, /* SELECTED_ALTERNATIVE */
};
private final Context mContext;
private final Resources mResources;
/**
* Whether the shortcuts should be qwerty-accessible. Use isQwertyMode()
* instead of accessing this directly.
*/
private boolean mQwertyMode;
/** Contains all of the items for this menu */
private ArrayList<MenuItemImpl> mItems;
/** Contains only the items that are currently visible. This will be created/refreshed from
* {@link #getVisibleItems()} */
private ArrayList<MenuItemImpl> mVisibleItems;
/**
* Whether or not the items (or any one item's shown state) has changed since it was last
* fetched from {@link #getVisibleItems()}
*/
private boolean mIsVisibleItemsStale;
/**
* Current use case is Context Menus: As Views populate the context menu, each one has
* extra information that should be passed along. This is the current menu info that
* should be set on all items added to this menu.
*/
private ContextMenuInfo mCurrentMenuInfo;
/** Header title for menu types that have a header (context and submenus) */
CharSequence mHeaderTitle;
/** Header icon for menu types that have a header and support icons (context) */
Drawable mHeaderIcon;
/** Header custom view for menu types that have a header and support custom views (context) */
View mHeaderView;
/**
* Prevents onItemsChanged from doing its junk, useful for batching commands
* that may individually call onItemsChanged.
*/
private boolean mPreventDispatchingItemsChanged = false;
private MenuType[] mMenuTypes;
class MenuType {
MenuType(int menuType) {
}
boolean hasMenuView() {
return false;
}
}
/**
* Called by menu items to execute their associated action
*/
public interface ItemInvoker {
public boolean invokeItem(MenuItemImpl item);
}
public MenuBuilder(Context context) {
mMenuTypes = new MenuType[NUM_TYPES];
mContext = context;
mResources = context.getResources();
mItems = new ArrayList<MenuItemImpl>();
mVisibleItems = new ArrayList<MenuItemImpl>();
mIsVisibleItemsStale = true;
}
MenuType getMenuType(int menuType) {
if (mMenuTypes[menuType] == null) {
mMenuTypes[menuType] = new MenuType(menuType);
}
return mMenuTypes[menuType];
}
/**
* Adds an item to the menu. The other add methods funnel to this.
*/
private MenuItem addInternal(int group, int id, int categoryOrder, CharSequence title) {
final int ordering = getOrdering(categoryOrder);
final MenuItemImpl item = new MenuItemImpl(this, group, id, categoryOrder, ordering, title);
if (mCurrentMenuInfo != null) {
// Pass along the current menu info
item.setMenuInfo(mCurrentMenuInfo);
}
mItems.add(findInsertIndex(mItems, ordering), item);
onItemsChanged(false);
return item;
}
@Override
public MenuItem add(CharSequence title) {
return addInternal(0, 0, 0, title);
}
@Override
public MenuItem add(int titleRes) {
return addInternal(0, 0, 0, mResources.getString(titleRes));
}
@Override
public MenuItem add(int group, int id, int categoryOrder, CharSequence title) {
return addInternal(group, id, categoryOrder, title);
}
@Override
public MenuItem add(int group, int id, int categoryOrder, int title) {
return addInternal(group, id, categoryOrder, mResources.getString(title));
}
@Override
public SubMenu addSubMenu(CharSequence title) {
return addSubMenu(0, 0, 0, title);
}
@Override
public SubMenu addSubMenu(int titleRes) {
return addSubMenu(0, 0, 0, mResources.getString(titleRes));
}
@Override
public SubMenu addSubMenu(int group, int id, int categoryOrder, CharSequence title) {
throw new UnsupportedOperationException("No submenu for context menu");
}
@Override
public SubMenu addSubMenu(int group, int id, int categoryOrder, int title) {
return addSubMenu(group, id, categoryOrder, mResources.getString(title));
}
@Override
public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller,
Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
PackageManager pm = mContext.getPackageManager();
final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller, specifics, intent, 0);
final int N = lri != null ? lri.size() : 0;
if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
removeGroup(group);
}
for (int i=0; i<N; i++) {
final ResolveInfo ri = lri.get(i);
Intent rintent = new Intent(ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
rintent.setComponent(new ComponentName(ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name));
final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm))
.setIcon(ri.loadIcon(pm))
.setIntent(rintent);
if (outSpecificItems != null && ri.specificIndex >= 0) {
outSpecificItems[ri.specificIndex] = item;
}
}
return N;
}
@Override
public void removeItem(int id) {
removeItemAtInt(findItemIndex(id), true);
}
@Override
public void removeGroup(int group) {
final int i = findGroupIndex(group);
if (i >= 0) {
final int maxRemovable = mItems.size() - i;
int numRemoved = 0;
while ((numRemoved++ < maxRemovable) && (mItems.get(i).getGroupId() == group)) {
// Don't force update for each one, this method will do it at the end
removeItemAtInt(i, false);
}
// Notify menu views
onItemsChanged(false);
}
}
/**
* Remove the item at the given index and optionally forces menu views to
* update.
*
* @param index The index of the item to be removed. If this index is
* invalid an exception is thrown.
* @param updateChildrenOnMenuViews Whether to force update on menu views.
* Please make sure you eventually call this after your batch of
* removals.
*/
private void removeItemAtInt(int index, boolean updateChildrenOnMenuViews) {
if ((index < 0) || (index >= mItems.size())) return;
mItems.remove(index);
if (updateChildrenOnMenuViews) onItemsChanged(false);
}
@Override
public void clear() {
mItems.clear();
onItemsChanged(true);
}
void setExclusiveItemChecked(MenuItem item) {
final int group = item.getGroupId();
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl curItem = mItems.get(i);
if (curItem.getGroupId() == group) {
if (!curItem.isExclusiveCheckable()) continue;
if (!curItem.isCheckable()) continue;
// Check the item meant to be checked, uncheck the others (that are in the group)
curItem.setCheckedInt(curItem == item);
}
}
}
@Override
public void setGroupCheckable(int group, boolean checkable, boolean exclusive) {
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
item.setExclusiveCheckable(exclusive);
item.setCheckable(checkable);
}
}
}
@Override
public void setGroupVisible(int group, boolean visible) {
final int N = mItems.size();
// We handle the notification of items being changed ourselves, so we use setVisibleInt rather
// than setVisible and at the end notify of items being changed
boolean changedAtLeastOneItem = false;
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
if (item.setVisibleInt(visible)) changedAtLeastOneItem = true;
}
}
if (changedAtLeastOneItem) onItemsChanged(false);
}
@Override
public void setGroupEnabled(int group, boolean enabled) {
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
item.setEnabled(enabled);
}
}
}
@Override
public boolean hasVisibleItems() {
final int size = size();
for (int i = 0; i < size; i++) {
MenuItemImpl item = mItems.get(i);
if (item.isVisible()) {
return true;
}
}
return false;
}
@Override
public MenuItem findItem(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getItemId() == id) {
return item;
} else if (item.hasSubMenu()) {
MenuItem possibleItem = item.getSubMenu().findItem(id);
if (possibleItem != null) {
return possibleItem;
}
}
}
return null;
}
public int findItemIndex(int id) {
final int size = size();
for (int i = 0; i < size; i++) {
MenuItemImpl item = mItems.get(i);
if (item.getItemId() == id) {
return i;
}
}
return -1;
}
public int findGroupIndex(int group) {
return findGroupIndex(group, 0);
}
public int findGroupIndex(int group, int start) {
final int size = size();
if (start < 0) {
start = 0;
}
for (int i = start; i < size; i++) {
final MenuItemImpl item = mItems.get(i);
if (item.getGroupId() == group) {
return i;
}
}
return -1;
}
@Override
public int size() {
return mItems.size();
}
/** {@inheritDoc} */
@Override
public MenuItem getItem(int index) {
return mItems.get(index);
}
@Override
public boolean isShortcutKey(int keyCode, KeyEvent event) {
return findItemWithShortcutForKey(keyCode, event) != null;
}
/*
* We want to return the menu item associated with the key, but if there is no
* ambiguity (i.e. there is only one menu item corresponding to the key) we want
* to return it even if it's not an exact match; this allow the user to
* _not_ use the ALT key for example, making the use of shortcuts slightly more
* user-friendly. An example is on the G1, '!' and '1' are on the same key, and
* in Gmail, Menu+1 will trigger Menu+! (the actual shortcut).
*
* On the other hand, if two (or more) shortcuts corresponds to the same key,
* we have to only return the exact match.
*/
MenuItemImpl findItemWithShortcutForKey(int keyCode, KeyEvent event) {
// Get all items that can be associated directly or indirectly with the keyCode
List<MenuItemImpl> items = findItemsWithShortcutForKey(keyCode, event);
if (items == null) {
return null;
}
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
event.getKeyData(possibleChars);
// If we have only one element, we can safely returns it
if (items.size() == 1) {
return items.get(0);
}
final boolean qwerty = isQwertyMode();
// If we found more than one item associated with the key,
// we have to return the exact match
for (MenuItemImpl item : items) {
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut();
if ((shortcutChar == possibleChars.meta[0] &&
(metaState & KeyEvent.META_ALT_ON) == 0)
|| (shortcutChar == possibleChars.meta[2] &&
(metaState & KeyEvent.META_ALT_ON) != 0)
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) {
return item;
}
}
return null;
}
@Override
public void setQwertyMode(boolean isQwerty) {
mQwertyMode = isQwerty;
}
/**
* This is the part of an order integer that supplies the category of the
* item.
* @hide
*/
static final int CATEGORY_MASK = 0xffff0000;
/**
* Bit shift of the category portion of the order integer.
* @hide
*/
static final int CATEGORY_SHIFT = 16;
/**
* This is the part of an order integer that the user can provide.
* @hide
*/
static final int USER_MASK = 0x0000ffff;
/**
* Returns the ordering across all items. This will grab the category from
* the upper bits, find out how to order the category with respect to other
* categories, and combine it with the lower bits.
*
* @param categoryOrder The category order for a particular item (if it has
* not been or/add with a category, the default category is
* assumed).
* @return An ordering integer that can be used to order this item across
* all the items (even from other categories).
*/
private static int getOrdering(int categoryOrder)
{
final int index = (categoryOrder & CATEGORY_MASK) >> CATEGORY_SHIFT;
if (index < 0 || index >= sCategoryToOrder.length) {
throw new IllegalArgumentException("order does not contain a valid category.");
}
return (sCategoryToOrder[index] << CATEGORY_SHIFT) | (categoryOrder & USER_MASK);
}
/**
* @return whether the menu shortcuts are in qwerty mode or not
*/
boolean isQwertyMode() {
return mQwertyMode;
}
Resources getResources() {
return mResources;
}
private static int findInsertIndex(ArrayList<MenuItemImpl> items, int ordering) {
for (int i = items.size() - 1; i >= 0; i--) {
MenuItemImpl item = items.get(i);
if (item.getOrdering() <= ordering) {
return i + 1;
}
}
return 0;
}
@Override
public boolean performShortcut(int keyCode, KeyEvent event, int flags) {
final MenuItemImpl item = findItemWithShortcutForKey(keyCode, event);
boolean handled = false;
if (item != null) {
handled = performItemAction(item, flags);
}
if ((flags & FLAG_ALWAYS_PERFORM_CLOSE) != 0) {
close(true);
}
return handled;
}
/*
* This function will return all the menu and sub-menu items that can
* be directly (the shortcut directly corresponds) and indirectly
* (the ALT-enabled char corresponds to the shortcut) associated
* with the keyCode.
*/
List<MenuItemImpl> findItemsWithShortcutForKey(int keyCode, KeyEvent event) {
final boolean qwerty = isQwertyMode();
final int metaState = event.getMetaState();
final KeyCharacterMap.KeyData possibleChars = new KeyCharacterMap.KeyData();
// Get the chars associated with the keyCode (i.e using any chording combo)
final boolean isKeyCodeMapped = event.getKeyData(possibleChars);
// The delete key is not mapped to '\b' so we treat it specially
if (!isKeyCodeMapped && (keyCode != KeyEvent.KEYCODE_DEL)) {
return null;
}
Vector<MenuItemImpl> items = new Vector<MenuItemImpl>();
// Look for an item whose shortcut is this key.
final int N = mItems.size();
for (int i = 0; i < N; i++) {
MenuItemImpl item = mItems.get(i);
if (item.hasSubMenu()) {
List<MenuItemImpl> subMenuItems = ((MenuBuilder)item.getSubMenu())
.findItemsWithShortcutForKey(keyCode, event);
items.addAll(subMenuItems);
}
final char shortcutChar = qwerty ? item.getAlphabeticShortcut() : item.getNumericShortcut();
if (((metaState & (KeyEvent.META_SHIFT_ON | KeyEvent.META_SYM_ON)) == 0) &&
(shortcutChar != 0) &&
(shortcutChar == possibleChars.meta[0]
|| shortcutChar == possibleChars.meta[2]
|| (qwerty && shortcutChar == '\b' &&
keyCode == KeyEvent.KEYCODE_DEL)) &&
item.isEnabled()) {
items.add(item);
}
}
return items;
}
@Override
public boolean performIdentifierAction(int id, int flags) {
// Look for an item whose identifier is the id.
return performItemAction(findItem(id), flags);
}
public boolean performItemAction(MenuItem item, int flags) {
MenuItemImpl itemImpl = (MenuItemImpl) item;
if (itemImpl == null || !itemImpl.isEnabled()) {
return false;
}
if (item.hasSubMenu()) {
} else {
if ((flags & FLAG_PERFORM_NO_CLOSE) == 0) {
close(true);
}
}
return true;
}
/**
* Closes the visible menu.
*
* @param allMenusAreClosing Whether the menus are completely closing (true),
* or whether there is another menu coming in this menu's place
* (false). For example, if the menu is closing because a
* sub menu is about to be shown, <var>allMenusAreClosing</var>
* is false.
*/
final void close(boolean allMenusAreClosing) {
}
/** {@inheritDoc} */
@Override
public void close() {
close(true);
}
/**
* Called when an item is added or removed.
*
* @param cleared Whether the items were cleared or just changed.
*/
private void onItemsChanged(boolean cleared) {
if (!mPreventDispatchingItemsChanged) {
if (mIsVisibleItemsStale == false) mIsVisibleItemsStale = true;
}
}
/**
* Called by {@link MenuItemImpl} when its visible flag is changed.
* @param item The item that has gone through a visibility change.
*/
void onItemVisibleChanged(MenuItemImpl item) {
// Notify of items being changed
onItemsChanged(false);
}
ArrayList<MenuItemImpl> getVisibleItems() {
if (!mIsVisibleItemsStale) return mVisibleItems;
// Refresh the visible items
mVisibleItems.clear();
final int itemsSize = mItems.size();
MenuItemImpl item;
for (int i = 0; i < itemsSize; i++) {
item = mItems.get(i);
if (item.isVisible()) mVisibleItems.add(item);
}
mIsVisibleItemsStale = false;
return mVisibleItems;
}
public Context getContext() {
return mContext;
}
}
| 04146814d-23 | IconContextMenu/src/yuku/androidsdk/com/android/internal/view/menu/MenuBuilder.java | Java | asf20 | 21,581 |
package com.actionbarsherlock.app;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockPreferenceActivity extends PreferenceActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockPreferenceActivity.java | Java | asf20 | 8,058 |
package com.actionbarsherlock.app;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockActivity extends Activity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockActivity.java | Java | asf20 | 8,021 |
package com.actionbarsherlock.app;
import static com.actionbarsherlock.app.SherlockFragmentActivity.DEBUG;
import android.app.Activity;
import android.support.v4.app.Fragment;
import android.util.Log;
import com.actionbarsherlock.internal.view.menu.MenuItemMule;
import com.actionbarsherlock.internal.view.menu.MenuMule;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class SherlockFragment extends Fragment {
private static final String TAG = "SherlockFragment";
private SherlockFragmentActivity mActivity;
public SherlockFragmentActivity getSherlockActivity() {
return mActivity;
}
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(TAG + " must be attached to a SherlockFragmentActivity.");
}
mActivity = (SherlockFragmentActivity)activity;
super.onAttach(activity);
}
@Override
public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) {
if (DEBUG) Log.d(TAG, "[onCreateOptionsMenu] menu: " + menu + ", inflater: " + inflater);
if (menu instanceof MenuMule) {
onCreateOptionsMenu(((MenuMule)menu).unwrap(), mActivity.getSupportMenuInflater());
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Nothing to see here.
}
@Override
public final void onPrepareOptionsMenu(android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[onPrepareOptionsMenu] menu: " + menu);
if (menu instanceof MenuMule) {
onPrepareOptionsMenu(((MenuMule)menu).unwrap());
}
}
public void onPrepareOptionsMenu(Menu menu) {
//Nothing to see here.
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
if (DEBUG) Log.d(TAG, "[onOptionsItemSelected] item: " + item);
if (item instanceof MenuItemMule) {
return onOptionsItemSelected(((MenuItemMule)item).unwrap());
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
//Nothing to see here.
return false;
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockFragment.java | Java | asf20 | 2,319 |
package com.actionbarsherlock.app;
import static com.actionbarsherlock.app.SherlockFragmentActivity.DEBUG;
import android.app.Activity;
import android.support.v4.app.ListFragment;
import android.util.Log;
import com.actionbarsherlock.internal.view.menu.MenuItemMule;
import com.actionbarsherlock.internal.view.menu.MenuMule;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class SherlockListFragment extends ListFragment {
private static final String TAG = "SherlockListFragment";
private SherlockFragmentActivity mActivity;
public SherlockFragmentActivity getSherlockActivity() {
return mActivity;
}
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(TAG + " must be attached to a SherlockFragmentActivity.");
}
mActivity = (SherlockFragmentActivity)activity;
super.onAttach(activity);
}
@Override
public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) {
if (DEBUG) Log.d(TAG, "[onCreateOptionsMenu] menu: " + menu + ", inflater: " + inflater);
if (menu instanceof MenuMule) {
onCreateOptionsMenu(((MenuMule)menu).unwrap(), mActivity.getSupportMenuInflater());
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Nothing to see here.
}
@Override
public final void onPrepareOptionsMenu(android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[onPrepareOptionsMenu] menu: " + menu);
if (menu instanceof MenuMule) {
onPrepareOptionsMenu(((MenuMule)menu).unwrap());
}
}
public void onPrepareOptionsMenu(Menu menu) {
//Nothing to see here.
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
if (DEBUG) Log.d(TAG, "[onOptionsItemSelected] item: " + item);
if (item instanceof MenuItemMule) {
return onOptionsItemSelected(((MenuItemMule)item).unwrap());
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
//Nothing to see here.
return false;
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockListFragment.java | Java | asf20 | 2,335 |
package com.actionbarsherlock.app;
import android.app.ExpandableListActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockExpandableListActivity extends ExpandableListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockExpandableListActivity.java | Java | asf20 | 8,063 |
package com.actionbarsherlock.app;
import static com.actionbarsherlock.app.SherlockFragmentActivity.DEBUG;
import android.app.Activity;
import android.support.v4.app.DialogFragment;
import android.util.Log;
import com.actionbarsherlock.internal.view.menu.MenuItemMule;
import com.actionbarsherlock.internal.view.menu.MenuMule;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public class SherlockDialogFragment extends DialogFragment {
private static final String TAG = "SherlockDialogFragment";
private SherlockFragmentActivity mActivity;
public SherlockFragmentActivity getSherlockActivity() {
return mActivity;
}
@Override
public void onAttach(Activity activity) {
if (!(activity instanceof SherlockFragmentActivity)) {
throw new IllegalStateException(TAG + " must be attached to a SherlockFragmentActivity.");
}
mActivity = (SherlockFragmentActivity)activity;
super.onAttach(activity);
}
@Override
public final void onCreateOptionsMenu(android.view.Menu menu, android.view.MenuInflater inflater) {
if (DEBUG) Log.d(TAG, "[onCreateOptionsMenu] menu: " + menu + ", inflater: " + inflater);
if (menu instanceof MenuMule) {
onCreateOptionsMenu(((MenuMule)menu).unwrap(), mActivity.getSupportMenuInflater());
}
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
//Nothing to see here.
}
@Override
public final void onPrepareOptionsMenu(android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[onPrepareOptionsMenu] menu: " + menu);
if (menu instanceof MenuMule) {
onPrepareOptionsMenu(((MenuMule)menu).unwrap());
}
}
public void onPrepareOptionsMenu(Menu menu) {
//Nothing to see here.
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
if (DEBUG) Log.d(TAG, "[onOptionsItemSelected] item: " + item);
if (item instanceof MenuItemMule) {
return onOptionsItemSelected(((MenuItemMule)item).unwrap());
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
//Nothing to see here.
return false;
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockDialogFragment.java | Java | asf20 | 2,343 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 com.actionbarsherlock.app;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.View;
import android.view.ViewDebug;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.SpinnerAdapter;
/**
* A window feature at the top of the activity that may display the activity title, navigation
* modes, and other interactive items.
* <p>Beginning with Android 3.0 (API level 11), the action bar appears at the top of an
* activity's window when the activity uses the system's {@link
* android.R.style#Theme_Holo Holo} theme (or one of its descendant themes), which is the default.
* You may otherwise add the action bar by calling {@link
* android.view.Window#requestFeature requestFeature(FEATURE_ACTION_BAR)} or by declaring it in a
* custom theme with the {@link android.R.styleable#Theme_windowActionBar windowActionBar} property.
* <p>By default, the action bar shows the application icon on
* the left, followed by the activity title. If your activity has an options menu, you can make
* select items accessible directly from the action bar as "action items". You can also
* modify various characteristics of the action bar or remove it completely.</p>
* <p>From your activity, you can retrieve an instance of {@link ActionBar} by calling {@link
* android.app.Activity#getActionBar getActionBar()}.</p>
* <p>In some cases, the action bar may be overlayed by another bar that enables contextual actions,
* using an {@link android.view.ActionMode}. For example, when the user selects one or more items in
* your activity, you can enable an action mode that offers actions specific to the selected
* items, with a UI that temporarily replaces the action bar. Although the UI may occupy the
* same space, the {@link android.view.ActionMode} APIs are distinct and independent from those for
* {@link ActionBar}.
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For information about how to use the action bar, including how to add action items, navigation
* modes and more, read the <a href="{@docRoot}guide/topics/ui/actionbar.html">Action
* Bar</a> developer guide.</p>
* </div>
*/
public abstract class ActionBar {
/**
* Standard navigation mode. Consists of either a logo or icon
* and title text with an optional subtitle. Clicking any of these elements
* will dispatch onOptionsItemSelected to the host Activity with
* a MenuItem with item ID android.R.id.home.
*/
public static final int NAVIGATION_MODE_STANDARD = android.app.ActionBar.NAVIGATION_MODE_STANDARD;
/**
* List navigation mode. Instead of static title text this mode
* presents a list menu for navigation within the activity.
* e.g. this might be presented to the user as a dropdown list.
*/
public static final int NAVIGATION_MODE_LIST = android.app.ActionBar.NAVIGATION_MODE_LIST;
/**
* Tab navigation mode. Instead of static title text this mode
* presents a series of tabs for navigation within the activity.
*/
public static final int NAVIGATION_MODE_TABS = android.app.ActionBar.NAVIGATION_MODE_TABS;
/**
* Use logo instead of icon if available. This flag will cause appropriate
* navigation modes to use a wider logo in place of the standard icon.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_USE_LOGO = android.app.ActionBar.DISPLAY_USE_LOGO;
/**
* Show 'home' elements in this action bar, leaving more space for other
* navigation elements. This includes logo and icon.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_SHOW_HOME = android.app.ActionBar.DISPLAY_SHOW_HOME;
/**
* Display the 'home' element such that it appears as an 'up' affordance.
* e.g. show an arrow to the left indicating the action that will be taken.
*
* Set this flag if selecting the 'home' button in the action bar to return
* up by a single level in your UI rather than back to the top level or front page.
*
* <p>Setting this option will implicitly enable interaction with the home/up
* button. See {@link #setHomeButtonEnabled(boolean)}.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_HOME_AS_UP = android.app.ActionBar.DISPLAY_HOME_AS_UP;
/**
* Show the activity title and subtitle, if present.
*
* @see #setTitle(CharSequence)
* @see #setTitle(int)
* @see #setSubtitle(CharSequence)
* @see #setSubtitle(int)
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_SHOW_TITLE = android.app.ActionBar.DISPLAY_SHOW_TITLE;
/**
* Show the custom view if one has been set.
* @see #setCustomView(View)
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public static final int DISPLAY_SHOW_CUSTOM = android.app.ActionBar.DISPLAY_SHOW_CUSTOM;
/**
* Set the action bar into custom navigation mode, supplying a view
* for custom navigation.
*
* Custom navigation views appear between the application icon and
* any action buttons and may use any space available there. Common
* use cases for custom navigation views might include an auto-suggesting
* address bar for a browser or other navigation mechanisms that do not
* translate well to provided navigation modes.
*
* @param view Custom navigation view to place in the ActionBar.
*/
public abstract void setCustomView(View view);
/**
* Set the action bar into custom navigation mode, supplying a view
* for custom navigation.
*
* <p>Custom navigation views appear between the application icon and
* any action buttons and may use any space available there. Common
* use cases for custom navigation views might include an auto-suggesting
* address bar for a browser or other navigation mechanisms that do not
* translate well to provided navigation modes.</p>
*
* <p>The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for
* the custom view to be displayed.</p>
*
* @param view Custom navigation view to place in the ActionBar.
* @param layoutParams How this custom view should layout in the bar.
*
* @see #setDisplayOptions(int, int)
*/
public abstract void setCustomView(View view, LayoutParams layoutParams);
/**
* Set the action bar into custom navigation mode, supplying a view
* for custom navigation.
*
* <p>Custom navigation views appear between the application icon and
* any action buttons and may use any space available there. Common
* use cases for custom navigation views might include an auto-suggesting
* address bar for a browser or other navigation mechanisms that do not
* translate well to provided navigation modes.</p>
*
* <p>The display option {@link #DISPLAY_SHOW_CUSTOM} must be set for
* the custom view to be displayed.</p>
*
* @param resId Resource ID of a layout to inflate into the ActionBar.
*
* @see #setDisplayOptions(int, int)
*/
public abstract void setCustomView(int resId);
/**
* Set the icon to display in the 'home' section of the action bar.
* The action bar will use an icon specified by its style or the
* activity icon by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param resId Resource ID of a drawable to show as an icon.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setIcon(int resId);
/**
* Set the icon to display in the 'home' section of the action bar.
* The action bar will use an icon specified by its style or the
* activity icon by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param icon Drawable to show as an icon.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setIcon(Drawable icon);
/**
* Set the logo to display in the 'home' section of the action bar.
* The action bar will use a logo specified by its style or the
* activity logo by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param resId Resource ID of a drawable to show as a logo.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setLogo(int resId);
/**
* Set the logo to display in the 'home' section of the action bar.
* The action bar will use a logo specified by its style or the
* activity logo by default.
*
* Whether the home section shows an icon or logo is controlled
* by the display option {@link #DISPLAY_USE_LOGO}.
*
* @param logo Drawable to show as a logo.
*
* @see #setDisplayUseLogoEnabled(boolean)
* @see #setDisplayShowHomeEnabled(boolean)
*/
public abstract void setLogo(Drawable logo);
/**
* Set the adapter and navigation callback for list navigation mode.
*
* The supplied adapter will provide views for the expanded list as well as
* the currently selected item. (These may be displayed differently.)
*
* The supplied OnNavigationListener will alert the application when the user
* changes the current list selection.
*
* @param adapter An adapter that will provide views both to display
* the current navigation selection and populate views
* within the dropdown navigation menu.
* @param callback An OnNavigationListener that will receive events when the user
* selects a navigation item.
*/
public abstract void setListNavigationCallbacks(SpinnerAdapter adapter,
OnNavigationListener callback);
/**
* Set the selected navigation item in list or tabbed navigation modes.
*
* @param position Position of the item to select.
*/
public abstract void setSelectedNavigationItem(int position);
/**
* Get the position of the selected navigation item in list or tabbed navigation modes.
*
* @return Position of the selected item.
*/
public abstract int getSelectedNavigationIndex();
/**
* Get the number of navigation items present in the current navigation mode.
*
* @return Number of navigation items.
*/
public abstract int getNavigationItemCount();
/**
* Set the action bar's title. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set.
*
* @param title Title to set
*
* @see #setTitle(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setTitle(CharSequence title);
/**
* Set the action bar's title. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set.
*
* @param resId Resource ID of title string to set
*
* @see #setTitle(CharSequence)
* @see #setDisplayOptions(int, int)
*/
public abstract void setTitle(int resId);
/**
* Set the action bar's subtitle. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set. Set to null to disable the
* subtitle entirely.
*
* @param subtitle Subtitle to set
*
* @see #setSubtitle(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setSubtitle(CharSequence subtitle);
/**
* Set the action bar's subtitle. This will only be displayed if
* {@link #DISPLAY_SHOW_TITLE} is set.
*
* @param resId Resource ID of subtitle string to set
*
* @see #setSubtitle(CharSequence)
* @see #setDisplayOptions(int, int)
*/
public abstract void setSubtitle(int resId);
/**
* Set display options. This changes all display option bits at once. To change
* a limited subset of display options, see {@link #setDisplayOptions(int, int)}.
*
* @param options A combination of the bits defined by the DISPLAY_ constants
* defined in ActionBar.
*/
public abstract void setDisplayOptions(int options);
/**
* Set selected display options. Only the options specified by mask will be changed.
* To change all display option bits at once, see {@link #setDisplayOptions(int)}.
*
* <p>Example: setDisplayOptions(0, DISPLAY_SHOW_HOME) will disable the
* {@link #DISPLAY_SHOW_HOME} option.
* setDisplayOptions(DISPLAY_SHOW_HOME, DISPLAY_SHOW_HOME | DISPLAY_USE_LOGO)
* will enable {@link #DISPLAY_SHOW_HOME} and disable {@link #DISPLAY_USE_LOGO}.
*
* @param options A combination of the bits defined by the DISPLAY_ constants
* defined in ActionBar.
* @param mask A bit mask declaring which display options should be changed.
*/
public abstract void setDisplayOptions(int options, int mask);
/**
* Set whether to display the activity logo rather than the activity icon.
* A logo is often a wider, more detailed image.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param useLogo true to use the activity logo, false to use the activity icon.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayUseLogoEnabled(boolean useLogo);
/**
* Set whether to include the application home affordance in the action bar.
* Home is presented as either an activity icon or logo.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showHome true to show home, false otherwise.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayShowHomeEnabled(boolean showHome);
/**
* Set whether home should be displayed as an "up" affordance.
* Set this to true if selecting "home" returns up by a single level in your UI
* rather than back to the top level or front page.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showHomeAsUp true to show the user that selecting home will return one
* level up rather than to the top level of the app.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayHomeAsUpEnabled(boolean showHomeAsUp);
/**
* Set whether an activity title/subtitle should be displayed.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showTitle true to display a title/subtitle if present.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayShowTitleEnabled(boolean showTitle);
/**
* Set whether a custom view should be displayed, if set.
*
* <p>To set several display options at once, see the setDisplayOptions methods.
*
* @param showCustom true if the currently set custom view should be displayed, false otherwise.
*
* @see #setDisplayOptions(int)
* @see #setDisplayOptions(int, int)
*/
public abstract void setDisplayShowCustomEnabled(boolean showCustom);
/**
* Set the ActionBar's background. This will be used for the primary
* action bar.
*
* @param d Background drawable
* @see #setStackedBackgroundDrawable(Drawable)
* @see #setSplitBackgroundDrawable(Drawable)
*/
public abstract void setBackgroundDrawable(Drawable d);
/**
* Set the ActionBar's stacked background. This will appear
* in the second row/stacked bar on some devices and configurations.
*
* @param d Background drawable for the stacked row
*/
public void setStackedBackgroundDrawable(Drawable d) { }
/**
* Set the ActionBar's split background. This will appear in
* the split action bar containing menu-provided action buttons
* on some devices and configurations.
* <p>You can enable split action bar with {@link android.R.attr#uiOptions}
*
* @param d Background drawable for the split bar
*/
public void setSplitBackgroundDrawable(Drawable d) { }
/**
* @return The current custom view.
*/
public abstract View getCustomView();
/**
* Returns the current ActionBar title in standard mode.
* Returns null if {@link #getNavigationMode()} would not return
* {@link #NAVIGATION_MODE_STANDARD}.
*
* @return The current ActionBar title or null.
*/
public abstract CharSequence getTitle();
/**
* Returns the current ActionBar subtitle in standard mode.
* Returns null if {@link #getNavigationMode()} would not return
* {@link #NAVIGATION_MODE_STANDARD}.
*
* @return The current ActionBar subtitle or null.
*/
public abstract CharSequence getSubtitle();
/**
* Returns the current navigation mode. The result will be one of:
* <ul>
* <li>{@link #NAVIGATION_MODE_STANDARD}</li>
* <li>{@link #NAVIGATION_MODE_LIST}</li>
* <li>{@link #NAVIGATION_MODE_TABS}</li>
* </ul>
*
* @return The current navigation mode.
*/
public abstract int getNavigationMode();
/**
* Set the current navigation mode.
*
* @param mode The new mode to set.
* @see #NAVIGATION_MODE_STANDARD
* @see #NAVIGATION_MODE_LIST
* @see #NAVIGATION_MODE_TABS
*/
public abstract void setNavigationMode(int mode);
/**
* @return The current set of display options.
*/
public abstract int getDisplayOptions();
/**
* Create and return a new {@link Tab}.
* This tab will not be included in the action bar until it is added.
*
* <p>Very often tabs will be used to switch between {@link Fragment}
* objects. Here is a typical implementation of such tabs:</p>
*
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentTabs.java
* complete}
*
* @return A new Tab
*
* @see #addTab(Tab)
*/
public abstract Tab newTab();
/**
* Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list.
* If this is the first tab to be added it will become the selected tab.
*
* @param tab Tab to add
*/
public abstract void addTab(Tab tab);
/**
* Add a tab for use in tabbed navigation mode. The tab will be added at the end of the list.
*
* @param tab Tab to add
* @param setSelected True if the added tab should become the selected tab.
*/
public abstract void addTab(Tab tab, boolean setSelected);
/**
* Add a tab for use in tabbed navigation mode. The tab will be inserted at
* <code>position</code>. If this is the first tab to be added it will become
* the selected tab.
*
* @param tab The tab to add
* @param position The new position of the tab
*/
public abstract void addTab(Tab tab, int position);
/**
* Add a tab for use in tabbed navigation mode. The tab will be insterted at
* <code>position</code>.
*
* @param tab The tab to add
* @param position The new position of the tab
* @param setSelected True if the added tab should become the selected tab.
*/
public abstract void addTab(Tab tab, int position, boolean setSelected);
/**
* Remove a tab from the action bar. If the removed tab was selected it will be deselected
* and another tab will be selected if present.
*
* @param tab The tab to remove
*/
public abstract void removeTab(Tab tab);
/**
* Remove a tab from the action bar. If the removed tab was selected it will be deselected
* and another tab will be selected if present.
*
* @param position Position of the tab to remove
*/
public abstract void removeTabAt(int position);
/**
* Remove all tabs from the action bar and deselect the current tab.
*/
public abstract void removeAllTabs();
/**
* Select the specified tab. If it is not a child of this action bar it will be added.
*
* <p>Note: If you want to select by index, use {@link #setSelectedNavigationItem(int)}.</p>
*
* @param tab Tab to select
*/
public abstract void selectTab(Tab tab);
/**
* Returns the currently selected tab if in tabbed navigation mode and there is at least
* one tab present.
*
* @return The currently selected tab or null
*/
public abstract Tab getSelectedTab();
/**
* Returns the tab at the specified index.
*
* @param index Index value in the range 0-get
* @return
*/
public abstract Tab getTabAt(int index);
/**
* Returns the number of tabs currently registered with the action bar.
* @return Tab count
*/
public abstract int getTabCount();
/**
* Retrieve the current height of the ActionBar.
*
* @return The ActionBar's height
*/
public abstract int getHeight();
/**
* Show the ActionBar if it is not currently showing.
* If the window hosting the ActionBar does not have the feature
* {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application
* content to fit the new space available.
*/
public abstract void show();
/**
* Hide the ActionBar if it is currently showing.
* If the window hosting the ActionBar does not have the feature
* {@link Window#FEATURE_ACTION_BAR_OVERLAY} it will resize application
* content to fit the new space available.
*/
public abstract void hide();
/**
* @return <code>true</code> if the ActionBar is showing, <code>false</code> otherwise.
*/
public abstract boolean isShowing();
/**
* Add a listener that will respond to menu visibility change events.
*
* @param listener The new listener to add
*/
public abstract void addOnMenuVisibilityListener(OnMenuVisibilityListener listener);
/**
* Remove a menu visibility listener. This listener will no longer receive menu
* visibility change events.
*
* @param listener A listener to remove that was previously added
*/
public abstract void removeOnMenuVisibilityListener(OnMenuVisibilityListener listener);
/**
* Enable or disable the "home" button in the corner of the action bar. (Note that this
* is the application home/up affordance on the action bar, not the systemwide home
* button.)
*
* <p>This defaults to true for packages targeting < API 14. For packages targeting
* API 14 or greater, the application should call this method to enable interaction
* with the home/up affordance.
*
* <p>Setting the {@link #DISPLAY_HOME_AS_UP} display option will automatically enable
* the home button.
*
* @param enabled true to enable the home button, false to disable the home button.
*/
public void setHomeButtonEnabled(boolean enabled) { }
/**
* Returns a {@link Context} with an appropriate theme for creating views that
* will appear in the action bar. If you are inflating or instantiating custom views
* that will appear in an action bar, you should use the Context returned by this method.
* (This includes adapters used for list navigation mode.)
* This will ensure that views contrast properly against the action bar.
*
* @return A themed Context for creating views
*/
public Context getThemedContext() { return null; }
/**
* Listener interface for ActionBar navigation events.
*/
public interface OnNavigationListener {
/**
* This method is called whenever a navigation item in your action bar
* is selected.
*
* @param itemPosition Position of the item clicked.
* @param itemId ID of the item clicked.
* @return True if the event was handled, false otherwise.
*/
public boolean onNavigationItemSelected(int itemPosition, long itemId);
}
/**
* Listener for receiving events when action bar menus are shown or hidden.
*/
public interface OnMenuVisibilityListener {
/**
* Called when an action bar menu is shown or hidden. Applications may want to use
* this to tune auto-hiding behavior for the action bar or pause/resume video playback,
* gameplay, or other activity within the main content area.
*
* @param isVisible True if an action bar menu is now visible, false if no action bar
* menus are visible.
*/
public void onMenuVisibilityChanged(boolean isVisible);
}
/**
* A tab in the action bar.
*
* <p>Tabs manage the hiding and showing of {@link Fragment}s.
*/
public static abstract class Tab {
/**
* An invalid position for a tab.
*
* @see #getPosition()
*/
public static final int INVALID_POSITION = -1;
/**
* Return the current position of this tab in the action bar.
*
* @return Current position, or {@link #INVALID_POSITION} if this tab is not currently in
* the action bar.
*/
public abstract int getPosition();
/**
* Return the icon associated with this tab.
*
* @return The tab's icon
*/
public abstract Drawable getIcon();
/**
* Return the text of this tab.
*
* @return The tab's text
*/
public abstract CharSequence getText();
/**
* Set the icon displayed on this tab.
*
* @param icon The drawable to use as an icon
* @return The current instance for call chaining
*/
public abstract Tab setIcon(Drawable icon);
/**
* Set the icon displayed on this tab.
*
* @param resId Resource ID referring to the drawable to use as an icon
* @return The current instance for call chaining
*/
public abstract Tab setIcon(int resId);
/**
* Set the text displayed on this tab. Text may be truncated if there is not
* room to display the entire string.
*
* @param text The text to display
* @return The current instance for call chaining
*/
public abstract Tab setText(CharSequence text);
/**
* Set the text displayed on this tab. Text may be truncated if there is not
* room to display the entire string.
*
* @param resId A resource ID referring to the text that should be displayed
* @return The current instance for call chaining
*/
public abstract Tab setText(int resId);
/**
* Set a custom view to be used for this tab. This overrides values set by
* {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}.
*
* @param view Custom view to be used as a tab.
* @return The current instance for call chaining
*/
public abstract Tab setCustomView(View view);
/**
* Set a custom view to be used for this tab. This overrides values set by
* {@link #setText(CharSequence)} and {@link #setIcon(Drawable)}.
*
* @param layoutResId A layout resource to inflate and use as a custom tab view
* @return The current instance for call chaining
*/
public abstract Tab setCustomView(int layoutResId);
/**
* Retrieve a previously set custom view for this tab.
*
* @return The custom view set by {@link #setCustomView(View)}.
*/
public abstract View getCustomView();
/**
* Give this Tab an arbitrary object to hold for later use.
*
* @param obj Object to store
* @return The current instance for call chaining
*/
public abstract Tab setTag(Object obj);
/**
* @return This Tab's tag object.
*/
public abstract Object getTag();
/**
* Set the {@link TabListener} that will handle switching to and from this tab.
* All tabs must have a TabListener set before being added to the ActionBar.
*
* @param listener Listener to handle tab selection events
* @return The current instance for call chaining
*/
public abstract Tab setTabListener(TabListener listener);
/**
* Select this tab. Only valid if the tab has been added to the action bar.
*/
public abstract void select();
/**
* Set a description of this tab's content for use in accessibility support.
* If no content description is provided the title will be used.
*
* @param resId A resource ID referring to the description text
* @return The current instance for call chaining
* @see #setContentDescription(CharSequence)
* @see #getContentDescription()
*/
public abstract Tab setContentDescription(int resId);
/**
* Set a description of this tab's content for use in accessibility support.
* If no content description is provided the title will be used.
*
* @param contentDesc Description of this tab's content
* @return The current instance for call chaining
* @see #setContentDescription(int)
* @see #getContentDescription()
*/
public abstract Tab setContentDescription(CharSequence contentDesc);
/**
* Gets a brief description of this tab's content for use in accessibility support.
*
* @return Description of this tab's content
* @see #setContentDescription(CharSequence)
* @see #setContentDescription(int)
*/
public abstract CharSequence getContentDescription();
}
/**
* Callback interface invoked when a tab is focused, unfocused, added, or removed.
*/
public interface TabListener {
/**
* Called when a tab enters the selected state.
*
* @param tab The tab that was selected
* @param ft A {@link FragmentTransaction} for queuing fragment operations to execute
* during a tab switch. The previous tab's unselect and this tab's select will be
* executed in a single transaction. This FragmentTransaction does not support
* being added to the back stack.
*/
public void onTabSelected(Tab tab, FragmentTransaction ft);
/**
* Called when a tab exits the selected state.
*
* @param tab The tab that was unselected
* @param ft A {@link FragmentTransaction} for queuing fragment operations to execute
* during a tab switch. This tab's unselect and the newly selected tab's select
* will be executed in a single transaction. This FragmentTransaction does not
* support being added to the back stack.
*/
public void onTabUnselected(Tab tab, FragmentTransaction ft);
/**
* Called when a tab that is already selected is chosen again by the user.
* Some applications may use this action to return to the top level of a category.
*
* @param tab The tab that was reselected.
* @param ft A {@link FragmentTransaction} for queuing fragment operations to execute
* once this method returns. This FragmentTransaction does not support
* being added to the back stack.
*/
public void onTabReselected(Tab tab, FragmentTransaction ft);
}
/**
* Per-child layout information associated with action bar custom views.
*
* @attr ref android.R.styleable#ActionBar_LayoutParams_layout_gravity
*/
public static class LayoutParams extends MarginLayoutParams {
/**
* Gravity for the view associated with these LayoutParams.
*
* @see android.view.Gravity
*/
@ViewDebug.ExportedProperty(mapping = {
@ViewDebug.IntToString(from = -1, to = "NONE"),
@ViewDebug.IntToString(from = Gravity.NO_GRAVITY, to = "NONE"),
@ViewDebug.IntToString(from = Gravity.TOP, to = "TOP"),
@ViewDebug.IntToString(from = Gravity.BOTTOM, to = "BOTTOM"),
@ViewDebug.IntToString(from = Gravity.LEFT, to = "LEFT"),
@ViewDebug.IntToString(from = Gravity.RIGHT, to = "RIGHT"),
@ViewDebug.IntToString(from = Gravity.CENTER_VERTICAL, to = "CENTER_VERTICAL"),
@ViewDebug.IntToString(from = Gravity.FILL_VERTICAL, to = "FILL_VERTICAL"),
@ViewDebug.IntToString(from = Gravity.CENTER_HORIZONTAL, to = "CENTER_HORIZONTAL"),
@ViewDebug.IntToString(from = Gravity.FILL_HORIZONTAL, to = "FILL_HORIZONTAL"),
@ViewDebug.IntToString(from = Gravity.CENTER, to = "CENTER"),
@ViewDebug.IntToString(from = Gravity.FILL, to = "FILL")
})
public int gravity = -1;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
}
public LayoutParams(int width, int height) {
super(width, height);
this.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT;
}
public LayoutParams(int width, int height, int gravity) {
super(width, height);
this.gravity = gravity;
}
public LayoutParams(int gravity) {
this(WRAP_CONTENT, FILL_PARENT, gravity);
}
public LayoutParams(LayoutParams source) {
super(source);
this.gravity = source.gravity;
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/ActionBar.java | Java | asf20 | 36,639 |
package com.actionbarsherlock.app;
import android.app.ListActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockListActivity extends ListActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
private ActionBarSherlock mSherlock;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
getSherlock().dispatchInvalidateOptionsMenu();
}
public void supportInvalidateOptionsMenu() {
invalidateOptionsMenu();
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchCreateOptionsMenu(menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return getSherlock().dispatchPrepareOptionsMenu(menu);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return getSherlock().dispatchOptionsItemSelected(item);
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onCreateOptionsMenu(menu);
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onPrepareOptionsMenu(menu);
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
return onOptionsItemSelected(item);
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockListActivity.java | Java | asf20 | 8,033 |
package com.actionbarsherlock.app;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import com.actionbarsherlock.ActionBarSherlock;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeFinishedListener;
import com.actionbarsherlock.ActionBarSherlock.OnActionModeStartedListener;
import com.actionbarsherlock.ActionBarSherlock.OnCreatePanelMenuListener;
import com.actionbarsherlock.ActionBarSherlock.OnMenuItemSelectedListener;
import com.actionbarsherlock.ActionBarSherlock.OnPreparePanelListener;
import com.actionbarsherlock.internal.view.menu.MenuItemMule;
import com.actionbarsherlock.internal.view.menu.MenuMule;
import com.actionbarsherlock.view.ActionMode;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
public abstract class SherlockFragmentActivity extends FragmentActivity implements OnCreatePanelMenuListener, OnPreparePanelListener, OnMenuItemSelectedListener, OnActionModeStartedListener, OnActionModeFinishedListener {
static final boolean DEBUG = false;
private static final String TAG = "SherlockFragmentActivity";
private ActionBarSherlock mSherlock;
private boolean mIgnoreNativeCreate = false;
private boolean mIgnoreNativePrepare = false;
private boolean mIgnoreNativeSelected = false;
private Boolean mOverrideNativeCreate = null;
protected final ActionBarSherlock getSherlock() {
if (mSherlock == null) {
mSherlock = ActionBarSherlock.wrap(this, ActionBarSherlock.FLAG_DELEGATE);
}
return mSherlock;
}
///////////////////////////////////////////////////////////////////////////
// Action bar and mode
///////////////////////////////////////////////////////////////////////////
public ActionBar getSupportActionBar() {
return getSherlock().getActionBar();
}
public ActionMode startActionMode(ActionMode.Callback callback) {
return getSherlock().startActionMode(callback);
}
@Override
public void onActionModeStarted(ActionMode mode) {}
@Override
public void onActionModeFinished(ActionMode mode) {}
///////////////////////////////////////////////////////////////////////////
// General lifecycle/callback dispatching
///////////////////////////////////////////////////////////////////////////
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
getSherlock().dispatchConfigurationChanged(newConfig);
}
@Override
protected void onPostResume() {
super.onPostResume();
getSherlock().dispatchPostResume();
}
@Override
protected void onPause() {
getSherlock().dispatchPause();
super.onPause();
}
@Override
protected void onStop() {
getSherlock().dispatchStop();
super.onStop();
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
getSherlock().dispatchPostCreate(savedInstanceState);
super.onPostCreate(savedInstanceState);
}
@Override
protected void onTitleChanged(CharSequence title, int color) {
getSherlock().dispatchTitleChanged(title, color);
super.onTitleChanged(title, color);
}
@Override
public final boolean onMenuOpened(int featureId, android.view.Menu menu) {
if (getSherlock().dispatchMenuOpened(featureId, menu)) {
return true;
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, android.view.Menu menu) {
getSherlock().dispatchPanelClosed(featureId, menu);
super.onPanelClosed(featureId, menu);
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (getSherlock().dispatchKeyEvent(event)) {
return true;
}
return super.dispatchKeyEvent(event);
}
///////////////////////////////////////////////////////////////////////////
// Native menu handling
///////////////////////////////////////////////////////////////////////////
public MenuInflater getSupportMenuInflater() {
if (DEBUG) Log.d(TAG, "[getSupportMenuInflater]");
return getSherlock().getMenuInflater();
}
public void invalidateOptionsMenu() {
if (DEBUG) Log.d(TAG, "[invalidateOptionsMenu]");
getSherlock().dispatchInvalidateOptionsMenu();
}
protected void supportInvalidateOptionsMenu() {
if (DEBUG) Log.d(TAG, "[supportInvalidateOptionsMenu]");
invalidateOptionsMenu();
}
@Override
public final boolean onCreatePanelMenu(int featureId, android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeCreate) {
mIgnoreNativeCreate = true;
boolean result = getSherlock().dispatchCreateOptionsMenu(menu);
mIgnoreNativeCreate = false;
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] returning " + result);
return result;
}
return super.onCreatePanelMenu(featureId, menu);
}
@Override
public final boolean onCreateOptionsMenu(android.view.Menu menu) {
return (mOverrideNativeCreate != null) ? mOverrideNativeCreate.booleanValue() : true;
}
@Override
public final boolean onPreparePanel(int featureId, View view, android.view.Menu menu) {
if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + ", menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativePrepare) {
mIgnoreNativePrepare = true;
boolean result = getSherlock().dispatchPrepareOptionsMenu(menu);
mIgnoreNativePrepare = false;
if (DEBUG) Log.d(TAG, "[onPreparePanel] returning " + result);
return result;
}
return super.onPreparePanel(featureId, view, menu);
}
@Override
public final boolean onPrepareOptionsMenu(android.view.Menu menu) {
return true;
}
@Override
public final boolean onMenuItemSelected(int featureId, android.view.MenuItem item) {
if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item);
if (featureId == Window.FEATURE_OPTIONS_PANEL && !mIgnoreNativeSelected) {
mIgnoreNativeSelected = true;
boolean result = getSherlock().dispatchOptionsItemSelected(item);
mIgnoreNativeSelected = false;
if (DEBUG) Log.d(TAG, "[onMenuItemSelected] returning " + result);
return result;
}
return super.onMenuItemSelected(featureId, item);
}
@Override
public final boolean onOptionsItemSelected(android.view.MenuItem item) {
return false;
}
@Override
public void openOptionsMenu() {
if (!getSherlock().dispatchOpenOptionsMenu()) {
super.openOptionsMenu();
}
}
@Override
public void closeOptionsMenu() {
if (!getSherlock().dispatchCloseOptionsMenu()) {
super.closeOptionsMenu();
}
}
///////////////////////////////////////////////////////////////////////////
// Sherlock menu handling
///////////////////////////////////////////////////////////////////////////
@Override
public boolean onCreatePanelMenu(int featureId, Menu menu) {
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] featureId: " + featureId + ", menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean result = onCreateOptionsMenu(menu);
//Dispatch to parent panel creation for fragment dispatching
if (DEBUG) Log.d(TAG, "[onCreatePanelMenu] dispatching to native with mule");
mOverrideNativeCreate = result;
boolean fragResult = super.onCreatePanelMenu(featureId, new MenuMule(menu));
mOverrideNativeCreate = null;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
result |= menu.hasVisibleItems();
} else {
result |= fragResult;
}
return result;
}
return false;
}
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onPreparePanel(int featureId, View view, Menu menu) {
if (DEBUG) Log.d(TAG, "[onPreparePanel] featureId: " + featureId + ", view: " + view + " menu: " + menu);
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean result = onPrepareOptionsMenu(menu);
//Dispatch to parent panel preparation for fragment dispatching
if (DEBUG) Log.d(TAG, "[onPreparePanel] dispatching to native with mule");
super.onPreparePanel(featureId, view, new MenuMule(menu));
return result;
}
return false;
}
public boolean onPrepareOptionsMenu(Menu menu) {
return true;
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
if (DEBUG) Log.d(TAG, "[onMenuItemSelected] featureId: " + featureId + ", item: " + item);
if (featureId == Window.FEATURE_OPTIONS_PANEL) {
boolean result = onOptionsItemSelected(item);
//Dispatch to parent panel selection for fragment dispatching
if (DEBUG) Log.d(TAG, "[onMenuItemSelected] dispatching to native with mule");
result |= super.onMenuItemSelected(featureId, new MenuItemMule(item));
return result;
}
return false;
}
public boolean onOptionsItemSelected(MenuItem item) {
return false;
}
///////////////////////////////////////////////////////////////////////////
// Content
///////////////////////////////////////////////////////////////////////////
@Override
public void addContentView(View view, LayoutParams params) {
getSherlock().addContentView(view, params);
}
@Override
public void setContentView(int layoutResId) {
getSherlock().setContentView(layoutResId);
}
@Override
public void setContentView(View view, LayoutParams params) {
getSherlock().setContentView(view, params);
}
@Override
public void setContentView(View view) {
getSherlock().setContentView(view);
}
public void requestWindowFeature(long featureId) {
getSherlock().requestFeature((int)featureId);
}
///////////////////////////////////////////////////////////////////////////
// Progress Indication
///////////////////////////////////////////////////////////////////////////
public void setSupportProgress(int progress) {
getSherlock().setProgress(progress);
}
public void setSupportProgressBarIndeterminate(boolean indeterminate) {
getSherlock().setProgressBarIndeterminate(indeterminate);
}
public void setSupportProgressBarIndeterminateVisibility(boolean visible) {
getSherlock().setProgressBarIndeterminateVisibility(visible);
}
public void setSupportProgressBarVisibility(boolean visible) {
getSherlock().setProgressBarVisibility(visible);
}
public void setSupportSecondaryProgress(int secondaryProgress) {
getSherlock().setSecondaryProgress(secondaryProgress);
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/app/SherlockFragmentActivity.java | Java | asf20 | 11,754 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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 com.actionbarsherlock.view;
import android.view.View;
/**
* Represents a contextual mode of the user interface. Action modes can be used for
* modal interactions with content and replace parts of the normal UI until finished.
* Examples of good action modes include selection modes, search, content editing, etc.
*/
public abstract class ActionMode {
private Object mTag;
/**
* Set a tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @param tag Tag to associate with this ActionMode
*
* @see #getTag()
*/
public void setTag(Object tag) {
mTag = tag;
}
/**
* Retrieve the tag object associated with this ActionMode.
*
* <p>Like the tag available to views, this allows applications to associate arbitrary
* data with an ActionMode for later reference.
*
* @return Tag associated with this ActionMode
*
* @see #setTag(Object)
*/
public Object getTag() {
return mTag;
}
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param title Title string to set
*
* @see #setTitle(int)
* @see #setCustomView(View)
*/
public abstract void setTitle(CharSequence title);
/**
* Set the title of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param resId Resource ID of a string to set as the title
*
* @see #setTitle(CharSequence)
* @see #setCustomView(View)
*/
public abstract void setTitle(int resId);
/**
* Set the subtitle of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param subtitle Subtitle string to set
*
* @see #setSubtitle(int)
* @see #setCustomView(View)
*/
public abstract void setSubtitle(CharSequence subtitle);
/**
* Set the subtitle of the action mode. This method will have no visible effect if
* a custom view has been set.
*
* @param resId Resource ID of a string to set as the subtitle
*
* @see #setSubtitle(CharSequence)
* @see #setCustomView(View)
*/
public abstract void setSubtitle(int resId);
/**
* Set a custom view for this action mode. The custom view will take the place of
* the title and subtitle. Useful for things like search boxes.
*
* @param view Custom view to use in place of the title/subtitle.
*
* @see #setTitle(CharSequence)
* @see #setSubtitle(CharSequence)
*/
public abstract void setCustomView(View view);
/**
* Invalidate the action mode and refresh menu content. The mode's
* {@link ActionMode.Callback} will have its
* {@link Callback#onPrepareActionMode(ActionMode, Menu)} method called.
* If it returns true the menu will be scanned for updated content and any relevant changes
* will be reflected to the user.
*/
public abstract void invalidate();
/**
* Finish and close this action mode. The action mode's {@link ActionMode.Callback} will
* have its {@link Callback#onDestroyActionMode(ActionMode)} method called.
*/
public abstract void finish();
/**
* Returns the menu of actions that this action mode presents.
* @return The action mode's menu.
*/
public abstract Menu getMenu();
/**
* Returns the current title of this action mode.
* @return Title text
*/
public abstract CharSequence getTitle();
/**
* Returns the current subtitle of this action mode.
* @return Subtitle text
*/
public abstract CharSequence getSubtitle();
/**
* Returns the current custom view for this action mode.
* @return The current custom view
*/
public abstract View getCustomView();
/**
* Returns a {@link MenuInflater} with the ActionMode's context.
*/
public abstract MenuInflater getMenuInflater();
/**
* Returns whether the UI presenting this action mode can take focus or not.
* This is used by internal components within the framework that would otherwise
* present an action mode UI that requires focus, such as an EditText as a custom view.
*
* @return true if the UI used to show this action mode can take focus
* @hide Internal use only
*/
public boolean isUiFocusable() {
return true;
}
/**
* Callback interface for action modes. Supplied to
* {@link View#startActionMode(Callback)}, a Callback
* configures and handles events raised by a user's interaction with an action mode.
*
* <p>An action mode's lifecycle is as follows:
* <ul>
* <li>{@link Callback#onCreateActionMode(ActionMode, Menu)} once on initial
* creation</li>
* <li>{@link Callback#onPrepareActionMode(ActionMode, Menu)} after creation
* and any time the {@link ActionMode} is invalidated</li>
* <li>{@link Callback#onActionItemClicked(ActionMode, MenuItem)} any time a
* contextual action button is clicked</li>
* <li>{@link Callback#onDestroyActionMode(ActionMode)} when the action mode
* is closed</li>
* </ul>
*/
public interface Callback {
/**
* Called when action mode is first created. The menu supplied will be used to
* generate action buttons for the action mode.
*
* @param mode ActionMode being created
* @param menu Menu used to populate action buttons
* @return true if the action mode should be created, false if entering this
* mode should be aborted.
*/
public boolean onCreateActionMode(ActionMode mode, Menu menu);
/**
* Called to refresh an action mode's action menu whenever it is invalidated.
*
* @param mode ActionMode being prepared
* @param menu Menu used to populate action buttons
* @return true if the menu or action mode was updated, false otherwise.
*/
public boolean onPrepareActionMode(ActionMode mode, Menu menu);
/**
* Called to report a user click on an action button.
*
* @param mode The current ActionMode
* @param item The item that was clicked
* @return true if this callback handled the event, false if the standard MenuItem
* invocation should continue.
*/
public boolean onActionItemClicked(ActionMode mode, MenuItem item);
/**
* Called when an action mode is about to be exited and destroyed.
*
* @param mode The current ActionMode being destroyed
*/
public void onDestroyActionMode(ActionMode mode);
}
} | 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/view/ActionMode.java | Java | asf20 | 7,820 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* 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 com.actionbarsherlock.view;
/**
* When a {@link View} implements this interface it will receive callbacks
* when expanded or collapsed as an action view alongside the optional,
* app-specified callbacks to {@link OnActionExpandListener}.
*
* <p>See {@link MenuItem} for more information about action views.
* See {@link android.app.ActionBar} for more information about the action bar.
*/
public interface CollapsibleActionView {
/**
* Called when this view is expanded as an action view.
* See {@link MenuItem#expandActionView()}.
*/
public void onActionViewExpanded();
/**
* Called when this view is collapsed as an action view.
* See {@link MenuItem#collapseActionView()}.
*/
public void onActionViewCollapsed();
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/view/CollapsibleActionView.java | Java | asf20 | 1,402 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* 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 com.actionbarsherlock.view;
import android.content.Context;
import android.view.View;
/**
* This class is a mediator for accomplishing a given task, for example sharing a file.
* It is responsible for creating a view that performs an action that accomplishes the task.
* This class also implements other functions such a performing a default action.
* <p>
* An ActionProvider can be optionally specified for a {@link MenuItem} and in such a
* case it will be responsible for creating the action view that appears in the
* {@link android.app.ActionBar} as a substitute for the menu item when the item is
* displayed as an action item. Also the provider is responsible for performing a
* default action if a menu item placed on the overflow menu of the ActionBar is
* selected and none of the menu item callbacks has handled the selection. For this
* case the provider can also optionally provide a sub-menu for accomplishing the
* task at hand.
* </p>
* <p>
* There are two ways for using an action provider for creating and handling of action views:
* <ul>
* <li>
* Setting the action provider on a {@link MenuItem} directly by calling
* {@link MenuItem#setActionProvider(ActionProvider)}.
* </li>
* <li>
* Declaring the action provider in the menu XML resource. For example:
* <pre>
* <code>
* <item android:id="@+id/my_menu_item"
* android:title="Title"
* android:icon="@drawable/my_menu_item_icon"
* android:showAsAction="ifRoom"
* android:actionProviderClass="foo.bar.SomeActionProvider" />
* </code>
* </pre>
* </li>
* </ul>
* </p>
*
* @see MenuItem#setActionProvider(ActionProvider)
* @see MenuItem#getActionProvider()
*/
public abstract class ActionProvider {
private SubUiVisibilityListener mSubUiVisibilityListener;
/**
* Creates a new instance.
*
* @param context Context for accessing resources.
*/
public ActionProvider(Context context) {
}
/**
* Factory method for creating new action views.
*
* @return A new action view.
*/
public abstract View onCreateActionView();
/**
* Performs an optional default action.
* <p>
* For the case of an action provider placed in a menu item not shown as an action this
* method is invoked if previous callbacks for processing menu selection has handled
* the event.
* </p>
* <p>
* A menu item selection is processed in the following order:
* <ul>
* <li>
* Receiving a call to {@link MenuItem.OnMenuItemClickListener#onMenuItemClick
* MenuItem.OnMenuItemClickListener.onMenuItemClick}.
* </li>
* <li>
* Receiving a call to {@link android.app.Activity#onOptionsItemSelected(MenuItem)
* Activity.onOptionsItemSelected(MenuItem)}
* </li>
* <li>
* Receiving a call to {@link android.app.Fragment#onOptionsItemSelected(MenuItem)
* Fragment.onOptionsItemSelected(MenuItem)}
* </li>
* <li>
* Launching the {@link android.content.Intent} set via
* {@link MenuItem#setIntent(android.content.Intent) MenuItem.setIntent(android.content.Intent)}
* </li>
* <li>
* Invoking this method.
* </li>
* </ul>
* </p>
* <p>
* The default implementation does not perform any action and returns false.
* </p>
*/
public boolean onPerformDefaultAction() {
return false;
}
/**
* Determines if this ActionProvider has a submenu associated with it.
*
* <p>Associated submenus will be shown when an action view is not. This
* provider instance will receive a call to {@link #onPrepareSubMenu(SubMenu)}
* after the call to {@link #onPerformDefaultAction()} and before a submenu is
* displayed to the user.
*
* @return true if the item backed by this provider should have an associated submenu
*/
public boolean hasSubMenu() {
return false;
}
/**
* Called to prepare an associated submenu for the menu item backed by this ActionProvider.
*
* <p>if {@link #hasSubMenu()} returns true, this method will be called when the
* menu item is selected to prepare the submenu for presentation to the user. Apps
* may use this to create or alter submenu content right before display.
*
* @param subMenu Submenu that will be displayed
*/
public void onPrepareSubMenu(SubMenu subMenu) {
}
/**
* Notify the system that the visibility of an action view's sub-UI such as
* an anchored popup has changed. This will affect how other system
* visibility notifications occur.
*
* @hide Pending future API approval
*/
public void subUiVisibilityChanged(boolean isVisible) {
if (mSubUiVisibilityListener != null) {
mSubUiVisibilityListener.onSubUiVisibilityChanged(isVisible);
}
}
/**
* @hide Internal use only
*/
public void setSubUiVisibilityListener(SubUiVisibilityListener listener) {
mSubUiVisibilityListener = listener;
}
/**
* @hide Internal use only
*/
public interface SubUiVisibilityListener {
public void onSubUiVisibilityChanged(boolean isVisible);
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/view/ActionProvider.java | Java | asf20 | 5,865 |
/*
* Copyright (C) 2006 The Android Open Source Project
* 2011 Jake Wharton
*
* 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 com.actionbarsherlock.view;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.TypedArray;
import android.content.res.XmlResourceParser;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.view.InflateException;
import android.view.View;
import com.actionbarsherlock.R;
import com.actionbarsherlock.internal.view.menu.MenuItemImpl;
/**
* This class is used to instantiate menu XML files into Menu objects.
* <p>
* For performance reasons, menu inflation relies heavily on pre-processing of
* XML files that is done at build time. Therefore, it is not currently possible
* to use MenuInflater with an XmlPullParser over a plain XML file at runtime;
* it only works with an XmlPullParser returned from a compiled resource (R.
* <em>something</em> file.)
*/
public class MenuInflater {
private static final String LOG_TAG = "MenuInflater";
/** Menu tag name in XML. */
private static final String XML_MENU = "menu";
/** Group tag name in XML. */
private static final String XML_GROUP = "group";
/** Item tag name in XML. */
private static final String XML_ITEM = "item";
private static final int NO_ID = 0;
private static final Class<?>[] ACTION_VIEW_CONSTRUCTOR_SIGNATURE = new Class[] {Context.class};
private static final Class<?>[] ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE = ACTION_VIEW_CONSTRUCTOR_SIGNATURE;
private final Object[] mActionViewConstructorArguments;
private final Object[] mActionProviderConstructorArguments;
private Context mContext;
/**
* Constructs a menu inflater.
*
* @see Activity#getMenuInflater()
*/
public MenuInflater(Context context) {
mContext = context;
mActionViewConstructorArguments = new Object[] {context};
mActionProviderConstructorArguments = mActionViewConstructorArguments;
}
/**
* Inflate a menu hierarchy from the specified XML resource. Throws
* {@link InflateException} if there is an error.
*
* @param menuRes Resource ID for an XML layout resource to load (e.g.,
* <code>R.menu.main_activity</code>)
* @param menu The Menu to inflate into. The items and submenus will be
* added to this Menu.
*/
public void inflate(int menuRes, Menu menu) {
XmlResourceParser parser = null;
try {
parser = mContext.getResources().getLayout(menuRes);
AttributeSet attrs = Xml.asAttributeSet(parser);
parseMenu(parser, attrs, menu);
} catch (XmlPullParserException e) {
throw new InflateException("Error inflating menu XML", e);
} catch (IOException e) {
throw new InflateException("Error inflating menu XML", e);
} finally {
if (parser != null) parser.close();
}
}
/**
* Called internally to fill the given menu. If a sub menu is seen, it will
* call this recursively.
*/
private void parseMenu(XmlPullParser parser, AttributeSet attrs, Menu menu)
throws XmlPullParserException, IOException {
MenuState menuState = new MenuState(menu);
int eventType = parser.getEventType();
String tagName;
boolean lookingForEndOfUnknownTag = false;
String unknownTagName = null;
// This loop will skip to the menu start tag
do {
if (eventType == XmlPullParser.START_TAG) {
tagName = parser.getName();
if (tagName.equals(XML_MENU)) {
// Go to next tag
eventType = parser.next();
break;
}
throw new RuntimeException("Expecting menu, got " + tagName);
}
eventType = parser.next();
} while (eventType != XmlPullParser.END_DOCUMENT);
boolean reachedEndOfMenu = false;
while (!reachedEndOfMenu) {
switch (eventType) {
case XmlPullParser.START_TAG:
if (lookingForEndOfUnknownTag) {
break;
}
tagName = parser.getName();
if (tagName.equals(XML_GROUP)) {
menuState.readGroup(attrs);
} else if (tagName.equals(XML_ITEM)) {
menuState.readItem(attrs);
} else if (tagName.equals(XML_MENU)) {
// A menu start tag denotes a submenu for an item
SubMenu subMenu = menuState.addSubMenuItem();
// Parse the submenu into returned SubMenu
parseMenu(parser, attrs, subMenu);
} else {
lookingForEndOfUnknownTag = true;
unknownTagName = tagName;
}
break;
case XmlPullParser.END_TAG:
tagName = parser.getName();
if (lookingForEndOfUnknownTag && tagName.equals(unknownTagName)) {
lookingForEndOfUnknownTag = false;
unknownTagName = null;
} else if (tagName.equals(XML_GROUP)) {
menuState.resetGroup();
} else if (tagName.equals(XML_ITEM)) {
// Add the item if it hasn't been added (if the item was
// a submenu, it would have been added already)
if (!menuState.hasAddedItem()) {
if (menuState.itemActionProvider != null &&
menuState.itemActionProvider.hasSubMenu()) {
menuState.addSubMenuItem();
} else {
menuState.addItem();
}
}
} else if (tagName.equals(XML_MENU)) {
reachedEndOfMenu = true;
}
break;
case XmlPullParser.END_DOCUMENT:
throw new RuntimeException("Unexpected end of document");
}
eventType = parser.next();
}
}
private static class InflatedOnMenuItemClickListener
implements MenuItem.OnMenuItemClickListener {
private static final Class<?>[] PARAM_TYPES = new Class[] { MenuItem.class };
private Context mContext;
private Method mMethod;
public InflatedOnMenuItemClickListener(Context context, String methodName) {
mContext = context;
Class<?> c = context.getClass();
try {
mMethod = c.getMethod(methodName, PARAM_TYPES);
} catch (Exception e) {
InflateException ex = new InflateException(
"Couldn't resolve menu item onClick handler " + methodName +
" in class " + c.getName());
ex.initCause(e);
throw ex;
}
}
public boolean onMenuItemClick(MenuItem item) {
try {
if (mMethod.getReturnType() == Boolean.TYPE) {
return (Boolean) mMethod.invoke(mContext, item);
} else {
mMethod.invoke(mContext, item);
return true;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
/**
* State for the current menu.
* <p>
* Groups can not be nested unless there is another menu (which will have
* its state class).
*/
private class MenuState {
private Menu menu;
/*
* Group state is set on items as they are added, allowing an item to
* override its group state. (As opposed to set on items at the group end tag.)
*/
private int groupId;
private int groupCategory;
private int groupOrder;
private int groupCheckable;
private boolean groupVisible;
private boolean groupEnabled;
private boolean itemAdded;
private int itemId;
private int itemCategoryOrder;
private CharSequence itemTitle;
private CharSequence itemTitleCondensed;
private int itemIconResId;
private char itemAlphabeticShortcut;
private char itemNumericShortcut;
/**
* Sync to attrs.xml enum:
* - 0: none
* - 1: all
* - 2: exclusive
*/
private int itemCheckable;
private boolean itemChecked;
private boolean itemVisible;
private boolean itemEnabled;
/**
* Sync to attrs.xml enum, values in MenuItem:
* - 0: never
* - 1: ifRoom
* - 2: always
* - -1: Safe sentinel for "no value".
*/
private int itemShowAsAction;
private int itemActionViewLayout;
private String itemActionViewClassName;
private String itemActionProviderClassName;
private String itemListenerMethodName;
private ActionProvider itemActionProvider;
private static final int defaultGroupId = NO_ID;
private static final int defaultItemId = NO_ID;
private static final int defaultItemCategory = 0;
private static final int defaultItemOrder = 0;
private static final int defaultItemCheckable = 0;
private static final boolean defaultItemChecked = false;
private static final boolean defaultItemVisible = true;
private static final boolean defaultItemEnabled = true;
public MenuState(final Menu menu) {
this.menu = menu;
resetGroup();
}
public void resetGroup() {
groupId = defaultGroupId;
groupCategory = defaultItemCategory;
groupOrder = defaultItemOrder;
groupCheckable = defaultItemCheckable;
groupVisible = defaultItemVisible;
groupEnabled = defaultItemEnabled;
}
/**
* Called when the parser is pointing to a group tag.
*/
public void readGroup(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.SherlockMenuGroup);
groupId = a.getResourceId(R.styleable.SherlockMenuGroup_android_id, defaultGroupId);
groupCategory = a.getInt(R.styleable.SherlockMenuGroup_android_menuCategory, defaultItemCategory);
groupOrder = a.getInt(R.styleable.SherlockMenuGroup_android_orderInCategory, defaultItemOrder);
groupCheckable = a.getInt(R.styleable.SherlockMenuGroup_android_checkableBehavior, defaultItemCheckable);
groupVisible = a.getBoolean(R.styleable.SherlockMenuGroup_android_visible, defaultItemVisible);
groupEnabled = a.getBoolean(R.styleable.SherlockMenuGroup_android_enabled, defaultItemEnabled);
a.recycle();
}
/**
* Called when the parser is pointing to an item tag.
*/
public void readItem(AttributeSet attrs) {
TypedArray a = mContext.obtainStyledAttributes(attrs,
R.styleable.SherlockMenuItem);
// Inherit attributes from the group as default value
itemId = a.getResourceId(R.styleable.SherlockMenuItem_android_id, defaultItemId);
final int category = a.getInt(R.styleable.SherlockMenuItem_android_menuCategory, groupCategory);
final int order = a.getInt(R.styleable.SherlockMenuItem_android_orderInCategory, groupOrder);
itemCategoryOrder = (category & Menu.CATEGORY_MASK) | (order & Menu.USER_MASK);
itemTitle = a.getText(R.styleable.SherlockMenuItem_android_title);
itemTitleCondensed = a.getText(R.styleable.SherlockMenuItem_android_titleCondensed);
itemIconResId = a.getResourceId(R.styleable.SherlockMenuItem_android_icon, 0);
itemAlphabeticShortcut =
getShortcut(a.getString(R.styleable.SherlockMenuItem_android_alphabeticShortcut));
itemNumericShortcut =
getShortcut(a.getString(R.styleable.SherlockMenuItem_android_numericShortcut));
if (a.hasValue(R.styleable.SherlockMenuItem_android_checkable)) {
// Item has attribute checkable, use it
itemCheckable = a.getBoolean(R.styleable.SherlockMenuItem_android_checkable, false) ? 1 : 0;
} else {
// Item does not have attribute, use the group's (group can have one more state
// for checkable that represents the exclusive checkable)
itemCheckable = groupCheckable;
}
itemChecked = a.getBoolean(R.styleable.SherlockMenuItem_android_checked, defaultItemChecked);
itemVisible = a.getBoolean(R.styleable.SherlockMenuItem_android_visible, groupVisible);
itemEnabled = a.getBoolean(R.styleable.SherlockMenuItem_android_enabled, groupEnabled);
TypedValue value = new TypedValue();
a.getValue(R.styleable.SherlockMenuItem_android_showAsAction, value);
itemShowAsAction = value.type == TypedValue.TYPE_INT_HEX ? value.data : -1;
itemListenerMethodName = a.getString(R.styleable.SherlockMenuItem_android_onClick);
itemActionViewLayout = a.getResourceId(R.styleable.SherlockMenuItem_android_actionLayout, 0);
itemActionViewClassName = a.getString(R.styleable.SherlockMenuItem_android_actionViewClass);
itemActionProviderClassName = a.getString(R.styleable.SherlockMenuItem_android_actionProviderClass);
final boolean hasActionProvider = itemActionProviderClassName != null;
if (hasActionProvider && itemActionViewLayout == 0 && itemActionViewClassName == null) {
itemActionProvider = newInstance(itemActionProviderClassName,
ACTION_PROVIDER_CONSTRUCTOR_SIGNATURE,
mActionProviderConstructorArguments);
} else {
if (hasActionProvider) {
Log.w(LOG_TAG, "Ignoring attribute 'actionProviderClass'."
+ " Action view already specified.");
}
itemActionProvider = null;
}
a.recycle();
itemAdded = false;
}
private char getShortcut(String shortcutString) {
if (shortcutString == null) {
return 0;
} else {
return shortcutString.charAt(0);
}
}
private void setItem(MenuItem item) {
item.setChecked(itemChecked)
.setVisible(itemVisible)
.setEnabled(itemEnabled)
.setCheckable(itemCheckable >= 1)
.setTitleCondensed(itemTitleCondensed)
.setIcon(itemIconResId)
.setAlphabeticShortcut(itemAlphabeticShortcut)
.setNumericShortcut(itemNumericShortcut);
if (itemShowAsAction >= 0) {
item.setShowAsAction(itemShowAsAction);
}
if (itemListenerMethodName != null) {
if (mContext.isRestricted()) {
throw new IllegalStateException("The android:onClick attribute cannot "
+ "be used within a restricted context");
}
item.setOnMenuItemClickListener(
new InflatedOnMenuItemClickListener(mContext, itemListenerMethodName));
}
if (itemCheckable >= 2) {
if (item instanceof MenuItemImpl) {
MenuItemImpl impl = (MenuItemImpl) item;
impl.setExclusiveCheckable(true);
} else {
menu.setGroupCheckable(groupId, true, true);
}
}
boolean actionViewSpecified = false;
if (itemActionViewClassName != null) {
View actionView = (View) newInstance(itemActionViewClassName,
ACTION_VIEW_CONSTRUCTOR_SIGNATURE, mActionViewConstructorArguments);
item.setActionView(actionView);
actionViewSpecified = true;
}
if (itemActionViewLayout > 0) {
if (!actionViewSpecified) {
item.setActionView(itemActionViewLayout);
actionViewSpecified = true;
} else {
Log.w(LOG_TAG, "Ignoring attribute 'itemActionViewLayout'."
+ " Action view already specified.");
}
}
if (itemActionProvider != null) {
item.setActionProvider(itemActionProvider);
}
}
public void addItem() {
itemAdded = true;
setItem(menu.add(groupId, itemId, itemCategoryOrder, itemTitle));
}
public SubMenu addSubMenuItem() {
itemAdded = true;
SubMenu subMenu = menu.addSubMenu(groupId, itemId, itemCategoryOrder, itemTitle);
setItem(subMenu.getItem());
return subMenu;
}
public boolean hasAddedItem() {
return itemAdded;
}
@SuppressWarnings("unchecked")
private <T> T newInstance(String className, Class<?>[] constructorSignature,
Object[] arguments) {
try {
Class<?> clazz = mContext.getClassLoader().loadClass(className);
Constructor<?> constructor = clazz.getConstructor(constructorSignature);
return (T) constructor.newInstance(arguments);
} catch (Exception e) {
Log.w(LOG_TAG, "Cannot instantiate class: " + className, e);
}
return null;
}
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/view/MenuInflater.java | Java | asf20 | 19,430 |
/*
* Copyright (C) 2006 The Android Open Source Project
* Copyright (C) 2011 Jake Wharton
*
* 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 com.actionbarsherlock.view;
import android.content.Context;
/**
* <p>Abstract base class for a top-level window look and behavior policy. An
* instance of this class should be used as the top-level view added to the
* window manager. It provides standard UI policies such as a background, title
* area, default key processing, etc.</p>
*
* <p>The only existing implementation of this abstract class is
* android.policy.PhoneWindow, which you should instantiate when needing a
* Window. Eventually that class will be refactored and a factory method added
* for creating Window instances without knowing about a particular
* implementation.</p>
*/
public abstract class Window extends android.view.Window {
public static final long FEATURE_ACTION_BAR = android.view.Window.FEATURE_ACTION_BAR;
public static final long FEATURE_ACTION_BAR_OVERLAY = android.view.Window.FEATURE_ACTION_BAR_OVERLAY;
public static final long FEATURE_ACTION_MODE_OVERLAY = android.view.Window.FEATURE_ACTION_MODE_OVERLAY;
public static final long FEATURE_NO_TITLE = android.view.Window.FEATURE_NO_TITLE;
public static final long FEATURE_PROGRESS = android.view.Window.FEATURE_PROGRESS;
public static final long FEATURE_INDETERMINATE_PROGRESS = android.view.Window.FEATURE_INDETERMINATE_PROGRESS;
/**
* Create a new instance for a context.
*
* @param context Context.
*/
private Window(Context context) {
super(context);
}
public interface Callback {
/**
* Called when a panel's menu item has been selected by the user.
*
* @param featureId The panel that the menu is in.
* @param item The menu item that was selected.
*
* @return boolean Return true to finish processing of selection, or
* false to perform the normal menu handling (calling its
* Runnable or sending a Message to its target Handler).
*/
public boolean onMenuItemSelected(int featureId, MenuItem item);
}
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/view/Window.java | Java | asf20 | 2,778 |
/*
* Copyright (C) 2006 The Android Open Source Project
*
* 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 com.actionbarsherlock.view;
import android.content.ComponentName;
import android.content.Intent;
import android.view.KeyEvent;
/**
* Interface for managing the items in a menu.
* <p>
* By default, every Activity supports an options menu of actions or options.
* You can add items to this menu and handle clicks on your additions. The
* easiest way of adding menu items is inflating an XML file into the
* {@link Menu} via {@link MenuInflater}. The easiest way of attaching code to
* clicks is via {@link Activity#onOptionsItemSelected(MenuItem)} and
* {@link Activity#onContextItemSelected(MenuItem)}.
* <p>
* Different menu types support different features:
* <ol>
* <li><b>Context menus</b>: Do not support item shortcuts and item icons.
* <li><b>Options menus</b>: The <b>icon menus</b> do not support item check
* marks and only show the item's
* {@link MenuItem#setTitleCondensed(CharSequence) condensed title}. The
* <b>expanded menus</b> (only available if six or more menu items are visible,
* reached via the 'More' item in the icon menu) do not show item icons, and
* item check marks are discouraged.
* <li><b>Sub menus</b>: Do not support item icons, or nested sub menus.
* </ol>
*
* <div class="special reference">
* <h3>Developer Guides</h3>
* <p>For more information about creating menus, read the
* <a href="{@docRoot}guide/topics/ui/menus.html">Menus</a> developer guide.</p>
* </div>
*/
public interface Menu {
/**
* This is the part of an order integer that the user can provide.
* @hide
*/
static final int USER_MASK = 0x0000ffff;
/**
* Bit shift of the user portion of the order integer.
* @hide
*/
static final int USER_SHIFT = 0;
/**
* This is the part of an order integer that supplies the category of the
* item.
* @hide
*/
static final int CATEGORY_MASK = 0xffff0000;
/**
* Bit shift of the category portion of the order integer.
* @hide
*/
static final int CATEGORY_SHIFT = 16;
/**
* Value to use for group and item identifier integers when you don't care
* about them.
*/
static final int NONE = 0;
/**
* First value for group and item identifier integers.
*/
static final int FIRST = 1;
// Implementation note: Keep these CATEGORY_* in sync with the category enum
// in attrs.xml
/**
* Category code for the order integer for items/groups that are part of a
* container -- or/add this with your base value.
*/
static final int CATEGORY_CONTAINER = 0x00010000;
/**
* Category code for the order integer for items/groups that are provided by
* the system -- or/add this with your base value.
*/
static final int CATEGORY_SYSTEM = 0x00020000;
/**
* Category code for the order integer for items/groups that are
* user-supplied secondary (infrequently used) options -- or/add this with
* your base value.
*/
static final int CATEGORY_SECONDARY = 0x00030000;
/**
* Category code for the order integer for items/groups that are
* alternative actions on the data that is currently displayed -- or/add
* this with your base value.
*/
static final int CATEGORY_ALTERNATIVE = 0x00040000;
/**
* Flag for {@link #addIntentOptions}: if set, do not automatically remove
* any existing menu items in the same group.
*/
static final int FLAG_APPEND_TO_GROUP = 0x0001;
/**
* Flag for {@link #performShortcut}: if set, do not close the menu after
* executing the shortcut.
*/
static final int FLAG_PERFORM_NO_CLOSE = 0x0001;
/**
* Flag for {@link #performShortcut(int, KeyEvent, int)}: if set, always
* close the menu after executing the shortcut. Closing the menu also resets
* the prepared state.
*/
static final int FLAG_ALWAYS_PERFORM_CLOSE = 0x0002;
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param title The text to display for the item.
* @return The newly added menu item.
*/
public MenuItem add(CharSequence title);
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param titleRes Resource identifier of title string.
* @return The newly added menu item.
*/
public MenuItem add(int titleRes);
/**
* Add a new item to the menu. This item displays the given title for its
* label.
*
* @param groupId The group identifier that this item should be part of.
* This can be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param title The text to display for the item.
* @return The newly added menu item.
*/
public MenuItem add(int groupId, int itemId, int order, CharSequence title);
/**
* Variation on {@link #add(int, int, int, CharSequence)} that takes a
* string resource identifier instead of the string itself.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param titleRes Resource identifier of title string.
* @return The newly added menu item.
*/
public MenuItem add(int groupId, int itemId, int order, int titleRes);
/**
* Add a new sub-menu to the menu. This item displays the given title for
* its label. To modify other attributes on the submenu's menu item, use
* {@link SubMenu#getItem()}.
*
* @param title The text to display for the item.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final CharSequence title);
/**
* Add a new sub-menu to the menu. This item displays the given title for
* its label. To modify other attributes on the submenu's menu item, use
* {@link SubMenu#getItem()}.
*
* @param titleRes Resource identifier of title string.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final int titleRes);
/**
* Add a new sub-menu to the menu. This item displays the given
* <var>title</var> for its label. To modify other attributes on the
* submenu's menu item, use {@link SubMenu#getItem()}.
*<p>
* Note that you can only have one level of sub-menus, i.e. you cannnot add
* a subMenu to a subMenu: An {@link UnsupportedOperationException} will be
* thrown if you try.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a
* group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care
* about the order. See {@link MenuItem#getOrder()}.
* @param title The text to display for the item.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(final int groupId, final int itemId, int order, final CharSequence title);
/**
* Variation on {@link #addSubMenu(int, int, int, CharSequence)} that takes
* a string resource identifier for the title instead of the string itself.
*
* @param groupId The group identifier that this item should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if an item should not be in a group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a unique ID.
* @param order The order for the item. Use {@link #NONE} if you do not care about the
* order. See {@link MenuItem#getOrder()}.
* @param titleRes Resource identifier of title string.
* @return The newly added sub-menu
*/
SubMenu addSubMenu(int groupId, int itemId, int order, int titleRes);
/**
* Add a group of menu items corresponding to actions that can be performed
* for a particular Intent. The Intent is most often configured with a null
* action, the data that the current activity is working with, and includes
* either the {@link Intent#CATEGORY_ALTERNATIVE} or
* {@link Intent#CATEGORY_SELECTED_ALTERNATIVE} to find activities that have
* said they would like to be included as optional action. You can, however,
* use any Intent you want.
*
* <p>
* See {@link android.content.pm.PackageManager#queryIntentActivityOptions}
* for more * details on the <var>caller</var>, <var>specifics</var>, and
* <var>intent</var> arguments. The list returned by that function is used
* to populate the resulting menu items.
*
* <p>
* All of the menu items of possible options for the intent will be added
* with the given group and id. You can use the group to control ordering of
* the items in relation to other items in the menu. Normally this function
* will automatically remove any existing items in the menu in the same
* group and place a divider above and below the added items; this behavior
* can be modified with the <var>flags</var> parameter. For each of the
* generated items {@link MenuItem#setIntent} is called to associate the
* appropriate Intent with the item; this means the activity will
* automatically be started for you without having to do anything else.
*
* @param groupId The group identifier that the items should be part of.
* This can also be used to define groups of items for batch state
* changes. Normally use {@link #NONE} if the items should not be in
* a group.
* @param itemId Unique item ID. Use {@link #NONE} if you do not need a
* unique ID.
* @param order The order for the items. Use {@link #NONE} if you do not
* care about the order. See {@link MenuItem#getOrder()}.
* @param caller The current activity component name as defined by
* queryIntentActivityOptions().
* @param specifics Specific items to place first as defined by
* queryIntentActivityOptions().
* @param intent Intent describing the kinds of items to populate in the
* list as defined by queryIntentActivityOptions().
* @param flags Additional options controlling how the items are added.
* @param outSpecificItems Optional array in which to place the menu items
* that were generated for each of the <var>specifics</var> that were
* requested. Entries may be null if no activity was found for that
* specific action.
* @return The number of menu items that were added.
*
* @see #FLAG_APPEND_TO_GROUP
* @see MenuItem#setIntent
* @see android.content.pm.PackageManager#queryIntentActivityOptions
*/
public int addIntentOptions(int groupId, int itemId, int order,
ComponentName caller, Intent[] specifics,
Intent intent, int flags, MenuItem[] outSpecificItems);
/**
* Remove the item with the given identifier.
*
* @param id The item to be removed. If there is no item with this
* identifier, nothing happens.
*/
public void removeItem(int id);
/**
* Remove all items in the given group.
*
* @param groupId The group to be removed. If there are no items in this
* group, nothing happens.
*/
public void removeGroup(int groupId);
/**
* Remove all existing items from the menu, leaving it empty as if it had
* just been created.
*/
public void clear();
/**
* Control whether a particular group of items can show a check mark. This
* is similar to calling {@link MenuItem#setCheckable} on all of the menu items
* with the given group identifier, but in addition you can control whether
* this group contains a mutually-exclusive set items. This should be called
* after the items of the group have been added to the menu.
*
* @param group The group of items to operate on.
* @param checkable Set to true to allow a check mark, false to
* disallow. The default is false.
* @param exclusive If set to true, only one item in this group can be
* checked at a time; checking an item will automatically
* uncheck all others in the group. If set to false, each
* item can be checked independently of the others.
*
* @see MenuItem#setCheckable
* @see MenuItem#setChecked
*/
public void setGroupCheckable(int group, boolean checkable, boolean exclusive);
/**
* Show or hide all menu items that are in the given group.
*
* @param group The group of items to operate on.
* @param visible If true the items are visible, else they are hidden.
*
* @see MenuItem#setVisible
*/
public void setGroupVisible(int group, boolean visible);
/**
* Enable or disable all menu items that are in the given group.
*
* @param group The group of items to operate on.
* @param enabled If true the items will be enabled, else they will be disabled.
*
* @see MenuItem#setEnabled
*/
public void setGroupEnabled(int group, boolean enabled);
/**
* Return whether the menu currently has item items that are visible.
*
* @return True if there is one or more item visible,
* else false.
*/
public boolean hasVisibleItems();
/**
* Return the menu item with a particular identifier.
*
* @param id The identifier to find.
*
* @return The menu item object, or null if there is no item with
* this identifier.
*/
public MenuItem findItem(int id);
/**
* Get the number of items in the menu. Note that this will change any
* times items are added or removed from the menu.
*
* @return The item count.
*/
public int size();
/**
* Gets the menu item at the given index.
*
* @param index The index of the menu item to return.
* @return The menu item.
* @exception IndexOutOfBoundsException
* when {@code index < 0 || >= size()}
*/
public MenuItem getItem(int index);
/**
* Closes the menu, if open.
*/
public void close();
/**
* Execute the menu item action associated with the given shortcut
* character.
*
* @param keyCode The keycode of the shortcut key.
* @param event Key event message.
* @param flags Additional option flags or 0.
*
* @return If the given shortcut exists and is shown, returns
* true; else returns false.
*
* @see #FLAG_PERFORM_NO_CLOSE
*/
public boolean performShortcut(int keyCode, KeyEvent event, int flags);
/**
* Is a keypress one of the defined shortcut keys for this window.
* @param keyCode the key code from {@link KeyEvent} to check.
* @param event the {@link KeyEvent} to use to help check.
*/
boolean isShortcutKey(int keyCode, KeyEvent event);
/**
* Execute the menu item action associated with the given menu identifier.
*
* @param id Identifier associated with the menu item.
* @param flags Additional option flags or 0.
*
* @return If the given identifier exists and is shown, returns
* true; else returns false.
*
* @see #FLAG_PERFORM_NO_CLOSE
*/
public boolean performIdentifierAction(int id, int flags);
/**
* Control whether the menu should be running in qwerty mode (alphabetic
* shortcuts) or 12-key mode (numeric shortcuts).
*
* @param isQwerty If true the menu will use alphabetic shortcuts; else it
* will use numeric shortcuts.
*/
public void setQwertyMode(boolean isQwerty);
}
| 04146814d-23 | ActionBarSherlock4/src/com/actionbarsherlock/view/Menu.java | Java | asf20 | 17,460 |