Genericized all of our Collections extensions; switched numerous other classes
to typesafe 1.5 patterns; tidied some things up. Two impactful changes: - jora.Table now takes the class object of the row class, rather than its name; I also removed support for the derived table stuff as we don't use it and it was a PITA to make work cleanly with proper type-safety; - SortableArrayList got split into SortableArrayList (which does its sorting using a Comparator) and ComparableArrayList which contains elements that implement Comparable. In the world of loose typing, one class could do both, but in strong typing land, they have to be separate classes. git-svn-id: https://samskivert.googlecode.com/svn/trunk@1810 6335cc39-0255-0410-8fd6-9bcaacd3b74c
This commit is contained in:
@@ -59,28 +59,27 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* Inserts the supplied object into the specified table. The table
|
||||
* must be configured to store items of the supplied type.
|
||||
*/
|
||||
protected int insert (final Table table, final Object object)
|
||||
protected <T> int insert (final Table<T> table, final T object)
|
||||
throws PersistenceException
|
||||
{
|
||||
Integer iid = (Integer)execute(new Operation() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
return execute(new Operation<Integer>() {
|
||||
public Integer invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
table.insert(object);
|
||||
return new Integer(liaison.lastInsertedId(conn));
|
||||
return liaison.lastInsertedId(conn);
|
||||
}
|
||||
});
|
||||
return iid.intValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates the supplied object in the specified table. The table must
|
||||
* be configured to store items of the supplied type.
|
||||
*/
|
||||
protected void update (final Table table, final Object object)
|
||||
protected <T> void update (final Table<T> table, final T object)
|
||||
throws PersistenceException
|
||||
{
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
@@ -94,11 +93,13 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* Loads all objects from the specified table that match the supplied
|
||||
* query.
|
||||
*/
|
||||
protected ArrayList loadAll (final Table table, final String query)
|
||||
protected <T> ArrayList<T> loadAll (final Table<T> table,
|
||||
final String query)
|
||||
throws PersistenceException
|
||||
{
|
||||
return (ArrayList)execute(new Operation() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
return execute(new Operation<ArrayList<T>>() {
|
||||
public ArrayList<T> invoke (
|
||||
Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
return table.select(query).toArrayList();
|
||||
@@ -111,11 +112,11 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* supplied query. <em>Note:</em> the query should match one or zero
|
||||
* records, not more.
|
||||
*/
|
||||
protected Object load (final Table table, final String query)
|
||||
protected <T> T load (final Table<T> table, final String query)
|
||||
throws PersistenceException
|
||||
{
|
||||
return execute(new Operation() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
return execute(new Operation<T>() {
|
||||
public T invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
return table.select(query).get();
|
||||
@@ -128,11 +129,11 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* supplied example. <em>Note:</em> the query should match one or zero
|
||||
* records, not more.
|
||||
*/
|
||||
protected Object loadByExample (final Table table, final Object example)
|
||||
protected <T> T loadByExample (final Table<T> table, final T example)
|
||||
throws PersistenceException
|
||||
{
|
||||
return execute(new Operation() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
return execute(new Operation<T>() {
|
||||
public T invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
return table.queryByExample(example).get();
|
||||
@@ -145,12 +146,12 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* supplied example. <em>Note:</em> the query should match one or zero
|
||||
* records, not more.
|
||||
*/
|
||||
protected Object loadByExample (
|
||||
final Table table, final FieldMask mask, final Object example)
|
||||
protected <T> T loadByExample (
|
||||
final Table<T> table, final FieldMask mask, final T example)
|
||||
throws PersistenceException
|
||||
{
|
||||
return execute(new Operation() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
return execute(new Operation<T>() {
|
||||
public T invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
return table.queryByExample(example, mask).get();
|
||||
@@ -163,10 +164,10 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* zero rows, inserts the object into the specified table. The table
|
||||
* must be configured to store items of the supplied type.
|
||||
*/
|
||||
protected void store (final Table table, final Object object)
|
||||
protected <T> void store (final Table<T> table, final T object)
|
||||
throws PersistenceException
|
||||
{
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
@@ -182,13 +183,13 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* Updates the specified field in the supplied object (which must
|
||||
* correspond to the supplied table).
|
||||
*/
|
||||
protected void updateField (
|
||||
final Table table, final Object object, String field)
|
||||
protected <T> void updateField (
|
||||
final Table<T> table, final T object, String field)
|
||||
throws PersistenceException
|
||||
{
|
||||
final FieldMask mask = table.getFieldMask();
|
||||
mask.setModified(field);
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
@@ -202,15 +203,15 @@ public abstract class JORARepository extends SimpleRepository
|
||||
* Updates the specified fields in the supplied object (which must
|
||||
* correspond to the supplied table).
|
||||
*/
|
||||
protected void updateFields (
|
||||
final Table table, final Object object, String[] fields)
|
||||
protected <T> void updateFields (
|
||||
final Table<T> table, final T object, String[] fields)
|
||||
throws PersistenceException
|
||||
{
|
||||
final FieldMask mask = table.getFieldMask();
|
||||
for (int ii = 0; ii < fields.length; ii++) {
|
||||
mask.setModified(fields[ii]);
|
||||
}
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
@@ -220,10 +221,10 @@ public abstract class JORARepository extends SimpleRepository
|
||||
});
|
||||
}
|
||||
|
||||
protected void delete (final Table table, final Object object)
|
||||
protected <T> void delete (final Table<T> table, final T object)
|
||||
throws PersistenceException
|
||||
{
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
|
||||
@@ -45,13 +45,11 @@ public class LiaisonRegistry
|
||||
String url = dmd.getURL();
|
||||
|
||||
// see if we already have a liaison mapped for this connection
|
||||
DatabaseLiaison liaison = (DatabaseLiaison)_mappings.get(url);
|
||||
DatabaseLiaison liaison = _mappings.get(url);
|
||||
|
||||
if (liaison == null) {
|
||||
// scan the list looking for a matching liaison
|
||||
Iterator iter = _liaisons.iterator();
|
||||
while (iter.hasNext()) {
|
||||
DatabaseLiaison candidate = (DatabaseLiaison)iter.next();
|
||||
for (DatabaseLiaison candidate : _liaisons) {
|
||||
if (candidate.matchesURL(url)) {
|
||||
liaison = candidate;
|
||||
break;
|
||||
@@ -72,7 +70,8 @@ public class LiaisonRegistry
|
||||
return liaison;
|
||||
}
|
||||
|
||||
protected static void registerLiaisonClass (Class lclass)
|
||||
protected static void registerLiaisonClass (
|
||||
Class<? extends DatabaseLiaison> lclass)
|
||||
{
|
||||
// create a new instance and stick it on our list
|
||||
try {
|
||||
@@ -83,8 +82,10 @@ public class LiaisonRegistry
|
||||
}
|
||||
}
|
||||
|
||||
protected static ArrayList _liaisons = new ArrayList();
|
||||
protected static HashMap _mappings = new HashMap();
|
||||
protected static ArrayList<DatabaseLiaison> _liaisons =
|
||||
new ArrayList<DatabaseLiaison>();
|
||||
protected static HashMap<String,DatabaseLiaison> _mappings =
|
||||
new HashMap<String,DatabaseLiaison>();
|
||||
|
||||
// register our liaison classes
|
||||
static {
|
||||
|
||||
@@ -70,7 +70,7 @@ public class SimpleRepository extends Repository
|
||||
// give the repository a chance to do any schema migration before
|
||||
// things get further underway
|
||||
try {
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
@@ -257,7 +257,7 @@ public class SimpleRepository extends Repository
|
||||
protected void checkedUpdate (final String query, final int count)
|
||||
throws PersistenceException
|
||||
{
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
@@ -287,7 +287,7 @@ public class SimpleRepository extends Repository
|
||||
protected void maintenance (final String action, final String table)
|
||||
throws PersistenceException
|
||||
{
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws SQLException, PersistenceException
|
||||
{
|
||||
|
||||
@@ -130,7 +130,7 @@ public class StaticConnectionProvider implements ConnectionProvider
|
||||
public Connection getConnection (String ident)
|
||||
throws PersistenceException
|
||||
{
|
||||
Mapping conmap = (Mapping)_idents.get(ident);
|
||||
Mapping conmap = _idents.get(ident);
|
||||
|
||||
// open the connection if we haven't already
|
||||
if (conmap == null) {
|
||||
@@ -150,7 +150,7 @@ public class StaticConnectionProvider implements ConnectionProvider
|
||||
// we cache connections by username+url to avoid making more
|
||||
// that one connection to a particular database server
|
||||
String key = username + "@" + url;
|
||||
conmap = (Mapping)_keys.get(key);
|
||||
conmap = _keys.get(key);
|
||||
if (conmap == null) {
|
||||
Log.debug("Creating " + key + " for " + ident + ".");
|
||||
conmap = new Mapping();
|
||||
@@ -180,7 +180,7 @@ public class StaticConnectionProvider implements ConnectionProvider
|
||||
public void connectionFailed (String ident, Connection conn,
|
||||
SQLException error)
|
||||
{
|
||||
Mapping conmap = (Mapping)_idents.get(ident);
|
||||
Mapping conmap = _idents.get(ident);
|
||||
if (conmap == null) {
|
||||
Log.warning("Unknown connection failed!? [ident=" + ident + "].");
|
||||
return;
|
||||
@@ -249,17 +249,17 @@ public class StaticConnectionProvider implements ConnectionProvider
|
||||
public Connection connection;
|
||||
|
||||
/** The database identifiers that are mapped to this connection. */
|
||||
public ArrayList idents = new ArrayList();
|
||||
public ArrayList<String> idents = new ArrayList<String>();
|
||||
}
|
||||
|
||||
/** Our configuration in the form of a properties object. */
|
||||
protected Properties _props;
|
||||
|
||||
/** A mapping from database identifier to connection records. */
|
||||
protected HashMap _idents = new HashMap();
|
||||
protected HashMap<String,Mapping> _idents = new HashMap<String,Mapping>();
|
||||
|
||||
/** A mapping from connection key to connection records. */
|
||||
protected HashMap _keys = new HashMap();
|
||||
protected HashMap<String,Mapping> _keys = new HashMap<String,Mapping>();
|
||||
|
||||
/** The key used as defaults for the database definitions. */
|
||||
protected static final String DEFAULTS_KEY = "default";
|
||||
|
||||
@@ -38,18 +38,21 @@ public class Cursor<V>
|
||||
public V next ()
|
||||
throws SQLException
|
||||
{
|
||||
// if we closed everything up after the last call to next(),
|
||||
// nTables will be zero here and we should bail immediately
|
||||
if (nTables == 0) {
|
||||
// // if we closed everything up after the last call to next(),
|
||||
// // table will be null here and we should bail immediately
|
||||
if (table == null) {
|
||||
return null;
|
||||
}
|
||||
// if (nTables == 0) {
|
||||
// return null;
|
||||
// }
|
||||
|
||||
do {
|
||||
// do {
|
||||
if (result == null) {
|
||||
if (table.isAbstract) {
|
||||
table = table.derived;
|
||||
continue;
|
||||
}
|
||||
// if (table.isAbstract) {
|
||||
// table = table.derived;
|
||||
// continue;
|
||||
// }
|
||||
if (qbeObject != null) {
|
||||
PreparedStatement qbeStmt;
|
||||
synchronized(session.preparedStmtHash) {
|
||||
@@ -81,8 +84,9 @@ public class Cursor<V>
|
||||
result.close();
|
||||
result = null;
|
||||
currObject = null;
|
||||
table = table.derived;
|
||||
} while (--nTables != 0);
|
||||
table = null;
|
||||
// table = table.derived;
|
||||
// } while (--nTables != 0);
|
||||
|
||||
if (stmt != null) {
|
||||
stmt.close();
|
||||
@@ -170,7 +174,7 @@ public class Cursor<V>
|
||||
result = null;
|
||||
stmt = null;
|
||||
}
|
||||
nTables = 0;
|
||||
// nTables = 0;
|
||||
}
|
||||
|
||||
/** Extracts no more than <I>maxElements</I> records from database and
|
||||
@@ -186,7 +190,7 @@ public class Cursor<V>
|
||||
public ArrayList<V> toArrayList (int maxElements)
|
||||
throws SQLException
|
||||
{
|
||||
ArrayList<V> al = new ArrayList(Math.min(maxElements, 100));
|
||||
ArrayList<V> al = new ArrayList<V>(Math.min(maxElements, 100));
|
||||
V o;
|
||||
while (--maxElements >= 0 && (o = next()) != null) {
|
||||
al.add(o);
|
||||
@@ -217,7 +221,7 @@ public class Cursor<V>
|
||||
}
|
||||
this.table = table;
|
||||
this.session = session;
|
||||
this.nTables = nTables;
|
||||
// this.nTables = nTables;
|
||||
this.query = query;
|
||||
}
|
||||
|
||||
@@ -229,7 +233,7 @@ public class Cursor<V>
|
||||
}
|
||||
this.table = table;
|
||||
this.session = session;
|
||||
this.nTables = nTables;
|
||||
// this.nTables = nTables;
|
||||
this.like = like;
|
||||
qbeObject = obj;
|
||||
qbeMask = mask;
|
||||
@@ -239,7 +243,7 @@ public class Cursor<V>
|
||||
|
||||
private Table<V> table;
|
||||
private Session session;
|
||||
private int nTables;
|
||||
// private int nTables;
|
||||
private ResultSet result;
|
||||
private String query;
|
||||
private Statement stmt;
|
||||
|
||||
@@ -53,7 +53,7 @@ public class FieldMask
|
||||
public FieldMask (FieldDescriptor[] descrips)
|
||||
{
|
||||
// create a mapping from field name to descriptor index
|
||||
_descripMap = new HashMap();
|
||||
_descripMap = new HashMap<String,Integer>();
|
||||
int dcount = descrips.length;
|
||||
for (int i = 0; i < dcount; i++) {
|
||||
_descripMap.put(descrips[i].field.getName(), new Integer(i));
|
||||
@@ -89,7 +89,7 @@ public class FieldMask
|
||||
*/
|
||||
public final boolean isModified (String fieldName)
|
||||
{
|
||||
Integer index = (Integer)_descripMap.get(fieldName);
|
||||
Integer index = _descripMap.get(fieldName);
|
||||
if (index == null) {
|
||||
String errmsg = "Passed in field not in mask.";
|
||||
throw new IllegalArgumentException(errmsg);
|
||||
@@ -103,14 +103,11 @@ public class FieldMask
|
||||
*/
|
||||
public final boolean onlySubsetModified (Set fieldSet)
|
||||
{
|
||||
Iterator itr = _descripMap.keySet().iterator();
|
||||
while (itr.hasNext()) {
|
||||
String field = (String)itr.next();
|
||||
for (String field : _descripMap.keySet()) {
|
||||
if (isModified(field) && (!fieldSet.contains(field))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -119,7 +116,7 @@ public class FieldMask
|
||||
*/
|
||||
public void setModified (String fieldName)
|
||||
{
|
||||
Integer index = (Integer)_descripMap.get(fieldName);
|
||||
Integer index = _descripMap.get(fieldName);
|
||||
if (index == null) {
|
||||
String errmsg = "";
|
||||
throw new IllegalArgumentException(errmsg);
|
||||
@@ -156,9 +153,8 @@ public class FieldMask
|
||||
// return a list of the modified fields
|
||||
StringBuffer buf = new StringBuffer("FieldMask [modified={");
|
||||
boolean added = false;
|
||||
for (Iterator itr=_descripMap.entrySet().iterator(); itr.hasNext(); ) {
|
||||
Map.Entry entry = (Map.Entry) itr.next();
|
||||
if (_modified[((Integer) entry.getValue()).intValue()]) {
|
||||
for (Map.Entry<String,Integer> entry : _descripMap.entrySet()) {
|
||||
if (_modified[entry.getValue().intValue()]) {
|
||||
if (added) {
|
||||
buf.append(", ");
|
||||
} else {
|
||||
@@ -176,5 +172,5 @@ public class FieldMask
|
||||
protected boolean[] _modified;
|
||||
|
||||
/** A mapping from field names to field descriptor index. */
|
||||
protected HashMap _descripMap;
|
||||
protected HashMap<String,Integer> _descripMap;
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ public class Session {
|
||||
public Session(String driverClass)
|
||||
{
|
||||
driver = driverClass;
|
||||
preparedStmtHash = new Hashtable();
|
||||
preparedStmtHash = new Hashtable<String,PreparedStatement>();
|
||||
connectionID = 0;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ public class Session {
|
||||
public Session(Connection connection)
|
||||
{
|
||||
connectionID = 0;
|
||||
preparedStmtHash = new Hashtable();
|
||||
preparedStmtHash = new Hashtable<String,PreparedStatement>();
|
||||
setConnection(connection);
|
||||
}
|
||||
|
||||
@@ -57,10 +57,9 @@ public class Session {
|
||||
if (connection != conn) {
|
||||
// clear out our prepared statement hash because we've got a
|
||||
// new connection
|
||||
Enumeration items = preparedStmtHash.elements();
|
||||
while (items.hasMoreElements()) {
|
||||
for (PreparedStatement pstmt : preparedStmtHash.values()) {
|
||||
try {
|
||||
((PreparedStatement)items.nextElement()).close();
|
||||
pstmt.close();
|
||||
} catch (SQLException sqe) {
|
||||
Log.warning("Error closing cached prepared statement " +
|
||||
"[error=" + sqe + "].");
|
||||
@@ -134,17 +133,13 @@ public class Session {
|
||||
public void close()
|
||||
throws SQLException
|
||||
{
|
||||
// try {
|
||||
Enumeration items = preparedStmtHash.elements();
|
||||
while (items.hasMoreElements()) {
|
||||
((PreparedStatement)items.nextElement()).close();
|
||||
}
|
||||
preparedStmtHash.clear();
|
||||
if (connection != null) {
|
||||
connection.close();
|
||||
}
|
||||
// }
|
||||
// catch (SQLException ex) { handleSQLException(ex); }
|
||||
for (PreparedStatement pstmt : preparedStmtHash.values()) {
|
||||
pstmt.close();
|
||||
}
|
||||
preparedStmtHash.clear();
|
||||
if (connection != null) {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -197,7 +192,7 @@ public class Session {
|
||||
// } catch(SQLException ex) { handleSQLException(ex); }
|
||||
}
|
||||
|
||||
protected String driver; // driver class name
|
||||
protected Hashtable preparedStmtHash;
|
||||
protected int connectionID;
|
||||
protected String driver; // driver class name
|
||||
protected Hashtable<String,PreparedStatement> preparedStmtHash;
|
||||
protected int connectionID;
|
||||
}
|
||||
|
||||
@@ -146,25 +146,6 @@ public class Table<T>
|
||||
return new Cursor<T>(this, session, 1, query);
|
||||
}
|
||||
|
||||
/** Select records from specified and derived database tables
|
||||
*
|
||||
* @param condition valid SQL condition expression started with WHERE
|
||||
* or empty string if all records should be fetched.
|
||||
*/
|
||||
public final Cursor<T> selectAll(String condition) {
|
||||
return new Cursor<T>(this, session, nDerived+1, condition);
|
||||
}
|
||||
|
||||
/** Select records from specified and derived database tables
|
||||
*
|
||||
* @param condition valid SQL condition expression started with WHERE
|
||||
* or empty string if all records should be fetched.
|
||||
* @param session user database session
|
||||
*/
|
||||
public final Cursor<T> selectAll(String condition, Session session) {
|
||||
return new Cursor<T>(this, session, nDerived+1, condition);
|
||||
}
|
||||
|
||||
/** Select records from database table using <I>obj</I> object as
|
||||
* template.
|
||||
*
|
||||
@@ -245,32 +226,7 @@ public class Table<T>
|
||||
*/
|
||||
public final Cursor<T> queryByLikeExample(
|
||||
T obj, Session session, FieldMask mask) {
|
||||
return new Cursor(this, session, 1, obj, mask, true);
|
||||
}
|
||||
|
||||
/** Select records from specified and derived database tables using
|
||||
* <I>obj</I> object as template for selection. All non-builtin
|
||||
* fields of this object, which are not null, are compared with
|
||||
* correspondent table values.
|
||||
*
|
||||
* @param obj object for construction search condition: selected
|
||||
* objects should match all non-null fields of specified object.
|
||||
*/
|
||||
public final Cursor queryAllByExample(T obj) {
|
||||
return new Cursor(this, session, nDerived+1, obj, null, false);
|
||||
}
|
||||
|
||||
/** Select records from specified and derived database tables using
|
||||
* <I>obj</I> object as template for selection.
|
||||
* All non-builtin fields of this object,
|
||||
* which are not null, are compared with correspondent table values.
|
||||
*
|
||||
* @param obj object for construction search condition: selected objects
|
||||
* should match all non-null fields of specified object.
|
||||
* @param session user database session
|
||||
*/
|
||||
public final Cursor queryAllByExample(T obj, Session session) {
|
||||
return new Cursor(this, session, nDerived+1, obj, null, false);
|
||||
return new Cursor<T>(this, session, 1, obj, mask, true);
|
||||
}
|
||||
|
||||
/** Insert new record in the table. Values of inserted record fields
|
||||
@@ -639,8 +595,7 @@ public class Table<T>
|
||||
*/
|
||||
public String toString ()
|
||||
{
|
||||
return "[isAbstract=" + isAbstract + ", derived=" + derived +
|
||||
", nDerived=" + nDerived + ", name=" + name +
|
||||
return "[name=" + name +
|
||||
", primaryKeys=" + StringUtil.toString(primaryKeys) + "]";
|
||||
}
|
||||
|
||||
@@ -655,22 +610,20 @@ public class Table<T>
|
||||
|
||||
// --- Implementation -----------------------------------------
|
||||
|
||||
/** Is table abstract - not present in database.
|
||||
*/
|
||||
protected boolean isAbstract;
|
||||
protected Table derived;
|
||||
protected int nDerived;
|
||||
// /** Is table abstract - not present in database.
|
||||
// */
|
||||
// protected boolean isAbstract;
|
||||
// protected Table<?> derived;
|
||||
|
||||
protected String name;
|
||||
protected String listOfFields;
|
||||
protected String qualifiedListOfFields;
|
||||
protected String listOfAssignments;
|
||||
protected Class cls;
|
||||
protected Class<T> cls;
|
||||
protected Session session;
|
||||
|
||||
protected boolean mixedCaseConvert = false;
|
||||
|
||||
static private Class serializableClass;
|
||||
private FieldDescriptor[] fields;
|
||||
private FieldMask fMask;
|
||||
|
||||
@@ -686,10 +639,11 @@ public class Table<T>
|
||||
private PreparedStatement deleteStmt;
|
||||
private PreparedStatement insertStmt;
|
||||
|
||||
private static Table allTables;
|
||||
// private static Table<?> allTables;
|
||||
private Constructor<T> constructor;
|
||||
private static Method setBypass;
|
||||
|
||||
private static Class serializableClass;
|
||||
private static final Object[] bypassFlag = { new Boolean(true) };
|
||||
private static final Object[] constructorArgs = {};
|
||||
|
||||
@@ -709,17 +663,17 @@ public class Table<T>
|
||||
name = tableName;
|
||||
this.mixedCaseConvert = mixedCaseConvert;
|
||||
cls = clazz;
|
||||
isAbstract = tableName == null;
|
||||
// isAbstract = tableName == null;
|
||||
session = s;
|
||||
primaryKeys = keys;
|
||||
listOfFields = "";
|
||||
qualifiedListOfFields = "";
|
||||
listOfAssignments = "";
|
||||
connectionID = 0;
|
||||
Vector fieldsVector = new Vector();
|
||||
ArrayList<FieldDescriptor> fieldsVector =
|
||||
new ArrayList<FieldDescriptor>();
|
||||
nFields = buildFieldsList(fieldsVector, cls, "");
|
||||
fields = new FieldDescriptor[nFields];
|
||||
fieldsVector.copyInto(fields);
|
||||
fields = fieldsVector.toArray(new FieldDescriptor[nFields]);
|
||||
fMask = new FieldMask(fields);
|
||||
|
||||
try {
|
||||
@@ -749,51 +703,51 @@ public class Table<T>
|
||||
}
|
||||
}
|
||||
}
|
||||
insertIntoTableHierarchy();
|
||||
// insertIntoTableHierarchy();
|
||||
}
|
||||
|
||||
private final void insertIntoTableHierarchy()
|
||||
{
|
||||
Table t, prev = null;
|
||||
Table after = null;
|
||||
int nChilds = 0;
|
||||
for (t = allTables; t != null; prev = t, t = t.derived) {
|
||||
if (t.cls.isAssignableFrom(cls)) {
|
||||
if (primaryKeys == null && t.primaryKeys != null) {
|
||||
primaryKeys = t.primaryKeys;
|
||||
primaryKeyIndices = t.primaryKeyIndices;
|
||||
}
|
||||
if (session == null) {
|
||||
session = t.session;
|
||||
}
|
||||
t.nDerived += 1;
|
||||
after = t;
|
||||
} else if (cls.isAssignableFrom(t.cls)) {
|
||||
after = prev;
|
||||
do {
|
||||
if (cls.isAssignableFrom(t.cls)) {
|
||||
if (primaryKeys != null && t.primaryKeys == null) {
|
||||
t.primaryKeys = primaryKeys;
|
||||
t.primaryKeyIndices = primaryKeyIndices;
|
||||
}
|
||||
if (t.session == null) {
|
||||
t.session = session;
|
||||
}
|
||||
nChilds += 1;
|
||||
}
|
||||
} while ((t = t.derived) != null);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (after == null) {
|
||||
derived = allTables;
|
||||
allTables = this;
|
||||
} else {
|
||||
derived = after.derived;
|
||||
after.derived = this;
|
||||
}
|
||||
nDerived = nChilds;
|
||||
}
|
||||
// private final void insertIntoTableHierarchy()
|
||||
// {
|
||||
// Table<?> t, prev = null;
|
||||
// Table<?> after = null;
|
||||
// int nChilds = 0;
|
||||
// for (t = allTables; t != null; prev = t, t = t.derived) {
|
||||
// if (t.cls.isAssignableFrom(cls)) {
|
||||
// if (primaryKeys == null && t.primaryKeys != null) {
|
||||
// primaryKeys = t.primaryKeys;
|
||||
// primaryKeyIndices = t.primaryKeyIndices;
|
||||
// }
|
||||
// if (session == null) {
|
||||
// session = t.session;
|
||||
// }
|
||||
// t.nDerived += 1;
|
||||
// after = t;
|
||||
// } else if (cls.isAssignableFrom(t.cls)) {
|
||||
// after = prev;
|
||||
// do {
|
||||
// if (cls.isAssignableFrom(t.cls)) {
|
||||
// if (primaryKeys != null && t.primaryKeys == null) {
|
||||
// t.primaryKeys = primaryKeys;
|
||||
// t.primaryKeyIndices = primaryKeyIndices;
|
||||
// }
|
||||
// if (t.session == null) {
|
||||
// t.session = session;
|
||||
// }
|
||||
// nChilds += 1;
|
||||
// }
|
||||
// } while ((t = t.derived) != null);
|
||||
// break;
|
||||
// }
|
||||
// }
|
||||
// if (after == null) {
|
||||
// derived = allTables;
|
||||
// allTables = this;
|
||||
// } else {
|
||||
// derived = after.derived;
|
||||
// after.derived = this;
|
||||
// }
|
||||
// nDerived = nChilds;
|
||||
// }
|
||||
|
||||
private final void checkConnection(Session s) throws SQLException {
|
||||
if (connectionID != s.connectionID) {
|
||||
@@ -822,7 +776,8 @@ public class Table<T>
|
||||
}
|
||||
}
|
||||
|
||||
private final int buildFieldsList(Vector buf, Class cls, String prefix)
|
||||
private final int buildFieldsList(ArrayList<FieldDescriptor> buf, Class cls,
|
||||
String prefix)
|
||||
{
|
||||
Field[] f = cls.getDeclaredFields();
|
||||
|
||||
@@ -854,7 +809,7 @@ public class Table<T>
|
||||
FieldDescriptor fd = new FieldDescriptor(f[i], fullName);
|
||||
int type;
|
||||
|
||||
buf.addElement(fd);
|
||||
buf.add(fd);
|
||||
n += 1;
|
||||
|
||||
String c = fieldClass.getName();
|
||||
|
||||
@@ -23,7 +23,8 @@ public class AttachableURLFactory implements URLStreamHandlerFactory
|
||||
* @param protocol the protocol to register.
|
||||
* @param handlerClass a Class of type java.net.URLStreamHandler
|
||||
*/
|
||||
public static void attachHandler (String protocol, Class handlerClass)
|
||||
public static void attachHandler (
|
||||
String protocol, Class<? extends URLStreamHandler> handlerClass)
|
||||
{
|
||||
if (!URLStreamHandler.class.isAssignableFrom(handlerClass)) {
|
||||
throw new IllegalArgumentException(
|
||||
@@ -32,7 +33,7 @@ public class AttachableURLFactory implements URLStreamHandlerFactory
|
||||
|
||||
// set up the factory.
|
||||
if (_handlers == null) {
|
||||
_handlers = new HashMap();
|
||||
_handlers = new HashMap<String,Class<? extends URLStreamHandler>>();
|
||||
|
||||
// There are two ways to do this.
|
||||
|
||||
@@ -74,10 +75,11 @@ public class AttachableURLFactory implements URLStreamHandlerFactory
|
||||
// documentation inherited from interface URLStreamHandlerFactory
|
||||
public URLStreamHandler createURLStreamHandler (String protocol)
|
||||
{
|
||||
Class handler = (Class) _handlers.get(protocol.toLowerCase());
|
||||
Class<? extends URLStreamHandler> handler =
|
||||
_handlers.get(protocol.toLowerCase());
|
||||
if (handler != null) {
|
||||
try {
|
||||
return (URLStreamHandler) handler.newInstance();
|
||||
return handler.newInstance();
|
||||
} catch (Exception e) {
|
||||
Log.warning("Unable to instantiate URLStreamHandler" +
|
||||
" [protocol=" + protocol + ", cause=" + e + "].");
|
||||
@@ -87,5 +89,6 @@ public class AttachableURLFactory implements URLStreamHandlerFactory
|
||||
}
|
||||
|
||||
/** A mapping of protocol name to handler classes. */
|
||||
protected static HashMap _handlers;
|
||||
protected static HashMap<String,Class<? extends URLStreamHandler>>
|
||||
_handlers;
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ public class MACUtil
|
||||
{
|
||||
Matcher m = MACRegex.matcher(text);
|
||||
|
||||
ArrayList list = new ArrayList();
|
||||
ArrayList<String> list = new ArrayList<String>();
|
||||
while (m.find()) {
|
||||
String mac = m.group(1).toUpperCase();
|
||||
mac = mac.replace(':', '-');
|
||||
@@ -94,7 +94,7 @@ public class MACUtil
|
||||
list.add(mac);
|
||||
}
|
||||
|
||||
return (String[])list.toArray(new String[0]);
|
||||
return list.toArray(new String[0]);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -266,7 +266,7 @@ public class CDDB
|
||||
|
||||
} else if (rsp.code == 211 /* inexact matches */) {
|
||||
// read the matches from the server
|
||||
ArrayList list = new ArrayList();
|
||||
ArrayList<Entry> list = new ArrayList<Entry>();
|
||||
String input = _in.readLine();
|
||||
System.out.println("...: " + input);
|
||||
while (!input.equals(CDDBProtocol.TERMINATOR)) {
|
||||
@@ -349,8 +349,8 @@ public class CDDB
|
||||
detail.category = rsp.message.substring(0, sidx);
|
||||
detail.discid = rsp.message.substring(sidx+1);
|
||||
|
||||
ArrayList tnames = new ArrayList();
|
||||
ArrayList texts = new ArrayList();
|
||||
ArrayList<String> tnames = new ArrayList<String>();
|
||||
ArrayList<String> texts = new ArrayList<String>();
|
||||
|
||||
// now parse the contents
|
||||
String input = _in.readLine();
|
||||
@@ -439,7 +439,8 @@ public class CDDB
|
||||
* supplied index. If the list has no contents at the supplied
|
||||
* index, the supplied value becomes the contents at that index.
|
||||
*/
|
||||
protected final void append (ArrayList list, int index, String value)
|
||||
protected final void append (
|
||||
ArrayList<String> list, int index, String value)
|
||||
{
|
||||
// expand the list as necessary
|
||||
while (list.size() <= index) {
|
||||
|
||||
@@ -59,12 +59,12 @@ public class IndiscriminateSiteIdentifier implements SiteIdentifier
|
||||
}
|
||||
|
||||
// documented inherited from interface
|
||||
public Iterator enumerateSites ()
|
||||
public Iterator<Site> enumerateSites ()
|
||||
{
|
||||
return _sites.iterator();
|
||||
}
|
||||
|
||||
protected static ArrayList _sites = new ArrayList();
|
||||
protected static ArrayList<Site> _sites = new ArrayList<Site>();
|
||||
static {
|
||||
_sites.add(new Site(DEFAULT_SITE_ID, DEFAULT_SITE_STRING));
|
||||
}
|
||||
|
||||
@@ -95,7 +95,7 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
// scan for the mapping that matches the specified domain
|
||||
int msize = _mappings.size();
|
||||
for (int i = 0; i < msize; i++) {
|
||||
SiteMapping mapping = (SiteMapping)_mappings.get(i);
|
||||
SiteMapping mapping = _mappings.get(i);
|
||||
if (serverName.endsWith(mapping.domain)) {
|
||||
return mapping.siteId;
|
||||
}
|
||||
@@ -109,7 +109,7 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
public String getSiteString (int siteId)
|
||||
{
|
||||
checkReloadSites();
|
||||
Site site = (Site)_sitesById.get(siteId);
|
||||
Site site = _sitesById.get(siteId);
|
||||
return (site == null) ? DEFAULT_SITE_STRING : site.siteString;
|
||||
}
|
||||
|
||||
@@ -117,12 +117,12 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
public int getSiteId (String siteString)
|
||||
{
|
||||
checkReloadSites();
|
||||
Site site = (Site)_sitesByString.get(siteString);
|
||||
Site site = _sitesByString.get(siteString);
|
||||
return (site == null) ? DEFAULT_SITE_ID : site.siteId;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Iterator enumerateSites ()
|
||||
public Iterator<Site> enumerateSites ()
|
||||
{
|
||||
checkReloadSites();
|
||||
return _sitesById.values().iterator();
|
||||
@@ -131,6 +131,7 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
/**
|
||||
* Insert a new site into the site table and into this mapping.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public Site insertNewSite (String siteString)
|
||||
throws PersistenceException
|
||||
{
|
||||
@@ -143,10 +144,11 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
site.siteString = siteString;
|
||||
_repo.insertNewSite(site);
|
||||
|
||||
// add it to our two mapping tables,
|
||||
// avoiding causing enumerateSites() to choke
|
||||
HashMap newStrings = (HashMap) _sitesByString.clone();
|
||||
HashIntMap newIds = (HashIntMap) _sitesById.clone();
|
||||
// add it to our two mapping tables, taking care to avoid causing
|
||||
// enumerateSites() to choke
|
||||
HashMap<String,Site> newStrings = (HashMap<String,Site>)
|
||||
_sitesByString.clone();
|
||||
HashIntMap<Site> newIds = (HashIntMap<Site>)_sitesById.clone();
|
||||
newIds.put(site.siteId, site);
|
||||
newStrings.put(site.siteString, site);
|
||||
_sitesByString = newStrings;
|
||||
@@ -182,7 +184,7 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
* Used to load information from the site database.
|
||||
*/
|
||||
protected class SiteIdentifierRepository extends SimpleRepository
|
||||
implements SimpleRepository.Operation
|
||||
implements SimpleRepository.Operation<Object>
|
||||
{
|
||||
public SiteIdentifierRepository (ConnectionProvider conprov)
|
||||
{
|
||||
@@ -204,8 +206,8 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
// first load up the list of sites
|
||||
String query = "select siteId, siteString from sites";
|
||||
ResultSet rs = stmt.executeQuery(query);
|
||||
HashIntMap sites = new HashIntMap();
|
||||
HashMap strings = new HashMap();
|
||||
HashIntMap<Site> sites = new HashIntMap<Site>();
|
||||
HashMap<String,Site> strings = new HashMap<String,Site>();
|
||||
while (rs.next()) {
|
||||
Site site = new Site(rs.getInt(1), rs.getString(2));
|
||||
sites.put(site.siteId, site);
|
||||
@@ -217,7 +219,7 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
// now load up the domain mappings
|
||||
query = "select domain, siteId from domains";
|
||||
rs = stmt.executeQuery(query);
|
||||
ArrayList mappings = new ArrayList();
|
||||
ArrayList<SiteMapping> mappings = new ArrayList<SiteMapping>();
|
||||
while (rs.next()) {
|
||||
mappings.add(new SiteMapping(rs.getInt(2),
|
||||
rs.getString(1)));
|
||||
@@ -243,7 +245,7 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
public void insertNewSite (final Site site)
|
||||
throws PersistenceException
|
||||
{
|
||||
execute(new Operation() {
|
||||
execute(new Operation<Object>() {
|
||||
public Object invoke (Connection conn, DatabaseLiaison liaison)
|
||||
throws PersistenceException, SQLException
|
||||
{
|
||||
@@ -271,7 +273,7 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
/**
|
||||
* Used to track domain to site identifier mappings.
|
||||
*/
|
||||
protected static class SiteMapping implements Comparable
|
||||
protected static class SiteMapping implements Comparable<SiteMapping>
|
||||
{
|
||||
/** The domain to match. */
|
||||
public String domain;
|
||||
@@ -292,16 +294,9 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
* Site mappings sort from most specific (www.yahoo.com) to least
|
||||
* specific (yahoo.com).
|
||||
*/
|
||||
public int compareTo (Object other)
|
||||
public int compareTo (SiteMapping other)
|
||||
{
|
||||
if (other instanceof SiteMapping) {
|
||||
SiteMapping orec = (SiteMapping)other;
|
||||
return orec._rdomain.compareTo(_rdomain);
|
||||
} else {
|
||||
// no comparablo
|
||||
return getClass().getName().compareTo(
|
||||
other.getClass().getName());
|
||||
}
|
||||
return other._rdomain.compareTo(_rdomain);
|
||||
}
|
||||
|
||||
/** Returns a string representation of this site mapping. */
|
||||
@@ -319,15 +314,17 @@ public class JDBCTableSiteIdentifier implements SiteIdentifier
|
||||
|
||||
/** The list of domain to site identifier mappings ordered from most
|
||||
* specific domain to least specific. */
|
||||
protected volatile ArrayList _mappings = new ArrayList();
|
||||
protected volatile ArrayList<SiteMapping> _mappings =
|
||||
new ArrayList<SiteMapping>();
|
||||
|
||||
/** The mapping from integer site identifiers to string site
|
||||
* identifiers. */
|
||||
protected volatile HashIntMap _sitesById = new HashIntMap();
|
||||
protected volatile HashIntMap<Site> _sitesById = new HashIntMap<Site>();
|
||||
|
||||
/** The mapping from string site identifiers to integer site
|
||||
* identifiers. */
|
||||
protected volatile HashMap _sitesByString = new HashMap();
|
||||
protected volatile HashMap<String,Site> _sitesByString =
|
||||
new HashMap<String,Site>();
|
||||
|
||||
/** Used to periodically reload our site data. */
|
||||
protected long _lastReload;
|
||||
|
||||
@@ -86,5 +86,5 @@ public interface SiteIdentifier
|
||||
* Returns an enumerator over all {@link Site} mappings known to this
|
||||
* SiteIdentifier.
|
||||
*/
|
||||
public Iterator enumerateSites ();
|
||||
public Iterator<Site> enumerateSites ();
|
||||
}
|
||||
|
||||
@@ -155,7 +155,7 @@ public class SiteResourceLoader
|
||||
// is concurrently executing
|
||||
synchronized (getLock(siteId)) {
|
||||
// see if we've already got one
|
||||
ClassLoader loader = (ClassLoader)_loaders.get(siteId);
|
||||
ClassLoader loader = _loaders.get(siteId);
|
||||
|
||||
// create one if we've not
|
||||
if (loader == null) {
|
||||
@@ -211,8 +211,7 @@ public class SiteResourceLoader
|
||||
throws IOException
|
||||
{
|
||||
// look up the site resource bundle for this site
|
||||
SiteResourceBundle bundle = (SiteResourceBundle)
|
||||
_bundles.get(siteId);
|
||||
SiteResourceBundle bundle = _bundles.get(siteId);
|
||||
|
||||
// if we haven't got one, create one
|
||||
if (bundle == null) {
|
||||
@@ -364,13 +363,14 @@ public class SiteResourceLoader
|
||||
protected String _jarPath;
|
||||
|
||||
/** We synchronize on a per-site basis. */
|
||||
protected HashIntMap _locks = new HashIntMap();
|
||||
protected HashIntMap<Object> _locks = new HashIntMap<Object>();
|
||||
|
||||
/** The table of site-specific jar file information. */
|
||||
protected HashIntMap _bundles = new HashIntMap();
|
||||
protected HashIntMap<SiteResourceBundle> _bundles =
|
||||
new HashIntMap<SiteResourceBundle>();
|
||||
|
||||
/** The table of site-specific class loaders. */
|
||||
protected HashIntMap _loaders = new HashIntMap();
|
||||
protected HashIntMap<ClassLoader> _loaders = new HashIntMap<ClassLoader>();
|
||||
|
||||
/** The default path to the site-specific jar files. This won't be
|
||||
* used without logging a complaint first. */
|
||||
|
||||
@@ -74,13 +74,6 @@ public class UserRepository extends JORARepository
|
||||
super(provider, USER_REPOSITORY_IDENT);
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
protected void createTables (Session session)
|
||||
{
|
||||
// create our table object
|
||||
_utable = new Table<User>(User.class, "users", session, "userId");
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests that a new user be created in the repository.
|
||||
*
|
||||
@@ -151,10 +144,10 @@ public class UserRepository extends JORARepository
|
||||
String query = "where authcode = '" + sessionKey +
|
||||
"' AND sessions.userId = users.userId";
|
||||
// look up the user
|
||||
Cursor ec = _utable.select("sessions", query);
|
||||
Cursor<User> ec = _utable.select("sessions", query);
|
||||
|
||||
// fetch the user from the cursor
|
||||
User user = (User)ec.next();
|
||||
User user = ec.next();
|
||||
if (user != null) {
|
||||
// call next() again to cause the cursor to close itself
|
||||
ec.next();
|
||||
@@ -172,30 +165,29 @@ public class UserRepository extends JORARepository
|
||||
*
|
||||
* @return the users whom have a user id in the userIds array.
|
||||
*/
|
||||
public HashIntMap loadUsersFromId (int[] userIds)
|
||||
public HashIntMap<User> loadUsersFromId (int[] userIds)
|
||||
throws PersistenceException
|
||||
{
|
||||
// make sure we actually have something to do
|
||||
if (userIds.length == 0) {
|
||||
return new HashIntMap();
|
||||
return new HashIntMap<User>();
|
||||
}
|
||||
|
||||
final String ids = genIdString(userIds);
|
||||
|
||||
return execute(new Operation<HashIntMap>() {
|
||||
public HashIntMap invoke (Connection conn, DatabaseLiaison liaison)
|
||||
return execute(new Operation<HashIntMap<User>>() {
|
||||
public HashIntMap<User> invoke (Connection conn,
|
||||
DatabaseLiaison liaison)
|
||||
throws PersistenceException, SQLException
|
||||
{
|
||||
// look up the users
|
||||
Cursor ec = _utable.select("where userid in (" + ids + ")");
|
||||
|
||||
Cursor<User> ec = _utable.select(
|
||||
"where userid in (" + ids + ")");
|
||||
User user;
|
||||
HashIntMap data = new HashIntMap();
|
||||
while ((user = (User)ec.next()) != null) {
|
||||
HashIntMap<User> data = new HashIntMap<User>();
|
||||
while ((user = ec.next()) != null) {
|
||||
user.setDirtyMask(_utable.getFieldMask());
|
||||
data.put(user.userId, user);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
});
|
||||
@@ -236,14 +228,15 @@ public class UserRepository extends JORARepository
|
||||
throws PersistenceException
|
||||
{
|
||||
return execute(new Operation<ArrayList<User>>() {
|
||||
public ArrayList invoke (Connection conn, DatabaseLiaison liaison)
|
||||
public ArrayList<User> invoke (
|
||||
Connection conn, DatabaseLiaison liaison)
|
||||
throws PersistenceException, SQLException
|
||||
{
|
||||
ArrayList<User> users = (ArrayList<User>)
|
||||
ArrayList<User> users =
|
||||
_utable.select("where " + where).toArrayList();
|
||||
for (Iterator iter = users.iterator(); iter.hasNext(); ) {
|
||||
for (User user : users) {
|
||||
// configure the user record with its field mask
|
||||
((User)iter.next()).setDirtyMask(_utable.getFieldMask());
|
||||
user.setDirtyMask(_utable.getFieldMask());
|
||||
}
|
||||
return users;
|
||||
}
|
||||
@@ -416,14 +409,11 @@ public class UserRepository extends JORARepository
|
||||
|
||||
/**
|
||||
* Returns an array with the real names of every user in the system.
|
||||
* This is for Paul who whined about not knowing who was using Who,
|
||||
* Where, When because he didn't feel like emailing anyone that wasn't
|
||||
* already using it to link up.
|
||||
*/
|
||||
public String[] loadAllRealNames ()
|
||||
throws PersistenceException
|
||||
{
|
||||
final ArrayList names = new ArrayList();
|
||||
final ArrayList<String> names = new ArrayList<String>();
|
||||
|
||||
// do the query
|
||||
execute(new Operation<Object>() {
|
||||
@@ -448,9 +438,7 @@ public class UserRepository extends JORARepository
|
||||
});
|
||||
|
||||
// finally construct our result
|
||||
String[] result = new String[names.size()];
|
||||
names.toArray(result);
|
||||
return result;
|
||||
return names.toArray(new String[names.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -512,10 +500,10 @@ public class UserRepository extends JORARepository
|
||||
throws PersistenceException, SQLException
|
||||
{
|
||||
// look up the user
|
||||
Cursor ec = _utable.select(whereClause);
|
||||
Cursor<User> ec = _utable.select(whereClause);
|
||||
|
||||
// fetch the user from the cursor
|
||||
User user = (User)ec.next();
|
||||
User user = ec.next();
|
||||
if (user != null) {
|
||||
// call next() again to cause the cursor to close itself
|
||||
ec.next();
|
||||
@@ -538,7 +526,7 @@ public class UserRepository extends JORARepository
|
||||
|
||||
final String ids = genIdString(userIds);
|
||||
|
||||
final HashIntMap map = new HashIntMap();
|
||||
final HashIntMap<String> map = new HashIntMap<String>();
|
||||
|
||||
// do the query
|
||||
execute(new Operation<Object>() {
|
||||
@@ -569,7 +557,7 @@ public class UserRepository extends JORARepository
|
||||
// finally construct our result
|
||||
String[] result = new String[userIds.length];
|
||||
for (int i = 0; i < userIds.length; i++) {
|
||||
result[i] = (String)map.get(userIds[i]);
|
||||
result[i] = map.get(userIds[i]);
|
||||
}
|
||||
|
||||
return result;
|
||||
@@ -594,6 +582,13 @@ public class UserRepository extends JORARepository
|
||||
return ids.toString();
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
protected void createTables (Session session)
|
||||
{
|
||||
// create our table object
|
||||
_utable = new Table<User>(User.class, "users", session, "userId");
|
||||
}
|
||||
|
||||
/** A wrapper that provides access to the userstable. */
|
||||
protected Table _utable;
|
||||
protected Table<User> _utable;
|
||||
}
|
||||
|
||||
@@ -80,8 +80,8 @@ public class ExceptionMap
|
||||
if (_keys != null) {
|
||||
return;
|
||||
} else {
|
||||
_keys = new ArrayList();
|
||||
_values = new ArrayList();
|
||||
_keys = new ArrayList<Class>();
|
||||
_values = new ArrayList<String>();
|
||||
}
|
||||
|
||||
// first try loading the properties file without a leading slash
|
||||
@@ -93,14 +93,15 @@ public class ExceptionMap
|
||||
} else {
|
||||
// otherwise process ye old config file.
|
||||
try {
|
||||
// we'll do some serious jiggery pokery to leverage the
|
||||
// parsing implementation provided by
|
||||
// java.util.Properties. god bless method overloading
|
||||
Properties loader = new Properties() {
|
||||
// we'll do some serious jiggery pokery to leverage the parsing
|
||||
// implementation provided by java.util.Properties. god bless
|
||||
// method overloading
|
||||
final ArrayList<String> classes = new ArrayList<String>();
|
||||
Properties loader = new Properties() {
|
||||
public Object put (Object key, Object value)
|
||||
{
|
||||
_keys.add(key);
|
||||
_values.add(value);
|
||||
classes.add((String)key);
|
||||
_values.add((String)value);
|
||||
return key;
|
||||
}
|
||||
};
|
||||
@@ -108,18 +109,17 @@ public class ExceptionMap
|
||||
|
||||
// now cruise through and resolve the exceptions named as
|
||||
// keys and throw out any that don't appear to exist
|
||||
for (int i = 0; i < _keys.size(); i++) {
|
||||
String exclass = (String)_keys.get(i);
|
||||
for (int i = 0; i < classes.size(); i++) {
|
||||
String exclass = classes.get(i);
|
||||
try {
|
||||
Class cl = Class.forName(exclass);
|
||||
// replace the string with the class object
|
||||
_keys.set(i, cl);
|
||||
_keys.add(cl);
|
||||
|
||||
} catch (Throwable t) {
|
||||
Log.warning("Unable to resolve exception class. " +
|
||||
"[class=" + exclass +
|
||||
", error=" + t + "].");
|
||||
_keys.remove(i);
|
||||
_values.remove(i);
|
||||
i--; // back on up a notch
|
||||
}
|
||||
@@ -144,26 +144,18 @@ public class ExceptionMap
|
||||
public static String getMessage (Throwable ex)
|
||||
{
|
||||
String msg = DEFAULT_ERROR_MSG;
|
||||
|
||||
for (int i = 0; i < _keys.size(); i++) {
|
||||
Class cl = (Class)_keys.get(i);
|
||||
Class cl = _keys.get(i);
|
||||
if (cl.isInstance(ex)) {
|
||||
msg = (String)_values.get(i);
|
||||
msg = _values.get(i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return StringUtil.replace(msg, MESSAGE_MARKER, ex.getMessage());
|
||||
}
|
||||
|
||||
public static void main (String[] args)
|
||||
{
|
||||
ExceptionMap map = new ExceptionMap();
|
||||
System.out.println(ExceptionMap.getMessage(new Exception("Test error")));
|
||||
}
|
||||
|
||||
protected static List _keys;
|
||||
protected static List _values;
|
||||
protected static List<Class> _keys;
|
||||
protected static List<String> _values;
|
||||
|
||||
// initialize ourselves
|
||||
static { init(); }
|
||||
|
||||
@@ -146,10 +146,11 @@ public class ParameterUtil
|
||||
* Fetches all the values from the request with the specified name and
|
||||
* converts them to a HashSet.
|
||||
*/
|
||||
public static HashSet getParameters (HttpServletRequest req, String name)
|
||||
public static HashSet<String> getParameters (
|
||||
HttpServletRequest req, String name)
|
||||
throws DataValidationException
|
||||
{
|
||||
HashSet set = new HashSet();
|
||||
HashSet<String> set = new HashSet<String>();
|
||||
String[] values = req.getParameterValues(name);
|
||||
if (values != null) {
|
||||
for (int ii = 0; ii < values.length; ii++) {
|
||||
|
||||
@@ -157,5 +157,6 @@ public class AbsoluteLayout
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected HashMap _constraints = new HashMap();
|
||||
protected HashMap<Component,Object> _constraints =
|
||||
new HashMap<Component,Object>();
|
||||
}
|
||||
|
||||
@@ -212,9 +212,9 @@ public abstract class GroupLayout
|
||||
if (constraints != null) {
|
||||
if (constraints instanceof Constraints) {
|
||||
if (_constraints == null) {
|
||||
_constraints = new HashMap();
|
||||
_constraints = new HashMap<Component,Constraints>();
|
||||
}
|
||||
_constraints.put(comp, constraints);
|
||||
_constraints.put(comp, (Constraints)constraints);
|
||||
|
||||
} else {
|
||||
throw new RuntimeException("GroupLayout constraints " +
|
||||
@@ -268,7 +268,7 @@ public abstract class GroupLayout
|
||||
protected Constraints getConstraints (Component child)
|
||||
{
|
||||
if (_constraints != null) {
|
||||
Constraints c = (Constraints) _constraints.get(child);
|
||||
Constraints c = _constraints.get(child);
|
||||
if (c != null) {
|
||||
return c;
|
||||
}
|
||||
@@ -476,7 +476,7 @@ public abstract class GroupLayout
|
||||
protected Justification _justification = CENTER;
|
||||
protected Justification _offjust = CENTER;
|
||||
|
||||
protected HashMap _constraints;
|
||||
protected HashMap<Component,Constraints> _constraints;
|
||||
|
||||
protected static final int MINIMUM = 0;
|
||||
protected static final int PREFERRED = 1;
|
||||
|
||||
@@ -401,7 +401,7 @@ public class Label implements SwingConstants, LabelStyleConstants
|
||||
public void layout (Graphics2D gfx)
|
||||
{
|
||||
FontRenderContext frc = gfx.getFontRenderContext();
|
||||
ArrayList layouts = null;
|
||||
ArrayList<Tuple<TextLayout,Rectangle2D>> layouts = null;
|
||||
|
||||
// if we have a target height, do some processing and convert that
|
||||
// into a target width
|
||||
@@ -470,8 +470,8 @@ public class Label implements SwingConstants, LabelStyleConstants
|
||||
// for some reason JDK1.3 on Linux chokes on setSize(double,double)
|
||||
_size.setSize(Math.ceil(getWidth(bounds)),
|
||||
Math.ceil(getHeight(layout)));
|
||||
layouts = new ArrayList();
|
||||
layouts.add(new Tuple(layout, bounds));
|
||||
layouts = new ArrayList<Tuple<TextLayout,Rectangle2D>>();
|
||||
layouts.add(new Tuple<TextLayout,Rectangle2D>(layout, bounds));
|
||||
}
|
||||
|
||||
// create our layouts array
|
||||
@@ -480,9 +480,9 @@ public class Label implements SwingConstants, LabelStyleConstants
|
||||
_lbounds = new Rectangle2D[lcount];
|
||||
_leaders = new float[lcount];
|
||||
for (int ii = 0; ii < lcount; ii++) {
|
||||
Tuple tup = (Tuple)layouts.get(ii);
|
||||
_layouts[ii] = (TextLayout)tup.left;
|
||||
_lbounds[ii] = (Rectangle2D)tup.right;
|
||||
Tuple<TextLayout,Rectangle2D> tup = layouts.get(ii);
|
||||
_layouts[ii] = tup.left;
|
||||
_lbounds[ii] = tup.right;
|
||||
// account for potential leaders
|
||||
if (_lbounds[ii].getX() < 0) {
|
||||
_leaders[ii] = (float)-_lbounds[ii].getX();
|
||||
@@ -498,13 +498,14 @@ public class Label implements SwingConstants, LabelStyleConstants
|
||||
* @return an {@link ArrayList} or null if <code>keepWordsWhole</code>
|
||||
* was true and the lines could not be layed out in the target width.
|
||||
*/
|
||||
protected ArrayList computeLines (
|
||||
protected ArrayList<Tuple<TextLayout,Rectangle2D>> computeLines (
|
||||
LineBreakMeasurer measurer, int targetWidth, Dimension size,
|
||||
boolean keepWordsWhole)
|
||||
{
|
||||
// start with a size of zero
|
||||
double width = 0, height = 0;
|
||||
ArrayList layouts = new ArrayList();
|
||||
ArrayList<Tuple<TextLayout,Rectangle2D>> layouts =
|
||||
new ArrayList<Tuple<TextLayout,Rectangle2D>>();
|
||||
|
||||
try {
|
||||
// obtain our new dimensions by using a line break iterator to
|
||||
@@ -524,7 +525,7 @@ public class Label implements SwingConstants, LabelStyleConstants
|
||||
Rectangle2D bounds = getBounds(layout);
|
||||
width = Math.max(width, getWidth(bounds));
|
||||
height += getHeight(layout);
|
||||
layouts.add(new Tuple(layout, bounds));
|
||||
layouts.add(new Tuple<TextLayout,Rectangle2D>(layout, bounds));
|
||||
}
|
||||
|
||||
// fill in the computed size; for some reason JDK1.3 on Linux
|
||||
@@ -644,7 +645,7 @@ public class Label implements SwingConstants, LabelStyleConstants
|
||||
{
|
||||
// first set up any attributes that apply to the entire text
|
||||
Font font = (_font == null) ? gfx.getFont() : _font;
|
||||
HashMap map = new HashMap();
|
||||
HashMap<TextAttribute,Object> map = new HashMap<TextAttribute,Object>();
|
||||
map.put(TextAttribute.FONT, font);
|
||||
if ((_style & UNDERLINE) != 0) {
|
||||
map.put(TextAttribute.UNDERLINE,
|
||||
|
||||
@@ -184,7 +184,7 @@ public class ObjectEditorTable extends JTable
|
||||
/**
|
||||
* Set the data to be viewed or edited.
|
||||
*/
|
||||
public void setData (Collection data)
|
||||
public void setData (Collection<?> data)
|
||||
{
|
||||
_data.clear();
|
||||
_data.addAll(data);
|
||||
@@ -376,5 +376,5 @@ public class ObjectEditorTable extends JTable
|
||||
protected BitSet _editable = new BitSet();
|
||||
|
||||
/** The data being edited. */
|
||||
protected ArrayList _data = new ArrayList();
|
||||
protected ArrayList<Object> _data = new ArrayList<Object>();
|
||||
}
|
||||
|
||||
@@ -468,9 +468,9 @@ public class RadialMenu
|
||||
// notify our listeners that the action is posted
|
||||
final CommandEvent evt = new CommandEvent(
|
||||
_host.getComponent(), _activeItem.command, arg);
|
||||
_actlist.apply(new ObserverList.ObserverOp() {
|
||||
public boolean apply (Object obs) {
|
||||
((ActionListener)obs).actionPerformed(evt);
|
||||
_actlist.apply(new ObserverList.ObserverOp<ActionListener>() {
|
||||
public boolean apply (ActionListener obs) {
|
||||
obs.actionPerformed(evt);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
@@ -495,7 +495,7 @@ public class RadialMenu
|
||||
|
||||
// figure out which items are included
|
||||
int icount = _items.size();
|
||||
ArrayList items = new ArrayList();
|
||||
ArrayList<RadialMenuItem> items = new ArrayList<RadialMenuItem>();
|
||||
for (int i = 0; i < icount; i++) {
|
||||
RadialMenuItem item = (RadialMenuItem)_items.get(i);
|
||||
if (item.isIncluded(this)) {
|
||||
@@ -625,7 +625,8 @@ public class RadialMenu
|
||||
protected RadialLabelSausage _centerLabel;
|
||||
|
||||
/** Our menu items. */
|
||||
protected ArrayList _items = new ArrayList();
|
||||
protected ArrayList<RadialMenuItem> _items =
|
||||
new ArrayList<RadialMenuItem>();
|
||||
|
||||
/** The item that has the mouse over it presently, and the default item
|
||||
* if we're double clicked. */
|
||||
@@ -655,6 +656,6 @@ public class RadialMenu
|
||||
protected MouseHijacker _hijacker;
|
||||
|
||||
/** Maintains a list of action listeners. */
|
||||
protected ObserverList _actlist = new ObserverList(
|
||||
ObserverList.SAFE_IN_ORDER_NOTIFY);
|
||||
protected ObserverList<ActionListener> _actlist =
|
||||
new ObserverList<ActionListener>(ObserverList.SAFE_IN_ORDER_NOTIFY);
|
||||
}
|
||||
|
||||
+11
-10
@@ -1,7 +1,7 @@
|
||||
//
|
||||
// $Id: RuntimeAdjust.java,v 1.11 2004/02/25 13:20:44 mdb Exp $
|
||||
|
||||
package com.samskivert.util;
|
||||
package com.samskivert.swing;
|
||||
|
||||
import java.awt.Dimension;
|
||||
import java.awt.Font;
|
||||
@@ -30,10 +30,10 @@ import javax.swing.JTextField;
|
||||
import javax.swing.Scrollable;
|
||||
|
||||
import com.samskivert.Log;
|
||||
import com.samskivert.swing.CollapsiblePanel;
|
||||
import com.samskivert.swing.GroupLayout;
|
||||
import com.samskivert.swing.MultiLineLabel;
|
||||
import com.samskivert.swing.VGroupLayout;
|
||||
import com.samskivert.util.ComparableArrayList;
|
||||
import com.samskivert.util.Config;
|
||||
import com.samskivert.util.ListUtil;
|
||||
import com.samskivert.util.StringUtil;
|
||||
|
||||
/**
|
||||
* Provides a service where named variables can be registered as
|
||||
@@ -81,7 +81,7 @@ public class RuntimeAdjust
|
||||
|
||||
int acount = _adjusts.size();
|
||||
for (int ii = 0; ii < acount; ii++) {
|
||||
Adjust adjust = (Adjust)_adjusts.get(ii);
|
||||
Adjust adjust = _adjusts.get(ii);
|
||||
|
||||
// create a new library label if necessary
|
||||
if (!adjust.getLibrary().equals(library)) {
|
||||
@@ -461,7 +461,7 @@ public class RuntimeAdjust
|
||||
|
||||
/** Base class for type-specific adjustments. */
|
||||
protected abstract static class Adjust
|
||||
implements PropertyChangeListener, Comparable
|
||||
implements PropertyChangeListener, Comparable<Adjust>
|
||||
{
|
||||
public Adjust (String descrip, String name, Config config)
|
||||
{
|
||||
@@ -498,9 +498,9 @@ public class RuntimeAdjust
|
||||
return _name.equals(((Adjust)other)._name);
|
||||
}
|
||||
|
||||
public int compareTo (Object other)
|
||||
public int compareTo (Adjust other)
|
||||
{
|
||||
return _name.compareTo(((Adjust)other)._name);
|
||||
return _name.compareTo(other._name);
|
||||
}
|
||||
|
||||
public String getName ()
|
||||
@@ -553,5 +553,6 @@ public class RuntimeAdjust
|
||||
protected JPanel _editor;
|
||||
}
|
||||
|
||||
protected static SortableArrayList _adjusts = new SortableArrayList();
|
||||
protected static ComparableArrayList<Adjust> _adjusts =
|
||||
new ComparableArrayList<Adjust>();
|
||||
}
|
||||
@@ -91,8 +91,9 @@ public class TableSorter extends AbstractTableModel {
|
||||
private JTableHeader tableHeader;
|
||||
private MouseListener mouseListener;
|
||||
private TableModelListener tableModelListener;
|
||||
private Map columnComparators = new HashMap();
|
||||
private List sortingColumns = new ArrayList();
|
||||
private Map<Class,Comparator<Object>> columnComparators =
|
||||
new HashMap<Class,Comparator<Object>>();
|
||||
private List<Directive> sortingColumns = new ArrayList<Directive>();
|
||||
|
||||
public TableSorter() {
|
||||
this.mouseListener = new MouseHandler();
|
||||
@@ -159,7 +160,7 @@ public class TableSorter extends AbstractTableModel {
|
||||
|
||||
private Directive getDirective(int column) {
|
||||
for (int i = 0; i < sortingColumns.size(); i++) {
|
||||
Directive directive = (Directive)sortingColumns.get(i);
|
||||
Directive directive = sortingColumns.get(i);
|
||||
if (directive.column == column) {
|
||||
return directive;
|
||||
}
|
||||
@@ -203,7 +204,7 @@ public class TableSorter extends AbstractTableModel {
|
||||
sortingStatusChanged();
|
||||
}
|
||||
|
||||
public void setColumnComparator(Class type, Comparator comparator) {
|
||||
public void setColumnComparator(Class type, Comparator<Object> comparator) {
|
||||
if (comparator == null) {
|
||||
columnComparators.remove(type);
|
||||
} else {
|
||||
@@ -211,9 +212,9 @@ public class TableSorter extends AbstractTableModel {
|
||||
}
|
||||
}
|
||||
|
||||
protected Comparator getComparator(int column) {
|
||||
protected Comparator<Object> getComparator(int column) {
|
||||
Class columnType = tableModel.getColumnClass(column);
|
||||
Comparator comparator = (Comparator) columnComparators.get(columnType);
|
||||
Comparator<Object> comparator = columnComparators.get(columnType);
|
||||
if (comparator != null) {
|
||||
return comparator;
|
||||
}
|
||||
@@ -285,19 +286,19 @@ public class TableSorter extends AbstractTableModel {
|
||||
|
||||
// Helper classes
|
||||
|
||||
private class Row implements Comparable {
|
||||
private class Row implements Comparable<Row> {
|
||||
private int modelIndex;
|
||||
|
||||
public Row(int index) {
|
||||
this.modelIndex = index;
|
||||
}
|
||||
|
||||
public int compareTo(Object o) {
|
||||
public int compareTo(Row orow) {
|
||||
int row1 = modelIndex;
|
||||
int row2 = ((Row) o).modelIndex;
|
||||
int row2 = orow.modelIndex;
|
||||
|
||||
for (Iterator it = sortingColumns.iterator(); it.hasNext();) {
|
||||
Directive directive = (Directive) it.next();
|
||||
for (Iterator<Directive> it = sortingColumns.iterator(); it.hasNext();) {
|
||||
Directive directive = it.next();
|
||||
int column = directive.column;
|
||||
Object o1 = tableModel.getValueAt(row1, column);
|
||||
Object o2 = tableModel.getValueAt(row2, column);
|
||||
|
||||
@@ -260,8 +260,7 @@ public class DnDManager
|
||||
DropTarget target;
|
||||
while (comp != null) {
|
||||
// here we sneakily prevent dropping on the source
|
||||
target = (comp == _sourceComp) ? null
|
||||
: (DropTarget) _droppers.get(comp);
|
||||
target = (comp == _sourceComp) ? null : _droppers.get(comp);
|
||||
if ((target != null) && comp.isEnabled() &&
|
||||
_source.checkDrop(target) &&
|
||||
target.checkDrop(_source, _data[0])) {
|
||||
@@ -288,7 +287,7 @@ public class DnDManager
|
||||
}
|
||||
|
||||
Component parent;
|
||||
Object target;
|
||||
DropTarget target;
|
||||
while (true) {
|
||||
target = _droppers.get(comp);
|
||||
if (target instanceof AutoscrollingDropTarget) {
|
||||
@@ -391,7 +390,7 @@ public class DnDManager
|
||||
}
|
||||
|
||||
_sourceComp = me.getComponent();
|
||||
_source = (DragSource) _draggers.get(_sourceComp);
|
||||
_source = _draggers.get(_sourceComp);
|
||||
|
||||
// make sure the source wants to start a drag.
|
||||
if ((_source == null) || (!_sourceComp.isEnabled()) ||
|
||||
@@ -550,10 +549,12 @@ public class DnDManager
|
||||
};
|
||||
|
||||
/** Our DropTargets, indexed by associated Component. */
|
||||
protected HashMap _droppers = new HashMap();
|
||||
protected HashMap<Component,DropTarget> _droppers =
|
||||
new HashMap<Component,DropTarget>();
|
||||
|
||||
/** Our DragSources, indexed by associated component. */
|
||||
protected HashMap _draggers = new HashMap();
|
||||
protected HashMap<Component,DragSource> _draggers =
|
||||
new HashMap<Component,DragSource>();
|
||||
|
||||
/** The original, last, and top-level components during a drag. */
|
||||
protected Component _sourceComp, _lastComp, _topComp;
|
||||
|
||||
@@ -154,8 +154,8 @@ public class SwingUtil
|
||||
Rectangle r, Rectangle bounds, Collection avoidShapes)
|
||||
{
|
||||
Point origPos = r.getLocation();
|
||||
Comparator comp = createPointComparator(origPos);
|
||||
SortableArrayList possibles = new SortableArrayList();
|
||||
Comparator<Point> comp = createPointComparator(origPos);
|
||||
SortableArrayList<Point> possibles = new SortableArrayList<Point>();
|
||||
// we start things off with the passed-in point (adjusted to
|
||||
// be inside the bounds, if needed)
|
||||
possibles.add(fitRectInRect(r, bounds));
|
||||
@@ -165,7 +165,7 @@ public class SwingUtil
|
||||
|
||||
CHECKPOSSIBLES:
|
||||
while (!possibles.isEmpty()) {
|
||||
r.setLocation((Point) possibles.remove(0));
|
||||
r.setLocation(possibles.remove(0));
|
||||
|
||||
// make sure the rectangle is in the view and not over a dead area
|
||||
if ((!bounds.contains(r)) || dead.intersects(r)) {
|
||||
@@ -211,17 +211,14 @@ public class SwingUtil
|
||||
*
|
||||
* Used by positionRect().
|
||||
*/
|
||||
public static Comparator createPointComparator (Point origin)
|
||||
public static Comparator<Point> createPointComparator (Point origin)
|
||||
{
|
||||
final int xo = origin.x;
|
||||
final int yo = origin.y;
|
||||
|
||||
return new Comparator() {
|
||||
public int compare (Object o1, Object o2)
|
||||
return new Comparator<Point>() {
|
||||
public int compare (Point p1, Point p2)
|
||||
{
|
||||
Point p1 = (Point) o1;
|
||||
Point p2 = (Point) o2;
|
||||
|
||||
int x1 = xo - p1.x;
|
||||
int y1 = yo - p1.y;
|
||||
int x2 = xo - p2.x;
|
||||
|
||||
@@ -186,5 +186,6 @@ public class TaskMaster
|
||||
protected Object _source;
|
||||
}
|
||||
|
||||
protected static Hashtable _tasks = new Hashtable();
|
||||
protected static Hashtable<String,TaskRunner> _tasks =
|
||||
new Hashtable<String,TaskRunner>();
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ import java.util.NoSuchElementException;
|
||||
* Provides an {@link IntSet} implementation using a sorted array of
|
||||
* integers to maintain the contents of the set.
|
||||
*/
|
||||
public class ArrayIntSet extends AbstractSet
|
||||
public class ArrayIntSet extends AbstractSet<Integer>
|
||||
implements IntSet, Cloneable, Serializable
|
||||
{
|
||||
/**
|
||||
@@ -112,7 +112,7 @@ public class ArrayIntSet extends AbstractSet
|
||||
}
|
||||
}
|
||||
|
||||
public Object next () {
|
||||
public Integer next () {
|
||||
return new Integer(nextInt());
|
||||
}
|
||||
|
||||
@@ -133,7 +133,7 @@ public class ArrayIntSet extends AbstractSet
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Iterator iterator ()
|
||||
public Iterator<Integer> iterator ()
|
||||
{
|
||||
return interator();
|
||||
}
|
||||
@@ -145,7 +145,7 @@ public class ArrayIntSet extends AbstractSet
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object[] toArray (Object[] a)
|
||||
public Integer[] toArray (Integer[] a)
|
||||
{
|
||||
for (int i = 0; i < _size; i++) {
|
||||
a[i] = new Integer(_values[i]);
|
||||
@@ -189,9 +189,9 @@ public class ArrayIntSet extends AbstractSet
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean add (Object o)
|
||||
public boolean add (Integer o)
|
||||
{
|
||||
return add(((Integer)o).intValue());
|
||||
return add(o.intValue());
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
@@ -312,7 +312,7 @@ public class ArrayIntSet extends AbstractSet
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean addAll (Collection c)
|
||||
public boolean addAll (Collection<? extends Integer> c)
|
||||
{
|
||||
if (c instanceof Interable) {
|
||||
Interator inter = ((Interable) c).interator();
|
||||
@@ -330,7 +330,7 @@ public class ArrayIntSet extends AbstractSet
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean retainAll (Collection c)
|
||||
public boolean retainAll (Collection<?> c)
|
||||
{
|
||||
if (c instanceof IntSet) {
|
||||
IntSet other = (IntSet)c;
|
||||
|
||||
@@ -320,13 +320,13 @@ public class ArrayUtil
|
||||
* <code>(-(<i>insertion point</i>) - 1)</code> (always a negative
|
||||
* value) if the object was not found in the list.
|
||||
*/
|
||||
public static int binarySearch (
|
||||
Object[] array, int offset, int length, Object key)
|
||||
public static <T extends Comparable<? super T>> int binarySearch (
|
||||
T[] array, int offset, int length, T key)
|
||||
{
|
||||
int low = offset, high = offset+length-1;
|
||||
while (low <= high) {
|
||||
int mid = (low + high) >> 1;
|
||||
Comparable midVal = (Comparable)array[mid];
|
||||
T midVal = array[mid];
|
||||
int cmp = midVal.compareTo(key);
|
||||
if (cmp < 0) {
|
||||
low = mid + 1;
|
||||
@@ -356,13 +356,13 @@ public class ArrayUtil
|
||||
* <code>(-(<i>insertion point</i>) - 1)</code> (always a negative
|
||||
* value) if the object was not found in the list.
|
||||
*/
|
||||
public static int binarySearch (
|
||||
Object[] array, int offset, int length, Object key, Comparator comp)
|
||||
public static <T> int binarySearch (
|
||||
T[] array, int offset, int length, T key, Comparator<T> comp)
|
||||
{
|
||||
int low = offset, high = offset+length-1;
|
||||
while (low <= high) {
|
||||
int mid = (low + high) >> 1;
|
||||
Object midVal = array[mid];
|
||||
T midVal = array[mid];
|
||||
int cmp = comp.compare(midVal, key);
|
||||
if (cmp < 0) {
|
||||
low = mid + 1;
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
//
|
||||
// $Id: BaseArrayList.java,v 1.21 2004/02/25 13:20:44 mdb Exp $
|
||||
//
|
||||
// samskivert library - useful routines for java programs
|
||||
// Copyright (C) 2001 Michael Bayne
|
||||
//
|
||||
// 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
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
package com.samskivert.util;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import java.util.AbstractList;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.RandomAccess;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
|
||||
/**
|
||||
* Provides a base for extending the standard Java {@link ArrayList}
|
||||
* functionality (which we'd just extend directly if those pig fuckers hadn't
|
||||
* made the instance variables private).
|
||||
*/
|
||||
public abstract class BaseArrayList<T> extends AbstractList<T>
|
||||
implements List<T>, RandomAccess, Cloneable, Serializable
|
||||
{
|
||||
// documentation inherited from interface
|
||||
public int size ()
|
||||
{
|
||||
return _size;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean isEmpty ()
|
||||
{
|
||||
return (_size == 0);
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean contains (Object o)
|
||||
{
|
||||
return ListUtil.contains(_elements, o);
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object[] toArray ()
|
||||
{
|
||||
return toArray(new Object[_size]);
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public <T> T[] toArray (T[] target)
|
||||
{
|
||||
// create the target array if necessary
|
||||
if (target.length < _size) {
|
||||
target = (T[])Array.newInstance(
|
||||
target.getClass().getComponentType(), _size);
|
||||
}
|
||||
|
||||
// copy the elements
|
||||
if (_elements != null) {
|
||||
System.arraycopy(_elements, 0, target, 0, _size);
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public void clear ()
|
||||
{
|
||||
_elements = null;
|
||||
_size = 0;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean add (T o)
|
||||
{
|
||||
_elements = (T[])ListUtil.add(_elements, _size, o);
|
||||
_size++;
|
||||
return true;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean remove (Object o)
|
||||
{
|
||||
if (ListUtil.remove(_elements, o) != null) {
|
||||
_size--;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public T get (int index)
|
||||
{
|
||||
rangeCheck(index, false);
|
||||
return _elements[index];
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public T set (int index, T element)
|
||||
{
|
||||
rangeCheck(index, false);
|
||||
T old = _elements[index];
|
||||
_elements[index] = element;
|
||||
return old;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public void add (int index, T element)
|
||||
{
|
||||
rangeCheck(index, true);
|
||||
_elements = (T[])ListUtil.insert(_elements, index, element);
|
||||
_size++;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public T remove (int index)
|
||||
{
|
||||
rangeCheck(index, false);
|
||||
T oval = (T)ListUtil.remove(_elements, index);
|
||||
_size--;
|
||||
return oval;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public int indexOf (Object o)
|
||||
{
|
||||
return ListUtil.indexOf(_elements, o);
|
||||
}
|
||||
|
||||
// // documentation inherited from interface
|
||||
// public int lastIndexOf (Object o)
|
||||
// {
|
||||
// }
|
||||
|
||||
/**
|
||||
* Check the range of a passed-in index to make sure it's valid.
|
||||
*
|
||||
* @param insert if true, an index equal to our size is valid.
|
||||
*/
|
||||
protected final void rangeCheck (int index, boolean insert)
|
||||
{
|
||||
if ((index < 0) || (insert ? (index > _size) : (index >= _size))) {
|
||||
throw new IndexOutOfBoundsException(
|
||||
"Index: " + index + ", Size: " + _size);
|
||||
}
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Object clone ()
|
||||
{
|
||||
try {
|
||||
BaseArrayList<T> dup = (BaseArrayList<T>) super.clone();
|
||||
if (_elements != null) {
|
||||
dup._elements = (T[])new Object[_size];
|
||||
System.arraycopy(_elements, 0, dup._elements, 0, _size);
|
||||
}
|
||||
return dup;
|
||||
|
||||
} catch (CloneNotSupportedException cnse) {
|
||||
com.samskivert.Log.logStackTrace(cnse); // won't happen.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The array of elements in our list. */
|
||||
protected T[] _elements;
|
||||
|
||||
/** The number of elements in our list. */
|
||||
protected int _size;
|
||||
|
||||
/** Change this if the fields or inheritance hierarchy ever changes
|
||||
* (which is extremely unlikely). We override this because I'm tired
|
||||
* of serialized crap not working depending on whether I compiled with
|
||||
* jikes or javac. */
|
||||
private static final long serialVersionUID = 1;
|
||||
}
|
||||
@@ -51,18 +51,16 @@ public class ClassUtil
|
||||
*/
|
||||
public static Field[] getFields (Class clazz)
|
||||
{
|
||||
ArrayList list = new ArrayList();
|
||||
ArrayList<Field> list = new ArrayList<Field>();
|
||||
getFields(clazz, list);
|
||||
Field[] fields = new Field[list.size()];
|
||||
list.toArray(fields);
|
||||
return fields;
|
||||
return list.toArray(new Field[list.size()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add all the fields of the specifed class (and its ancestors) to the
|
||||
* list.
|
||||
*/
|
||||
public static void getFields (Class clazz, List addTo)
|
||||
public static void getFields (Class clazz, List<Field> addTo)
|
||||
{
|
||||
// first get the fields of the superclass
|
||||
Class pclazz = clazz.getSuperclass();
|
||||
@@ -129,7 +127,7 @@ public class ClassUtil
|
||||
*
|
||||
* @return true if compatible, false otherwise.
|
||||
*/
|
||||
public static boolean compatibleClasses (Class[] lhs, Class[] rhs)
|
||||
public static boolean compatibleClasses (Class<?>[] lhs, Class<?>[] rhs)
|
||||
{
|
||||
if (lhs.length != rhs.length) {
|
||||
return false;
|
||||
@@ -143,11 +141,10 @@ public class ClassUtil
|
||||
continue;
|
||||
}
|
||||
|
||||
if (! lhs[i].isAssignableFrom(rhs[i])) {
|
||||
Class lhsPrimEquiv = primitiveEquivalentOf(lhs[i]);
|
||||
Class rhsPrimEquiv = primitiveEquivalentOf(rhs[i]);
|
||||
|
||||
if (! primitiveIsAssignableFrom(lhsPrimEquiv, rhsPrimEquiv))
|
||||
if (!lhs[i].isAssignableFrom(rhs[i])) {
|
||||
Class<?> lhsPrimEquiv = primitiveEquivalentOf(lhs[i]);
|
||||
Class<?> rhsPrimEquiv = primitiveEquivalentOf(rhs[i]);
|
||||
if (!primitiveIsAssignableFrom(lhsPrimEquiv, rhsPrimEquiv))
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -244,19 +241,17 @@ public class ClassUtil
|
||||
* wrapper. If clazz is primitive, returns clazz. Otherwise,
|
||||
* returns null.
|
||||
*/
|
||||
public static Class primitiveEquivalentOf (Class clazz)
|
||||
public static Class<?> primitiveEquivalentOf (Class clazz)
|
||||
{
|
||||
return clazz.isPrimitive() ?
|
||||
clazz : (Class)_objectToPrimitiveMap.get(clazz);
|
||||
return clazz.isPrimitive() ? clazz : _objectToPrimitiveMap.get(clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the class's object equivalent if the class is a primitive type.
|
||||
*/
|
||||
public static Class objectEquivalentOf (Class clazz)
|
||||
public static Class<?> objectEquivalentOf (Class clazz)
|
||||
{
|
||||
return clazz.isPrimitive() ?
|
||||
(Class) _primitiveToObjectMap.get(clazz) : clazz;
|
||||
return clazz.isPrimitive() ? _primitiveToObjectMap.get(clazz) : clazz;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -273,19 +268,19 @@ public class ClassUtil
|
||||
*/
|
||||
public static boolean primitiveIsAssignableFrom (Class lhs, Class rhs)
|
||||
{
|
||||
if (lhs == null || rhs == null)
|
||||
if (lhs == null || rhs == null) {
|
||||
return false;
|
||||
|
||||
if (! (lhs.isPrimitive() && rhs.isPrimitive()))
|
||||
}
|
||||
if (!(lhs.isPrimitive() && rhs.isPrimitive())) {
|
||||
return false;
|
||||
|
||||
if (lhs.equals(rhs))
|
||||
}
|
||||
if (lhs.equals(rhs)) {
|
||||
return true;
|
||||
|
||||
Set wideningSet = (Set)_primitiveWideningsMap.get(rhs);
|
||||
if (wideningSet == null)
|
||||
}
|
||||
Set<Class> wideningSet = _primitiveWideningsMap.get(rhs);
|
||||
if (wideningSet == null) {
|
||||
return false;
|
||||
|
||||
}
|
||||
return wideningSet.contains(lhs);
|
||||
}
|
||||
|
||||
@@ -293,8 +288,10 @@ public class ClassUtil
|
||||
* Mapping from primitive wrapper Classes to their corresponding
|
||||
* primitive Classes.
|
||||
*/
|
||||
private static final Map _objectToPrimitiveMap = new HashMap(13);
|
||||
private static final Map _primitiveToObjectMap = new HashMap(13);
|
||||
private static final Map<Class<?>,Class<?>> _objectToPrimitiveMap =
|
||||
new HashMap<Class<?>,Class<?>>(13);
|
||||
private static final Map<Class<?>,Class<?>> _primitiveToObjectMap =
|
||||
new HashMap<Class<?>,Class<?>>(13);
|
||||
|
||||
static {
|
||||
_objectToPrimitiveMap.put(Boolean.class, Boolean.TYPE);
|
||||
@@ -319,10 +316,11 @@ public class ClassUtil
|
||||
* Mapping from primitive wrapper Classes to the sets of primitive
|
||||
* classes whose instances can be assigned an instance of the first.
|
||||
*/
|
||||
private static final Map _primitiveWideningsMap = new HashMap(11);
|
||||
private static final Map<Class,Set<Class>> _primitiveWideningsMap =
|
||||
new HashMap<Class,Set<Class>>(11);
|
||||
|
||||
static {
|
||||
Set set = new HashSet();
|
||||
Set<Class> set = new HashSet<Class>();
|
||||
set.add(Short.TYPE);
|
||||
set.add(Integer.TYPE);
|
||||
set.add(Long.TYPE);
|
||||
@@ -330,7 +328,7 @@ public class ClassUtil
|
||||
set.add(Double.TYPE);
|
||||
_primitiveWideningsMap.put(Byte.TYPE, set);
|
||||
|
||||
set = new HashSet();
|
||||
set = new HashSet<Class>();
|
||||
set.add(Integer.TYPE);
|
||||
set.add(Long.TYPE);
|
||||
set.add(Float.TYPE);
|
||||
@@ -338,18 +336,18 @@ public class ClassUtil
|
||||
_primitiveWideningsMap.put(Short.TYPE, set);
|
||||
_primitiveWideningsMap.put(Character.TYPE, set);
|
||||
|
||||
set = new HashSet();
|
||||
set = new HashSet<Class>();
|
||||
set.add(Long.TYPE);
|
||||
set.add(Float.TYPE);
|
||||
set.add(Double.TYPE);
|
||||
_primitiveWideningsMap.put(Integer.TYPE, set);
|
||||
|
||||
set = new HashSet();
|
||||
set = new HashSet<Class>();
|
||||
set.add(Float.TYPE);
|
||||
set.add(Double.TYPE);
|
||||
_primitiveWideningsMap.put(Long.TYPE, set);
|
||||
|
||||
set = new HashSet();
|
||||
set = new HashSet<Class>();
|
||||
set.add(Double.TYPE);
|
||||
_primitiveWideningsMap.put(Float.TYPE, set);
|
||||
}
|
||||
|
||||
@@ -35,7 +35,8 @@ public class CollectionUtil
|
||||
* Adds all items returned by the enumeration to the supplied
|
||||
* collection and returns the supplied collection.
|
||||
*/
|
||||
public static Collection addAll (Collection col, Enumeration enm)
|
||||
public static <T> Collection<T> addAll (
|
||||
Collection<T> col, Enumeration<T> enm)
|
||||
{
|
||||
while (enm.hasMoreElements()) {
|
||||
col.add(enm.nextElement());
|
||||
@@ -47,7 +48,7 @@ public class CollectionUtil
|
||||
* Adds all items returned by the iterator to the supplied collection
|
||||
* and returns the supplied collection.
|
||||
*/
|
||||
public static Collection addAll (Collection col, Iterator iter)
|
||||
public static <T> Collection<T> addAll (Collection<T> col, Iterator<T> iter)
|
||||
{
|
||||
while (iter.hasNext()) {
|
||||
col.add(iter.next());
|
||||
@@ -59,7 +60,7 @@ public class CollectionUtil
|
||||
* Adds all items in the given object array to the supplied
|
||||
* collection and returns the supplied collection.
|
||||
*/
|
||||
public static Collection addAll (Collection col, Object[] values)
|
||||
public static <T> Collection<T> addAll (Collection<T> col, T[] values)
|
||||
{
|
||||
for (int ii = 0; ii < values.length; ii++) {
|
||||
col.add(values[ii]);
|
||||
@@ -83,7 +84,7 @@ public class CollectionUtil
|
||||
* collection is smaller than the number of elements requested for the
|
||||
* random subset.
|
||||
*/
|
||||
public static List selectRandomSubset (Collection col, int count)
|
||||
public static <T> List<T> selectRandomSubset (Collection<T> col, int count)
|
||||
{
|
||||
int csize = col.size();
|
||||
if (csize < count) {
|
||||
@@ -92,12 +93,12 @@ public class CollectionUtil
|
||||
throw new IllegalArgumentException(errmsg);
|
||||
}
|
||||
|
||||
ArrayList subset = new ArrayList();
|
||||
Iterator iter = col.iterator();
|
||||
ArrayList<T> subset = new ArrayList<T>();
|
||||
Iterator<T> iter = col.iterator();
|
||||
int s = 0;
|
||||
|
||||
for (int k = 0; iter.hasNext(); k++) {
|
||||
Object elem = iter.next();
|
||||
T elem = iter.next();
|
||||
|
||||
// the probability that an element is select for inclusion in
|
||||
// our random subset is proportional to the number of elements
|
||||
@@ -121,24 +122,21 @@ public class CollectionUtil
|
||||
|
||||
|
||||
/**
|
||||
* If a collection contains only <code>Integer</code> objects, it can
|
||||
* be passed to this function and converted into an int array.
|
||||
* If a collection contains only <code>Integer</code> objects, it can be
|
||||
* passed to this function and converted into an int array.
|
||||
*
|
||||
* @param col the collection to be converted.
|
||||
*
|
||||
* @return an int array containing the contents of the collection (in
|
||||
* the order returned by the collection's iterator). The size of the
|
||||
* array will be equal to the size of the collection.
|
||||
*
|
||||
* @exception ClassCastException thrown if the collection contains
|
||||
* elements that are not instances of <code>Integer</code>.
|
||||
* @return an int array containing the contents of the collection (in the
|
||||
* order returned by the collection's iterator). The size of the array will
|
||||
* be equal to the size of the collection.
|
||||
*/
|
||||
public static int[] toIntArray (Collection col)
|
||||
public static int[] toIntArray (Collection<Integer> col)
|
||||
{
|
||||
Iterator iter = col.iterator();
|
||||
Iterator<Integer> iter = col.iterator();
|
||||
int[] array = new int[col.size()];
|
||||
for (int i = 0; iter.hasNext(); i++) {
|
||||
array[i] = ((Integer)iter.next()).intValue();
|
||||
array[i] = iter.next().intValue();
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
@@ -15,32 +15,44 @@ import java.util.*;
|
||||
public class Collections
|
||||
{
|
||||
/**
|
||||
* Returns an Iterator that iterates over all the elements contained
|
||||
* within the Collections within the specified Collection.
|
||||
* Returns an Iterator that iterates over all the elements contained within
|
||||
* the Iterators within the specified Collection.
|
||||
*
|
||||
* @param metaCollection a collection of either other Collections and/or
|
||||
* of Iterators.
|
||||
* @param metaCollection a collection of Iterators.
|
||||
*/
|
||||
public static Iterator getMetaIterator (Collection metaCollection)
|
||||
public static <T> Iterator<T> getMetaIterator (
|
||||
Collection<Iterator<T>> metaCollection)
|
||||
{
|
||||
return new MetaIterator(metaCollection);
|
||||
return new MetaIterator<T>(metaCollection);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an Iterator over the supplied Collection that returns the
|
||||
* elements in their natural order.
|
||||
*/
|
||||
public static Iterator getSortedIterator (Collection coll)
|
||||
public static <T extends Comparable<? super T>>
|
||||
Iterator<T> getSortedIterator (Collection<T> coll)
|
||||
{
|
||||
return getSortedIterator(coll.iterator(), Comparators.COMPARABLE);
|
||||
return getSortedIterator(coll.iterator(), new Comparator<T>() {
|
||||
public int compare (T o1, T o2) {
|
||||
if (o1 == o2) { // catches null == null
|
||||
return 0;
|
||||
} else if (o1 == null) {
|
||||
return 1;
|
||||
} else if (o2 == null) {
|
||||
return -1;
|
||||
}
|
||||
return o1.compareTo(o2); // null-free
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an Iterator over the supplied Collection that returns the
|
||||
* elements in the order dictated by the supplied Comparator.
|
||||
*/
|
||||
public static Iterator getSortedIterator (Collection coll,
|
||||
Comparator comparator)
|
||||
public static <T> Iterator<T> getSortedIterator (
|
||||
Collection<T> coll, Comparator<T> comparator)
|
||||
{
|
||||
return getSortedIterator(coll.iterator(), comparator);
|
||||
}
|
||||
@@ -49,9 +61,21 @@ public class Collections
|
||||
* Get an Iterator that returns the same elements returned by
|
||||
* the supplied Iterator, but in their natural order.
|
||||
*/
|
||||
public static Iterator getSortedIterator (Iterator itr)
|
||||
public static <T extends Comparable<? super T>>
|
||||
Iterator<T> getSortedIterator (Iterator<T> itr)
|
||||
{
|
||||
return getSortedIterator(itr, Comparators.COMPARABLE);
|
||||
return getSortedIterator(itr, new Comparator<T>() {
|
||||
public int compare (T o1, T o2) {
|
||||
if (o1 == o2) { // catches null == null
|
||||
return 0;
|
||||
} else if (o1 == null) {
|
||||
return 1;
|
||||
} else if (o2 == null) {
|
||||
return -1;
|
||||
}
|
||||
return o1.compareTo(o2); // null-free
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -59,10 +83,10 @@ public class Collections
|
||||
* the supplied Iterator, but in the order dictated by the supplied
|
||||
* Comparator.
|
||||
*/
|
||||
public static Iterator getSortedIterator (Iterator itr,
|
||||
Comparator comparator)
|
||||
public static <T> Iterator<T> getSortedIterator (
|
||||
Iterator<T> itr, Comparator<T> comparator)
|
||||
{
|
||||
SortableArrayList list = new SortableArrayList();
|
||||
SortableArrayList<T> list = new SortableArrayList<T>();
|
||||
CollectionUtil.addAll(list, itr);
|
||||
list.sort(comparator);
|
||||
return getUnmodifiableIterator(list);
|
||||
@@ -75,7 +99,7 @@ public class Collections
|
||||
* between different invocations as long as the underlying Collection
|
||||
* has not changed. This method mixes things up.
|
||||
*/
|
||||
public static Iterator getRandomIterator (Collection c)
|
||||
public static <T> Iterator<T> getRandomIterator (Collection<T> c)
|
||||
{
|
||||
return getRandomIterator(c.iterator());
|
||||
}
|
||||
@@ -84,9 +108,9 @@ public class Collections
|
||||
* Get an Iterator that returns the same elements returned by
|
||||
* the supplied Iterator, but in a completely random order.
|
||||
*/
|
||||
public static Iterator getRandomIterator (Iterator itr)
|
||||
public static <T> Iterator<T> getRandomIterator (Iterator<T> itr)
|
||||
{
|
||||
ArrayList list = new ArrayList();
|
||||
ArrayList<T> list = new ArrayList<T>();
|
||||
CollectionUtil.addAll(list, itr);
|
||||
java.util.Collections.shuffle(list);
|
||||
return getUnmodifiableIterator(list);
|
||||
@@ -96,7 +120,7 @@ public class Collections
|
||||
* Get an Iterator that returns the elements in the supplied
|
||||
* Collection but blocks removal.
|
||||
*/
|
||||
public static Iterator getUnmodifiableIterator (Collection c)
|
||||
public static <T> Iterator<T> getUnmodifiableIterator (Collection<T> c)
|
||||
{
|
||||
return getUnmodifiableIterator(c.iterator());
|
||||
}
|
||||
@@ -105,21 +129,17 @@ public class Collections
|
||||
* Get an iterator that returns the same elements as the supplied
|
||||
* iterator but blocks removal.
|
||||
*/
|
||||
public static Iterator getUnmodifiableIterator (final Iterator itr)
|
||||
public static <T> Iterator<T> getUnmodifiableIterator (
|
||||
final Iterator<T> itr)
|
||||
{
|
||||
return new Iterator() {
|
||||
public boolean hasNext ()
|
||||
{
|
||||
return new Iterator<T>() {
|
||||
public boolean hasNext () {
|
||||
return itr.hasNext();
|
||||
}
|
||||
|
||||
public Object next ()
|
||||
{
|
||||
public T next () {
|
||||
return itr.next();
|
||||
}
|
||||
|
||||
public void remove ()
|
||||
{
|
||||
public void remove () {
|
||||
throw new UnsupportedOperationException(
|
||||
"Cannot remove from an UnmodifiableIterator!");
|
||||
}
|
||||
@@ -157,8 +177,8 @@ public class Collections
|
||||
*
|
||||
* @return a synchronized view of the specified int map.
|
||||
*/
|
||||
public static IntMap synchronizedIntMap (IntMap m) {
|
||||
return new SynchronizedIntMap(m);
|
||||
public static <V> IntMap<V> synchronizedIntMap (IntMap<V> m) {
|
||||
return new SynchronizedIntMap<V>(m);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -197,12 +217,12 @@ public class Collections
|
||||
/**
|
||||
* Horked from the Java util class and extended for <code>IntMap</code>.
|
||||
*/
|
||||
protected static class SynchronizedIntMap implements IntMap
|
||||
protected static class SynchronizedIntMap<V> implements IntMap<V>
|
||||
{
|
||||
private IntMap m; // Backing Map
|
||||
private IntMap<V> m; // Backing Map
|
||||
private Object mutex; // Object on which to synchronize
|
||||
|
||||
SynchronizedIntMap(IntMap m) {
|
||||
SynchronizedIntMap(IntMap<V> m) {
|
||||
if (m == null) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
@@ -210,7 +230,7 @@ public class Collections
|
||||
mutex = this;
|
||||
}
|
||||
|
||||
SynchronizedIntMap(IntMap m, Object mutex) {
|
||||
SynchronizedIntMap(IntMap<V> m, Object mutex) {
|
||||
if (m == null) {
|
||||
throw new NullPointerException();
|
||||
}
|
||||
@@ -238,31 +258,31 @@ public class Collections
|
||||
synchronized(mutex) {return m.containsValue(value);}
|
||||
}
|
||||
|
||||
public Object get(int key) {
|
||||
public V get(int key) {
|
||||
synchronized(mutex) {return m.get(key);}
|
||||
}
|
||||
|
||||
public Object get(Object key) {
|
||||
public V get(Object key) {
|
||||
synchronized(mutex) {return m.get(key);}
|
||||
}
|
||||
|
||||
public Object put(int key, Object value) {
|
||||
public V put(int key, V value) {
|
||||
synchronized(mutex) {return m.put(key, value);}
|
||||
}
|
||||
|
||||
public Object put(Object key, Object value) {
|
||||
public V put(Integer key, V value) {
|
||||
synchronized(mutex) {return m.put(key, value);}
|
||||
}
|
||||
|
||||
public Object remove(int key) {
|
||||
public V remove(int key) {
|
||||
synchronized(mutex) {return m.remove(key);}
|
||||
}
|
||||
|
||||
public Object remove(Object key) {
|
||||
public V remove(Object key) {
|
||||
synchronized(mutex) {return m.remove(key);}
|
||||
}
|
||||
|
||||
public void putAll(Map map) {
|
||||
public void putAll(Map<? extends Integer,? extends V> map) {
|
||||
synchronized(mutex) {m.putAll(map);}
|
||||
}
|
||||
|
||||
@@ -271,10 +291,10 @@ public class Collections
|
||||
}
|
||||
|
||||
private transient IntSet keySet = null;
|
||||
private transient Set entrySet = null;
|
||||
private transient Collection values = null;
|
||||
private transient Set<Map.Entry<Integer,V>> entrySet = null;
|
||||
private transient Collection<V> values = null;
|
||||
|
||||
public Set keySet() {
|
||||
public Set<Integer> keySet() {
|
||||
return intKeySet();
|
||||
}
|
||||
|
||||
@@ -286,18 +306,25 @@ public class Collections
|
||||
}
|
||||
}
|
||||
|
||||
public Set entrySet() {
|
||||
public Set<Map.Entry<Integer,V>> entrySet() {
|
||||
synchronized(mutex) {
|
||||
if (entrySet==null)
|
||||
entrySet = new SynchronizedSet(m.entrySet(), mutex);
|
||||
entrySet = new SynchronizedSet<Map.Entry<Integer,V>>(
|
||||
m.entrySet(), mutex);
|
||||
return entrySet;
|
||||
}
|
||||
}
|
||||
|
||||
public Collection values() {
|
||||
public Set<IntEntry<V>> intEntrySet() {
|
||||
synchronized(mutex) {
|
||||
return new SynchronizedSet<IntEntry<V>>(m.intEntrySet(), mutex);
|
||||
}
|
||||
}
|
||||
|
||||
public Collection<V> values() {
|
||||
synchronized(mutex) {
|
||||
if (values==null)
|
||||
values = new SynchronizedCollection(m.values(), mutex);
|
||||
values = new SynchronizedCollection<V>(m.values(), mutex);
|
||||
return values;
|
||||
}
|
||||
}
|
||||
@@ -321,12 +348,12 @@ public class Collections
|
||||
* default access and pointlessly preventing people from properly
|
||||
* reusing their code. Yay!
|
||||
*/
|
||||
protected static class SynchronizedSet
|
||||
extends SynchronizedCollection implements Set {
|
||||
SynchronizedSet(Set s) {
|
||||
protected static class SynchronizedSet<T>
|
||||
extends SynchronizedCollection<T> implements Set<T> {
|
||||
SynchronizedSet(Set<T> s) {
|
||||
super(s);
|
||||
}
|
||||
SynchronizedSet(Set s, Object mutex) {
|
||||
SynchronizedSet(Set<T> s, Object mutex) {
|
||||
super(s, mutex);
|
||||
}
|
||||
|
||||
@@ -338,7 +365,7 @@ public class Collections
|
||||
}
|
||||
}
|
||||
|
||||
protected static class SynchronizedIntSet extends SynchronizedSet
|
||||
protected static class SynchronizedIntSet extends SynchronizedSet<Integer>
|
||||
implements IntSet
|
||||
{
|
||||
SynchronizedIntSet (IntSet s) {
|
||||
@@ -382,18 +409,18 @@ public class Collections
|
||||
* default access and pointlessly preventing people from properly
|
||||
* reusing their code. Yay!
|
||||
*/
|
||||
protected static class SynchronizedCollection
|
||||
implements Collection {
|
||||
Collection c; // Backing Collection
|
||||
protected static class SynchronizedCollection<T>
|
||||
implements Collection<T> {
|
||||
Collection<T> c; // Backing Collection
|
||||
Object mutex; // Object on which to synchronize
|
||||
|
||||
SynchronizedCollection(Collection c) {
|
||||
SynchronizedCollection(Collection<T> c) {
|
||||
if (c==null)
|
||||
throw new NullPointerException();
|
||||
this.c = c;
|
||||
mutex = this;
|
||||
}
|
||||
SynchronizedCollection(Collection c, Object mutex) {
|
||||
SynchronizedCollection(Collection<T> c, Object mutex) {
|
||||
this.c = c;
|
||||
this.mutex = mutex;
|
||||
}
|
||||
@@ -410,31 +437,31 @@ public class Collections
|
||||
public Object[] toArray() {
|
||||
synchronized(mutex) {return c.toArray();}
|
||||
}
|
||||
public Object[] toArray(Object[] a) {
|
||||
public <T> T[] toArray(T[] a) {
|
||||
synchronized(mutex) {return c.toArray(a);}
|
||||
}
|
||||
|
||||
public Iterator iterator() {
|
||||
public Iterator<T> iterator() {
|
||||
return c.iterator(); // Must be manually synched by user!
|
||||
}
|
||||
|
||||
public boolean add(Object o) {
|
||||
public boolean add(T o) {
|
||||
synchronized(mutex) {return c.add(o);}
|
||||
}
|
||||
public boolean remove(Object o) {
|
||||
synchronized(mutex) {return c.remove(o);}
|
||||
}
|
||||
|
||||
public boolean containsAll(Collection coll) {
|
||||
public boolean containsAll(Collection<?> coll) {
|
||||
synchronized(mutex) {return c.containsAll(coll);}
|
||||
}
|
||||
public boolean addAll(Collection coll) {
|
||||
public boolean addAll(Collection<? extends T> coll) {
|
||||
synchronized(mutex) {return c.addAll(coll);}
|
||||
}
|
||||
public boolean removeAll(Collection coll) {
|
||||
public boolean removeAll(Collection<?> coll) {
|
||||
synchronized(mutex) {return c.removeAll(coll);}
|
||||
}
|
||||
public boolean retainAll(Collection coll) {
|
||||
public boolean retainAll(Collection<?> coll) {
|
||||
synchronized(mutex) {return c.retainAll(coll);}
|
||||
}
|
||||
public void clear() {
|
||||
@@ -447,15 +474,15 @@ public class Collections
|
||||
|
||||
/**
|
||||
* An iterator that iterates over the union of the iterators provided by a
|
||||
* collection of collections.
|
||||
* collection of iterators.
|
||||
*/
|
||||
protected static class MetaIterator implements Iterator
|
||||
protected static class MetaIterator<T> implements Iterator<T>
|
||||
{
|
||||
/**
|
||||
* @param collections a Collection containing more Collections
|
||||
* whose elements we are to iterate over.
|
||||
*/
|
||||
public MetaIterator (Collection collections)
|
||||
public MetaIterator (Collection<Iterator<T>> collections)
|
||||
{
|
||||
_meta = collections.iterator();
|
||||
}
|
||||
@@ -465,21 +492,7 @@ public class Collections
|
||||
{
|
||||
while ((_current == null) || (!_current.hasNext())) {
|
||||
if (_meta.hasNext()) {
|
||||
Object o = _meta.next();
|
||||
if (o instanceof Iterator) {
|
||||
_current = (Iterator) o;
|
||||
// TODO: jdk1.5,
|
||||
// (obsoletes the Collection case, below)
|
||||
//} else if (o instanceof Iterable) {
|
||||
// _current = ((Iterable) o).iterator();
|
||||
} else if (o instanceof Collection) {
|
||||
_current = ((Collection) o).iterator();
|
||||
} else {
|
||||
throw new IllegalArgumentException(
|
||||
"MetaIterator must be constructed with a " +
|
||||
"collection of Iterators or other collections.");
|
||||
}
|
||||
|
||||
_current = _meta.next();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
@@ -488,7 +501,7 @@ public class Collections
|
||||
}
|
||||
|
||||
// documentation inherited from interface Iterator
|
||||
public Object next ()
|
||||
public T next ()
|
||||
{
|
||||
if (hasNext()) {
|
||||
return _current.next();
|
||||
@@ -508,9 +521,9 @@ public class Collections
|
||||
}
|
||||
|
||||
/** The iterator through the collection we were constructed with. */
|
||||
protected Iterator _meta;
|
||||
protected Iterator<Iterator<T>> _meta;
|
||||
|
||||
/** The current sub-collection's iterator. */
|
||||
protected Iterator _current;
|
||||
protected Iterator<T> _current;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//
|
||||
// $Id: ComparableArrayList.java,v 1.21 2004/02/25 13:20:44 mdb Exp $
|
||||
//
|
||||
// samskivert library - useful routines for java programs
|
||||
// Copyright (C) 2001 Michael Bayne
|
||||
//
|
||||
// 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
|
||||
// Lesser General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Lesser General Public
|
||||
// License along with this library; if not, write to the Free Software
|
||||
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
||||
|
||||
package com.samskivert.util;
|
||||
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* Provides a mechanism ({@link #sort}) for sorting the contents of the list
|
||||
* that doesn't involve creating two object arrays. Two copies of the elements
|
||||
* array are made if you called {@link java.util.Collections#sort}</code> (the
|
||||
* first is when {@link #toArray} is called on the collection and the second is
|
||||
* when {@link Arrays#sort} clones the supplied array so that it can do a merge
|
||||
* sort).
|
||||
*/
|
||||
public class ComparableArrayList<T extends Comparable<? super T>>
|
||||
extends SortableArrayList<T>
|
||||
{
|
||||
/**
|
||||
* Sorts the elements in this list using the quick sort algorithm
|
||||
* (which does not involve any object allocation). The elements must
|
||||
* implement {@link Comparable} and all be mutually comparable.
|
||||
*/
|
||||
public void sort ()
|
||||
{
|
||||
sort(_comp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the elements in this list using the quick sort algorithm
|
||||
* according to their reverse natural ordering. The elements must
|
||||
* implement {@link Comparable} and all be mutually comparable.
|
||||
*/
|
||||
public void rsort ()
|
||||
{
|
||||
sort(java.util.Collections.reverseOrder(_comp));
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the specified item into the list into a position that
|
||||
* preserves the sorting of the list. The list must be sorted prior to
|
||||
* the call to this method (an empty list built up entirely via calls
|
||||
* to {@link #insertSorted} will be properly sorted). The list must be
|
||||
* entirely comprised of elements that implement {@link Comparable}
|
||||
* and the element being added must implement {@link Comparable} as
|
||||
* well.
|
||||
*
|
||||
* @return the index at which the element was inserted.
|
||||
*/
|
||||
public int insertSorted (T value)
|
||||
{
|
||||
return insertSorted(value, _comp);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a binary search, attempting to locate the specified
|
||||
* object. The array must be sorted for this to operate correctly and
|
||||
* the contents of the array must all implement {@link Comparable}
|
||||
* (and actually be comparable to one another).
|
||||
*
|
||||
* @return the index of the object in question or
|
||||
* <code>(-(<i>insertion point</i>) - 1)</code> (always a negative
|
||||
* value) if the object was not found in the list.
|
||||
*/
|
||||
public int binarySearch (T key)
|
||||
{
|
||||
return ArrayUtil.binarySearch(_elements, 0, _size, key);
|
||||
}
|
||||
|
||||
protected Comparator<T> _comp = new Comparator<T>() {
|
||||
public int compare (T o1, T o2) {
|
||||
if (o1 == o2) { // catches null == null
|
||||
return 0;
|
||||
} else if (o1 == null) {
|
||||
return 1;
|
||||
} else if (o2 == null) {
|
||||
return -1;
|
||||
}
|
||||
return o1.compareTo(o2); // null-free
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -27,52 +27,12 @@ import java.util.Comparator;
|
||||
*/
|
||||
public class Comparators
|
||||
{
|
||||
/**
|
||||
* A comparator that can be used to reverse the results of another
|
||||
* comparator.
|
||||
* TODO: deprecate this when we more globally move to 1.5:
|
||||
* @use java.util.Collections.reverseOrder(Comparator c);
|
||||
*/
|
||||
public static class ReversingComparator implements Comparator
|
||||
{
|
||||
public ReversingComparator (Comparator reversable)
|
||||
{
|
||||
_reversable = reversable;
|
||||
}
|
||||
|
||||
// documentation inherited from interface Comparator
|
||||
public int compare (Object o1, Object o2)
|
||||
{
|
||||
return _reversable.compare(o2, o1); // switching the order
|
||||
}
|
||||
|
||||
protected Comparator _reversable;
|
||||
}
|
||||
|
||||
/**
|
||||
* A comparator that compares {@link Comparable} instances.
|
||||
* Can you believe this isn't defined somewhere in the standard
|
||||
* java libraries?
|
||||
*/
|
||||
public static final Comparator COMPARABLE = new Comparator() {
|
||||
public int compare (Object o1, Object o2)
|
||||
{
|
||||
if (o1 == o2) { // catches null == null
|
||||
return 0;
|
||||
} else if (o1 == null) {
|
||||
return 1;
|
||||
} else if (o2 == null) {
|
||||
return -1;
|
||||
}
|
||||
return ((Comparable)o1).compareTo(o2); // null-free
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A comparator that compares the toString() value of all objects
|
||||
* case insensitively.
|
||||
*/
|
||||
public static final Comparator LEXICAL_CASE_INSENSITIVE = new Comparator() {
|
||||
public static final Comparator<Object> LEXICAL_CASE_INSENSITIVE =
|
||||
new Comparator<Object>() {
|
||||
public int compare (Object o1, Object o2)
|
||||
{
|
||||
if (o1 == o2) { // catches null == null
|
||||
@@ -89,11 +49,21 @@ public class Comparators
|
||||
};
|
||||
|
||||
/**
|
||||
* A comparator that imposes a reverse ordering on {@link Comparable}
|
||||
* instances.
|
||||
*
|
||||
* @deprecated use java.util.Collections.reverseOrder()
|
||||
* A comparator that compares {@link Comparable} instances.
|
||||
*/
|
||||
public static final Comparator REVERSE_COMPARABLE =
|
||||
java.util.Collections.reverseOrder();
|
||||
public static final Comparator<Object> COMPARABLE =
|
||||
new Comparator<Object>() {
|
||||
@SuppressWarnings("unchecked")
|
||||
public int compare (Object o1, Object o2)
|
||||
{
|
||||
if (o1 == o2) { // catches null == null
|
||||
return 0;
|
||||
} else if (o1 == null) {
|
||||
return 1;
|
||||
} else if (o2 == null) {
|
||||
return -1;
|
||||
}
|
||||
return ((Comparable<Object>)o1).compareTo(o2); // null-free
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -690,16 +690,16 @@ public class Config
|
||||
* Returns an iterator that returns all of the configuration keys in
|
||||
* this config object.
|
||||
*/
|
||||
public Iterator keys ()
|
||||
public Iterator<String> keys ()
|
||||
{
|
||||
// what with all the complicated business, we just need to take
|
||||
// the brute force approach and enumerate everything up front
|
||||
HashSet matches = new HashSet();
|
||||
HashSet<String> matches = new HashSet<String>();
|
||||
|
||||
// add the keys provided in the config files
|
||||
Enumeration defkeys = _props.propertyNames();
|
||||
while (defkeys.hasMoreElements()) {
|
||||
matches.add(defkeys.nextElement());
|
||||
matches.add((String)defkeys.nextElement());
|
||||
}
|
||||
|
||||
// then add the overridden keys
|
||||
|
||||
@@ -283,7 +283,7 @@ public class ConfigUtil
|
||||
throws IOException
|
||||
{
|
||||
// first look for the files in the supplied class loader
|
||||
Enumeration enm = getResources(path, loader);
|
||||
Enumeration<URL> enm = getResources(path, loader);
|
||||
if (!enm.hasMoreElements()) {
|
||||
// if we couldn't find anything there, try the system class
|
||||
// loader (but only if that's not where we were already
|
||||
@@ -299,7 +299,7 @@ public class ConfigUtil
|
||||
}
|
||||
|
||||
// stick the matches into an array list so that we can count them
|
||||
ArrayList rsrcs = new ArrayList();
|
||||
ArrayList<URL> rsrcs = new ArrayList<URL>();
|
||||
while (enm.hasMoreElements()) {
|
||||
rsrcs.add(enm.nextElement());
|
||||
}
|
||||
@@ -327,14 +327,14 @@ public class ConfigUtil
|
||||
|
||||
// load up the metadata for the properties files
|
||||
PropRecord root = null, crown = null;
|
||||
HashMap map = null;
|
||||
HashMap<String,PropRecord> map = null;
|
||||
|
||||
if (rsrcs.size() == 1) {
|
||||
// parse the metadata for our only properties file
|
||||
root = parseMetaData(path, (URL)rsrcs.get(0));
|
||||
|
||||
} else {
|
||||
map = new HashMap();
|
||||
map = new HashMap<String,PropRecord>();
|
||||
for (int ii = 0; ii < rsrcs.size(); ii++) {
|
||||
// parse the metadata for this properties file
|
||||
PropRecord record = parseMetaData(path, (URL)rsrcs.get(ii));
|
||||
@@ -360,9 +360,7 @@ public class ConfigUtil
|
||||
}
|
||||
|
||||
// now wire up all the records according to the hierarchy
|
||||
Iterator iter = map.values().iterator();
|
||||
while (iter.hasNext()) {
|
||||
PropRecord prec = (PropRecord)iter.next();
|
||||
for (PropRecord prec : map.values()) {
|
||||
if (prec._overrides == null) {
|
||||
// sanity check
|
||||
if (prec != root) {
|
||||
@@ -377,7 +375,7 @@ public class ConfigUtil
|
||||
// wire this guy up to whomever he overrides
|
||||
for (int ii = 0; ii < prec._overrides.length; ii++) {
|
||||
String ppkg = prec._overrides[ii];
|
||||
PropRecord parent = (PropRecord)map.get(ppkg);
|
||||
PropRecord parent = map.get(ppkg);
|
||||
if (parent == null) {
|
||||
throw new IOException("Cannot find parent '" + ppkg +
|
||||
"' for " + prec);
|
||||
@@ -387,10 +385,8 @@ public class ConfigUtil
|
||||
}
|
||||
|
||||
// verify that there is only one crown
|
||||
ArrayList crowns = new ArrayList();
|
||||
iter = map.values().iterator();
|
||||
while (iter.hasNext()) {
|
||||
PropRecord prec = (PropRecord)iter.next();
|
||||
ArrayList<PropRecord> crowns = new ArrayList<PropRecord>();
|
||||
for (PropRecord prec : map.values()) {
|
||||
if (prec.size() == 0) {
|
||||
crowns.add(prec);
|
||||
}
|
||||
@@ -416,7 +412,7 @@ public class ConfigUtil
|
||||
throw new IOException(errmsg.toString());
|
||||
}
|
||||
|
||||
crown = (PropRecord)crowns.get(0);
|
||||
crown = crowns.get(0);
|
||||
}
|
||||
|
||||
// if the root extends another file, resolve that first
|
||||
@@ -432,7 +428,8 @@ public class ConfigUtil
|
||||
|
||||
// now apply all of the overrides, in the appropriate order
|
||||
if (crown != null) {
|
||||
HashMap applied = new HashMap();
|
||||
HashMap<String,PropRecord> applied =
|
||||
new HashMap<String,PropRecord>();
|
||||
loadPropertiesOverrides(crown, map, applied, loader, target);
|
||||
|
||||
} else {
|
||||
@@ -451,8 +448,9 @@ public class ConfigUtil
|
||||
/** {@link #loadInheritedProperties(String,ClassLoader,Properties)}
|
||||
* helper function. */
|
||||
protected static void loadPropertiesOverrides (
|
||||
PropRecord prec, HashMap records, HashMap applied,
|
||||
ClassLoader loader, Properties target)
|
||||
PropRecord prec, HashMap<String,PropRecord> records,
|
||||
HashMap<String,PropRecord> applied, ClassLoader loader,
|
||||
Properties target)
|
||||
throws IOException
|
||||
{
|
||||
if (applied.containsKey(prec._package)) {
|
||||
@@ -462,8 +460,7 @@ public class ConfigUtil
|
||||
// first load up properties from all of our parent nodes
|
||||
if (prec._overrides != null) {
|
||||
for (int ii = 0; ii < prec._overrides.length; ii++) {
|
||||
PropRecord parent = (PropRecord)
|
||||
records.get(prec._overrides[ii]);
|
||||
PropRecord parent = records.get(prec._overrides[ii]);
|
||||
loadPropertiesOverrides(
|
||||
parent, records, applied, loader, target);
|
||||
}
|
||||
@@ -598,7 +595,7 @@ public class ConfigUtil
|
||||
return loader.getResourceAsStream(togglePath(path));
|
||||
}
|
||||
|
||||
protected static Enumeration getResources (
|
||||
protected static Enumeration<URL> getResources (
|
||||
String path, ClassLoader loader)
|
||||
throws IOException
|
||||
{
|
||||
@@ -609,7 +606,7 @@ public class ConfigUtil
|
||||
return null;
|
||||
}
|
||||
// try the path as is
|
||||
Enumeration enm = loader.getResources(path);
|
||||
Enumeration<URL> enm = loader.getResources(path);
|
||||
if (enm.hasMoreElements()) {
|
||||
return enm;
|
||||
}
|
||||
@@ -627,7 +624,7 @@ public class ConfigUtil
|
||||
}
|
||||
|
||||
/** Used when parsing inherited properties. */
|
||||
protected static final class PropRecord extends ArrayList
|
||||
protected static final class PropRecord extends ArrayList<PropRecord>
|
||||
{
|
||||
public String _package;
|
||||
public String[] _overrides;
|
||||
|
||||
@@ -27,15 +27,15 @@ import java.util.Iterator;
|
||||
* This implementation may change, but I find it useful to inherit all
|
||||
* the goodness of clear(), keySet(), size(), etc.
|
||||
*/
|
||||
public class CountHashMap extends HashMap
|
||||
public class CountHashMap<K> extends HashMap<K,int[]>
|
||||
{
|
||||
/**
|
||||
* Increment the value associated with the specified key, return
|
||||
* the new value.
|
||||
*/
|
||||
public int incrementCount (Object key, int amount)
|
||||
public int incrementCount (K key, int amount)
|
||||
{
|
||||
int[] val = (int[]) get(key);
|
||||
int[] val = get(key);
|
||||
if (val == null) {
|
||||
put(key, val = new int[1]);
|
||||
}
|
||||
@@ -46,9 +46,9 @@ public class CountHashMap extends HashMap
|
||||
/**
|
||||
* Get the count associated with the specified key.
|
||||
*/
|
||||
public int getCount (Object key)
|
||||
public int getCount (K key)
|
||||
{
|
||||
int[] val = (int[]) get(key);
|
||||
int[] val = get(key);
|
||||
return (val == null) ? 0 : val[0];
|
||||
}
|
||||
|
||||
@@ -58,8 +58,8 @@ public class CountHashMap extends HashMap
|
||||
public int getTotalCount ()
|
||||
{
|
||||
int count = 0;
|
||||
for (Iterator itr = values().iterator(); itr.hasNext(); ) {
|
||||
count += ((int[]) itr.next())[0];
|
||||
for (Iterator<int[]> itr = values().iterator(); itr.hasNext(); ) {
|
||||
count += itr.next()[0];
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
@@ -69,14 +69,14 @@ public class DebugChords
|
||||
public static void registerHook (int modifierMask, int keyCode, Hook hook)
|
||||
{
|
||||
// store the hooks mapped by key code
|
||||
ArrayList list = (ArrayList)_bindings.get(keyCode);
|
||||
ArrayList<Tuple<Integer,Hook>> list = _bindings.get(keyCode);
|
||||
if (list == null) {
|
||||
list = new ArrayList();
|
||||
list = new ArrayList<Tuple<Integer,Hook>>();
|
||||
_bindings.put(keyCode, list);
|
||||
}
|
||||
|
||||
// append the hook and modifier mask to the list
|
||||
list.add(new Tuple(new Integer(modifierMask), hook));
|
||||
list.add(new Tuple<Integer,Hook>(modifierMask, hook));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -91,7 +91,7 @@ public class DebugChords
|
||||
}
|
||||
|
||||
// bail here if we have no hooks registered for this key code
|
||||
ArrayList list = (ArrayList)_bindings.get(e.getKeyCode());
|
||||
ArrayList<Tuple<Integer,Hook>> list = _bindings.get(e.getKeyCode());
|
||||
if (list == null) {
|
||||
return false;
|
||||
}
|
||||
@@ -101,16 +101,15 @@ public class DebugChords
|
||||
boolean handled = false;
|
||||
int hcount = list.size();
|
||||
for (int ii = 0; ii < hcount; ii++) {
|
||||
Tuple tup = (Tuple)list.get(ii);
|
||||
int mask = ((Integer)tup.left).intValue();
|
||||
Tuple<Integer,Hook> tup = list.get(ii);
|
||||
int mask = tup.left.intValue();
|
||||
if ((e.getModifiersEx() & mask) == mask) {
|
||||
Hook hook = (Hook)tup.right;
|
||||
try {
|
||||
hook.invoke();
|
||||
tup.right.invoke();
|
||||
handled = true;
|
||||
} catch (Throwable t) {
|
||||
Log.warning("Hook failed [event=" + e +
|
||||
", hook=" + hook + "].");
|
||||
", hook=" + tup.right + "].");
|
||||
Log.logStackTrace(t);
|
||||
}
|
||||
}
|
||||
@@ -123,5 +122,6 @@ public class DebugChords
|
||||
protected static KeyEventDispatcher _dispatcher;
|
||||
|
||||
/** A mapping from key binding to debug code. */
|
||||
protected static HashIntMap _bindings = new HashIntMap();
|
||||
protected static HashIntMap<ArrayList<Tuple<Integer,Hook>>> _bindings =
|
||||
new HashIntMap<ArrayList<Tuple<Integer,Hook>>>();
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ import java.text.FieldPosition;
|
||||
import java.text.SimpleDateFormat;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.Hashtable;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* If no log provider is registered with the log services, the default
|
||||
@@ -67,7 +67,7 @@ public class DefaultLogProvider implements LogProvider
|
||||
public synchronized void log (
|
||||
int level, String moduleName, String message)
|
||||
{
|
||||
Integer tlevel = (Integer)_levels.get(moduleName);
|
||||
Integer tlevel = _levels.get(moduleName);
|
||||
if (level >= getLevel(moduleName)) {
|
||||
System.err.println(formatEntry(moduleName, level, message));
|
||||
}
|
||||
@@ -76,7 +76,7 @@ public class DefaultLogProvider implements LogProvider
|
||||
public synchronized void logStackTrace (
|
||||
int level, String moduleName, Throwable t)
|
||||
{
|
||||
Integer tlevel = (Integer)_levels.get(moduleName);
|
||||
Integer tlevel = _levels.get(moduleName);
|
||||
if (level >= getLevel(moduleName)) {
|
||||
System.err.print(formatEntry(moduleName, level, ""));
|
||||
t.printStackTrace(System.err);
|
||||
@@ -85,7 +85,7 @@ public class DefaultLogProvider implements LogProvider
|
||||
|
||||
public synchronized void setLevel (String moduleName, int level)
|
||||
{
|
||||
_levels.put(moduleName, new Integer(level));
|
||||
_levels.put(moduleName, level);
|
||||
}
|
||||
|
||||
public synchronized void setLevel (int level)
|
||||
@@ -96,7 +96,7 @@ public class DefaultLogProvider implements LogProvider
|
||||
|
||||
public synchronized int getLevel (String moduleName)
|
||||
{
|
||||
Integer level = (Integer)_levels.get(moduleName);
|
||||
Integer level = _levels.get(moduleName);
|
||||
return (level == null) ? _level : level.intValue();
|
||||
}
|
||||
|
||||
@@ -198,7 +198,7 @@ public class DefaultLogProvider implements LogProvider
|
||||
protected int _level = Log.INFO;
|
||||
|
||||
/** The levels of each module. */
|
||||
protected Hashtable _levels = new Hashtable();
|
||||
protected HashMap<String,Integer> _levels = new HashMap<String,Integer>();
|
||||
|
||||
/** Used to accompany log messages with time stamps. */
|
||||
protected SimpleDateFormat _format =
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//
|
||||
// samskivert library - useful routines for java programs
|
||||
// Copyright (C) 2001 Michael Bayne
|
||||
//
|
||||
//
|
||||
// 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
|
||||
@@ -27,6 +27,7 @@ import java.io.Serializable;
|
||||
|
||||
import java.util.AbstractMap;
|
||||
import java.util.AbstractSet;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Iterator;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
@@ -38,15 +39,9 @@ import java.util.Set;
|
||||
* lookup or insert values. The hash int map is an int map that uses a
|
||||
* hashtable mechanism to store its key/value mappings.
|
||||
*/
|
||||
public class HashIntMap extends AbstractMap
|
||||
implements IntMap, Cloneable, Serializable
|
||||
public class HashIntMap<V> extends AbstractMap<Integer,V>
|
||||
implements IntMap<V>, Cloneable, Serializable
|
||||
{
|
||||
public interface Entry extends IntMap.Entry
|
||||
{
|
||||
// this interface does nothing,
|
||||
// is included for bass-ackwards compatability
|
||||
}
|
||||
|
||||
/**
|
||||
* The default number of buckets to use for the hash table.
|
||||
*/
|
||||
@@ -69,7 +64,7 @@ public class HashIntMap extends AbstractMap
|
||||
capacity <<= 1;
|
||||
}
|
||||
|
||||
_buckets = new Record[capacity];
|
||||
_buckets = createBuckets(capacity);
|
||||
_loadFactor = loadFactor;
|
||||
}
|
||||
|
||||
@@ -103,8 +98,8 @@ public class HashIntMap extends AbstractMap
|
||||
// documentation inherited
|
||||
public boolean containsValue (Object o)
|
||||
{
|
||||
for (int i = 0; i < _buckets.length; i++) {
|
||||
for (Record r = _buckets[i]; r != null; r = r.next) {
|
||||
for (int ii = 0, ll = _buckets.size(); ii < ll; ii++) {
|
||||
for (Record<V> r = _buckets.get(ii); r != null; r = r.next) {
|
||||
if (ObjectUtil.equals(r.value, o)) {
|
||||
return true;
|
||||
}
|
||||
@@ -114,16 +109,16 @@ public class HashIntMap extends AbstractMap
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Object get (Object key)
|
||||
public V get (Object key)
|
||||
{
|
||||
return get(((Integer)key).intValue());
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Object get (int key)
|
||||
public V get (int key)
|
||||
{
|
||||
int index = keyToIndex(key);
|
||||
for (Record rec = _buckets[index]; rec != null; rec = rec.next) {
|
||||
for (Record<V> rec = _buckets.get(index); rec != null; rec = rec.next) {
|
||||
if (rec.key == key) {
|
||||
return rec.value;
|
||||
}
|
||||
@@ -132,32 +127,32 @@ public class HashIntMap extends AbstractMap
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Object put (Object key, Object value)
|
||||
public V put (Integer key, V value)
|
||||
{
|
||||
return put(((Integer)key).intValue(), value);
|
||||
return put(key.intValue(), value);
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Object put (int key, Object value)
|
||||
public V put (int key, V value)
|
||||
{
|
||||
// check to see if we've passed our load factor, if so: resize
|
||||
ensureCapacity(_size + 1);
|
||||
|
||||
int index = keyToIndex(key);
|
||||
Record rec = _buckets[index];
|
||||
Record<V> rec = _buckets.get(index);
|
||||
|
||||
// either we start a new chain
|
||||
if (rec == null) {
|
||||
_buckets[index] = new Record(key, value);
|
||||
_buckets.set(index, new Record<V>(key, value));
|
||||
_size++; // we're bigger
|
||||
return null;
|
||||
}
|
||||
|
||||
// or we replace an element in an existing chain
|
||||
Record prev = rec;
|
||||
Record<V> prev = rec;
|
||||
for (; rec != null; rec = rec.next) {
|
||||
if (rec.key == key) {
|
||||
Object ovalue = rec.value;
|
||||
V ovalue = rec.value;
|
||||
rec.value = value; // we're not bigger
|
||||
return ovalue;
|
||||
}
|
||||
@@ -165,21 +160,21 @@ public class HashIntMap extends AbstractMap
|
||||
}
|
||||
|
||||
// or we append it to this chain
|
||||
prev.next = new Record(key, value);
|
||||
prev.next = new Record<V>(key, value);
|
||||
_size++; // we're bigger
|
||||
return null;
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Object remove (Object key)
|
||||
public V remove (Object key)
|
||||
{
|
||||
return remove(((Integer)key).intValue());
|
||||
}
|
||||
|
||||
|
||||
// documentation inherited
|
||||
public Object remove (int key)
|
||||
public V remove (int key)
|
||||
{
|
||||
Object removed = removeImpl(key);
|
||||
V removed = removeImpl(key);
|
||||
if (removed != null) {
|
||||
checkShrink();
|
||||
}
|
||||
@@ -189,16 +184,16 @@ public class HashIntMap extends AbstractMap
|
||||
/**
|
||||
* Remove an element with no checking to see if we should shrink.
|
||||
*/
|
||||
protected Object removeImpl (int key)
|
||||
protected V removeImpl (int key)
|
||||
{
|
||||
int index = keyToIndex(key);
|
||||
Record prev = null;
|
||||
Record<V> prev = null;
|
||||
|
||||
// go through the chain looking for a match
|
||||
for (Record rec = _buckets[index]; rec != null; rec = rec.next) {
|
||||
for (Record<V> rec = _buckets.get(index); rec != null; rec = rec.next) {
|
||||
if (rec.key == key) {
|
||||
if (prev == null) {
|
||||
_buckets[index] = rec.next;
|
||||
_buckets.set(index, rec.next);
|
||||
} else {
|
||||
prev.next = rec.next;
|
||||
}
|
||||
@@ -212,17 +207,11 @@ public class HashIntMap extends AbstractMap
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public void putAll (Map t)
|
||||
public void putAll (IntMap<V> t)
|
||||
{
|
||||
if (t instanceof IntMap) {
|
||||
// if we can, avoid creating Integer objects while copying
|
||||
for (Iterator itr = t.entrySet().iterator(); itr.hasNext(); ) {
|
||||
IntMap.Entry entry = (IntMap.Entry) itr.next();
|
||||
put(entry.getIntKey(), entry.getValue());
|
||||
}
|
||||
|
||||
} else {
|
||||
super.putAll(t);
|
||||
// if we can, avoid creating Integer objects while copying
|
||||
for (IntEntry<V> entry : t.intEntrySet()) {
|
||||
put(entry.getIntKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,8 +219,8 @@ public class HashIntMap extends AbstractMap
|
||||
public void clear ()
|
||||
{
|
||||
// abandon all of our hash chains (the joy of garbage collection)
|
||||
for (int i = 0; i < _buckets.length; i++) {
|
||||
_buckets[i] = null;
|
||||
for (int i = 0; i < _buckets.size(); i++) {
|
||||
_buckets.set(i, null);
|
||||
}
|
||||
// zero out our size
|
||||
_size = 0;
|
||||
@@ -244,11 +233,11 @@ public class HashIntMap extends AbstractMap
|
||||
*/
|
||||
public void ensureCapacity (int minCapacity)
|
||||
{
|
||||
int size = _buckets.length;
|
||||
int size = _buckets.size();
|
||||
while (minCapacity > (int) (size * _loadFactor)) {
|
||||
size *= 2;
|
||||
}
|
||||
if (size != _buckets.length) {
|
||||
if (size != _buckets.size()) {
|
||||
resizeBuckets(size);
|
||||
}
|
||||
}
|
||||
@@ -264,7 +253,7 @@ public class HashIntMap extends AbstractMap
|
||||
key ^= (key >>> 14);
|
||||
key += (key << 4);
|
||||
key ^= (key >>> 10);
|
||||
return key & (_buckets.length - 1);
|
||||
return key & (_buckets.size() - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -272,9 +261,9 @@ public class HashIntMap extends AbstractMap
|
||||
*/
|
||||
protected void checkShrink ()
|
||||
{
|
||||
if ((_buckets.length > DEFAULT_BUCKETS) &&
|
||||
(_size < (int) (_buckets.length * _loadFactor * .125))) {
|
||||
resizeBuckets(Math.max(DEFAULT_BUCKETS, _buckets.length >> 1));
|
||||
if ((_buckets.size() > DEFAULT_BUCKETS) &&
|
||||
(_size < (int) (_buckets.size() * _loadFactor * .125))) {
|
||||
resizeBuckets(Math.max(DEFAULT_BUCKETS, _buckets.size() >> 1));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -285,42 +274,52 @@ public class HashIntMap extends AbstractMap
|
||||
*/
|
||||
protected void resizeBuckets (int newsize)
|
||||
{
|
||||
Record[] oldbuckets = _buckets;
|
||||
_buckets = new Record[newsize];
|
||||
ArrayList<Record<V>> oldbuckets = _buckets;
|
||||
_buckets = createBuckets(newsize);
|
||||
|
||||
// we shuffle the records around without allocating new ones
|
||||
int index = oldbuckets.length;
|
||||
int index = oldbuckets.size();
|
||||
while (index-- > 0) {
|
||||
Record oldrec = oldbuckets[index];
|
||||
Record<V> oldrec = oldbuckets.get(index);
|
||||
while (oldrec != null) {
|
||||
Record newrec = oldrec;
|
||||
Record<V> newrec = oldrec;
|
||||
oldrec = oldrec.next;
|
||||
|
||||
// always put the newrec at the start of a chain
|
||||
int newdex = keyToIndex(newrec.key);
|
||||
newrec.next = _buckets[newdex];
|
||||
_buckets[newdex] = newrec;
|
||||
newrec.next = _buckets.get(newdex);
|
||||
_buckets.set(newdex, newrec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Set entrySet ()
|
||||
public Set<Entry<Integer,V>> entrySet ()
|
||||
{
|
||||
return new AbstractSet() {
|
||||
public int size ()
|
||||
{
|
||||
return new AbstractSet<Entry<Integer,V>>() {
|
||||
public int size () {
|
||||
return _size;
|
||||
}
|
||||
|
||||
public Iterator iterator ()
|
||||
{
|
||||
return new EntryIterator();
|
||||
public Iterator<Entry<Integer,V>> iterator () {
|
||||
return new MapEntryIterator();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected class EntryIterator implements Iterator
|
||||
// documentation inherited
|
||||
public Set<IntEntry<V>> intEntrySet()
|
||||
{
|
||||
return new AbstractSet<IntEntry<V>>() {
|
||||
public int size () {
|
||||
return _size;
|
||||
}
|
||||
public Iterator<IntEntry<V>> iterator () {
|
||||
return new IntEntryIterator();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
protected abstract class RecordIterator
|
||||
{
|
||||
public boolean hasNext ()
|
||||
{
|
||||
@@ -332,7 +331,7 @@ public class HashIntMap extends AbstractMap
|
||||
// search backward through the buckets looking for the next
|
||||
// non-empty hash chain
|
||||
while (_index-- > 0) {
|
||||
if ((_record = _buckets[_index]) != null) {
|
||||
if ((_record = _buckets.get(_index)) != null) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -341,13 +340,13 @@ public class HashIntMap extends AbstractMap
|
||||
return false;
|
||||
}
|
||||
|
||||
public Object next ()
|
||||
public Record<V> nextRecord ()
|
||||
{
|
||||
// if we're not pointing to an entry, search for the next
|
||||
// non-empty hash chain
|
||||
if (_record == null) {
|
||||
while ((_index-- > 0) &&
|
||||
((_record = _buckets[_index]) == null));
|
||||
((_record = _buckets.get(_index)) == null));
|
||||
}
|
||||
|
||||
// keep track of the last thing we returned
|
||||
@@ -374,36 +373,48 @@ public class HashIntMap extends AbstractMap
|
||||
_last = null;
|
||||
}
|
||||
|
||||
protected int _index = _buckets.length;
|
||||
protected Record _record, _last;
|
||||
protected int _index = _buckets.size();
|
||||
protected Record<V> _record, _last;
|
||||
}
|
||||
|
||||
protected class IntKeySet extends AbstractSet
|
||||
protected class IntEntryIterator extends RecordIterator
|
||||
implements Iterator<IntEntry<V>>
|
||||
{
|
||||
public IntEntry<V> next () {
|
||||
return nextRecord();
|
||||
}
|
||||
}
|
||||
|
||||
protected class MapEntryIterator extends RecordIterator
|
||||
implements Iterator<Entry<Integer,V>>
|
||||
{
|
||||
public Entry<Integer,V> next () {
|
||||
return nextRecord();
|
||||
}
|
||||
}
|
||||
|
||||
protected class IntKeySet extends AbstractSet<Integer>
|
||||
implements IntSet
|
||||
{
|
||||
public Iterator iterator () {
|
||||
public Iterator<Integer> iterator () {
|
||||
return interator();
|
||||
}
|
||||
|
||||
|
||||
public Interator interator () {
|
||||
return new Interator () {
|
||||
private Iterator i = entrySet().iterator();
|
||||
|
||||
public boolean hasNext () {
|
||||
return i.hasNext();
|
||||
}
|
||||
|
||||
public Object next () {
|
||||
return ((IntMap.Entry) i.next()).getKey();
|
||||
public Integer next () {
|
||||
return i.next().getKey();
|
||||
}
|
||||
|
||||
public int nextInt () {
|
||||
return ((IntMap.Entry) i.next()).getIntKey();
|
||||
return i.next().getIntKey();
|
||||
}
|
||||
|
||||
public void remove () {
|
||||
i.remove();
|
||||
}
|
||||
private Iterator<IntEntry<V>> i = intEntrySet().iterator();
|
||||
};
|
||||
}
|
||||
|
||||
@@ -453,7 +464,7 @@ public class HashIntMap extends AbstractMap
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Set keySet ()
|
||||
public Set<Integer> keySet ()
|
||||
{
|
||||
return intKeySet();
|
||||
}
|
||||
@@ -478,10 +489,8 @@ public class HashIntMap extends AbstractMap
|
||||
// documentation inherited from interface cloneable
|
||||
public Object clone ()
|
||||
{
|
||||
HashIntMap copy = new HashIntMap(_buckets.length, _loadFactor);
|
||||
|
||||
for (Iterator itr = new EntryIterator(); itr.hasNext(); ) {
|
||||
Entry entry = (Entry) itr.next();
|
||||
HashIntMap<V> copy = new HashIntMap<V>(_buckets.size(), _loadFactor);
|
||||
for (IntEntry<V> entry : intEntrySet()) {
|
||||
copy.put(entry.getIntKey(), entry.getValue());
|
||||
}
|
||||
return copy;
|
||||
@@ -494,17 +503,16 @@ public class HashIntMap extends AbstractMap
|
||||
throws IOException
|
||||
{
|
||||
// write out number of buckets
|
||||
s.writeInt(_buckets.length);
|
||||
s.writeInt(_buckets.size());
|
||||
s.writeFloat(_loadFactor);
|
||||
|
||||
// write out size (number of mappings)
|
||||
s.writeInt(_size);
|
||||
|
||||
// write out keys and values
|
||||
for (Iterator i = entrySet().iterator(); i.hasNext(); ) {
|
||||
Entry e = (Entry)i.next();
|
||||
s.writeInt(e.getIntKey());
|
||||
s.writeObject(e.getValue());
|
||||
for (IntEntry<V> entry : intEntrySet()) {
|
||||
s.writeInt(entry.getIntKey());
|
||||
s.writeObject(entry.getValue());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -516,7 +524,7 @@ public class HashIntMap extends AbstractMap
|
||||
throws IOException, ClassNotFoundException
|
||||
{
|
||||
// read in number of buckets and allocate the bucket array
|
||||
_buckets = new Record[s.readInt()];
|
||||
_buckets = createBuckets(s.readInt());
|
||||
_loadFactor = s.readFloat();
|
||||
|
||||
// read in size (number of mappings)
|
||||
@@ -525,24 +533,33 @@ public class HashIntMap extends AbstractMap
|
||||
// read the keys and values
|
||||
for (int i=0; i<size; i++) {
|
||||
int key = s.readInt();
|
||||
Object value = s.readObject();
|
||||
V value = (V)s.readObject();
|
||||
put(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
protected static class Record implements Entry
|
||||
protected ArrayList<Record<V>> createBuckets (int size)
|
||||
{
|
||||
public Record next;
|
||||
public int key;
|
||||
public Object value;
|
||||
ArrayList<Record<V>> buckets = new ArrayList<Record<V>>(size);
|
||||
for (int ii = 0; ii < size; ii++) {
|
||||
buckets.add(null);
|
||||
}
|
||||
return buckets;
|
||||
}
|
||||
|
||||
public Record (int key, Object value)
|
||||
protected static class Record<V> implements Entry<Integer,V>, IntEntry<V>
|
||||
{
|
||||
public Record<V> next;
|
||||
public int key;
|
||||
public V value;
|
||||
|
||||
public Record (int key, V value)
|
||||
{
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Object getKey ()
|
||||
public Integer getKey ()
|
||||
{
|
||||
return new Integer(key);
|
||||
}
|
||||
@@ -552,26 +569,22 @@ public class HashIntMap extends AbstractMap
|
||||
return key;
|
||||
}
|
||||
|
||||
public Object getValue ()
|
||||
public V getValue ()
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
public Object setValue (Object value)
|
||||
public V setValue (V value)
|
||||
{
|
||||
Object ovalue = this.value;
|
||||
V ovalue = this.value;
|
||||
this.value = value;
|
||||
return ovalue;
|
||||
}
|
||||
|
||||
public boolean equals (Object o)
|
||||
{
|
||||
if (o instanceof Record) {
|
||||
Record or = (Record)o;
|
||||
return (key == or.key) && ObjectUtil.equals(value, or.value);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
Record<V> or = (Record<V>)o;
|
||||
return (key == or.key) && ObjectUtil.equals(value, or.value);
|
||||
}
|
||||
|
||||
public int hashCode ()
|
||||
@@ -585,7 +598,7 @@ public class HashIntMap extends AbstractMap
|
||||
}
|
||||
}
|
||||
|
||||
protected Record[] _buckets;
|
||||
protected ArrayList<Record<V>> _buckets;
|
||||
protected int _size;
|
||||
protected float _loadFactor;
|
||||
|
||||
|
||||
@@ -37,7 +37,7 @@ import java.util.Set;
|
||||
// or at least share a common abstract ancestor.
|
||||
public class IntIntMap
|
||||
{
|
||||
public interface Entry extends IntMap.Entry
|
||||
public interface IntIntEntry extends IntMap.IntEntry<Integer>
|
||||
{
|
||||
public int getIntValue ();
|
||||
|
||||
@@ -245,12 +245,12 @@ public class IntIntMap
|
||||
|
||||
public Interator keys ()
|
||||
{
|
||||
return new KeyValueInterator(true);
|
||||
return new KeyValueInterator(true, new IntEntryIterator());
|
||||
}
|
||||
|
||||
public Interator values ()
|
||||
{
|
||||
return new KeyValueInterator(false);
|
||||
return new KeyValueInterator(false, new IntEntryIterator());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -304,20 +304,20 @@ public class IntIntMap
|
||||
/**
|
||||
* Get a set of all the entries in this map.
|
||||
*/
|
||||
public Set entrySet ()
|
||||
public Set<IntIntEntry> entrySet ()
|
||||
{
|
||||
return new AbstractSet() {
|
||||
return new AbstractSet<IntIntEntry>() {
|
||||
public int size () {
|
||||
return _size;
|
||||
}
|
||||
|
||||
public Iterator iterator() {
|
||||
return new EntryIterator();
|
||||
public Iterator<IntIntEntry> iterator() {
|
||||
return new IntEntryIterator();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
class Record implements Entry
|
||||
class Record implements IntIntEntry
|
||||
{
|
||||
public Record next;
|
||||
public int key;
|
||||
@@ -329,7 +329,7 @@ public class IntIntMap
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public Object getKey () {
|
||||
public Integer getKey () {
|
||||
return new Integer(key);
|
||||
}
|
||||
|
||||
@@ -337,7 +337,7 @@ public class IntIntMap
|
||||
return key;
|
||||
}
|
||||
|
||||
public Object getValue () {
|
||||
public Integer getValue () {
|
||||
return new Integer(value);
|
||||
}
|
||||
|
||||
@@ -345,8 +345,8 @@ public class IntIntMap
|
||||
return value;
|
||||
}
|
||||
|
||||
public Object setValue (Object v) {
|
||||
return new Integer(setIntValue(((Integer) v).intValue()));
|
||||
public Integer setValue (Integer v) {
|
||||
return new Integer(setIntValue(v.intValue()));
|
||||
}
|
||||
|
||||
public int setIntValue (int v) {
|
||||
@@ -356,8 +356,8 @@ public class IntIntMap
|
||||
}
|
||||
|
||||
public boolean equals (Object o) {
|
||||
if (o instanceof Entry) {
|
||||
Entry that = (Entry) o;
|
||||
if (o instanceof IntIntEntry) {
|
||||
IntIntEntry that = (IntIntEntry) o;
|
||||
return (this.key == that.getIntKey()) &&
|
||||
(this.value == that.getIntValue());
|
||||
}
|
||||
@@ -369,9 +369,9 @@ public class IntIntMap
|
||||
}
|
||||
}
|
||||
|
||||
class EntryIterator implements Iterator
|
||||
class IntEntryIterator implements Iterator<IntIntEntry>
|
||||
{
|
||||
public EntryIterator ()
|
||||
public IntEntryIterator ()
|
||||
{
|
||||
this._modCount = IntIntMap.this._modCount;
|
||||
_index = _buckets.length;
|
||||
@@ -408,7 +408,7 @@ public class IntIntMap
|
||||
return false;
|
||||
}
|
||||
|
||||
public Object next ()
|
||||
public IntIntEntry next ()
|
||||
{
|
||||
// if we're not pointing to an entry, search for the next
|
||||
// non-empty hash chain
|
||||
@@ -440,26 +440,38 @@ public class IntIntMap
|
||||
private int _modCount;
|
||||
}
|
||||
|
||||
protected class KeyValueInterator extends EntryIterator
|
||||
protected class KeyValueInterator
|
||||
implements Interator
|
||||
{
|
||||
public KeyValueInterator (boolean keys)
|
||||
public KeyValueInterator (boolean keys, IntEntryIterator eiter)
|
||||
{
|
||||
_keys = keys;
|
||||
_eiter = eiter;
|
||||
}
|
||||
|
||||
public int nextInt ()
|
||||
{
|
||||
Entry entry = (Entry) super.next();
|
||||
IntIntEntry entry = _eiter.next();
|
||||
return _keys ? entry.getIntKey() : entry.getIntValue();
|
||||
}
|
||||
|
||||
public Object next ()
|
||||
public boolean hasNext ()
|
||||
{
|
||||
return _eiter.hasNext();
|
||||
}
|
||||
|
||||
public Integer next ()
|
||||
{
|
||||
return new Integer(nextInt());
|
||||
}
|
||||
|
||||
public void remove ()
|
||||
{
|
||||
_eiter.remove();
|
||||
}
|
||||
|
||||
protected boolean _keys;
|
||||
protected IntEntryIterator _eiter;
|
||||
}
|
||||
|
||||
// public static void main (String[] args)
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
package com.samskivert.util;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* An int map is a map that uses integers as keys and provides accessors
|
||||
@@ -29,13 +30,13 @@ import java.util.Map;
|
||||
* and therefore provides all of the standard accessors (for which
|
||||
* <code>Integer</code> objects should be supplied as keys).
|
||||
*/
|
||||
public interface IntMap extends Map
|
||||
public interface IntMap<V> extends Map<Integer,V>
|
||||
{
|
||||
/**
|
||||
* An IntMap entry (key-value pair). The int key may be retrieved
|
||||
* directly, avoiding the creation of an Integer object.
|
||||
* An IntMap entry (key-value pair). The int key may be retrieved directly,
|
||||
* avoiding the creation of an Integer object.
|
||||
*/
|
||||
public interface Entry extends Map.Entry
|
||||
public interface IntEntry<V> extends Entry<Integer,V>
|
||||
{
|
||||
public int getIntKey ();
|
||||
}
|
||||
@@ -60,7 +61,7 @@ public interface IntMap extends Map
|
||||
* @return the value to which this map maps the specified key, or
|
||||
* <tt>null</tt> if the map contains no mapping for this key.
|
||||
*/
|
||||
public Object get (int key);
|
||||
public V get (int key);
|
||||
|
||||
/**
|
||||
* Associates the specified value with the specified key in this map.
|
||||
@@ -73,7 +74,7 @@ public interface IntMap extends Map
|
||||
* @return previous value associated with specified key, or
|
||||
* <tt>null</tt> if there was no mapping for key.
|
||||
*/
|
||||
public Object put (int key, Object value);
|
||||
public V put (int key, V value);
|
||||
|
||||
/**
|
||||
* Removes the mapping for this key from this map if present.
|
||||
@@ -83,10 +84,15 @@ public interface IntMap extends Map
|
||||
* @return previous value associated with specified key, or
|
||||
* <tt>null</tt> if there was no mapping for key.
|
||||
*/
|
||||
public Object remove (int key);
|
||||
public V remove (int key);
|
||||
|
||||
/**
|
||||
* Get a set of all the keys, as an IntSet.
|
||||
*/
|
||||
public IntSet intKeySet ();
|
||||
|
||||
/**
|
||||
* Returns a set of all the map entries.
|
||||
*/
|
||||
public Set<IntEntry<V>> intEntrySet ();
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ import java.util.Set;
|
||||
* provides all of the standard methods (in which <code>Integer</code>
|
||||
* objects will be converted to ints).
|
||||
*/
|
||||
public interface IntSet extends Set, Interable
|
||||
public interface IntSet extends Set<Integer>, Interable
|
||||
{
|
||||
/**
|
||||
* Returns <tt>true</tt> if this set contains the specified element.
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.util.Iterator;
|
||||
* Can be used as an Iterator, and all Objects returned should be Integer
|
||||
* objects, but can also can avoid object creation by calling nextInt().
|
||||
*/
|
||||
public interface Interator extends Iterator
|
||||
public interface Interator extends Iterator<Integer>
|
||||
{
|
||||
/**
|
||||
* @return the next int value from this Iterator.
|
||||
|
||||
@@ -193,7 +193,7 @@ public class Invoker extends LoopingThread
|
||||
|
||||
protected void recordMetrics (Object key, long duration)
|
||||
{
|
||||
UnitProfile prof = (UnitProfile)_tracker.get(key);
|
||||
UnitProfile prof = _tracker.get(key);
|
||||
if (prof == null) {
|
||||
_tracker.put(key, prof = new UnitProfile());
|
||||
}
|
||||
@@ -232,7 +232,8 @@ public class Invoker extends LoopingThread
|
||||
protected RunQueue _receiver;
|
||||
|
||||
/** Tracks the counts of invocations by unit's class. */
|
||||
protected HashMap _tracker = new HashMap();
|
||||
protected HashMap<Object,UnitProfile> _tracker =
|
||||
new HashMap<Object,UnitProfile>();
|
||||
|
||||
/** The total number of invoker units run since the last report. */
|
||||
protected int _unitsRun;
|
||||
|
||||
@@ -21,19 +21,19 @@ package com.samskivert.util;
|
||||
* Object value = (oidx == -1) ? null : list.get(oidx);
|
||||
* </pre>
|
||||
*/
|
||||
public class KeyValue
|
||||
implements Comparable
|
||||
public class KeyValue<K extends Comparable<? super K>,V>
|
||||
implements Comparable<KeyValue<K,V>>
|
||||
{
|
||||
/** The key in this key/value pair. */
|
||||
public Comparable key;
|
||||
public K key;
|
||||
|
||||
/** The value in this key/value pair. */
|
||||
public Object value;
|
||||
public V value;
|
||||
|
||||
/**
|
||||
* Creates a key/value pair with the specified key and value.
|
||||
*/
|
||||
public KeyValue (Comparable key, Object value)
|
||||
public KeyValue (K key, V value)
|
||||
{
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
@@ -47,14 +47,10 @@ public class KeyValue
|
||||
return key + "=" + value;
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
@SuppressWarnings("unchecked") // documentation inherited
|
||||
public boolean equals (Object other)
|
||||
{
|
||||
if (other instanceof KeyValue) {
|
||||
return key.equals(((KeyValue)other).key);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
return key.equals(((KeyValue<K,V>)other).key);
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
@@ -64,12 +60,8 @@ public class KeyValue
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public int compareTo (Object other)
|
||||
public int compareTo (KeyValue<K,V> other)
|
||||
{
|
||||
if (other instanceof KeyValue) {
|
||||
return key.compareTo(((KeyValue)other).key);
|
||||
} else {
|
||||
return getClass().getName().compareTo(other.getClass().getName());
|
||||
}
|
||||
return key.compareTo(other.key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import java.util.Set;
|
||||
* A HashMap with LRU functionality and rudimentary performance tracking
|
||||
* facilities.
|
||||
*/
|
||||
public class LRUHashMap implements Map
|
||||
public class LRUHashMap<K,V> implements Map<K,V>
|
||||
{
|
||||
/**
|
||||
* Used to return the "size" of a cache item for systems that wish to
|
||||
@@ -25,10 +25,10 @@ public class LRUHashMap implements Map
|
||||
* recently used items will be flushed until the cache is back below
|
||||
* its target size.
|
||||
*/
|
||||
public static interface ItemSizer
|
||||
public static interface ItemSizer<V>
|
||||
{
|
||||
/** Returns the "size" of the specified object. */
|
||||
public int computeSize (Object item);
|
||||
public int computeSize (V item);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -36,10 +36,10 @@ public class LRUHashMap implements Map
|
||||
* when items are removed from the table (either explicitly or by
|
||||
* being replaced with another value or due to being flushed).
|
||||
*/
|
||||
public static interface RemovalObserver
|
||||
public static interface RemovalObserver<K,V>
|
||||
{
|
||||
/** Informs the observer that this item was removed from the map. */
|
||||
public void removedFromMap (LRUHashMap map, Object item);
|
||||
public void removedFromMap (LRUHashMap<K,V> map, V item);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,12 +56,16 @@ public class LRUHashMap implements Map
|
||||
* the supplied item sizer which will be used to compute the size of
|
||||
* each item.
|
||||
*/
|
||||
public LRUHashMap (int maxSize, ItemSizer sizer)
|
||||
public LRUHashMap (int maxSize, ItemSizer<V> sizer)
|
||||
{
|
||||
_delegate = new LinkedHashMap(
|
||||
_delegate = new LinkedHashMap<K,V>(
|
||||
Math.min(1024, Math.max(16, maxSize)), .75f, true);
|
||||
_maxSize = maxSize;
|
||||
_sizer = (sizer == null) ? _unitSizer : sizer;
|
||||
_sizer = (sizer == null) ? new ItemSizer<V>() {
|
||||
public int computeSize (V item) {
|
||||
return 1;
|
||||
}
|
||||
} : sizer;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -88,7 +92,7 @@ public class LRUHashMap implements Map
|
||||
/**
|
||||
* Configures this hash map with a removal observer.
|
||||
*/
|
||||
public void setRemovalObserver (RemovalObserver obs)
|
||||
public void setRemovalObserver (RemovalObserver<K,V> obs)
|
||||
{
|
||||
_remobs = obs;
|
||||
}
|
||||
@@ -115,7 +119,7 @@ public class LRUHashMap implements Map
|
||||
if (track != _tracking) {
|
||||
_tracking = track;
|
||||
if (track) {
|
||||
_seenKeys = new HashSet();
|
||||
_seenKeys = new HashSet<K>();
|
||||
_misses = _hits = 0;
|
||||
|
||||
// oh boy, but to properly track we need to clear the hash
|
||||
@@ -162,9 +166,9 @@ public class LRUHashMap implements Map
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object get (Object key)
|
||||
public V get (Object key)
|
||||
{
|
||||
Object result = _delegate.get(key);
|
||||
V result = _delegate.get(key);
|
||||
|
||||
if (_tracking) {
|
||||
if (result == null) {
|
||||
@@ -181,9 +185,9 @@ public class LRUHashMap implements Map
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object put (Object key, Object value)
|
||||
public V put (K key, V value)
|
||||
{
|
||||
Object result = _delegate.put(key, value);
|
||||
V result = _delegate.put(key, value);
|
||||
|
||||
if (_tracking) {
|
||||
_seenKeys.add(key);
|
||||
@@ -218,11 +222,11 @@ public class LRUHashMap implements Map
|
||||
if (_size > _maxSize) {
|
||||
// This works because the entrySet iterator of a LinkedHashMap
|
||||
// returns the entries in LRU order
|
||||
Iterator iter = _delegate.entrySet().iterator();
|
||||
Iterator<Map.Entry<K,V>> iter = _delegate.entrySet().iterator();
|
||||
// don't remove the last entry, even if it's too big, because
|
||||
// a cache with nothing in it sucks
|
||||
for (int ii = size(); (ii > 1) && (_size > _maxSize); ii--) {
|
||||
Map.Entry entry = (Map.Entry) iter.next();
|
||||
Map.Entry<K,V> entry = iter.next();
|
||||
entryRemoved(entry.getValue());
|
||||
iter.remove();
|
||||
}
|
||||
@@ -232,7 +236,7 @@ public class LRUHashMap implements Map
|
||||
/**
|
||||
* Adjust our size to reflect the removal of the specified entry.
|
||||
*/
|
||||
protected void entryRemoved (Object entry)
|
||||
protected void entryRemoved (V entry)
|
||||
{
|
||||
if (entry != null) {
|
||||
_size -= _sizer.computeSize(entry);
|
||||
@@ -243,18 +247,17 @@ public class LRUHashMap implements Map
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object remove (Object key)
|
||||
public V remove (Object key)
|
||||
{
|
||||
Object removed = _delegate.remove(key);
|
||||
V removed = _delegate.remove(key);
|
||||
entryRemoved(removed);
|
||||
return removed;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public void putAll (Map t)
|
||||
public void putAll (Map<? extends K,? extends V> t)
|
||||
{
|
||||
for (Iterator iter = t.entrySet().iterator(); iter.hasNext(); ) {
|
||||
Map.Entry entry = (Map.Entry) iter.next();
|
||||
for (Map.Entry<? extends K,? extends V> entry : t.entrySet()) {
|
||||
put(entry.getKey(), entry.getValue());
|
||||
}
|
||||
}
|
||||
@@ -264,7 +267,7 @@ public class LRUHashMap implements Map
|
||||
{
|
||||
// notify our removal observer if we have one
|
||||
if (_remobs != null) {
|
||||
for (Iterator iter = _delegate.values().iterator();
|
||||
for (Iterator<V> iter = _delegate.values().iterator();
|
||||
iter.hasNext(); ) {
|
||||
_remobs.removedFromMap(this, iter.next());
|
||||
}
|
||||
@@ -276,21 +279,21 @@ public class LRUHashMap implements Map
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Set keySet ()
|
||||
public Set<K> keySet ()
|
||||
{
|
||||
// no modifying except through put() and remove()
|
||||
return Collections.unmodifiableSet(_delegate.keySet());
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Collection values ()
|
||||
public Collection<V> values ()
|
||||
{
|
||||
// no modifying except through put() and remove()
|
||||
return Collections.unmodifiableCollection(_delegate.values());
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Set entrySet ()
|
||||
public Set<Map.Entry<K,V>> entrySet ()
|
||||
{
|
||||
// no modifying except through put() and remove()
|
||||
return Collections.unmodifiableSet(_delegate.entrySet());
|
||||
@@ -313,7 +316,7 @@ public class LRUHashMap implements Map
|
||||
* reimplement a crapload of stuff so that we can provide our required
|
||||
* size tracking support. Yay! I wish we could support code reuse as
|
||||
* well as Sun does. */
|
||||
protected LinkedHashMap _delegate;
|
||||
protected LinkedHashMap<K,V> _delegate;
|
||||
|
||||
/** The maximum size of this cache. */
|
||||
protected int _maxSize;
|
||||
@@ -325,20 +328,13 @@ public class LRUHashMap implements Map
|
||||
protected boolean _canFlush = true;
|
||||
|
||||
/** Notified when items are removed from the map, if non-null. */
|
||||
protected RemovalObserver _remobs;
|
||||
protected RemovalObserver<K,V> _remobs;
|
||||
|
||||
/** Used to compute the size of items in this cache. */
|
||||
protected ItemSizer _sizer;
|
||||
protected ItemSizer<V> _sizer;
|
||||
|
||||
/** Tracking info. */
|
||||
protected boolean _tracking;
|
||||
protected HashSet _seenKeys;
|
||||
protected HashSet<K> _seenKeys;
|
||||
protected int _hits, _misses;
|
||||
|
||||
/** Used for caches with no item sizer. */
|
||||
protected static final ItemSizer _unitSizer = new ItemSizer() {
|
||||
public int computeSize (Object item) {
|
||||
return 1;
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,10 +71,9 @@ public class LoggingLogProvider
|
||||
{
|
||||
Logger logger = Logger.global;
|
||||
if (!StringUtil.isBlank(moduleName)) {
|
||||
logger = (Logger)_loggers.get(moduleName);
|
||||
logger = _loggers.get(moduleName);
|
||||
if (logger == null) {
|
||||
_loggers.put(moduleName,
|
||||
logger = Logger.getLogger(moduleName));
|
||||
_loggers.put(moduleName, logger = Logger.getLogger(moduleName));
|
||||
}
|
||||
}
|
||||
return logger;
|
||||
@@ -101,5 +100,5 @@ public class LoggingLogProvider
|
||||
}
|
||||
}
|
||||
|
||||
protected HashMap _loggers = new HashMap();
|
||||
protected HashMap<String,Logger> _loggers = new HashMap<String,Logger>();
|
||||
}
|
||||
|
||||
@@ -143,7 +143,7 @@ public class MethodFinder
|
||||
// make sure the constructor list is loaded
|
||||
maybeLoadMethods();
|
||||
|
||||
List methodList = (List)methodMap.get(methodName);
|
||||
List<Member> methodList = methodMap.get(methodName);
|
||||
if (methodList == null) {
|
||||
throw new NoSuchMethodException(
|
||||
"No method named " + clazz.getName() + "." + methodName);
|
||||
@@ -173,14 +173,15 @@ public class MethodFinder
|
||||
* member list fed to this method will be either all {@link
|
||||
* Constructor} objects or all {@link Method} objects.
|
||||
*/
|
||||
private Member findMemberIn (List memberList, Class[] parameterTypes)
|
||||
private Member findMemberIn (List<Member> memberList,
|
||||
Class[] parameterTypes)
|
||||
throws NoSuchMethodException
|
||||
{
|
||||
List matchingMembers = new ArrayList();
|
||||
List<Member> matchingMembers = new ArrayList<Member>();
|
||||
|
||||
for (Iterator it = memberList.iterator(); it.hasNext();) {
|
||||
Member member = (Member)it.next();
|
||||
Class[] methodParamTypes = (Class[])paramMap.get(member);
|
||||
for (Iterator<Member> it = memberList.iterator(); it.hasNext();) {
|
||||
Member member = it.next();
|
||||
Class[] methodParamTypes = paramMap.get(member);
|
||||
|
||||
// check for exactly equal method signature
|
||||
if (Arrays.equals(methodParamTypes, parameterTypes)) {
|
||||
@@ -213,15 +214,12 @@ public class MethodFinder
|
||||
* @exception NoSuchMethodException if there is an ambiguity as to
|
||||
* which is most specific.
|
||||
*/
|
||||
private Member findMostSpecificMemberIn (List memberList)
|
||||
private Member findMostSpecificMemberIn (List<Member> memberList)
|
||||
throws NoSuchMethodException
|
||||
{
|
||||
List mostSpecificMembers = new ArrayList();
|
||||
|
||||
for (Iterator memberIt = memberList.iterator();
|
||||
memberIt.hasNext();) {
|
||||
Member member = (Member)memberIt.next();
|
||||
List<Member> mostSpecificMembers = new ArrayList<Member>();
|
||||
|
||||
for (Member member : memberList) {
|
||||
if (mostSpecificMembers.isEmpty()) {
|
||||
// First guy in is the most specific so far.
|
||||
mostSpecificMembers.add(member);
|
||||
@@ -232,10 +230,7 @@ public class MethodFinder
|
||||
|
||||
// Is member more specific than everyone in the
|
||||
// most-specific set?
|
||||
for (Iterator specificIt = mostSpecificMembers.iterator();
|
||||
specificIt.hasNext();) {
|
||||
Member moreSpecificMember = (Member)specificIt.next();
|
||||
|
||||
for (Member moreSpecificMember : mostSpecificMembers) {
|
||||
if (!memberIsMoreSpecific(member, moreSpecificMember)) {
|
||||
// if the candidate member is not more specific
|
||||
// than this member, then it's not more specific
|
||||
@@ -288,7 +283,7 @@ public class MethodFinder
|
||||
private void maybeLoadConstructors ()
|
||||
{
|
||||
if (ctorList == null) {
|
||||
ctorList = new ArrayList();
|
||||
ctorList = new ArrayList<Member>();
|
||||
Constructor[] ctors = clazz.getConstructors();
|
||||
for (int i = 0; i < ctors.length; ++i) {
|
||||
ctorList.add(ctors[i]);
|
||||
@@ -303,7 +298,7 @@ public class MethodFinder
|
||||
private void maybeLoadMethods ()
|
||||
{
|
||||
if (methodMap == null) {
|
||||
methodMap = new HashMap();
|
||||
methodMap = new HashMap<String,List<Member>>();
|
||||
Method[] methods = clazz.getMethods();
|
||||
|
||||
for (int i = 0; i < methods.length; ++i) {
|
||||
@@ -311,10 +306,10 @@ public class MethodFinder
|
||||
String methodName = m.getName();
|
||||
Class[] paramTypes = m.getParameterTypes();
|
||||
|
||||
List list = (List)methodMap.get(methodName);
|
||||
List<Member> list = methodMap.get(methodName);
|
||||
|
||||
if (list == null) {
|
||||
list = new ArrayList();
|
||||
list = new ArrayList<Member>();
|
||||
methodMap.put(methodName, list);
|
||||
}
|
||||
|
||||
@@ -341,8 +336,8 @@ public class MethodFinder
|
||||
*/
|
||||
private boolean memberIsMoreSpecific (Member first, Member second)
|
||||
{
|
||||
Class[] firstParamTypes = (Class[])paramMap.get(first);
|
||||
Class[] secondParamTypes = (Class[])paramMap.get(second);
|
||||
Class[] firstParamTypes = paramMap.get(first);
|
||||
Class[] secondParamTypes = paramMap.get(second);
|
||||
return ClassUtil.compatibleClasses(
|
||||
secondParamTypes, firstParamTypes);
|
||||
}
|
||||
@@ -356,16 +351,16 @@ public class MethodFinder
|
||||
* Mapping from method name to the Methods in the target class with
|
||||
* that name.
|
||||
*/
|
||||
private Map methodMap = null;
|
||||
private Map<String,List<Member>> methodMap = null;
|
||||
|
||||
/**
|
||||
* List of the Constructors in the target class.
|
||||
*/
|
||||
private List ctorList = null;
|
||||
private List<Member> ctorList = null;
|
||||
|
||||
/**
|
||||
* Mapping from a Constructor or Method object to the Class objects
|
||||
* representing its formal parameters.
|
||||
*/
|
||||
private Map paramMap = new HashMap();
|
||||
private Map<Member,Class[]> paramMap = new HashMap<Member,Class[]>();
|
||||
}
|
||||
|
||||
@@ -72,13 +72,13 @@ import com.samskivert.util.StringUtil;
|
||||
* these two will give you a useful starting point for determining what is
|
||||
* the most appropriate usage for your needs.
|
||||
*/
|
||||
public class ObserverList extends ArrayList
|
||||
public class ObserverList<T> extends ArrayList<T>
|
||||
{
|
||||
/**
|
||||
* Instances of this interface are used to apply methods to all
|
||||
* observers in a list.
|
||||
*/
|
||||
public static interface ObserverOp
|
||||
public static interface ObserverOp<T>
|
||||
{
|
||||
/**
|
||||
* Called once for each observer in the list.
|
||||
@@ -86,7 +86,7 @@ public class ObserverList extends ArrayList
|
||||
* @return true if the observer should remain in the list, false
|
||||
* if it should be removed in response to this application.
|
||||
*/
|
||||
public boolean apply (Object observer);
|
||||
public boolean apply (T observer);
|
||||
}
|
||||
|
||||
/** A notification ordering policy indicating that the observers
|
||||
@@ -143,7 +143,7 @@ public class ObserverList extends ArrayList
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public boolean add (Object o)
|
||||
public boolean add (T o)
|
||||
{
|
||||
// make sure we're not violating the list constraints
|
||||
if (!_allowDups && contains(o)) {
|
||||
@@ -159,13 +159,13 @@ public class ObserverList extends ArrayList
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public boolean addAll (Collection c)
|
||||
public boolean addAll (Collection<? extends T> c)
|
||||
{
|
||||
throw new UnsupportedOperationException(UNSUPPORTED_ADD_MESSAGE);
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public boolean addAll (int index, Collection c)
|
||||
public boolean addAll (int index, Collection<? extends T> c)
|
||||
{
|
||||
throw new UnsupportedOperationException(UNSUPPORTED_ADD_MESSAGE);
|
||||
}
|
||||
@@ -175,7 +175,7 @@ public class ObserverList extends ArrayList
|
||||
* list in a manner conforming to the notification ordering policy
|
||||
* specified at construct time.
|
||||
*/
|
||||
public void apply (ObserverOp obop)
|
||||
public void apply (ObserverOp<T> obop)
|
||||
{
|
||||
if (_policy == SAFE_IN_ORDER_NOTIFY) {
|
||||
// if we have to notify our observers in order, we need to
|
||||
@@ -188,7 +188,7 @@ public class ObserverList extends ArrayList
|
||||
}
|
||||
Object[] obs = toArray(_snap);
|
||||
for (int ii = 0; ii < ocount; ii++) {
|
||||
if (!checkedApply(obop, _snap[ii])) {
|
||||
if (!checkedApply(obop, (T)_snap[ii])) {
|
||||
remove(_snap[ii]);
|
||||
}
|
||||
}
|
||||
@@ -209,7 +209,7 @@ public class ObserverList extends ArrayList
|
||||
* Applies the operation to the observer, catching and logging any
|
||||
* exceptions thrown in the process.
|
||||
*/
|
||||
protected static boolean checkedApply (ObserverOp obop, Object obs)
|
||||
protected static <T> boolean checkedApply (ObserverOp<T> obop, T obs)
|
||||
{
|
||||
try {
|
||||
return obop.apply(obs);
|
||||
@@ -218,7 +218,6 @@ public class ObserverList extends ArrayList
|
||||
"[op=" + obop +
|
||||
", obs=" + StringUtil.safeToString(obs) + "].");
|
||||
Log.logStackTrace(thrown);
|
||||
|
||||
// if they booched it, definitely don't remove them
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
|
||||
/**
|
||||
* A class to sort arrays of objects (quickly even)
|
||||
* A class to sort arrays of objects (quickly even).
|
||||
*/
|
||||
public class QuickSort
|
||||
{
|
||||
@@ -32,7 +32,7 @@ public class QuickSort
|
||||
* Sorts the supplied array of objects from least to greatest, using
|
||||
* the supplied comparator.
|
||||
*/
|
||||
public static void sort (Object[] a, Comparator comp)
|
||||
public static <T> void sort (T[] a, Comparator<? super T> comp)
|
||||
{
|
||||
sort(a, 0, a.length - 1, comp);
|
||||
}
|
||||
@@ -41,7 +41,7 @@ public class QuickSort
|
||||
* Sorts the supplied array of comparable objects from least to
|
||||
* greatest.
|
||||
*/
|
||||
public static void sort (Comparable[] a)
|
||||
public static <T extends Comparable<? super T>> void sort (T[] a)
|
||||
{
|
||||
sort(a, 0, a.length - 1);
|
||||
}
|
||||
@@ -50,7 +50,7 @@ public class QuickSort
|
||||
* Sorts the supplied array of objects from greatest to least, using
|
||||
* the supplied comparator.
|
||||
*/
|
||||
public static void rsort (Object[] a, Comparator comp)
|
||||
public static <T> void rsort (T[] a, Comparator<? super T> comp)
|
||||
{
|
||||
rsort(a, 0, a.length - 1, comp);
|
||||
}
|
||||
@@ -59,7 +59,7 @@ public class QuickSort
|
||||
* Sorts the supplied array of comparable objects from greatest to
|
||||
* least.
|
||||
*/
|
||||
public static void rsort (Comparable[] a)
|
||||
public static <T extends Comparable<? super T>> void rsort (T[] a)
|
||||
{
|
||||
rsort(a, 0, a.length - 1);
|
||||
}
|
||||
@@ -76,14 +76,15 @@ public class QuickSort
|
||||
* @param comp the comparator to use to establish ordering between
|
||||
* elements.
|
||||
*/
|
||||
public static void sort (Object[] a, int lo0, int hi0, Comparator comp)
|
||||
public static <T> void sort (
|
||||
T[] a, int lo0, int hi0, Comparator<? super T> comp)
|
||||
{
|
||||
// bail out if we're already done
|
||||
if (hi0 <= lo0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object t;
|
||||
T t;
|
||||
|
||||
// if this is a two element file, do a simple sort on it
|
||||
if (hi0 - lo0 == 1) {
|
||||
@@ -95,7 +96,7 @@ public class QuickSort
|
||||
}
|
||||
|
||||
// the middle element in the array is our partitioning element
|
||||
Object mid = a[(lo0 + hi0)/2];
|
||||
T mid = a[(lo0 + hi0)/2];
|
||||
|
||||
// set up our partitioning boundaries
|
||||
int lo = lo0-1, hi = hi0+1;
|
||||
@@ -143,14 +144,15 @@ public class QuickSort
|
||||
* @param comp the comparator to use to establish ordering between
|
||||
* elements.
|
||||
*/
|
||||
public static void rsort (Object[] a, int lo0, int hi0, Comparator comp)
|
||||
public static <T> void rsort (
|
||||
T[] a, int lo0, int hi0, Comparator<? super T> comp)
|
||||
{
|
||||
// bail out if we're already done
|
||||
if (hi0 <= lo0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object t;
|
||||
T t;
|
||||
|
||||
// if this is a two element file, do a simple sort on it
|
||||
if (hi0 - lo0 == 1) {
|
||||
@@ -162,7 +164,7 @@ public class QuickSort
|
||||
}
|
||||
|
||||
// the middle element in the array is our partitioning element
|
||||
Object mid = a[(lo0 + hi0)/2];
|
||||
T mid = a[(lo0 + hi0)/2];
|
||||
|
||||
// set up our partitioning boundaries
|
||||
int lo = lo0-1, hi = hi0+1;
|
||||
@@ -208,14 +210,15 @@ public class QuickSort
|
||||
* @param hi0 the index of the highest element to be included in the
|
||||
* sort.
|
||||
*/
|
||||
public static void sort (Comparable[] a, int lo0, int hi0)
|
||||
public static <T extends Comparable<? super T>> void sort (
|
||||
T[] a, int lo0, int hi0)
|
||||
{
|
||||
// bail out if we're already done
|
||||
if (hi0 <= lo0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Comparable t;
|
||||
T t;
|
||||
|
||||
// if this is a two element file, do a simple sort on it
|
||||
if (hi0 - lo0 == 1) {
|
||||
@@ -227,7 +230,7 @@ public class QuickSort
|
||||
}
|
||||
|
||||
// the middle element in the array is our partitioning element
|
||||
Comparable mid = a[(lo0 + hi0)/2];
|
||||
T mid = a[(lo0 + hi0)/2];
|
||||
|
||||
// set up our partitioning boundaries
|
||||
int lo = lo0-1, hi = hi0+1;
|
||||
@@ -273,14 +276,15 @@ public class QuickSort
|
||||
* @param hi0 the index of the highest element to be included in the
|
||||
* sort.
|
||||
*/
|
||||
public static void rsort (Comparable[] a, int lo0, int hi0)
|
||||
public static <T extends Comparable<? super T>> void rsort (
|
||||
T[] a, int lo0, int hi0)
|
||||
{
|
||||
// bail out if we're already done
|
||||
if (hi0 <= lo0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Comparable t;
|
||||
T t;
|
||||
|
||||
// if this is a two element file, do a simple sort on it
|
||||
if (hi0 - lo0 == 1) {
|
||||
@@ -292,7 +296,7 @@ public class QuickSort
|
||||
}
|
||||
|
||||
// the middle element in the array is our partitioning element
|
||||
Comparable mid = a[(lo0 + hi0)/2];
|
||||
T mid = a[(lo0 + hi0)/2];
|
||||
|
||||
// set up our partitioning boundaries
|
||||
int lo = lo0-1, hi = hi0+1;
|
||||
@@ -332,16 +336,27 @@ public class QuickSort
|
||||
* Sort the elements in the specified ArrayList according to their
|
||||
* natural order.
|
||||
*/
|
||||
public static void sort (ArrayList a)
|
||||
public static <T extends Comparable<? super T>> void sort (ArrayList<T> a)
|
||||
{
|
||||
sort(a, Comparators.COMPARABLE);
|
||||
sort(a, new Comparator<T>() {
|
||||
public int compare (T o1, T o2) {
|
||||
if (o1 == o2) { // catches null == null
|
||||
return 0;
|
||||
} else if (o1 == null) {
|
||||
return 1;
|
||||
} else if (o2 == null) {
|
||||
return -1;
|
||||
}
|
||||
return o1.compareTo(o2); // null-free
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort the elements in the specified ArrayList according to the
|
||||
* ordering imposed by the specified Comparator.
|
||||
*/
|
||||
public static void sort (ArrayList a, Comparator comp)
|
||||
public static <T> void sort (ArrayList<T> a, Comparator<T> comp)
|
||||
{
|
||||
sort(a, 0, a.size() - 1, comp);
|
||||
}
|
||||
@@ -350,32 +365,44 @@ public class QuickSort
|
||||
* Sort the elements in the specified ArrayList according to their
|
||||
* reverse natural order.
|
||||
*/
|
||||
public static void rsort (ArrayList a)
|
||||
public static <T extends Comparable<? super T>> void rsort (ArrayList<T> a)
|
||||
{
|
||||
sort(a, java.util.Collections.reverseOrder());
|
||||
sort(a, new Comparator<T>() {
|
||||
public int compare (T o1, T o2) {
|
||||
if (o1 == o2) { // catches null == null
|
||||
return 0;
|
||||
} else if (o1 == null) {
|
||||
return -1;
|
||||
} else if (o2 == null) {
|
||||
return 1;
|
||||
}
|
||||
return o2.compareTo(o1); // null-free
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort the elements in the specified ArrayList according to the
|
||||
* reverse ordering imposed by the specified Comparator.
|
||||
*/
|
||||
public static void rsort (ArrayList a, Comparator comp)
|
||||
public static <T> void rsort (ArrayList<T> a, Comparator<T> comp)
|
||||
{
|
||||
sort(a, new Comparators.ReversingComparator(comp));
|
||||
sort(a, java.util.Collections.reverseOrder(comp));
|
||||
}
|
||||
|
||||
/**
|
||||
* Sort a subset of the elements in the specified ArrayList according
|
||||
* to the ordering imposed by the specified Comparator.
|
||||
*/
|
||||
public static void sort (ArrayList a, int lo0, int hi0, Comparator comp)
|
||||
public static <T> void sort (
|
||||
ArrayList<T> a, int lo0, int hi0, Comparator<T> comp)
|
||||
{
|
||||
// bail out if we're already done
|
||||
if (hi0 <= lo0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Object e1, e2, t;
|
||||
T e1, e2, t;
|
||||
|
||||
// if this is a two element file, do a simple sort on it
|
||||
if (hi0 - lo0 == 1) {
|
||||
@@ -390,7 +417,7 @@ public class QuickSort
|
||||
}
|
||||
|
||||
// the middle element in the array is our partitioning element
|
||||
Object mid = a.get((lo0 + hi0)/2);
|
||||
T mid = a.get((lo0 + hi0)/2);
|
||||
|
||||
// set up our partitioning boundaries
|
||||
int lo = lo0-1, hi = hi0+1;
|
||||
|
||||
@@ -6,7 +6,7 @@ package com.samskivert.util;
|
||||
/**
|
||||
* Multiplexes ResultListener responses to multiple ResultListeners.
|
||||
*/
|
||||
public class ResultListenerList extends ObserverList
|
||||
public class ResultListenerList extends ObserverList<ResultListener>
|
||||
implements ResultListener
|
||||
{
|
||||
/**
|
||||
@@ -31,9 +31,9 @@ public class ResultListenerList extends ObserverList
|
||||
*/
|
||||
public void requestCompleted (final Object result)
|
||||
{
|
||||
apply(new ObserverOp() {
|
||||
public boolean apply (Object observer) {
|
||||
((ResultListener) observer).requestCompleted(result);
|
||||
apply(new ObserverOp<ResultListener>() {
|
||||
public boolean apply (ResultListener observer) {
|
||||
observer.requestCompleted(result);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
@@ -45,9 +45,9 @@ public class ResultListenerList extends ObserverList
|
||||
*/
|
||||
public void requestFailed (final Exception cause)
|
||||
{
|
||||
apply(new ObserverOp() {
|
||||
public boolean apply (Object observer) {
|
||||
((ResultListener) observer).requestFailed(cause);
|
||||
apply(new ObserverOp<ResultListener>() {
|
||||
public boolean apply (ResultListener observer) {
|
||||
observer.requestFailed(cause);
|
||||
return true;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -73,7 +73,7 @@ public class SerialExecutor
|
||||
public void addTask (ExecutorTask task)
|
||||
{
|
||||
for (int ii=0, nn=_queue.size(); ii < nn; ii++) {
|
||||
ExecutorTask taskOnQueue = (ExecutorTask) _queue.get(ii);
|
||||
ExecutorTask taskOnQueue = _queue.get(ii);
|
||||
if (taskOnQueue.merge(task)) {
|
||||
return;
|
||||
}
|
||||
@@ -105,7 +105,7 @@ public class SerialExecutor
|
||||
_executingNow = !_queue.isEmpty();
|
||||
if (_executingNow) {
|
||||
// start up a thread to execute the task in question
|
||||
ExecutorTask task = (ExecutorTask) _queue.remove(0);
|
||||
ExecutorTask task = _queue.remove(0);
|
||||
final ExecutorThread thread = new ExecutorThread(task);
|
||||
thread.start();
|
||||
|
||||
@@ -196,5 +196,5 @@ public class SerialExecutor
|
||||
protected boolean _executingNow = false;
|
||||
|
||||
/** The queue of tasks to execute. */
|
||||
protected ArrayList _queue = new ArrayList();
|
||||
protected ArrayList<ExecutorTask> _queue = new ArrayList<ExecutorTask>();
|
||||
}
|
||||
|
||||
@@ -40,10 +40,10 @@ public class ShortestPath
|
||||
public interface Graph
|
||||
{
|
||||
/** Enumerates all nodes in the graph. */
|
||||
public Iterator enumerateNodes ();
|
||||
public Iterator<Object> enumerateNodes ();
|
||||
|
||||
/** Returns the list of the edges for the specified node. */
|
||||
public List getEdges (Object node);
|
||||
public List<Object> getEdges (Object node);
|
||||
|
||||
/** Returns the weight associated with the supplied edge in the
|
||||
* direction established by the supplied starting node. */
|
||||
@@ -59,18 +59,19 @@ public class ShortestPath
|
||||
* assumes that the graph is properly formed and may behave strangely
|
||||
* or throw an exception if provided with an invalid graph.
|
||||
*
|
||||
* @return a list of the edges that must be followed to traverse from
|
||||
* the starting node to the ending node. This list may be empty if the
|
||||
* graph is improperly formed.
|
||||
* @return a list of the edges that must be followed to traverse from the
|
||||
* starting node to the ending node. This list may be empty if the graph is
|
||||
* improperly formed.
|
||||
*/
|
||||
public static List compute (Graph graph, Object start, Object end)
|
||||
public static List<Object> compute (Graph graph, Object start, Object end)
|
||||
{
|
||||
HashMap nodes = new HashMap();
|
||||
HashSet relaxed = new HashSet();
|
||||
SortableArrayList uptight = new SortableArrayList();
|
||||
HashMap<Object,NodeInfo> nodes = new HashMap<Object,NodeInfo>();
|
||||
HashSet<Object> relaxed = new HashSet<Object>();
|
||||
ComparableArrayList<NodeInfo> uptight =
|
||||
new ComparableArrayList<NodeInfo>();
|
||||
|
||||
// initialize our searching info
|
||||
for (Iterator iter = graph.enumerateNodes(); iter.hasNext(); ) {
|
||||
for (Iterator<Object> iter = graph.enumerateNodes(); iter.hasNext(); ) {
|
||||
NodeInfo info = new NodeInfo();
|
||||
info.node = iter.next();
|
||||
if (info.node == start) {
|
||||
@@ -88,7 +89,7 @@ public class ShortestPath
|
||||
// make a note that it is now relaxed
|
||||
relaxed.add(info.node);
|
||||
// relax its uptight neighbors
|
||||
List edges = graph.getEdges(info.node);
|
||||
List<Object> edges = graph.getEdges(info.node);
|
||||
for (int ii = 0, ll = edges.size(); ii < ll; ii++) {
|
||||
Object edge = edges.get(ii);
|
||||
Object onode = graph.getOpposite(edge, info.node);
|
||||
@@ -110,19 +111,17 @@ public class ShortestPath
|
||||
}
|
||||
|
||||
// now trace the path from the final node back to the start
|
||||
ArrayList path = new ArrayList();
|
||||
NodeInfo info = (NodeInfo)nodes.get(end);
|
||||
ArrayList<Object> path = new ArrayList<Object>();
|
||||
NodeInfo info = nodes.get(end);
|
||||
while (info.edgeTo != null) {
|
||||
path.add(0, info.edgeTo);
|
||||
info = (NodeInfo)nodes.get(
|
||||
graph.getOpposite(info.edgeTo, info.node));
|
||||
info = nodes.get(graph.getOpposite(info.edgeTo, info.node));
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
/** Used to maintain information during the shortest path search. */
|
||||
protected static final class NodeInfo
|
||||
implements Comparable
|
||||
protected static final class NodeInfo implements Comparable<NodeInfo>
|
||||
{
|
||||
/** The node for which we're representing information. */
|
||||
public Object node;
|
||||
@@ -134,9 +133,9 @@ public class ShortestPath
|
||||
public Object edgeTo;
|
||||
|
||||
/** We order ourselves by the cumulative weight to this node. */
|
||||
public int compareTo (Object o)
|
||||
public int compareTo (NodeInfo o)
|
||||
{
|
||||
return ((NodeInfo)o).weightTo - weightTo;
|
||||
return o.weightTo - weightTo;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,79 +20,31 @@
|
||||
|
||||
package com.samskivert.util;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import java.util.AbstractList;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.RandomAccess;
|
||||
|
||||
import java.lang.reflect.Array;
|
||||
|
||||
/**
|
||||
* Extends the standard Java {@link ArrayList} functionality (which we'd
|
||||
* do with normal object extension if those pig fuckers hadn't made the
|
||||
* instance variables private) and provides a mechanism ({@link #sort})
|
||||
* for sorting the contents of the list that doesn't involve creating two
|
||||
* object arrays. Two copies of the elements array are made if you called
|
||||
* {@link java.util.Collections#sort}</code> (the first is when {@link
|
||||
* #toArray} is called on the collection and the second is when {@link
|
||||
* Arrays#sort} clones the supplied array so that it can do a merge sort).
|
||||
* Provides a mechanism ({@link #sort}) for sorting the contents of the list
|
||||
* that doesn't involve creating two object arrays. Two copies of the elements
|
||||
* array are made if you called {@link java.util.Collections#sort}</code> (the
|
||||
* first is when {@link #toArray} is called on the collection and the second is
|
||||
* when {@link Arrays#sort} clones the supplied array so that it can do a merge
|
||||
* sort).
|
||||
*/
|
||||
public class SortableArrayList extends AbstractList
|
||||
implements List, RandomAccess, Cloneable, Serializable
|
||||
public class SortableArrayList<T> extends BaseArrayList<T>
|
||||
{
|
||||
/**
|
||||
* Sorts the elements in this list using the quick sort algorithm
|
||||
* (which does not involve any object allocation). The elements must
|
||||
* implement {@link Comparable} and all be mutually comparable.
|
||||
*/
|
||||
public void sort ()
|
||||
{
|
||||
sort(Comparators.COMPARABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the elements in this list using the quick sort algorithm
|
||||
* according to their reverse natural ordering. The elements must
|
||||
* implement {@link Comparable} and all be mutually comparable.
|
||||
*/
|
||||
public void rsort ()
|
||||
{
|
||||
sort(java.util.Collections.reverseOrder());
|
||||
}
|
||||
|
||||
/**
|
||||
* Sorts the elements in this list with the supplied element
|
||||
* comparator using the quick sort algorithm (which does not involve
|
||||
* any object allocation). The elements must all be mutually
|
||||
* comparable.
|
||||
*/
|
||||
public void sort (Comparator comp)
|
||||
public void sort (Comparator<T> comp)
|
||||
{
|
||||
if (_size > 1) {
|
||||
QuickSort.sort(_elements, 0, _size-1, comp);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the specified item into the list into a position that
|
||||
* preserves the sorting of the list. The list must be sorted prior to
|
||||
* the call to this method (an empty list built up entirely via calls
|
||||
* to {@link #insertSorted} will be properly sorted). The list must be
|
||||
* entirely comprised of elements that implement {@link Comparable}
|
||||
* and the element being added must implement {@link Comparable} as
|
||||
* well.
|
||||
*
|
||||
* @return the index at which the element was inserted.
|
||||
*/
|
||||
public int insertSorted (Object value)
|
||||
{
|
||||
return insertSorted(value, Comparators.COMPARABLE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Inserts the specified item into the list into a position that
|
||||
* preserves the sorting of the list according to the supplied {@link
|
||||
@@ -102,32 +54,17 @@ public class SortableArrayList extends AbstractList
|
||||
*
|
||||
* @return the index at which the element was inserted.
|
||||
*/
|
||||
public int insertSorted (Object value, Comparator comp)
|
||||
public int insertSorted (T value, Comparator<T> comp)
|
||||
{
|
||||
int ipos = binarySearch(value, comp);
|
||||
if (ipos < 0) {
|
||||
ipos = -(ipos+1);
|
||||
}
|
||||
_elements = ListUtil.insert(_elements, ipos, value);
|
||||
_elements = (T[])ListUtil.insert(_elements, ipos, value);
|
||||
_size++;
|
||||
return ipos;
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a binary search, attempting to locate the specified
|
||||
* object. The array must be sorted for this to operate correctly and
|
||||
* the contents of the array must all implement {@link Comparable}
|
||||
* (and actually be comparable to one another).
|
||||
*
|
||||
* @return the index of the object in question or
|
||||
* <code>(-(<i>insertion point</i>) - 1)</code> (always a negative
|
||||
* value) if the object was not found in the list.
|
||||
*/
|
||||
public int binarySearch (Object key)
|
||||
{
|
||||
return ArrayUtil.binarySearch(_elements, 0, _size, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Performs a binary search, attempting to locate the specified
|
||||
* object. The array must be in the sort order defined by the supplied
|
||||
@@ -137,163 +74,8 @@ public class SortableArrayList extends AbstractList
|
||||
* <code>(-(<i>insertion point</i>) - 1)</code> (always a negative
|
||||
* value) if the object was not found in the list.
|
||||
*/
|
||||
public int binarySearch (Object key, Comparator comp)
|
||||
public int binarySearch (T key, Comparator<T> comp)
|
||||
{
|
||||
return ArrayUtil.binarySearch(_elements, 0, _size, key, comp);
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public int size ()
|
||||
{
|
||||
return _size;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean isEmpty ()
|
||||
{
|
||||
return (_size == 0);
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean contains (Object o)
|
||||
{
|
||||
return ListUtil.contains(_elements, o);
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object[] toArray ()
|
||||
{
|
||||
return toArray(new Object[_size]);
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object[] toArray (Object[] target)
|
||||
{
|
||||
// create the target array if necessary
|
||||
if (target.length < _size) {
|
||||
target = (Object[])Array.newInstance(
|
||||
target.getClass().getComponentType(), _size);
|
||||
}
|
||||
|
||||
// copy the elements
|
||||
if (_elements != null) {
|
||||
System.arraycopy(_elements, 0, target, 0, _size);
|
||||
}
|
||||
|
||||
return target;
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public void clear ()
|
||||
{
|
||||
_elements = null;
|
||||
_size = 0;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean add (Object o)
|
||||
{
|
||||
_elements = ListUtil.add(_elements, _size, o);
|
||||
_size++;
|
||||
return true;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public boolean remove (Object o)
|
||||
{
|
||||
if (ListUtil.remove(_elements, o) != null) {
|
||||
_size--;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object get (int index)
|
||||
{
|
||||
rangeCheck(index, false);
|
||||
return _elements[index];
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object set (int index, Object element)
|
||||
{
|
||||
rangeCheck(index, false);
|
||||
Object old = _elements[index];
|
||||
_elements[index] = element;
|
||||
return old;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public void add (int index, Object element)
|
||||
{
|
||||
rangeCheck(index, true);
|
||||
_elements = ListUtil.insert(_elements, index, element);
|
||||
_size++;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public Object remove (int index)
|
||||
{
|
||||
rangeCheck(index, false);
|
||||
Object oval = ListUtil.remove(_elements, index);
|
||||
_size--;
|
||||
return oval;
|
||||
}
|
||||
|
||||
// documentation inherited from interface
|
||||
public int indexOf (Object o)
|
||||
{
|
||||
return ListUtil.indexOf(_elements, o);
|
||||
}
|
||||
|
||||
// // documentation inherited from interface
|
||||
// public int lastIndexOf (Object o)
|
||||
// {
|
||||
// }
|
||||
|
||||
/**
|
||||
* Check the range of a passed-in index to make sure it's valid.
|
||||
*
|
||||
* @param insert if true, an index equal to our size is valid.
|
||||
*/
|
||||
protected final void rangeCheck (int index, boolean insert)
|
||||
{
|
||||
if ((index < 0) || (insert ? (index > _size) : (index >= _size))) {
|
||||
throw new IndexOutOfBoundsException(
|
||||
"Index: " + index + ", Size: " + _size);
|
||||
}
|
||||
}
|
||||
|
||||
// documentation inherited
|
||||
public Object clone ()
|
||||
{
|
||||
try {
|
||||
Object[] elDup = null;
|
||||
if (_elements != null) {
|
||||
elDup = new Object[_elements.length];
|
||||
System.arraycopy(_elements, 0, elDup, 0, _elements.length);
|
||||
}
|
||||
SortableArrayList dup = (SortableArrayList) super.clone();
|
||||
dup._elements = elDup;
|
||||
|
||||
return dup;
|
||||
|
||||
} catch (CloneNotSupportedException cnse) {
|
||||
com.samskivert.Log.logStackTrace(cnse); // won't happen.
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The array of elements in our list. */
|
||||
protected Object[] _elements;
|
||||
|
||||
/** The number of elements in our list. */
|
||||
protected int _size;
|
||||
|
||||
/** Change this if the fields or inheritance hierarchy ever changes
|
||||
* (which is extremely unlikely). We override this because I'm tired
|
||||
* of serialized crap not working depending on whether I compiled with
|
||||
* jikes or javac. */
|
||||
private static final long serialVersionUID = 1;
|
||||
}
|
||||
|
||||
@@ -175,7 +175,7 @@ public class StringUtil
|
||||
{
|
||||
// TODO: these regexes should probably be checked to make
|
||||
// sure that javascript can't live inside a link
|
||||
ArrayList allow = new ArrayList();
|
||||
ArrayList<String> allow = new ArrayList<String>();
|
||||
if (allowFormatting) {
|
||||
allow.add("<b>"); allow.add("</b>");
|
||||
allow.add("<i>"); allow.add("</i>");
|
||||
@@ -195,10 +195,7 @@ public class StringUtil
|
||||
allow.add("<a href=[^\"<>!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>");
|
||||
allow.add("</a>");
|
||||
}
|
||||
|
||||
String[] regexes = new String[allow.size()];
|
||||
allow.toArray(regexes);
|
||||
return restrictHTML(src, regexes);
|
||||
return restrictHTML(src, allow.toArray(new String[allow.size()]));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -211,12 +208,12 @@ public class StringUtil
|
||||
return src;
|
||||
}
|
||||
|
||||
ArrayList list = new ArrayList();
|
||||
ArrayList<String> list = new ArrayList<String>();
|
||||
list.add(src);
|
||||
for (int ii=0, nn = regexes.length; ii < nn; ii++) {
|
||||
Pattern p = Pattern.compile(regexes[ii], Pattern.CASE_INSENSITIVE);
|
||||
for (int jj=0; jj < list.size(); jj += 2) {
|
||||
String piece = (String) list.get(jj);
|
||||
String piece = list.get(jj);
|
||||
Matcher m = p.matcher(piece);
|
||||
if (m.find()) {
|
||||
list.set(jj, piece.substring(0, m.start()));
|
||||
@@ -230,7 +227,7 @@ public class StringUtil
|
||||
// odd elements contain stuff that matched a regex
|
||||
StringBuffer buf = new StringBuffer();
|
||||
for (int jj=0, nn = list.size(); jj < nn; jj++) {
|
||||
String s = (String) list.get(jj);
|
||||
String s = list.get(jj);
|
||||
if (jj % 2 == 0) {
|
||||
s = replace(s, "<", "<");
|
||||
s = replace(s, ">", ">");
|
||||
@@ -1424,7 +1421,8 @@ public class StringUtil
|
||||
|
||||
/** Maps the 16 most frequent letters in the English language to a
|
||||
* number between 0 and 15. Used by {@link #stringCode}. */
|
||||
protected static final HashIntMap _letterToBits = new HashIntMap();
|
||||
protected static final HashIntMap<Integer> _letterToBits =
|
||||
new HashIntMap<Integer>();
|
||||
static {
|
||||
_letterToBits.put('e', new Integer(0));
|
||||
_letterToBits.put('t', new Integer(1));
|
||||
|
||||
@@ -27,16 +27,16 @@ import java.io.Serializable;
|
||||
* It provides hashcode and equality semantics that allow it to be used to
|
||||
* combine two objects into a single key (for hashtables, etc.).
|
||||
*/
|
||||
public class Tuple implements Serializable
|
||||
public class Tuple<L,R> implements Serializable
|
||||
{
|
||||
/** The left object. */
|
||||
public Object left;
|
||||
public L left;
|
||||
|
||||
/** The right object. */
|
||||
public Object right;
|
||||
public R right;
|
||||
|
||||
/** Construct a tuple with the specified two objects. */
|
||||
public Tuple (Object left, Object right)
|
||||
public Tuple (L left, R right)
|
||||
{
|
||||
this.left = left;
|
||||
this.right = right;
|
||||
|
||||
@@ -25,7 +25,7 @@ public class ValueMarshaller
|
||||
throws Exception
|
||||
{
|
||||
// look up an argument parser for the field type
|
||||
Parser parser = (Parser)_parsers.get(type);
|
||||
Parser parser = _parsers.get(type);
|
||||
if (parser == null) {
|
||||
String errmsg = "Don't know how to convert strings into " +
|
||||
"values of type '" + type + "'.";
|
||||
@@ -39,7 +39,7 @@ public class ValueMarshaller
|
||||
public Object parse (String source) throws Exception;
|
||||
}
|
||||
|
||||
protected static HashMap _parsers;
|
||||
protected static HashMap<Class,Parser> _parsers;
|
||||
|
||||
protected static final byte[] BYTE_ARRAY_PROTOTYPE = new byte[0];
|
||||
protected static final int[] INT_ARRAY_PROTOTYPE = new int[0];
|
||||
@@ -47,7 +47,7 @@ public class ValueMarshaller
|
||||
protected static final String[] STRING_ARRAY_PROTOTYPE = new String[0];
|
||||
|
||||
static {
|
||||
_parsers = new HashMap();
|
||||
_parsers = new HashMap<Class,Parser>();
|
||||
|
||||
// we can parse strings
|
||||
_parsers.put(String.class, new Parser() {
|
||||
|
||||
@@ -74,7 +74,7 @@ public class DataTool
|
||||
* Sorts the supplied list and returns it. The elements <em>must</em>
|
||||
* implement {@link Comparable}.
|
||||
*/
|
||||
public List sort (List list)
|
||||
public <T extends Comparable<? super T>> List<T> sort (List<T> list)
|
||||
{
|
||||
Collections.sort(list);
|
||||
return list;
|
||||
@@ -85,9 +85,9 @@ public class DataTool
|
||||
* returns the list. The elements <em>must</em> implement {@link
|
||||
* Comparable}.
|
||||
*/
|
||||
public List sort (Collection data)
|
||||
public <T extends Comparable<? super T>> List<T> sort (Collection<T> data)
|
||||
{
|
||||
return sort(new ArrayList(data));
|
||||
return sort(new ArrayList<T>(data));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -95,9 +95,9 @@ public class DataTool
|
||||
* returns the list. The elements <em>must</em> implement {@link
|
||||
* Comparable}.
|
||||
*/
|
||||
public List sort (Iterator iter)
|
||||
public <T extends Comparable<? super T>> List<T> sort (Iterator<T> iter)
|
||||
{
|
||||
ArrayList list = new ArrayList();
|
||||
ArrayList<T> list = new ArrayList<T>();
|
||||
CollectionUtil.addAll(list, iter);
|
||||
return sort(list);
|
||||
}
|
||||
|
||||
@@ -216,6 +216,11 @@ public class DispatcherServlet extends VelocityServlet
|
||||
"from file '" + INIT_PROPS_KEY + "'.");
|
||||
}
|
||||
|
||||
// if we failed to create our application for whatever reason; bail
|
||||
if (_app == null) {
|
||||
return props;
|
||||
}
|
||||
|
||||
// let the application set up velocity properties
|
||||
_app.configureVelocity(config, props);
|
||||
|
||||
@@ -270,16 +275,24 @@ public class DispatcherServlet extends VelocityServlet
|
||||
ec.addEventHandler(this);
|
||||
}
|
||||
|
||||
// obtain the siteid for this request and stuff that into the
|
||||
// context
|
||||
// if our application failed to initialize, fail with a 500 response
|
||||
if (_app == null) {
|
||||
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
return null;
|
||||
}
|
||||
|
||||
// obtain the siteid for this request and stuff that into the context
|
||||
int siteId = SiteIdentifier.DEFAULT_SITE_ID;
|
||||
SiteIdentifier ident = _app.getSiteIdentifier();
|
||||
int siteId = ident.identifySite(req);
|
||||
if (ident != null) {
|
||||
siteId = ident.identifySite(req);
|
||||
}
|
||||
if (_usingSiteLoading) {
|
||||
ctx.put("__siteid__", new Integer(siteId));
|
||||
}
|
||||
|
||||
// put the context path in the context as well to make it easier
|
||||
// to construct full paths
|
||||
// put the context path in the context as well to make it easier to
|
||||
// construct full paths
|
||||
ctx.put("context_path", req.getContextPath());
|
||||
|
||||
// then select the template
|
||||
@@ -287,17 +300,16 @@ public class DispatcherServlet extends VelocityServlet
|
||||
try {
|
||||
tmpl = selectTemplate(siteId, ictx);
|
||||
} catch (ResourceNotFoundException rnfe) {
|
||||
// send up a 404. For some annoying reason, Jetty tells
|
||||
// Apache that all is okay (200) when sending its own custom
|
||||
// error pages, forcing us to use Jetty's custom error page
|
||||
// handling code rather than passing it up the chain to be
|
||||
// dealt with appropriately.
|
||||
ictx.getResponse().sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
// send up a 404. For some annoying reason, Jetty tells Apache
|
||||
// that all is okay (200) when sending its own custom error pages,
|
||||
// forcing us to use Jetty's custom error page handling code rather
|
||||
// than passing it up the chain to be dealt with appropriately.
|
||||
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
|
||||
return null;
|
||||
}
|
||||
|
||||
// assume the request is in the default character set unless it
|
||||
// has actually been sensibly supplied by the browser
|
||||
// assume the request is in the default character set unless it has
|
||||
// actually been sensibly supplied by the browser
|
||||
if (req.getCharacterEncoding() == null) {
|
||||
req.setCharacterEncoding(_charset);
|
||||
}
|
||||
@@ -308,12 +320,12 @@ public class DispatcherServlet extends VelocityServlet
|
||||
|
||||
Exception error = null;
|
||||
try {
|
||||
// insert the application into the context in case the
|
||||
// logic or a tool wishes to make use of it
|
||||
// insert the application into the context in case the logic or a
|
||||
// tool wishes to make use of it
|
||||
ictx.put(APPLICATION_KEY, _app);
|
||||
|
||||
// if the application provides a message manager, we want
|
||||
// create a translation tool and stuff that into the context
|
||||
// if the application provides a message manager, we want create a
|
||||
// translation tool and stuff that into the context
|
||||
MessageManager msgmgr = _app.getMessageManager();
|
||||
if (msgmgr != null) {
|
||||
I18nTool i18n = new I18nTool(req, msgmgr);
|
||||
@@ -342,8 +354,8 @@ public class DispatcherServlet extends VelocityServlet
|
||||
// allow the application to do global access control
|
||||
_app.checkAccess(ictx);
|
||||
|
||||
// resolve the appropriate logic class for this URI and
|
||||
// execute it if it exists
|
||||
// resolve the appropriate logic class for this URI and execute it
|
||||
// if it exists
|
||||
String path = req.getServletPath();
|
||||
logic = resolveLogic(path);
|
||||
if (logic != null) {
|
||||
@@ -363,15 +375,15 @@ public class DispatcherServlet extends VelocityServlet
|
||||
}
|
||||
|
||||
} catch (RedirectException re) {
|
||||
ictx.getResponse().sendRedirect(re.getRedirectURL());
|
||||
rsp.sendRedirect(re.getRedirectURL());
|
||||
return null;
|
||||
|
||||
} catch (HttpErrorException hee) {
|
||||
String msg = hee.getErrorMessage();
|
||||
if (msg != null) {
|
||||
ictx.getResponse().sendError(hee.getErrorCode(), msg);
|
||||
rsp.sendError(hee.getErrorCode(), msg);
|
||||
} else {
|
||||
ictx.getResponse().sendError(hee.getErrorCode());
|
||||
rsp.sendError(hee.getErrorCode());
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -465,7 +477,7 @@ public class DispatcherServlet extends VelocityServlet
|
||||
{
|
||||
// look for a cached logic instance
|
||||
String lclass = _app.generateClass(path);
|
||||
Logic logic = (Logic)_logic.get(lclass);
|
||||
Logic logic = _logic.get(lclass);
|
||||
|
||||
if (logic == null) {
|
||||
try {
|
||||
@@ -499,7 +511,7 @@ public class DispatcherServlet extends VelocityServlet
|
||||
protected Application _app;
|
||||
|
||||
/** A table of resolved logic instances. */
|
||||
protected HashMap _logic = new HashMap();
|
||||
protected HashMap<String,Logic> _logic = new HashMap<String,Logic>();
|
||||
|
||||
/** The character set in which serve our responses. */
|
||||
protected String _charset;
|
||||
|
||||
@@ -67,7 +67,7 @@ public class SetPropertyFieldsRule extends Rule
|
||||
public void addFieldParser (String property, FieldParser parser)
|
||||
{
|
||||
if (_parsers == null) {
|
||||
_parsers = new HashMap();
|
||||
_parsers = new HashMap<String,FieldParser>();
|
||||
}
|
||||
_parsers.put(property, parser);
|
||||
}
|
||||
@@ -115,7 +115,7 @@ public class SetPropertyFieldsRule extends Rule
|
||||
|
||||
// look for a custom field parser
|
||||
if ((_parsers != null) &&
|
||||
((parser = (FieldParser)_parsers.get(lname)) != null)) {
|
||||
((parser = _parsers.get(lname)) != null)) {
|
||||
value = parser.parse(valstr);
|
||||
} else {
|
||||
// otherwise use the value marshaller to parse the
|
||||
@@ -133,6 +133,6 @@ public class SetPropertyFieldsRule extends Rule
|
||||
}
|
||||
}
|
||||
|
||||
protected HashMap _parsers;
|
||||
protected HashMap<String,FieldParser> _parsers;
|
||||
protected boolean _warnNonFields;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user