diff --git a/build.xml b/build.xml index a9416db7..29c6f143 100644 --- a/build.xml +++ b/build.xml @@ -172,7 +172,7 @@ + source="1.5" target="1.5"> diff --git a/src/java/com/samskivert/jdbc/JORARepository.java b/src/java/com/samskivert/jdbc/JORARepository.java index fb6c8581..15b9deee 100644 --- a/src/java/com/samskivert/jdbc/JORARepository.java +++ b/src/java/com/samskivert/jdbc/JORARepository.java @@ -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 int insert (final Table table, final T object) throws PersistenceException { - Integer iid = (Integer)execute(new Operation() { - public Object invoke (Connection conn, DatabaseLiaison liaison) + return execute(new Operation() { + 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 void update (final Table table, final T object) throws PersistenceException { - execute(new Operation() { + execute(new Operation() { 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 ArrayList loadAll (final Table table, + final String query) throws PersistenceException { - return (ArrayList)execute(new Operation() { - public Object invoke (Connection conn, DatabaseLiaison liaison) + return execute(new Operation>() { + public ArrayList 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. Note: the query should match one or zero * records, not more. */ - protected Object load (final Table table, final String query) + protected T load (final Table table, final String query) throws PersistenceException { - return execute(new Operation() { - public Object invoke (Connection conn, DatabaseLiaison liaison) + return execute(new Operation() { + 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. Note: the query should match one or zero * records, not more. */ - protected Object loadByExample (final Table table, final Object example) + protected T loadByExample (final Table table, final T example) throws PersistenceException { - return execute(new Operation() { - public Object invoke (Connection conn, DatabaseLiaison liaison) + return execute(new Operation() { + 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. Note: the query should match one or zero * records, not more. */ - protected Object loadByExample ( - final Table table, final FieldMask mask, final Object example) + protected T loadByExample ( + final Table table, final FieldMask mask, final T example) throws PersistenceException { - return execute(new Operation() { - public Object invoke (Connection conn, DatabaseLiaison liaison) + return execute(new Operation() { + 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 void store (final Table table, final T object) throws PersistenceException { - execute(new Operation() { + execute(new Operation() { 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 void updateField ( + final Table table, final T object, String field) throws PersistenceException { final FieldMask mask = table.getFieldMask(); mask.setModified(field); - execute(new Operation() { + execute(new Operation() { 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 void updateFields ( + final Table 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() { 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 void delete (final Table table, final T object) throws PersistenceException { - execute(new Operation() { + execute(new Operation() { public Object invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { diff --git a/src/java/com/samskivert/jdbc/LiaisonRegistry.java b/src/java/com/samskivert/jdbc/LiaisonRegistry.java index 5bf7e4d4..c16f7337 100644 --- a/src/java/com/samskivert/jdbc/LiaisonRegistry.java +++ b/src/java/com/samskivert/jdbc/LiaisonRegistry.java @@ -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 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 _liaisons = + new ArrayList(); + protected static HashMap _mappings = + new HashMap(); // register our liaison classes static { diff --git a/src/java/com/samskivert/jdbc/SimpleRepository.java b/src/java/com/samskivert/jdbc/SimpleRepository.java index 421c8ecf..a50ac464 100644 --- a/src/java/com/samskivert/jdbc/SimpleRepository.java +++ b/src/java/com/samskivert/jdbc/SimpleRepository.java @@ -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() { 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() { 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() { public Object invoke (Connection conn, DatabaseLiaison liaison) throws SQLException, PersistenceException { diff --git a/src/java/com/samskivert/jdbc/StaticConnectionProvider.java b/src/java/com/samskivert/jdbc/StaticConnectionProvider.java index e6e430b6..8a433611 100644 --- a/src/java/com/samskivert/jdbc/StaticConnectionProvider.java +++ b/src/java/com/samskivert/jdbc/StaticConnectionProvider.java @@ -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 idents = new ArrayList(); } /** 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 _idents = new HashMap(); /** A mapping from connection key to connection records. */ - protected HashMap _keys = new HashMap(); + protected HashMap _keys = new HashMap(); /** The key used as defaults for the database definitions. */ protected static final String DEFAULTS_KEY = "default"; diff --git a/src/java/com/samskivert/jdbc/jora/Cursor.java b/src/java/com/samskivert/jdbc/jora/Cursor.java index 48047cfb..d079f759 100644 --- a/src/java/com/samskivert/jdbc/jora/Cursor.java +++ b/src/java/com/samskivert/jdbc/jora/Cursor.java @@ -38,18 +38,21 @@ public class Cursor 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 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 result = null; stmt = null; } - nTables = 0; +// nTables = 0; } /** Extracts no more than maxElements records from database and @@ -186,7 +190,7 @@ public class Cursor public ArrayList toArrayList (int maxElements) throws SQLException { - ArrayList al = new ArrayList(Math.min(maxElements, 100)); + ArrayList al = new ArrayList(Math.min(maxElements, 100)); V o; while (--maxElements >= 0 && (o = next()) != null) { al.add(o); @@ -217,7 +221,7 @@ public class Cursor } this.table = table; this.session = session; - this.nTables = nTables; +// this.nTables = nTables; this.query = query; } @@ -229,7 +233,7 @@ public class Cursor } 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 private Table table; private Session session; - private int nTables; +// private int nTables; private ResultSet result; private String query; private Statement stmt; diff --git a/src/java/com/samskivert/jdbc/jora/FieldMask.java b/src/java/com/samskivert/jdbc/jora/FieldMask.java index f98413fe..23bc9d2e 100644 --- a/src/java/com/samskivert/jdbc/jora/FieldMask.java +++ b/src/java/com/samskivert/jdbc/jora/FieldMask.java @@ -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(); 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 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 _descripMap; } diff --git a/src/java/com/samskivert/jdbc/jora/Session.java b/src/java/com/samskivert/jdbc/jora/Session.java index f90a4ef2..123a60a4 100644 --- a/src/java/com/samskivert/jdbc/jora/Session.java +++ b/src/java/com/samskivert/jdbc/jora/Session.java @@ -29,7 +29,7 @@ public class Session { public Session(String driverClass) { driver = driverClass; - preparedStmtHash = new Hashtable(); + preparedStmtHash = new Hashtable(); connectionID = 0; } @@ -41,7 +41,7 @@ public class Session { public Session(Connection connection) { connectionID = 0; - preparedStmtHash = new Hashtable(); + preparedStmtHash = new Hashtable(); 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 preparedStmtHash; + protected int connectionID; } diff --git a/src/java/com/samskivert/jdbc/jora/Table.java b/src/java/com/samskivert/jdbc/jora/Table.java index 8e4ed302..10cdd53b 100644 --- a/src/java/com/samskivert/jdbc/jora/Table.java +++ b/src/java/com/samskivert/jdbc/jora/Table.java @@ -146,25 +146,6 @@ public class Table return new Cursor(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 selectAll(String condition) { - return new Cursor(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 selectAll(String condition, Session session) { - return new Cursor(this, session, nDerived+1, condition); - } - /** Select records from database table using obj object as * template. * @@ -245,32 +226,7 @@ public class Table */ public final Cursor 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 - * obj 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 - * obj 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(this, session, 1, obj, mask, true); } /** Insert new record in the table. Values of inserted record fields @@ -639,8 +595,7 @@ public class Table */ 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 // --- 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 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 private PreparedStatement deleteStmt; private PreparedStatement insertStmt; - private static Table allTables; +// private static Table allTables; private Constructor 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 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 fieldsVector = + new ArrayList(); 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 } } } - 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 } } - private final int buildFieldsList(Vector buf, Class cls, String prefix) + private final int buildFieldsList(ArrayList buf, Class cls, + String prefix) { Field[] f = cls.getDeclaredFields(); @@ -854,7 +809,7 @@ public class Table FieldDescriptor fd = new FieldDescriptor(f[i], fullName); int type; - buf.addElement(fd); + buf.add(fd); n += 1; String c = fieldClass.getName(); diff --git a/src/java/com/samskivert/net/AttachableURLFactory.java b/src/java/com/samskivert/net/AttachableURLFactory.java index 8f0d8a4c..377f6b6e 100644 --- a/src/java/com/samskivert/net/AttachableURLFactory.java +++ b/src/java/com/samskivert/net/AttachableURLFactory.java @@ -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 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>(); // 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 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> + _handlers; } diff --git a/src/java/com/samskivert/net/MACUtil.java b/src/java/com/samskivert/net/MACUtil.java index c1ef3166..87393e36 100644 --- a/src/java/com/samskivert/net/MACUtil.java +++ b/src/java/com/samskivert/net/MACUtil.java @@ -56,7 +56,7 @@ public class MACUtil { Matcher m = MACRegex.matcher(text); - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); 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]); } /** diff --git a/src/java/com/samskivert/net/cddb/CDDB.java b/src/java/com/samskivert/net/cddb/CDDB.java index 1f09cad3..72eaad96 100644 --- a/src/java/com/samskivert/net/cddb/CDDB.java +++ b/src/java/com/samskivert/net/cddb/CDDB.java @@ -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 list = new ArrayList(); 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 tnames = new ArrayList(); + ArrayList texts = new ArrayList(); // 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 list, int index, String value) { // expand the list as necessary while (list.size() <= index) { diff --git a/src/java/com/samskivert/servlet/IndiscriminateSiteIdentifier.java b/src/java/com/samskivert/servlet/IndiscriminateSiteIdentifier.java index 05011131..8dfdf9a7 100644 --- a/src/java/com/samskivert/servlet/IndiscriminateSiteIdentifier.java +++ b/src/java/com/samskivert/servlet/IndiscriminateSiteIdentifier.java @@ -59,12 +59,12 @@ public class IndiscriminateSiteIdentifier implements SiteIdentifier } // documented inherited from interface - public Iterator enumerateSites () + public Iterator enumerateSites () { return _sites.iterator(); } - protected static ArrayList _sites = new ArrayList(); + protected static ArrayList _sites = new ArrayList(); static { _sites.add(new Site(DEFAULT_SITE_ID, DEFAULT_SITE_STRING)); } diff --git a/src/java/com/samskivert/servlet/JDBCTableSiteIdentifier.java b/src/java/com/samskivert/servlet/JDBCTableSiteIdentifier.java index d9df7a3e..bd307e79 100644 --- a/src/java/com/samskivert/servlet/JDBCTableSiteIdentifier.java +++ b/src/java/com/samskivert/servlet/JDBCTableSiteIdentifier.java @@ -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 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 newStrings = (HashMap) + _sitesByString.clone(); + HashIntMap newIds = (HashIntMap)_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 { 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 sites = new HashIntMap(); + HashMap strings = new HashMap(); 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 mappings = new ArrayList(); 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() { 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 { /** 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 _mappings = + new ArrayList(); /** The mapping from integer site identifiers to string site * identifiers. */ - protected volatile HashIntMap _sitesById = new HashIntMap(); + protected volatile HashIntMap _sitesById = new HashIntMap(); /** The mapping from string site identifiers to integer site * identifiers. */ - protected volatile HashMap _sitesByString = new HashMap(); + protected volatile HashMap _sitesByString = + new HashMap(); /** Used to periodically reload our site data. */ protected long _lastReload; diff --git a/src/java/com/samskivert/servlet/SiteIdentifier.java b/src/java/com/samskivert/servlet/SiteIdentifier.java index e091a295..543aaab3 100644 --- a/src/java/com/samskivert/servlet/SiteIdentifier.java +++ b/src/java/com/samskivert/servlet/SiteIdentifier.java @@ -86,5 +86,5 @@ public interface SiteIdentifier * Returns an enumerator over all {@link Site} mappings known to this * SiteIdentifier. */ - public Iterator enumerateSites (); + public Iterator enumerateSites (); } diff --git a/src/java/com/samskivert/servlet/SiteResourceLoader.java b/src/java/com/samskivert/servlet/SiteResourceLoader.java index 471b9b95..afa4961d 100644 --- a/src/java/com/samskivert/servlet/SiteResourceLoader.java +++ b/src/java/com/samskivert/servlet/SiteResourceLoader.java @@ -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 _locks = new HashIntMap(); /** The table of site-specific jar file information. */ - protected HashIntMap _bundles = new HashIntMap(); + protected HashIntMap _bundles = + new HashIntMap(); /** The table of site-specific class loaders. */ - protected HashIntMap _loaders = new HashIntMap(); + protected HashIntMap _loaders = new HashIntMap(); /** The default path to the site-specific jar files. This won't be * used without logging a complaint first. */ diff --git a/src/java/com/samskivert/servlet/user/UserRepository.java b/src/java/com/samskivert/servlet/user/UserRepository.java index 93af1d12..94408843 100644 --- a/src/java/com/samskivert/servlet/user/UserRepository.java +++ b/src/java/com/samskivert/servlet/user/UserRepository.java @@ -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.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 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 loadUsersFromId (int[] userIds) throws PersistenceException { // make sure we actually have something to do if (userIds.length == 0) { - return new HashIntMap(); + return new HashIntMap(); } final String ids = genIdString(userIds); - return execute(new Operation() { - public HashIntMap invoke (Connection conn, DatabaseLiaison liaison) + return execute(new Operation>() { + public HashIntMap invoke (Connection conn, + DatabaseLiaison liaison) throws PersistenceException, SQLException { - // look up the users - Cursor ec = _utable.select("where userid in (" + ids + ")"); - + Cursor ec = _utable.select( + "where userid in (" + ids + ")"); User user; - HashIntMap data = new HashIntMap(); - while ((user = (User)ec.next()) != null) { + HashIntMap data = new HashIntMap(); + 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>() { - public ArrayList invoke (Connection conn, DatabaseLiaison liaison) + public ArrayList invoke ( + Connection conn, DatabaseLiaison liaison) throws PersistenceException, SQLException { - ArrayList users = (ArrayList) + ArrayList 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 names = new ArrayList(); // do the query execute(new Operation() { @@ -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 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 map = new HashIntMap(); // do the query execute(new Operation() { @@ -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.class, "users", session, "userId"); + } + /** A wrapper that provides access to the userstable. */ - protected Table _utable; + protected Table _utable; } diff --git a/src/java/com/samskivert/servlet/util/ExceptionMap.java b/src/java/com/samskivert/servlet/util/ExceptionMap.java index eb353849..c2e55831 100644 --- a/src/java/com/samskivert/servlet/util/ExceptionMap.java +++ b/src/java/com/samskivert/servlet/util/ExceptionMap.java @@ -80,8 +80,8 @@ public class ExceptionMap if (_keys != null) { return; } else { - _keys = new ArrayList(); - _values = new ArrayList(); + _keys = new ArrayList(); + _values = new ArrayList(); } // 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 classes = new ArrayList(); + 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 _keys; + protected static List _values; // initialize ourselves static { init(); } diff --git a/src/java/com/samskivert/servlet/util/ParameterUtil.java b/src/java/com/samskivert/servlet/util/ParameterUtil.java index 1b4e25b4..443f0085 100644 --- a/src/java/com/samskivert/servlet/util/ParameterUtil.java +++ b/src/java/com/samskivert/servlet/util/ParameterUtil.java @@ -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 getParameters ( + HttpServletRequest req, String name) throws DataValidationException { - HashSet set = new HashSet(); + HashSet set = new HashSet(); String[] values = req.getParameterValues(name); if (values != null) { for (int ii = 0; ii < values.length; ii++) { diff --git a/src/java/com/samskivert/swing/AbsoluteLayout.java b/src/java/com/samskivert/swing/AbsoluteLayout.java index ca3371da..7604d297 100644 --- a/src/java/com/samskivert/swing/AbsoluteLayout.java +++ b/src/java/com/samskivert/swing/AbsoluteLayout.java @@ -157,5 +157,6 @@ public class AbsoluteLayout return 0; } - protected HashMap _constraints = new HashMap(); + protected HashMap _constraints = + new HashMap(); } diff --git a/src/java/com/samskivert/swing/GroupLayout.java b/src/java/com/samskivert/swing/GroupLayout.java index aa5898fd..e28df8ea 100644 --- a/src/java/com/samskivert/swing/GroupLayout.java +++ b/src/java/com/samskivert/swing/GroupLayout.java @@ -212,9 +212,9 @@ public abstract class GroupLayout if (constraints != null) { if (constraints instanceof Constraints) { if (_constraints == null) { - _constraints = new HashMap(); + _constraints = new HashMap(); } - _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 _constraints; protected static final int MINIMUM = 0; protected static final int PREFERRED = 1; diff --git a/src/java/com/samskivert/swing/Label.java b/src/java/com/samskivert/swing/Label.java index e426f50b..62d32510 100644 --- a/src/java/com/samskivert/swing/Label.java +++ b/src/java/com/samskivert/swing/Label.java @@ -401,7 +401,7 @@ public class Label implements SwingConstants, LabelStyleConstants public void layout (Graphics2D gfx) { FontRenderContext frc = gfx.getFontRenderContext(); - ArrayList layouts = null; + ArrayList> 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>(); + layouts.add(new Tuple(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 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 keepWordsWhole * was true and the lines could not be layed out in the target width. */ - protected ArrayList computeLines ( + protected ArrayList> 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> layouts = + new ArrayList>(); 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(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 map = new HashMap(); map.put(TextAttribute.FONT, font); if ((_style & UNDERLINE) != 0) { map.put(TextAttribute.UNDERLINE, diff --git a/src/java/com/samskivert/swing/ObjectEditorTable.java b/src/java/com/samskivert/swing/ObjectEditorTable.java index 991c082b..ca173b60 100644 --- a/src/java/com/samskivert/swing/ObjectEditorTable.java +++ b/src/java/com/samskivert/swing/ObjectEditorTable.java @@ -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 _data = new ArrayList(); } diff --git a/src/java/com/samskivert/swing/RadialMenu.java b/src/java/com/samskivert/swing/RadialMenu.java index 6f6b9351..d5faa757 100644 --- a/src/java/com/samskivert/swing/RadialMenu.java +++ b/src/java/com/samskivert/swing/RadialMenu.java @@ -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() { + 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 items = new ArrayList(); 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 _items = + new ArrayList(); /** 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 _actlist = + new ObserverList(ObserverList.SAFE_IN_ORDER_NOTIFY); } diff --git a/src/java/com/samskivert/util/RuntimeAdjust.java b/src/java/com/samskivert/swing/RuntimeAdjust.java similarity index 97% rename from src/java/com/samskivert/util/RuntimeAdjust.java rename to src/java/com/samskivert/swing/RuntimeAdjust.java index 400b8cbd..1ac32883 100644 --- a/src/java/com/samskivert/util/RuntimeAdjust.java +++ b/src/java/com/samskivert/swing/RuntimeAdjust.java @@ -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 { 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 _adjusts = + new ComparableArrayList(); } diff --git a/src/java/com/samskivert/swing/TableSorter.java b/src/java/com/samskivert/swing/TableSorter.java index 348f3b26..fd2c9aaa 100644 --- a/src/java/com/samskivert/swing/TableSorter.java +++ b/src/java/com/samskivert/swing/TableSorter.java @@ -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> columnComparators = + new HashMap>(); + private List sortingColumns = new ArrayList(); 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 comparator) { if (comparator == null) { columnComparators.remove(type); } else { @@ -211,9 +212,9 @@ public class TableSorter extends AbstractTableModel { } } - protected Comparator getComparator(int column) { + protected Comparator getComparator(int column) { Class columnType = tableModel.getColumnClass(column); - Comparator comparator = (Comparator) columnComparators.get(columnType); + Comparator 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 { 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 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); diff --git a/src/java/com/samskivert/swing/dnd/DnDManager.java b/src/java/com/samskivert/swing/dnd/DnDManager.java index 06aa41ce..55b095d7 100644 --- a/src/java/com/samskivert/swing/dnd/DnDManager.java +++ b/src/java/com/samskivert/swing/dnd/DnDManager.java @@ -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 _droppers = + new HashMap(); /** Our DragSources, indexed by associated component. */ - protected HashMap _draggers = new HashMap(); + protected HashMap _draggers = + new HashMap(); /** The original, last, and top-level components during a drag. */ protected Component _sourceComp, _lastComp, _topComp; diff --git a/src/java/com/samskivert/swing/util/SwingUtil.java b/src/java/com/samskivert/swing/util/SwingUtil.java index bc942976..9b094efa 100644 --- a/src/java/com/samskivert/swing/util/SwingUtil.java +++ b/src/java/com/samskivert/swing/util/SwingUtil.java @@ -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 comp = createPointComparator(origPos); + SortableArrayList possibles = new SortableArrayList(); // 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 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() { + 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; diff --git a/src/java/com/samskivert/swing/util/TaskMaster.java b/src/java/com/samskivert/swing/util/TaskMaster.java index 1a68dd48..e27bd300 100644 --- a/src/java/com/samskivert/swing/util/TaskMaster.java +++ b/src/java/com/samskivert/swing/util/TaskMaster.java @@ -186,5 +186,6 @@ public class TaskMaster protected Object _source; } - protected static Hashtable _tasks = new Hashtable(); + protected static Hashtable _tasks = + new Hashtable(); } diff --git a/src/java/com/samskivert/util/ArrayIntSet.java b/src/java/com/samskivert/util/ArrayIntSet.java index e7764cab..565a4b9d 100644 --- a/src/java/com/samskivert/util/ArrayIntSet.java +++ b/src/java/com/samskivert/util/ArrayIntSet.java @@ -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 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 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 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; diff --git a/src/java/com/samskivert/util/ArrayUtil.java b/src/java/com/samskivert/util/ArrayUtil.java index 4194e9ba..d081f6b7 100644 --- a/src/java/com/samskivert/util/ArrayUtil.java +++ b/src/java/com/samskivert/util/ArrayUtil.java @@ -320,13 +320,13 @@ public class ArrayUtil * (-(insertion point) - 1) (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 > 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 * (-(insertion point) - 1) (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 int binarySearch ( + T[] array, int offset, int length, T key, Comparator 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; diff --git a/src/java/com/samskivert/util/BaseArrayList.java b/src/java/com/samskivert/util/BaseArrayList.java new file mode 100644 index 00000000..cd9f0ce6 --- /dev/null +++ b/src/java/com/samskivert/util/BaseArrayList.java @@ -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 extends AbstractList + implements List, 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[] 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 dup = (BaseArrayList) 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; +} diff --git a/src/java/com/samskivert/util/ClassUtil.java b/src/java/com/samskivert/util/ClassUtil.java index 17349491..c0cb83b0 100644 --- a/src/java/com/samskivert/util/ClassUtil.java +++ b/src/java/com/samskivert/util/ClassUtil.java @@ -51,18 +51,16 @@ public class ClassUtil */ public static Field[] getFields (Class clazz) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); 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 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 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> _objectToPrimitiveMap = + new HashMap,Class>(13); + private static final Map,Class> _primitiveToObjectMap = + new HashMap,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> _primitiveWideningsMap = + new HashMap>(11); static { - Set set = new HashSet(); + Set set = new HashSet(); 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(); 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(); set.add(Long.TYPE); set.add(Float.TYPE); set.add(Double.TYPE); _primitiveWideningsMap.put(Integer.TYPE, set); - set = new HashSet(); + set = new HashSet(); set.add(Float.TYPE); set.add(Double.TYPE); _primitiveWideningsMap.put(Long.TYPE, set); - set = new HashSet(); + set = new HashSet(); set.add(Double.TYPE); _primitiveWideningsMap.put(Float.TYPE, set); } diff --git a/src/java/com/samskivert/util/CollectionUtil.java b/src/java/com/samskivert/util/CollectionUtil.java index bcdc72d8..887e79ba 100644 --- a/src/java/com/samskivert/util/CollectionUtil.java +++ b/src/java/com/samskivert/util/CollectionUtil.java @@ -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 Collection addAll ( + Collection col, Enumeration 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 Collection addAll (Collection col, Iterator 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 Collection addAll (Collection 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 List selectRandomSubset (Collection 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 subset = new ArrayList(); + Iterator 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 Integer objects, it can - * be passed to this function and converted into an int array. + * If a collection contains only Integer 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 Integer. + * @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 col) { - Iterator iter = col.iterator(); + Iterator 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; } diff --git a/src/java/com/samskivert/util/Collections.java b/src/java/com/samskivert/util/Collections.java index 20e5b2a0..67894d85 100644 --- a/src/java/com/samskivert/util/Collections.java +++ b/src/java/com/samskivert/util/Collections.java @@ -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 Iterator getMetaIterator ( + Collection> metaCollection) { - return new MetaIterator(metaCollection); + return new MetaIterator(metaCollection); } /** * Get an Iterator over the supplied Collection that returns the * elements in their natural order. */ - public static Iterator getSortedIterator (Collection coll) + public static > + Iterator getSortedIterator (Collection coll) { - return getSortedIterator(coll.iterator(), Comparators.COMPARABLE); + return getSortedIterator(coll.iterator(), new Comparator() { + 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 Iterator getSortedIterator ( + Collection coll, Comparator 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 > + Iterator getSortedIterator (Iterator itr) { - return getSortedIterator(itr, Comparators.COMPARABLE); + return getSortedIterator(itr, new Comparator() { + 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 Iterator getSortedIterator ( + Iterator itr, Comparator comparator) { - SortableArrayList list = new SortableArrayList(); + SortableArrayList list = new SortableArrayList(); 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 Iterator getRandomIterator (Collection 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 Iterator getRandomIterator (Iterator itr) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); 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 Iterator getUnmodifiableIterator (Collection 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 Iterator getUnmodifiableIterator ( + final Iterator itr) { - return new Iterator() { - public boolean hasNext () - { + return new Iterator() { + 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 IntMap synchronizedIntMap (IntMap m) { + return new SynchronizedIntMap(m); } /** @@ -197,12 +217,12 @@ public class Collections /** * Horked from the Java util class and extended for IntMap. */ - protected static class SynchronizedIntMap implements IntMap + protected static class SynchronizedIntMap implements IntMap { - private IntMap m; // Backing Map + private IntMap m; // Backing Map private Object mutex; // Object on which to synchronize - SynchronizedIntMap(IntMap m) { + SynchronizedIntMap(IntMap m) { if (m == null) { throw new NullPointerException(); } @@ -210,7 +230,7 @@ public class Collections mutex = this; } - SynchronizedIntMap(IntMap m, Object mutex) { + SynchronizedIntMap(IntMap 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 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> entrySet = null; + private transient Collection values = null; - public Set keySet() { + public Set keySet() { return intKeySet(); } @@ -286,18 +306,25 @@ public class Collections } } - public Set entrySet() { + public Set> entrySet() { synchronized(mutex) { if (entrySet==null) - entrySet = new SynchronizedSet(m.entrySet(), mutex); + entrySet = new SynchronizedSet>( + m.entrySet(), mutex); return entrySet; } } - public Collection values() { + public Set> intEntrySet() { + synchronized(mutex) { + return new SynchronizedSet>(m.intEntrySet(), mutex); + } + } + + public Collection values() { synchronized(mutex) { if (values==null) - values = new SynchronizedCollection(m.values(), mutex); + values = new SynchronizedCollection(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 + extends SynchronizedCollection implements Set { + SynchronizedSet(Set s) { super(s); } - SynchronizedSet(Set s, Object mutex) { + SynchronizedSet(Set 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 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 + implements Collection { + Collection c; // Backing Collection Object mutex; // Object on which to synchronize - SynchronizedCollection(Collection c) { + SynchronizedCollection(Collection c) { if (c==null) throw new NullPointerException(); this.c = c; mutex = this; } - SynchronizedCollection(Collection c, Object mutex) { + SynchronizedCollection(Collection 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[] toArray(T[] a) { synchronized(mutex) {return c.toArray(a);} } - public Iterator iterator() { + public Iterator 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 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 implements Iterator { /** * @param collections a Collection containing more Collections * whose elements we are to iterate over. */ - public MetaIterator (Collection collections) + public MetaIterator (Collection> 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> _meta; /** The current sub-collection's iterator. */ - protected Iterator _current; + protected Iterator _current; } } diff --git a/src/java/com/samskivert/util/ComparableArrayList.java b/src/java/com/samskivert/util/ComparableArrayList.java new file mode 100644 index 00000000..8b5bd2a0 --- /dev/null +++ b/src/java/com/samskivert/util/ComparableArrayList.java @@ -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} (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> + extends SortableArrayList +{ + /** + * 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 + * (-(insertion point) - 1) (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 _comp = new Comparator() { + 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 + } + }; +} diff --git a/src/java/com/samskivert/util/Comparators.java b/src/java/com/samskivert/util/Comparators.java index fd223a31..5fb89e73 100644 --- a/src/java/com/samskivert/util/Comparators.java +++ b/src/java/com/samskivert/util/Comparators.java @@ -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 LEXICAL_CASE_INSENSITIVE = + new Comparator() { 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 COMPARABLE = + new Comparator() { + @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)o1).compareTo(o2); // null-free + } + }; } diff --git a/src/java/com/samskivert/util/Config.java b/src/java/com/samskivert/util/Config.java index a33d46cf..6e9cf02b 100644 --- a/src/java/com/samskivert/util/Config.java +++ b/src/java/com/samskivert/util/Config.java @@ -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 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 matches = new HashSet(); // 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 diff --git a/src/java/com/samskivert/util/ConfigUtil.java b/src/java/com/samskivert/util/ConfigUtil.java index 23b5f2a0..888d13f3 100644 --- a/src/java/com/samskivert/util/ConfigUtil.java +++ b/src/java/com/samskivert/util/ConfigUtil.java @@ -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 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 rsrcs = new ArrayList(); 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 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(); 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 crowns = new ArrayList(); + 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 applied = + new HashMap(); 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 records, + HashMap 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 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 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 { public String _package; public String[] _overrides; diff --git a/src/java/com/samskivert/util/CountHashMap.java b/src/java/com/samskivert/util/CountHashMap.java index 11b2fb94..34bba982 100644 --- a/src/java/com/samskivert/util/CountHashMap.java +++ b/src/java/com/samskivert/util/CountHashMap.java @@ -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 extends HashMap { /** * 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 itr = values().iterator(); itr.hasNext(); ) { + count += itr.next()[0]; } return count; } diff --git a/src/java/com/samskivert/util/DebugChords.java b/src/java/com/samskivert/util/DebugChords.java index 43c2e7a4..634e04e2 100644 --- a/src/java/com/samskivert/util/DebugChords.java +++ b/src/java/com/samskivert/util/DebugChords.java @@ -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> list = _bindings.get(keyCode); if (list == null) { - list = new ArrayList(); + list = new ArrayList>(); _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(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> 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 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>> _bindings = + new HashIntMap>>(); } diff --git a/src/java/com/samskivert/util/DefaultLogProvider.java b/src/java/com/samskivert/util/DefaultLogProvider.java index 530e302f..938cf47a 100644 --- a/src/java/com/samskivert/util/DefaultLogProvider.java +++ b/src/java/com/samskivert/util/DefaultLogProvider.java @@ -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 _levels = new HashMap(); /** Used to accompany log messages with time stamps. */ protected SimpleDateFormat _format = diff --git a/src/java/com/samskivert/util/HashIntMap.java b/src/java/com/samskivert/util/HashIntMap.java index bee1646b..2ae123ac 100644 --- a/src/java/com/samskivert/util/HashIntMap.java +++ b/src/java/com/samskivert/util/HashIntMap.java @@ -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 extends AbstractMap + implements IntMap, 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 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 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 rec = _buckets.get(index); // either we start a new chain if (rec == null) { - _buckets[index] = new Record(key, value); + _buckets.set(index, new Record(key, value)); _size++; // we're bigger return null; } // or we replace an element in an existing chain - Record prev = rec; + Record 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(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 prev = null; // go through the chain looking for a match - for (Record rec = _buckets[index]; rec != null; rec = rec.next) { + for (Record 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 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 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> 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 oldrec = oldbuckets.get(index); while (oldrec != null) { - Record newrec = oldrec; + Record 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> entrySet () { - return new AbstractSet() { - public int size () - { + return new AbstractSet>() { + public int size () { return _size; } - - public Iterator iterator () - { - return new EntryIterator(); + public Iterator> iterator () { + return new MapEntryIterator(); } }; } - protected class EntryIterator implements Iterator + // documentation inherited + public Set> intEntrySet() + { + return new AbstractSet>() { + public int size () { + return _size; + } + public Iterator> 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 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 _record, _last; } - protected class IntKeySet extends AbstractSet + protected class IntEntryIterator extends RecordIterator + implements Iterator> + { + public IntEntry next () { + return nextRecord(); + } + } + + protected class MapEntryIterator extends RecordIterator + implements Iterator> + { + public Entry next () { + return nextRecord(); + } + } + + protected class IntKeySet extends AbstractSet implements IntSet { - public Iterator iterator () { + public Iterator 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> i = intEntrySet().iterator(); }; } @@ -453,7 +464,7 @@ public class HashIntMap extends AbstractMap } // documentation inherited - public Set keySet () + public Set 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 copy = new HashIntMap(_buckets.size(), _loadFactor); + for (IntEntry 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 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> createBuckets (int size) { - public Record next; - public int key; - public Object value; + ArrayList> buckets = new ArrayList>(size); + for (int ii = 0; ii < size; ii++) { + buckets.add(null); + } + return buckets; + } - public Record (int key, Object value) + protected static class Record implements Entry, IntEntry + { + public Record 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 or = (Record)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> _buckets; protected int _size; protected float _loadFactor; diff --git a/src/java/com/samskivert/util/IntIntMap.java b/src/java/com/samskivert/util/IntIntMap.java index 0af0d82b..ba18c4fc 100644 --- a/src/java/com/samskivert/util/IntIntMap.java +++ b/src/java/com/samskivert/util/IntIntMap.java @@ -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 { 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 entrySet () { - return new AbstractSet() { + return new AbstractSet() { public int size () { return _size; } - public Iterator iterator() { - return new EntryIterator(); + public Iterator 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 { - 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) diff --git a/src/java/com/samskivert/util/IntMap.java b/src/java/com/samskivert/util/IntMap.java index 7c181427..70d93d6d 100644 --- a/src/java/com/samskivert/util/IntMap.java +++ b/src/java/com/samskivert/util/IntMap.java @@ -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 * Integer objects should be supplied as keys). */ -public interface IntMap extends Map +public interface IntMap extends Map { /** - * 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 extends Entry { public int getIntKey (); } @@ -60,7 +61,7 @@ public interface IntMap extends Map * @return the value to which this map maps the specified key, or * null 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 * null 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 * null 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> intEntrySet (); } diff --git a/src/java/com/samskivert/util/IntSet.java b/src/java/com/samskivert/util/IntSet.java index d74beaa2..1aecdaf8 100644 --- a/src/java/com/samskivert/util/IntSet.java +++ b/src/java/com/samskivert/util/IntSet.java @@ -29,7 +29,7 @@ import java.util.Set; * provides all of the standard methods (in which Integer * objects will be converted to ints). */ -public interface IntSet extends Set, Interable +public interface IntSet extends Set, Interable { /** * Returns true if this set contains the specified element. diff --git a/src/java/com/samskivert/util/Interator.java b/src/java/com/samskivert/util/Interator.java index 0f075330..188bef0b 100644 --- a/src/java/com/samskivert/util/Interator.java +++ b/src/java/com/samskivert/util/Interator.java @@ -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 { /** * @return the next int value from this Iterator. diff --git a/src/java/com/samskivert/util/Invoker.java b/src/java/com/samskivert/util/Invoker.java index f86d29f2..76410a9f 100644 --- a/src/java/com/samskivert/util/Invoker.java +++ b/src/java/com/samskivert/util/Invoker.java @@ -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 _tracker = + new HashMap(); /** The total number of invoker units run since the last report. */ protected int _unitsRun; diff --git a/src/java/com/samskivert/util/KeyValue.java b/src/java/com/samskivert/util/KeyValue.java index 8b8bfe18..4c5f1206 100644 --- a/src/java/com/samskivert/util/KeyValue.java +++ b/src/java/com/samskivert/util/KeyValue.java @@ -21,19 +21,19 @@ package com.samskivert.util; * Object value = (oidx == -1) ? null : list.get(oidx); * */ -public class KeyValue - implements Comparable +public class KeyValue,V> + implements Comparable> { /** 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)other).key); } // documentation inherited @@ -64,12 +60,8 @@ public class KeyValue } // documentation inherited - public int compareTo (Object other) + public int compareTo (KeyValue other) { - if (other instanceof KeyValue) { - return key.compareTo(((KeyValue)other).key); - } else { - return getClass().getName().compareTo(other.getClass().getName()); - } + return key.compareTo(other.key); } } diff --git a/src/java/com/samskivert/util/LRUHashMap.java b/src/java/com/samskivert/util/LRUHashMap.java index 39788e34..033f6c5e 100644 --- a/src/java/com/samskivert/util/LRUHashMap.java +++ b/src/java/com/samskivert/util/LRUHashMap.java @@ -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 implements Map { /** * 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 { /** 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 { /** Informs the observer that this item was removed from the map. */ - public void removedFromMap (LRUHashMap map, Object item); + public void removedFromMap (LRUHashMap 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 sizer) { - _delegate = new LinkedHashMap( + _delegate = new LinkedHashMap( Math.min(1024, Math.max(16, maxSize)), .75f, true); _maxSize = maxSize; - _sizer = (sizer == null) ? _unitSizer : sizer; + _sizer = (sizer == null) ? new ItemSizer() { + 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 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(); _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> 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 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 t) { - for (Iterator iter = t.entrySet().iterator(); iter.hasNext(); ) { - Map.Entry entry = (Map.Entry) iter.next(); + for (Map.Entry 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 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 keySet () { // no modifying except through put() and remove() return Collections.unmodifiableSet(_delegate.keySet()); } // documentation inherited from interface - public Collection values () + public Collection values () { // no modifying except through put() and remove() return Collections.unmodifiableCollection(_delegate.values()); } // documentation inherited from interface - public Set entrySet () + public Set> 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 _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 _remobs; /** Used to compute the size of items in this cache. */ - protected ItemSizer _sizer; + protected ItemSizer _sizer; /** Tracking info. */ protected boolean _tracking; - protected HashSet _seenKeys; + protected HashSet _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; - } - }; } diff --git a/src/java/com/samskivert/util/LoggingLogProvider.java b/src/java/com/samskivert/util/LoggingLogProvider.java index c292180b..eebaea3b 100644 --- a/src/java/com/samskivert/util/LoggingLogProvider.java +++ b/src/java/com/samskivert/util/LoggingLogProvider.java @@ -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 _loggers = new HashMap(); } diff --git a/src/java/com/samskivert/util/MethodFinder.java b/src/java/com/samskivert/util/MethodFinder.java index 6b8c9565..0fd88611 100644 --- a/src/java/com/samskivert/util/MethodFinder.java +++ b/src/java/com/samskivert/util/MethodFinder.java @@ -143,7 +143,7 @@ public class MethodFinder // make sure the constructor list is loaded maybeLoadMethods(); - List methodList = (List)methodMap.get(methodName); + List 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 memberList, + Class[] parameterTypes) throws NoSuchMethodException { - List matchingMembers = new ArrayList(); + List matchingMembers = new ArrayList(); - for (Iterator it = memberList.iterator(); it.hasNext();) { - Member member = (Member)it.next(); - Class[] methodParamTypes = (Class[])paramMap.get(member); + for (Iterator 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 memberList) throws NoSuchMethodException { - List mostSpecificMembers = new ArrayList(); - - for (Iterator memberIt = memberList.iterator(); - memberIt.hasNext();) { - Member member = (Member)memberIt.next(); + List mostSpecificMembers = new ArrayList(); + 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(); 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>(); 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 list = methodMap.get(methodName); if (list == null) { - list = new ArrayList(); + list = new ArrayList(); 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> methodMap = null; /** * List of the Constructors in the target class. */ - private List ctorList = null; + private List ctorList = null; /** * Mapping from a Constructor or Method object to the Class objects * representing its formal parameters. */ - private Map paramMap = new HashMap(); + private Map paramMap = new HashMap(); } diff --git a/src/java/com/samskivert/util/ObserverList.java b/src/java/com/samskivert/util/ObserverList.java index 821e30e9..69e94d88 100644 --- a/src/java/com/samskivert/util/ObserverList.java +++ b/src/java/com/samskivert/util/ObserverList.java @@ -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 extends ArrayList { /** * Instances of this interface are used to apply methods to all * observers in a list. */ - public static interface ObserverOp + public static interface ObserverOp { /** * 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 c) { throw new UnsupportedOperationException(UNSUPPORTED_ADD_MESSAGE); } // documentation inherited - public boolean addAll (int index, Collection c) + public boolean addAll (int index, Collection 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 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 boolean checkedApply (ObserverOp 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; } diff --git a/src/java/com/samskivert/util/QuickSort.java b/src/java/com/samskivert/util/QuickSort.java index b17e81e3..1e9d36cb 100644 --- a/src/java/com/samskivert/util/QuickSort.java +++ b/src/java/com/samskivert/util/QuickSort.java @@ -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 void sort (T[] a, Comparator 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 > 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 void rsort (T[] a, Comparator 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 > 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 void sort ( + T[] a, int lo0, int hi0, Comparator 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 void rsort ( + T[] a, int lo0, int hi0, Comparator 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 > 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 > 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 > void sort (ArrayList a) { - sort(a, Comparators.COMPARABLE); + sort(a, new Comparator() { + 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 void sort (ArrayList a, Comparator 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 > void rsort (ArrayList a) { - sort(a, java.util.Collections.reverseOrder()); + sort(a, new Comparator() { + 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 void rsort (ArrayList a, Comparator 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 void sort ( + ArrayList a, int lo0, int hi0, Comparator 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; diff --git a/src/java/com/samskivert/util/ResultListenerList.java b/src/java/com/samskivert/util/ResultListenerList.java index 46741666..2d8993ba 100644 --- a/src/java/com/samskivert/util/ResultListenerList.java +++ b/src/java/com/samskivert/util/ResultListenerList.java @@ -6,7 +6,7 @@ package com.samskivert.util; /** * Multiplexes ResultListener responses to multiple ResultListeners. */ -public class ResultListenerList extends ObserverList +public class ResultListenerList extends ObserverList 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() { + 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() { + public boolean apply (ResultListener observer) { + observer.requestFailed(cause); return true; } }); diff --git a/src/java/com/samskivert/util/SerialExecutor.java b/src/java/com/samskivert/util/SerialExecutor.java index e1769550..b0c71b4d 100644 --- a/src/java/com/samskivert/util/SerialExecutor.java +++ b/src/java/com/samskivert/util/SerialExecutor.java @@ -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 _queue = new ArrayList(); } diff --git a/src/java/com/samskivert/util/ShortestPath.java b/src/java/com/samskivert/util/ShortestPath.java index 40703c76..b2ed8190 100644 --- a/src/java/com/samskivert/util/ShortestPath.java +++ b/src/java/com/samskivert/util/ShortestPath.java @@ -40,10 +40,10 @@ public class ShortestPath public interface Graph { /** Enumerates all nodes in the graph. */ - public Iterator enumerateNodes (); + public Iterator enumerateNodes (); /** Returns the list of the edges for the specified node. */ - public List getEdges (Object node); + public List 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 compute (Graph graph, Object start, Object end) { - HashMap nodes = new HashMap(); - HashSet relaxed = new HashSet(); - SortableArrayList uptight = new SortableArrayList(); + HashMap nodes = new HashMap(); + HashSet relaxed = new HashSet(); + ComparableArrayList uptight = + new ComparableArrayList(); // initialize our searching info - for (Iterator iter = graph.enumerateNodes(); iter.hasNext(); ) { + for (Iterator 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 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 path = new ArrayList(); + 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 { /** 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; } } } diff --git a/src/java/com/samskivert/util/SortableArrayList.java b/src/java/com/samskivert/util/SortableArrayList.java index 5bfb26d5..41a71e41 100644 --- a/src/java/com/samskivert/util/SortableArrayList.java +++ b/src/java/com/samskivert/util/SortableArrayList.java @@ -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} (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} (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 extends BaseArrayList { - /** - * 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 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 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 - * (-(insertion point) - 1) (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 * (-(insertion point) - 1) (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 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; } diff --git a/src/java/com/samskivert/util/StringUtil.java b/src/java/com/samskivert/util/StringUtil.java index 07f8bf25..e33a0394 100644 --- a/src/java/com/samskivert/util/StringUtil.java +++ b/src/java/com/samskivert/util/StringUtil.java @@ -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 allow = new ArrayList(); if (allowFormatting) { allow.add(""); allow.add(""); allow.add(""); allow.add(""); @@ -195,10 +195,7 @@ public class StringUtil allow.add("!-]*(\"[^\"<>!-]*\"[^\"<>!-]*)*>"); allow.add(""); } - - 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 list = new ArrayList(); 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 _letterToBits = + new HashIntMap(); static { _letterToBits.put('e', new Integer(0)); _letterToBits.put('t', new Integer(1)); diff --git a/src/java/com/samskivert/util/Tuple.java b/src/java/com/samskivert/util/Tuple.java index 47a587cb..a3fa293b 100644 --- a/src/java/com/samskivert/util/Tuple.java +++ b/src/java/com/samskivert/util/Tuple.java @@ -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 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; diff --git a/src/java/com/samskivert/util/ValueMarshaller.java b/src/java/com/samskivert/util/ValueMarshaller.java index f80e21d4..092b2c8e 100644 --- a/src/java/com/samskivert/util/ValueMarshaller.java +++ b/src/java/com/samskivert/util/ValueMarshaller.java @@ -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 _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(); // we can parse strings _parsers.put(String.class, new Parser() { diff --git a/src/java/com/samskivert/velocity/DataTool.java b/src/java/com/samskivert/velocity/DataTool.java index 650271d0..802226ed 100644 --- a/src/java/com/samskivert/velocity/DataTool.java +++ b/src/java/com/samskivert/velocity/DataTool.java @@ -74,7 +74,7 @@ public class DataTool * Sorts the supplied list and returns it. The elements must * implement {@link Comparable}. */ - public List sort (List list) + public > List sort (List list) { Collections.sort(list); return list; @@ -85,9 +85,9 @@ public class DataTool * returns the list. The elements must implement {@link * Comparable}. */ - public List sort (Collection data) + public > List sort (Collection data) { - return sort(new ArrayList(data)); + return sort(new ArrayList(data)); } /** @@ -95,9 +95,9 @@ public class DataTool * returns the list. The elements must implement {@link * Comparable}. */ - public List sort (Iterator iter) + public > List sort (Iterator iter) { - ArrayList list = new ArrayList(); + ArrayList list = new ArrayList(); CollectionUtil.addAll(list, iter); return sort(list); } diff --git a/src/java/com/samskivert/velocity/DispatcherServlet.java b/src/java/com/samskivert/velocity/DispatcherServlet.java index fd724586..371721e6 100644 --- a/src/java/com/samskivert/velocity/DispatcherServlet.java +++ b/src/java/com/samskivert/velocity/DispatcherServlet.java @@ -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 _logic = new HashMap(); /** The character set in which serve our responses. */ protected String _charset; diff --git a/src/java/com/samskivert/xml/SetPropertyFieldsRule.java b/src/java/com/samskivert/xml/SetPropertyFieldsRule.java index 432f20ae..8e594fdd 100644 --- a/src/java/com/samskivert/xml/SetPropertyFieldsRule.java +++ b/src/java/com/samskivert/xml/SetPropertyFieldsRule.java @@ -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(); } _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 _parsers; protected boolean _warnNonFields; }