Findbugs all over

- volatile -> atomic
 - unused code and fields
 - closing streams
 - hashCode / equals
 - known non-null
 - Number.valueOf
 - new String
 Still avoiding SAM, BOB, SusiMail
This commit is contained in:
zzz
2013-11-16 13:22:05 +00:00
parent 96cf1d60c2
commit 1d4190734d
30 changed files with 107 additions and 64 deletions

View File

@ -1301,6 +1301,15 @@ public class Storage
return name.compareTo(tf.name);
}
@Override
public int hashCode() { return RAFfile.getAbsolutePath().hashCode(); }
@Override
public boolean equals(Object o) {
return (o instanceof TorrentFile) &&
RAFfile.getAbsolutePath().equals(((TorrentFile)o).RAFfile.getAbsolutePath());
}
@Override
public String toString() { return name; }
}

View File

@ -273,11 +273,10 @@ class HTTPResponseOutputStream extends FilterOutputStream {
}
public void run() {
ReusableGZIPInputStream _in = null;
ReusableGZIPInputStream _in = ReusableGZIPInputStream.acquire();
long written = 0;
ByteArray ba = null;
try {
_in = ReusableGZIPInputStream.acquire();
// blocking
_in.initialize(_inRaw);
ba = _cache.acquire();
@ -294,7 +293,7 @@ class HTTPResponseOutputStream extends FilterOutputStream {
_log.info("Decompressed: " + written + ", " + _in.getTotalRead() + "/" + _in.getTotalExpanded());
} catch (IOException ioe) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error decompressing: " + written + ", " + (_in != null ? _in.getTotalRead() + "/" + _in.getTotalExpanded() : ""), ioe);
_log.warn("Error decompressing: " + written + ", " + _in.getTotalRead() + "/" + _in.getTotalExpanded(), ioe);
} catch (OutOfMemoryError oom) {
_log.error("OOM in HTTP Decompressor", oom);
} finally {

View File

@ -51,6 +51,7 @@ import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.atomic.AtomicLong;
import net.i2p.I2PAppContext;
import net.i2p.I2PException;
@ -78,7 +79,7 @@ import net.i2p.util.Log;
public class I2PTunnel extends EventDispatcherImpl implements Logging {
private final Log _log;
private final I2PAppContext _context;
private static long __tunnelId = 0;
private static final AtomicLong __tunnelId = new AtomicLong();
private final long _tunnelId;
private final Properties _clientOptions;
private final Set<I2PSession> _sessions;
@ -118,7 +119,7 @@ public class I2PTunnel extends EventDispatcherImpl implements Logging {
public I2PTunnel(String[] args, ConnectionEventListener lsnr) {
super();
_context = I2PAppContext.getGlobalContext(); // new I2PAppContext();
_tunnelId = ++__tunnelId;
_tunnelId = __tunnelId.incrementAndGet();
_log = _context.logManager().getLog(I2PTunnel.class);
// as of 0.8.4, include context properties
Properties p = _context.getProperties();

View File

@ -22,6 +22,7 @@ import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicLong;
import net.i2p.I2PAppContext;
import net.i2p.I2PException;
@ -43,7 +44,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask implements Runna
static final long DEFAULT_CONNECT_TIMEOUT = 60 * 1000;
private static volatile long __clientId = 0;
private static final AtomicLong __clientId = new AtomicLong();
protected long _clientId;
protected final Object sockLock = new Object(); // Guards sockMgr and mySockets
protected I2PSocketManager sockMgr; // should be final and use a factory. LINT
@ -161,7 +162,7 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask implements Runna
EventDispatcher notifyThis, String handlerName,
I2PTunnel tunnel, String pkf) throws IllegalArgumentException{
super(localPort + " (uninitialized)", notifyThis, tunnel);
_clientId = ++__clientId;
_clientId = __clientId.incrementAndGet();
this.localPort = localPort;
this.l = l;
_ownDest = ownDest; // == ! shared client

View File

@ -104,7 +104,7 @@ public class I2PTunnelConnectClient extends I2PTunnelHTTPClientBase implements R
public I2PTunnelConnectClient(int localPort, Logging l, boolean ownDest,
String wwwProxy, EventDispatcher notifyThis,
I2PTunnel tunnel) throws IllegalArgumentException {
super(localPort, ownDest, l, notifyThis, "HTTPS Proxy on " + tunnel.listenHost + ':' + localPort + " #" + (++__clientId), tunnel);
super(localPort, ownDest, l, notifyThis, "HTTPS Proxy on " + tunnel.listenHost + ':' + localPort, tunnel);
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openConnectClientResult", "error");
@ -167,7 +167,7 @@ public class I2PTunnelConnectClient extends I2PTunnelHTTPClientBase implements R
String targetRequest = null;
boolean usingWWWProxy = false;
String currentProxy = null;
long requestId = ++__requestId;
long requestId = __requestId.incrementAndGet();
try {
out = s.getOutputStream();
in = s.getInputStream();

View File

@ -202,7 +202,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelHTTPClientBase implements Runn
public I2PTunnelHTTPClient(int localPort, Logging l, boolean ownDest,
String wwwProxy, EventDispatcher notifyThis,
I2PTunnel tunnel) throws IllegalArgumentException {
super(localPort, ownDest, l, notifyThis, "HTTP Proxy on " + tunnel.listenHost + ':' + localPort + " #" + (++__clientId), tunnel);
super(localPort, ownDest, l, notifyThis, "HTTP Proxy on " + tunnel.listenHost + ':' + localPort, tunnel);
_proxyNonce = Long.toString(_context.random().nextLong());
//proxyList = new ArrayList(); // We won't use outside of i2p
@ -335,7 +335,7 @@ public class I2PTunnelHTTPClient extends I2PTunnelHTTPClientBase implements Runn
String internalPath = null;
String internalRawQuery = null;
String currentProxy = null;
long requestId = ++__requestId;
long requestId = __requestId.incrementAndGet();
boolean shout = false;
try {

View File

@ -18,6 +18,7 @@ import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import net.i2p.I2PAppContext;
import net.i2p.client.streaming.I2PSocketManager;
@ -69,9 +70,6 @@ public abstract class I2PTunnelHTTPClientBase extends I2PTunnelClientBase implem
"HTTP outproxy configured. Please configure an outproxy in I2PTunnel")
.getBytes();
/** used to assign unique IDs to the threads / clients. no logic or functionality */
protected static volatile long __clientId = 0;
private final byte[] _proxyNonce;
private final ConcurrentHashMap<String, NonceInfo> _nonces;
private final AtomicInteger _nonceCleanCounter = new AtomicInteger();
@ -90,7 +88,7 @@ public abstract class I2PTunnelHTTPClientBase extends I2PTunnelClientBase implem
protected static final int DEFAULT_READ_TIMEOUT = 5*60*1000;
protected static long __requestId = 0;
protected static final AtomicLong __requestId = new AtomicLong();
public I2PTunnelHTTPClientBase(int localPort, boolean ownDest, Logging l,
EventDispatcher notifyThis, String handlerName,

View File

@ -29,9 +29,6 @@ import net.i2p.util.PortMapper;
*/
public class I2PTunnelIRCClient extends I2PTunnelClientBase {
/** used to assign unique IDs to the threads / clients. no logic or functionality */
private static volatile long __clientId = 0;
/** list of Destination objects that we point at */
private final List<I2PSocketAddress> _addrs;
private static final long DEFAULT_READ_TIMEOUT = 5*60*1000; // -1
@ -61,7 +58,7 @@ public class I2PTunnelIRCClient extends I2PTunnelClientBase {
ownDest,
l,
notifyThis,
"IRC Client on " + tunnel.listenHost + ':' + localPort + " #" + (++__clientId), tunnel, pkf);
"IRC Client on " + tunnel.listenHost + ':' + localPort, tunnel, pkf);
_addrs = new ArrayList(4);
buildAddresses(destinations);
@ -139,9 +136,9 @@ public class I2PTunnelIRCClient extends I2PTunnelClientBase {
i2ps.setReadTimeout(readTimeout);
StringBuffer expectedPong = new StringBuffer();
DCCHelper dcc = _dccEnabled ? new DCC(s.getLocalAddress().getAddress()) : null;
Thread in = new I2PAppThread(new IrcInboundFilter(s,i2ps, expectedPong, _log, dcc), "IRC Client " + __clientId + " in", true);
Thread in = new I2PAppThread(new IrcInboundFilter(s,i2ps, expectedPong, _log, dcc), "IRC Client " + _clientId + " in", true);
in.start();
Thread out = new I2PAppThread(new IrcOutboundFilter(s,i2ps, expectedPong, _log, dcc), "IRC Client " + __clientId + " out", true);
Thread out = new I2PAppThread(new IrcOutboundFilter(s,i2ps, expectedPong, _log, dcc), "IRC Client " + _clientId + " out", true);
out.start();
} catch (Exception ex) {
// generally NoRouteToHostException

View File

@ -11,6 +11,7 @@ import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import javax.net.ssl.SSLException;
@ -26,7 +27,7 @@ import net.i2p.util.Log;
public class I2PTunnelRunner extends I2PAppThread implements I2PSocket.SocketErrorListener {
protected final Log _log;
private static volatile long __runnerId;
private static final AtomicLong __runnerId = new AtomicLong();
private final long _runnerId;
/**
* max bytes streamed in a packet - smaller ones might be filled
@ -96,7 +97,7 @@ public class I2PTunnelRunner extends I2PAppThread implements I2PSocket.SocketErr
_log = I2PAppContext.getGlobalContext().logManager().getLog(getClass());
if (_log.shouldLog(Log.INFO))
_log.info("I2PTunnelRunner started");
_runnerId = ++__runnerId;
_runnerId = __runnerId.incrementAndGet();
__forwarderId = i2ps.hashCode();
setName("I2PTunnelRunner " + _runnerId);
start();

View File

@ -6,6 +6,7 @@ package net.i2p.i2ptunnel.udpTunnel;
import java.io.ByteArrayOutputStream;
import java.io.ByteArrayInputStream;
import java.net.ServerSocket;
import java.util.concurrent.atomic.AtomicLong;
import net.i2p.I2PAppContext;
import net.i2p.client.I2PClient;
@ -48,13 +49,12 @@ import net.i2p.util.EventDispatcher;
static final long DEFAULT_CONNECT_TIMEOUT = 60 * 1000;
private static volatile long __clientId = 0;
private static final AtomicLong __clientId = new AtomicLong();
protected long _clientId;
protected Destination dest = null;
private final Object startLock = new Object();
private Object conLock = new Object();
private I2PSession _session;
private Source _i2pSource;
@ -67,7 +67,7 @@ import net.i2p.util.EventDispatcher;
public I2PTunnelUDPClientBase(String destination, Logging l, EventDispatcher notifyThis,
I2PTunnel tunnel) throws IllegalArgumentException {
super("UDPServer", notifyThis, tunnel);
_clientId = ++__clientId;
_clientId = __clientId.incrementAndGet();;
this.l = l;
_context = tunnel.getContext();

View File

@ -1104,7 +1104,6 @@ public class ConsoleUpdateManager implements UpdateManager {
case PLUGIN:
Properties props = PluginStarter.pluginProperties(_context, id);
String oldVersion = props.getProperty("version");
String xpi2pURL = props.getProperty("updateURL");
if (xpi2pURL != null) {
try {
@ -1472,6 +1471,12 @@ public class ConsoleUpdateManager implements UpdateManager {
return VersionComparator.comp(version, r.version);
}
@Override
public int hashCode() { return version.hashCode(); }
@Override
public boolean equals(Object o) { return (o instanceof Version) && version.equals(((Version)o).version); }
@Override
public String toString() {
return "Version " + version;

View File

@ -632,7 +632,7 @@ public class PluginStarter implements Runnable {
ClassLoader cl = null;
if (app.classpath != null) {
String cp = new String(app.classpath);
String cp = app.classpath;
if (cp.indexOf("$") >= 0) {
cp = cp.replace("$I2P", ctx.getBaseDir().getAbsolutePath());
cp = cp.replace("$CONFIG", ctx.getConfigDir().getAbsolutePath());

View File

@ -85,7 +85,7 @@ public class WebAppStarter {
throw new IOException("Web app " + warPath + " does not exist");
Long oldmod = warModTimes.get(warPath);
if (oldmod == null) {
warModTimes.put(warPath, new Long(newmod));
warModTimes.put(warPath, Long.valueOf(newmod));
} else if (oldmod.longValue() < newmod) {
// copy war to temporary directory
File warTmpDir = new SecureDirectory(ctx.getTempDir(), "war-copy-" + appName + ctx.random().nextInt());

View File

@ -354,12 +354,18 @@ public class AddressbookBean extends BaseBean
{
String filename = properties.getProperty( getBook() + "_addressbook" );
FileOutputStream fos = new SecureFileOutputStream( ConfigBean.addressbookPrefix + filename );
FileOutputStream fos = null;
try {
fos = new SecureFileOutputStream( ConfigBean.addressbookPrefix + filename );
addressbook.store( fos, null );
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {}
}
}
}
public String getFilter() {
return filter;

View File

@ -108,10 +108,6 @@ public class AESEngine {
byte decr[] = new byte[payload.length];
decrypt(payload, 0, decr, 0, sessionKey, iv, payload.length);
if (decr == null) {
_log.error("Error decrypting the data - payload " + payload.length + " decrypted to null");
return null;
}
byte h[] = SimpleByteCache.acquire(Hash.HASH_LENGTH);
_context.sha().calculateHash(iv, 0, 16, h, 0);

View File

@ -89,9 +89,9 @@ public class CertUtil {
log(I2PAppContext.getGlobalContext(), Log.ERROR, msg, t);
}
private static void error(I2PAppContext ctx, String msg, Throwable t) {
log(ctx, Log.ERROR, msg, t);
}
//private static void error(I2PAppContext ctx, String msg, Throwable t) {
// log(ctx, Log.ERROR, msg, t);
//}
private static void log(I2PAppContext ctx, int level, String msg, Throwable t) {
Log l = ctx.logManager().getLog(CertUtil.class);

View File

@ -4,6 +4,7 @@ import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.PrivateKey;
@ -54,11 +55,23 @@ public class KeyStoreUtil {
char[] pwchars = password != null ? password.toCharArray() : null;
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
if (exists) {
InputStream fis = new FileInputStream(ksFile);
InputStream fis = null;
try {
fis = new FileInputStream(ksFile);
ks.load(fis, pwchars);
} finally {
if (fis != null) try { fis.close(); } catch (IOException ioe) {}
}
}
if (ksFile != null && !exists) {
OutputStream fos = null;
try {
fos = new SecureFileOutputStream(ksFile);
ks.store(fos, pwchars);
} finally {
if (fos != null) try { fos.close(); } catch (IOException ioe) {}
}
}
if (ksFile != null && !exists)
ks.store(new SecureFileOutputStream(ksFile), pwchars);
return ks;
}
@ -452,13 +465,13 @@ public class KeyStoreUtil {
log(I2PAppContext.getGlobalContext(), Log.ERROR, msg, t);
}
private static void info(I2PAppContext ctx, String msg) {
log(ctx, Log.INFO, msg, null);
}
//private static void info(I2PAppContext ctx, String msg) {
// log(ctx, Log.INFO, msg, null);
//}
private static void error(I2PAppContext ctx, String msg, Throwable t) {
log(ctx, Log.ERROR, msg, t);
}
//private static void error(I2PAppContext ctx, String msg, Throwable t) {
// log(ctx, Log.ERROR, msg, t);
//}
private static void log(I2PAppContext ctx, int level, String msg, Throwable t) {
if (level >= Log.WARN && !ctx.isRouterContext()) {

View File

@ -174,7 +174,6 @@ class SigUtil {
private static ECPrivateKey cvtToJavaECKey(SigningPrivateKey pk)
throws GeneralSecurityException {
SigType type = pk.getType();
int len = type.getPubkeyLen();
byte[] b = pk.getData();
BigInteger s = new NativeBigInteger(1, b);
// see ECConstants re: casting

View File

@ -293,7 +293,7 @@ public class TransientSessionKeyManager extends SessionKeyManager {
}
if (sess == null) {
SessionKey key = _context.keyGenerator().generateSessionKey();
sess = createAndReturnSession(target, key);
createAndReturnSession(target, key);
return key;
}
return sess.getCurrentKey();

View File

@ -477,9 +477,11 @@ public class Base64 {
* @param breakLines Break lines at 80 characters or less.
* @since 1.4
*/
/***** unused
private static String encodeBytes(byte[] source, boolean breakLines) {
return encodeBytes(source, 0, source.length, breakLines);
} // end encodeBytes
******/
/**
* Encodes a byte array into Base64 notation.
@ -493,13 +495,13 @@ public class Base64 {
private static String encodeBytes(byte[] source, int off, int len) {
return encodeBytes(source, off, len, true);
} // end encodeBytes
******/
private static String encodeBytes(byte[] source, int off, int len, boolean breakLines) {
StringBuilder buf = new StringBuilder( (len*4)/3 );
encodeBytes(source, off, len, breakLines, buf, ALPHABET);
return buf.toString();
}
******/
/**
* Encodes a byte array into Base64 notation.

View File

@ -1291,7 +1291,7 @@ public class EepGet {
} catch (IOException ioe) {
_decompressException = ioe;
if (_log.shouldLog(Log.WARN))
_log.warn("Error decompressing: " + written + ", " + (in != null ? in.getTotalRead() + "/" + in.getTotalExpanded() : ""), ioe);
_log.warn("Error decompressing: " + written + ", " + in.getTotalRead() + "/" + in.getTotalExpanded(), ioe);
} catch (OutOfMemoryError oom) {
_decompressException = new IOException("OOM in HTTP Decompressor");
_log.error("OOM in HTTP Decompressor", oom);

View File

@ -522,9 +522,11 @@ public class NativeBigInteger extends BigInteger {
* @return true if it was loaded successfully, else false
*
*/
/****
private static final boolean loadGeneric(boolean optimized) {
return loadGeneric(getMiddleName(optimized));
}
****/
private static final boolean loadGeneric(String name) {
try {
@ -563,10 +565,12 @@ public class NativeBigInteger extends BigInteger {
* @return true if it was loaded successfully, else false
*
*/
/****
private static final boolean loadFromResource(boolean optimized) {
String resourceName = getResourceName(optimized);
return loadFromResource(resourceName);
}
****/
private static final boolean loadFromResource(String resourceName) {
if (resourceName == null) return false;

View File

@ -46,6 +46,6 @@ public class IntBytes implements Serializer {
((b[1] & 0xff) << 16) |
((b[2] & 0xff) << 8) |
(b[3] & 0xff));
return new Integer(v);
return Integer.valueOf(v);
}
}

View File

@ -54,6 +54,6 @@ public class LongBytes implements Serializer {
((long)(b[5] & 0xff) << 16) |
((long)(b[6] & 0xff) << 8) |
(b[7] & 0xff));
return new Long(v);
return Long.valueOf(v);
}
}

View File

@ -18,7 +18,7 @@ public class RouterVersion {
/** deprecated */
public final static String ID = "Monotone";
public final static String VERSION = CoreVersion.VERSION;
public final static long BUILD = 26;
public final static long BUILD = 27;
/** for example "-test" */
public final static String EXTRA = "";

View File

@ -285,7 +285,7 @@ public class TunnelPoolSettings {
private static final boolean getBoolean(String str, boolean defaultValue) {
if (str == null) return defaultValue;
boolean v = Boolean.parseBoolean(str) ||
(str != null && "YES".equals(str.toUpperCase(Locale.US)));
"YES".equals(str.toUpperCase(Locale.US));
return v;
}

View File

@ -681,10 +681,17 @@ public class OutboundClientMessageOneShotJob extends JobImpl {
*
* this is safe to call multiple times (only tells the client once)
*/
/****
private void dieFatal() {
dieFatal(MessageStatusMessage.STATUS_SEND_GUARANTEED_FAILURE);
}
****/
/**
* give up the ghost, this message just aint going through. tell the client.
*
* this is safe to call multiple times (only tells the client once)
*/
private void dieFatal(int status) {
if (_finished.getAndSet(true))
return;

View File

@ -97,10 +97,6 @@ class FloodfillVerifyStoreJob extends JobImpl {
return;
}
DatabaseLookupMessage lookup = buildLookup(replyTunnelInfo);
if (lookup == null) {
_facade.verifyFinished(_key);
return;
}
// If we are verifying a leaseset, use the destination's own tunnels,
// to avoid association by the exploratory tunnel OBEP.
@ -180,6 +176,7 @@ class FloodfillVerifyStoreJob extends JobImpl {
return _sentTo;
}
/** @return non-null */
private DatabaseLookupMessage buildLookup(TunnelInfo replyTunnelInfo) {
// If we are verifying a leaseset, use the destination's own tunnels,
// to avoid association by the exploratory tunnel OBEP.

View File

@ -8,6 +8,8 @@ package net.i2p.router.tasks;
*
*/
import java.util.concurrent.atomic.AtomicInteger;
import net.i2p.router.Router;
import net.i2p.router.RouterContext;
import net.i2p.router.RouterVersion;
@ -21,12 +23,12 @@ import net.i2p.util.Log;
*/
public class ShutdownHook extends Thread {
private final RouterContext _context;
private static int __id = 0;
private static final AtomicInteger __id = new AtomicInteger();
private final int _id;
public ShutdownHook(RouterContext ctx) {
_context = ctx;
_id = ++__id;
_id = __id.incrementAndGet();
}
@Override

View File

@ -292,6 +292,12 @@ class GeoIPv6 {
return 0;
}
@Override
public int hashCode() { return (((int) from) ^ ((int) to)); }
@Override
public boolean equals(Object o) { return (o instanceof V6Entry) && compareTo((V6Entry)o) == 0; }
@Override
public String toString() {
return "0x" + Long.toHexString(from) + " -> 0x" + Long.toHexString(to) + " : " + cc;