2009-08-11 sponge

* Code Janitor time! Many fixes and documenting fixes that should be
      done in the future. for the most part, this is a general code cleanup.
    * On smaller/embedded systems, the "final" keyword cleanups will have
      more of an impact than on larger systems.
    * Document missing hashCode() methods.
    * Unhide more variables to make code easier to read.
This commit is contained in:
sponge
2009-08-11 21:58:56 +00:00
parent e5eea47b66
commit 3fbff71861
166 changed files with 2575 additions and 2417 deletions

View File

@ -7,7 +7,6 @@ package org.klomp.snark;
import java.util.Arrays;
import java.util.Properties;
import net.i2p.I2PAppContext;
import net.i2p.client.I2PSessionException;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PSession;

View File

@ -137,6 +137,7 @@ public class BitField
return count >= size;
}
@Override
public String toString()
{
// Not very efficient

View File

@ -46,7 +46,7 @@ public class I2PSnarkUtil {
private Map _opts;
private I2PSocketManager _manager;
private boolean _configured;
private Set _shitlist;
private final Set _shitlist;
private int _maxUploaders;
private int _maxUpBW;
private int _maxConnections;

View File

@ -110,6 +110,7 @@ class Message
dos.write(data, off, len);
}
@Override
public String toString()
{
switch (type)

View File

@ -345,6 +345,7 @@ public class MetaInfo
return length;
}
@Override
public String toString()
{
return "MetaInfo[info_hash='" + hexencode(info_hash)

View File

@ -106,6 +106,7 @@ public class Peer implements Comparable
/**
* Returns the String representation of the peerID.
*/
@Override
public String toString()
{
if (peerID != null)
@ -125,6 +126,7 @@ public class Peer implements Comparable
/**
* The hash code of a Peer is the hash code of the peerID.
*/
@Override
public int hashCode()
{
return peerID.hashCode() ^ (2 << _id);
@ -134,6 +136,7 @@ public class Peer implements Comparable
* Two Peers are equal when they have the same PeerID.
* All other properties are ignored.
*/
@Override
public boolean equals(Object o)
{
if (o instanceof Peer)

View File

@ -41,7 +41,7 @@ class PeerConnectionOut implements Runnable
private boolean quit;
// Contains Messages.
private List sendQueue = new ArrayList();
private final List sendQueue = new ArrayList();
private static long __id = 0;
private long _id;

View File

@ -12,7 +12,7 @@ import java.util.Set;
* from it there too)
*/
public class PeerCoordinatorSet {
private Set _coordinators;
private final Set _coordinators;
public PeerCoordinatorSet() {
_coordinators = new HashSet();

View File

@ -107,6 +107,7 @@ public class PeerID implements Comparable
/**
* The hash code of a PeerID is the exclusive or of all id bytes.
*/
@Override
public int hashCode()
{
return hash;
@ -127,6 +128,7 @@ public class PeerID implements Comparable
/**
* Two PeerIDs are equal when they have the same id, address and port.
*/
@Override
public boolean equals(Object o)
{
if (o instanceof PeerID)
@ -171,6 +173,7 @@ public class PeerID implements Comparable
* and address is the base64 dest (was the base64 hash of the dest) which
* should match what the bytemonsoon tracker reports on its web pages.
*/
@Override
public String toString()
{
int nonZero = 0;

View File

@ -151,7 +151,7 @@ public interface PeerListener
*
* @param state the PeerState for the peer
*/
void savePeerPartial(PeerState state);
void savePeerPartial(PeerState state); /* FIXME Exporting non-public type through public API FIXME */
/**
* Called when a peer has connected and there may be a partially
@ -161,7 +161,7 @@ public interface PeerListener
*
* @return request (contains the partial data and valid length)
*/
Request getPeerPartial(BitField havePieces);
Request getPeerPartial(BitField havePieces); /* FIXME Exporting non-public type through public API FIXME */
/** Mark a peer's requested pieces unrequested when it is disconnected
* This prevents premature end game

View File

@ -20,13 +20,24 @@ public class Piece implements Comparable {
return this.peers.size() - ((Piece)o).peers.size();
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
try {
return this.id == ((Piece)o).id;
} catch (ClassCastException cce) {
return false;
if (o instanceof Piece) {
if (o == null) return false;
try {
return this.id == ((Piece)o).id;
} catch (ClassCastException cce) {
return false;
}
}
return false;
}
@Override
public int hashCode() {
int hash = 5;
hash = 31 * hash + this.id;
return hash;
}
public int getId() { return this.id; }
@ -36,6 +47,7 @@ public class Piece implements Comparable {
public boolean isRequested() { return this.requested; }
public void setRequested(boolean requested) { this.requested = requested; }
@Override
public String toString() {
return String.valueOf(id);
}

View File

@ -51,11 +51,13 @@ class Request
throw new IndexOutOfBoundsException("Illegal Request " + toString());
}
@Override
public int hashCode()
{
return piece ^ off ^ len;
}
@Override
public boolean equals(Object o)
{
if (o instanceof Request)
@ -67,6 +69,7 @@ class Request
return false;
}
@Override
public String toString()
{
return "(" + piece + "," + off + "," + len + ")";

View File

@ -28,7 +28,6 @@ import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.StringTokenizer;

View File

@ -29,13 +29,13 @@ public class SnarkManager implements Snark.CompleteListener {
public static SnarkManager instance() { return _instance; }
/** map of (canonical) filename to Snark instance (unsynchronized) */
private Map _snarks;
private Object _addSnarkLock;
private File _configFile;
private final Map _snarks;
private final Object _addSnarkLock;
private /* FIXME final FIXME */ File _configFile;
private Properties _config;
private I2PAppContext _context;
private Log _log;
private List _messages;
private final List _messages;
private I2PSnarkUtil _util;
private PeerCoordinatorSet _peerCoordinatorSet;
private ConnectionAcceptor _connectionAcceptor;
@ -747,6 +747,7 @@ public class SnarkManager implements Snark.CompleteListener {
}
public class SnarkManagerShutdown extends I2PAppThread {
@Override
public void run() {
Set names = listTorrentFiles();
for (Iterator iter = names.iterator(); iter.hasNext(); ) {

View File

@ -36,6 +36,7 @@ public class SnarkShutdown extends I2PAppThread
private final ShutdownListener listener;
/* FIXME Exporting non-public type through public API FIXME */
public SnarkShutdown(Storage storage,
PeerCoordinator coordinator,
ConnectionAcceptor acceptor,
@ -49,6 +50,7 @@ public class SnarkShutdown extends I2PAppThread
this.listener = listener;
}
@Override
public void run()
{
//Snark.debug("Shutting down...", Snark.NOTICE);

View File

@ -46,7 +46,7 @@ public class Storage
private final StorageListener listener;
private I2PSnarkUtil _util;
private BitField bitfield; // BitField to represent the pieces
private /* FIXME final FIXME */ BitField bitfield; // BitField to represent the pieces
private int needed; // Number of pieces needed
private boolean _probablyComplete; // use this to decide whether to open files RO

View File

@ -81,6 +81,7 @@ public class TrackerClient extends I2PAppThread
started = false;
}
@Override
public void start() {
if (stop) throw new RuntimeException("Dont rerun me, create a copy");
super.start();
@ -109,6 +110,7 @@ public class TrackerClient extends I2PAppThread
return !stop && _util.connected();
}
@Override
public void run()
{
String infoHash = urlencode(meta.getInfoHash());
@ -162,7 +164,7 @@ public class TrackerClient extends I2PAppThread
try
{
if (!verifyConnected()) return;
boolean started = false;
boolean runStarted = false;
boolean firstTime = true;
int consecutiveFails = 0;
Random r = new Random();
@ -178,7 +180,7 @@ public class TrackerClient extends I2PAppThread
if (firstTime) {
delay = r.nextInt(30*1000);
firstTime = false;
} else if (completed && started)
} else if (completed && runStarted)
delay = 3*SLEEP*60*1000 + random;
else if (coordinator.trackerProblems != null && ++consecutiveFails < MAX_CONSEC_FAILS)
delay = INITIAL_SLEEP;
@ -221,7 +223,7 @@ public class TrackerClient extends I2PAppThread
Tracker tr = (Tracker)iter.next();
if ((!stop) && (!tr.stop) &&
(completed || coordinator.needPeers()) &&
(event == COMPLETED_EVENT || System.currentTimeMillis() > tr.lastRequestTime + tr.interval))
(event.equals(COMPLETED_EVENT) || System.currentTimeMillis() > tr.lastRequestTime + tr.interval))
{
try
{
@ -237,7 +239,7 @@ public class TrackerClient extends I2PAppThread
tr.consecutiveFails = 0;
if (tr.isPrimary)
consecutiveFails = 0;
started = true;
runStarted = true;
tr.started = true;
Set peers = info.getPeers();
@ -296,7 +298,7 @@ public class TrackerClient extends I2PAppThread
// we could try and total the unique peers but that's too hard for now
coordinator.trackerSeenPeers = maxSeenPeers;
if (!started)
if (!runStarted)
_util.debug(" Retrying in one minute...", Snark.DEBUG);
} // *** end of while loop
} // try
@ -338,7 +340,7 @@ public class TrackerClient extends I2PAppThread
+ "&uploaded=" + uploaded
+ "&downloaded=" + downloaded
+ "&left=" + left
+ ((event != NO_EVENT) ? ("&event=" + event) : "");
+ ((! event.equals(NO_EVENT)) ? ("&event=" + event) : "");
_util.debug("Sending TrackerClient request: " + s, Snark.INFO);
tr.lastRequestTime = System.currentTimeMillis();

View File

@ -125,6 +125,7 @@ public class TrackerInfo
return interval;
}
@Override
public String toString()
{
if (failure_reason != null)

View File

@ -172,6 +172,7 @@ public class BEValue
/** return the untyped value */
public Object getValue() { return value; }
@Override
public String toString()
{
String valueString;

View File

@ -27,7 +27,6 @@ import net.i2p.util.FileUtil;
import net.i2p.util.I2PAppThread;
import net.i2p.util.Log;
import org.klomp.snark.I2PSnarkUtil;
import org.klomp.snark.MetaInfo;
import org.klomp.snark.Peer;
import org.klomp.snark.Snark;
@ -46,6 +45,7 @@ public class I2PSnarkServlet extends HttpServlet {
public static final String PROP_CONFIG_FILE = "i2psnark.configFile";
@Override
public void init(ServletConfig cfg) throws ServletException {
super.init(cfg);
_context = I2PAppContext.getGlobalContext();
@ -59,6 +59,7 @@ public class I2PSnarkServlet extends HttpServlet {
_manager.start();
}
@Override
public void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");

View File

@ -14,7 +14,7 @@ import net.i2p.util.Log;
*/
class BufferLogger implements Logging {
private final static Log _log = new Log(BufferLogger.class);
private ByteArrayOutputStream _baos; // should be final and use a factory. LINT
private ByteArrayOutputStream _baos; // FIXME should be final and use a factory. FIXME
private boolean _ignore;
/**

View File

@ -66,7 +66,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask implements Runna
// private Object conLock = new Object();
/** List of Socket for those accept()ed but not yet started up */
private List _waitingSockets = new ArrayList(); // should be final and use a factory. LINT
private List _waitingSockets = new ArrayList(); // FIXME should be final and use a factory. FIXME
/** How many connections will we allow to be in the process of being built at once? */
private int _numConnectionBuilders;
/** How long will we allow sockets to sit in the _waitingSockets map before killing them? */

View File

@ -153,6 +153,7 @@ public class I2PTunnelConnectClient extends I2PTunnelClientBase implements Runna
* create the default options (using the default timeout, etc)
*
*/
@Override
protected I2PSocketOptions getDefaultOptions() {
Properties defaultOpts = getTunnel().getClientOptions();
if (!defaultOpts.contains(I2PSocketOptions.PROP_READ_TIMEOUT))
@ -259,8 +260,8 @@ public class I2PTunnelConnectClient extends I2PTunnelClientBase implements Runna
return;
}
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
Destination clientDest = I2PTunnel.destFromName(destination);
if (clientDest == null) {
String str;
byte[] header;
if (usingWWWProxy)
@ -276,7 +277,7 @@ public class I2PTunnelConnectClient extends I2PTunnelClientBase implements Runna
return;
}
I2PSocket i2ps = createI2PSocket(dest, getDefaultOptions());
I2PSocket i2ps = createI2PSocket(clientDest, getDefaultOptions());
byte[] data = null;
byte[] response = null;
if (usingWWWProxy)

View File

@ -191,6 +191,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable
* create the default options (using the default timeout, etc)
* unused?
*/
@Override
protected I2PSocketOptions getDefaultOptions() {
Properties defaultOpts = getTunnel().getClientOptions();
if (!defaultOpts.contains(I2PSocketOptions.PROP_READ_TIMEOUT))
@ -207,6 +208,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable
* create the default options (using the default timeout, etc)
*
*/
@Override
protected I2PSocketOptions getDefaultOptions(Properties overrides) {
Properties defaultOpts = getTunnel().getClientOptions();
defaultOpts.putAll(overrides);
@ -561,8 +563,8 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable
return;
}
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
Destination clientDest = I2PTunnel.destFromName(destination);
if (clientDest == null) {
//l.log("Could not resolve " + destination + ".");
if (_log.shouldLog(Log.WARN))
_log.warn("Unable to resolve " + destination + " (proxy? " + usingWWWProxy + ", request: " + targetRequest);
@ -594,7 +596,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable
// 1 == disconnect. see ConnectionOptions in the new streaming lib, which i
// dont want to hard link to here
//opts.setProperty("i2p.streaming.inactivityTimeoutAction", ""+1);
I2PSocket i2ps = createI2PSocket(dest, getDefaultOptions(opts));
I2PSocket i2ps = createI2PSocket(clientDest, getDefaultOptions(opts));
byte[] data = newRequest.toString().getBytes("ISO-8859-1");
Runnable onTimeout = new OnTimeout(s, s.getOutputStream(), targetRequest, usingWWWProxy, currentProxy, requestId);
I2PTunnelRunner runner = new I2PTunnelHTTPClientRunner(s, i2ps, sockLock, data, mySockets, onTimeout);

View File

@ -77,10 +77,10 @@ public class I2PTunnelIRCClient extends I2PTunnelClientBase implements Runnable
protected void clientConnectionRun(Socket s) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("got a connection.");
Destination dest = pickDestination();
Destination clientDest = pickDestination();
I2PSocket i2ps = null;
try {
i2ps = createI2PSocket(dest);
i2ps = createI2PSocket(clientDest);
i2ps.setReadTimeout(readTimeout);
StringBuilder expectedPong = new StringBuilder();
Thread in = new I2PThread(new IrcInboundFilter(s,i2ps, expectedPong), "IRC Client " + __clientId + " in");

View File

@ -54,6 +54,6 @@ public class Pinger implements Source, Runnable {
protected Sink sink;
protected Thread thread;
protected Object waitlock; // should be final and use a factory. LINT
protected Object waitlock; // FIXME should be final and use a factory. FIXME
protected boolean running;
}

View File

@ -69,5 +69,5 @@ public class I2PSink implements Sink {
protected boolean raw;
protected I2PSession sess;
protected Destination dest;
protected I2PDatagramMaker maker; // should be final and use a factory. LINT
protected I2PDatagramMaker maker; // FIXME should be final and use a factory. FIXME
}

View File

@ -67,5 +67,5 @@ public class I2PSinkAnywhere implements Sink {
protected boolean raw;
protected I2PSession sess;
protected Destination dest;
protected I2PDatagramMaker maker; // should be final and use a factory. LINT
protected I2PDatagramMaker maker; // FIXME should be final and use a factory. FIXME
}

View File

@ -60,7 +60,7 @@ import net.i2p.util.Log;
private ServerSocket ss;
private Object startLock = new Object();
private final Object startLock = new Object();
private boolean startRunning = false;
private byte[] pubkey;

View File

@ -29,7 +29,7 @@ class I2PSocketImpl implements I2PSocket {
private Destination remote;
private String localID;
private String remoteID;
private Object remoteIDWaiter = new Object();
private final Object remoteIDWaiter = new Object();
private I2PInputStream in;
private I2POutputStream out;
private I2PSocket.SocketErrorListener _socketErrorListener;
@ -42,7 +42,7 @@ class I2PSocketImpl implements I2PSocket {
private long _closedOn;
private long _remoteIdSetTime;
private I2PSocketOptions _options;
private Object flagLock = new Object();
private final Object flagLock = new Object();
/**
* Whether the I2P socket has already been closed.
@ -306,7 +306,7 @@ class I2PSocketImpl implements I2PSocket {
//--------------------------------------------------
private class I2PInputStream extends InputStream {
private String streamName;
private ByteCollector bc = new ByteCollector();
private final ByteCollector bc = new ByteCollector();
private boolean inStreamClosed = false;
private long readTimeout = -1;

View File

@ -13,7 +13,6 @@ import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PSessionException;
import net.i2p.data.Destination;
import net.i2p.util.Log;
/**

View File

@ -40,7 +40,7 @@ import net.i2p.util.Log;
class I2PSocketManagerImpl implements I2PSocketManager, I2PSessionListener {
private I2PAppContext _context;
private Log _log;
private /* final */ I2PSession _session;
private /* FIXME final FIXME */ I2PSession _session;
private I2PServerSocketImpl _serverSocket = null;
private final Object lock = new Object(); // for locking socket lists
private HashMap<String,I2PSocket> _outSockets;

View File

@ -62,7 +62,7 @@ public class ConnectionOptions extends I2PSocketOptionsImpl {
private static final boolean DEFAULT_ANSWER_PINGS = true;
// Syncronization fix, but doing it this way causes NPE...
// private final int _trend[] = new int[TREND_COUNT];
// FIXME private final int _trend[] = new int[TREND_COUNT]; FIXME
private int _trend[];
/**