1
0
mirror of https://github.com/square/okhttp.git synced 2025-11-24 18:41:06 +03:00

FindBugs sweep.

This commit is contained in:
Adrian Cole and Jesse Wilson
2014-02-05 11:49:21 +01:00
parent b149fec75e
commit fdee6f13a4
15 changed files with 71 additions and 60 deletions

View File

@@ -50,7 +50,7 @@ class UrlConnection extends SynchronousHttpClient {
return new UrlConnectionRequest(url); return new UrlConnectionRequest(url);
} }
class UrlConnectionRequest implements Runnable { static class UrlConnectionRequest implements Runnable {
private final URL url; private final URL url;
public UrlConnectionRequest(URL url) { public UrlConnectionRequest(URL url) {

View File

@@ -18,6 +18,7 @@ package com.squareup.okhttp.internal.spdy;
import com.squareup.okhttp.Protocol; import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.internal.SslContextBuilder; import com.squareup.okhttp.internal.SslContextBuilder;
import com.squareup.okhttp.internal.Util;
import java.io.File; import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.IOException; import java.io.IOException;
@@ -130,17 +131,21 @@ public final class SpdyServer implements IncomingStreamHandler {
} }
private void serveFile(SpdyStream stream, File file) throws IOException { private void serveFile(SpdyStream stream, File file) throws IOException {
InputStream in = new FileInputStream(file);
byte[] buffer = new byte[8192]; byte[] buffer = new byte[8192];
stream.reply( stream.reply(
headerEntries(":status", "200", ":version", "HTTP/1.1", "content-type", contentType(file)), headerEntries(":status", "200", ":version", "HTTP/1.1", "content-type", contentType(file)),
true); true);
InputStream in = new FileInputStream(file);
OutputStream out = stream.getOutputStream(); OutputStream out = stream.getOutputStream();
try {
int count; int count;
while ((count = in.read(buffer)) != -1) { while ((count = in.read(buffer)) != -1) {
out.write(buffer, 0, count); out.write(buffer, 0, count);
} }
out.close(); } finally {
Util.closeQuietly(in);
Util.closeQuietly(out);
}
} }
private String contentType(File file) { private String contentType(File file) {

View File

@@ -181,9 +181,6 @@ public final class MockWebServer {
if (protocols.contains(null)) { if (protocols.contains(null)) {
throw new IllegalArgumentException("protocols must not contain null"); throw new IllegalArgumentException("protocols must not contain null");
} }
if (protocols.contains(ByteString.EMPTY)) {
throw new IllegalArgumentException("protocols contains an empty string");
}
this.npnProtocols = Util.immutableList(protocols); this.npnProtocols = Util.immutableList(protocols);
} }

View File

@@ -32,7 +32,6 @@ import java.net.Socket;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.net.URI; import java.net.URI;
import java.net.URL; import java.net.URL;
import java.nio.ByteOrder;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import java.security.MessageDigest; import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
@@ -88,20 +87,6 @@ public final class Util {
} }
} }
public static void pokeInt(byte[] dst, int offset, int value, ByteOrder order) {
if (order == ByteOrder.BIG_ENDIAN) {
dst[offset++] = (byte) ((value >> 24) & 0xff);
dst[offset++] = (byte) ((value >> 16) & 0xff);
dst[offset++] = (byte) ((value >> 8) & 0xff);
dst[offset] = (byte) ((value >> 0) & 0xff);
} else {
dst[offset++] = (byte) ((value >> 0) & 0xff);
dst[offset++] = (byte) ((value >> 8) & 0xff);
dst[offset++] = (byte) ((value >> 16) & 0xff);
dst[offset] = (byte) ((value >> 24) & 0xff);
}
}
/** Returns true if two possibly-null objects are equal. */ /** Returns true if two possibly-null objects are equal. */
public static boolean equal(Object a, Object b) { public static boolean equal(Object a, Object b) {
return a == b || (a != null && a.equals(b)); return a == b || (a != null && a.equals(b));

View File

@@ -71,7 +71,7 @@ public final class ByteString {
if (ascii == null || data.length != ascii.length()) { if (ascii == null || data.length != ascii.length()) {
return false; return false;
} }
if (ascii == this.utf8) { if (ascii == this.utf8) { // not using String.equals to avoid looping twice.
return true; return true;
} }
for (int i = 0; i < data.length; i++) { for (int i = 0; i < data.length; i++) {

View File

@@ -460,11 +460,9 @@ public final class Http20Draft09 implements Variant {
out.close(); out.close();
} }
private void frameHeader(int length, byte type, byte flags, int streamId) void frameHeader(int length, byte type, byte flags, int streamId) throws IOException {
throws IOException {
if (length > 16383) throw illegalArgument("FRAME_SIZE_ERROR length > 16383: %s", length); if (length > 16383) throw illegalArgument("FRAME_SIZE_ERROR length > 16383: %s", length);
if ((streamId & 0x80000000) == 1) throw illegalArgument("(streamId & 0x80000000) == 1: %s", if ((streamId & 0x80000000) != 0) throw illegalArgument("reserved bit set: %s", streamId);
streamId);
out.writeInt((length & 0x3fff) << 16 | (type & 0xff) << 8 | (flags & 0xff)); out.writeInt((length & 0x3fff) << 16 | (type & 0xff) << 8 | (flags & 0xff));
out.writeInt(streamId & 0x7fffffff); out.writeInt(streamId & 0x7fffffff);
} }

View File

@@ -200,7 +200,7 @@ final class Spdy3 implements Variant {
int streamId = w1 & 0x7fffffff; int streamId = w1 & 0x7fffffff;
int associatedStreamId = w2 & 0x7fffffff; int associatedStreamId = w2 & 0x7fffffff;
int priority = (s3 & 0xe000) >>> 13; int priority = (s3 & 0xe000) >>> 13;
int slot = s3 & 0xff; // int slot = s3 & 0xff;
List<Header> headerBlock = headerBlockReader.readNameValueBlock(length - 10); List<Header> headerBlock = headerBlockReader.readNameValueBlock(length - 10);
boolean inFinished = (flags & FLAG_FIN) != 0; boolean inFinished = (flags & FLAG_FIN) != 0;
@@ -248,7 +248,7 @@ final class Spdy3 implements Variant {
private void readPing(Handler handler, int flags, int length) throws IOException { private void readPing(Handler handler, int flags, int length) throws IOException {
if (length != 4) throw ioException("TYPE_PING length: %d != 4", length); if (length != 4) throw ioException("TYPE_PING length: %d != 4", length);
int id = in.readInt(); int id = in.readInt();
boolean ack = client == ((id % 2) == 1); boolean ack = client == ((id & 1) == 1);
handler.ping(ack, id, 0); handler.ping(ack, id, 0);
} }
@@ -439,7 +439,7 @@ final class Spdy3 implements Variant {
@Override public synchronized void ping(boolean reply, int payload1, int payload2) @Override public synchronized void ping(boolean reply, int payload1, int payload2)
throws IOException { throws IOException {
boolean payloadIsReply = client != ((payload1 % 2) == 1); boolean payloadIsReply = client != ((payload1 & 1) == 1);
if (reply != payloadIsReply) throw new IllegalArgumentException("payload != reply"); if (reply != payloadIsReply) throw new IllegalArgumentException("payload != reply");
int type = TYPE_PING; int type = TYPE_PING;
int flags = 0; int flags = 0;

View File

@@ -108,7 +108,7 @@ public final class SpdyStream {
/** Returns true if this stream was created by this peer. */ /** Returns true if this stream was created by this peer. */
public boolean isLocallyInitiated() { public boolean isLocallyInitiated() {
boolean streamIsClient = (id % 2 == 1); boolean streamIsClient = ((id & 1) == 1);
return connection.client == streamIsClient; return connection.client == streamIsClient;
} }

View File

@@ -477,6 +477,30 @@ public class Http20Draft09Test {
return new Http20Draft09.Reader(new ByteArrayInputStream(out.toByteArray()), 4096, false); return new Http20Draft09.Reader(new ByteArrayInputStream(out.toByteArray()), 4096, false);
} }
@Test public void frameSizeError() throws IOException {
Http20Draft09.Writer writer = new Http20Draft09.Writer(new ByteArrayOutputStream(), true);
try {
writer.frameHeader(16384, Http20Draft09.TYPE_DATA, Http20Draft09.FLAG_NONE, 0);
fail();
} catch (IllegalArgumentException e) {
assertEquals("FRAME_SIZE_ERROR length > 16383: 16384", e.getMessage());
}
}
@Test public void streamIdHasReservedBit() throws IOException {
Http20Draft09.Writer writer = new Http20Draft09.Writer(new ByteArrayOutputStream(), true);
try {
int streamId = 3;
streamId |= 1L << 31; // set reserved bit
writer.frameHeader(16383, Http20Draft09.TYPE_DATA, Http20Draft09.FLAG_NONE, streamId);
fail();
} catch (IllegalArgumentException e) {
assertEquals("reserved bit set: -2147483645", e.getMessage());
}
}
private byte[] literalHeaders(List<Header> sentHeaders) throws IOException { private byte[] literalHeaders(List<Header> sentHeaders) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream();
new HpackDraft05.Writer(new DataOutputStream(out)).writeHeaders(sentHeaders); new HpackDraft05.Writer(new DataOutputStream(out)).writeHeaders(sentHeaders);

View File

@@ -1376,7 +1376,7 @@ public final class SpdyConnectionTest {
new Header(Header.TARGET_AUTHORITY, "squareup.com"), new Header(Header.TARGET_AUTHORITY, "squareup.com"),
new Header(Header.TARGET_PATH, "/cached") new Header(Header.TARGET_PATH, "/cached")
)); ));
peer.sendFrame().synReply(true, 1, Arrays.asList( peer.sendFrame().synReply(true, 2, Arrays.asList(
new Header(Header.RESPONSE_STATUS, "200") new Header(Header.RESPONSE_STATUS, "200")
)); ));
peer.acceptFrame(); // RST_STREAM peer.acceptFrame(); // RST_STREAM

View File

@@ -23,7 +23,6 @@ import java.util.ArrayList;
import java.util.LinkedList; import java.util.LinkedList;
import java.util.List; import java.util.List;
import java.util.ListIterator; import java.util.ListIterator;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
@@ -83,8 +82,8 @@ public class ConnectionPool {
private final ExecutorService executorService = new ThreadPoolExecutor(0, 1, private final ExecutorService executorService = new ThreadPoolExecutor(0, 1,
60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(),
Util.threadFactory("OkHttp ConnectionPool", true)); Util.threadFactory("OkHttp ConnectionPool", true));
private final Callable<Void> connectionsCleanupCallable = new Callable<Void>() { private final Runnable connectionsCleanupRunnable = new Runnable() {
@Override public Void call() throws Exception { @Override public void run() {
List<Connection> expiredConnections = new ArrayList<Connection>(MAX_CONNECTIONS_TO_CLEANUP); List<Connection> expiredConnections = new ArrayList<Connection>(MAX_CONNECTIONS_TO_CLEANUP);
int idleConnectionCount = 0; int idleConnectionCount = 0;
synchronized (ConnectionPool.this) { synchronized (ConnectionPool.this) {
@@ -113,7 +112,6 @@ public class ConnectionPool {
for (Connection expiredConnection : expiredConnections) { for (Connection expiredConnection : expiredConnections) {
Util.closeQuietly(expiredConnection); Util.closeQuietly(expiredConnection);
} }
return null;
} }
}; };
@@ -205,7 +203,7 @@ public class ConnectionPool {
connections.addFirst(foundConnection); // Add it back after iteration. connections.addFirst(foundConnection); // Add it back after iteration.
} }
executorService.submit(connectionsCleanupCallable); executorService.execute(connectionsCleanupRunnable);
return foundConnection; return foundConnection;
} }
@@ -239,7 +237,7 @@ public class ConnectionPool {
connection.resetIdleStartTime(); connection.resetIdleStartTime();
} }
executorService.submit(connectionsCleanupCallable); executorService.execute(connectionsCleanupRunnable);
} }
/** /**
@@ -247,7 +245,7 @@ public class ConnectionPool {
* continue to use {@code connection}. * continue to use {@code connection}.
*/ */
public void maybeShare(Connection connection) { public void maybeShare(Connection connection) {
executorService.submit(connectionsCleanupCallable); executorService.execute(connectionsCleanupRunnable);
if (!connection.isSpdy()) { if (!connection.isSpdy()) {
// Only SPDY connections are sharable. // Only SPDY connections are sharable.
return; return;

View File

@@ -349,9 +349,6 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
if (protocols.contains(null)) { if (protocols.contains(null)) {
throw new IllegalArgumentException("protocols must not contain null"); throw new IllegalArgumentException("protocols must not contain null");
} }
if (protocols.contains(ByteString.EMPTY)) {
throw new IllegalArgumentException("protocols contains an empty string");
}
this.protocols = Util.immutableList(protocols); this.protocols = Util.immutableList(protocols);
return this; return this;
} }

View File

@@ -33,7 +33,6 @@ import java.io.Writer;
import java.util.Iterator; import java.util.Iterator;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@@ -160,19 +159,22 @@ public final class DiskLruCache implements Closeable {
/** This cache uses a single background thread to evict entries. */ /** This cache uses a single background thread to evict entries. */
final ThreadPoolExecutor executorService = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS, final ThreadPoolExecutor executorService = new ThreadPoolExecutor(0, 1, 60L, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true)); new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp DiskLruCache", true));
private final Callable<Void> cleanupCallable = new Callable<Void>() { private final Runnable cleanupRunnable = new Runnable() {
public Void call() throws Exception { public void run() {
synchronized (DiskLruCache.this) { synchronized (DiskLruCache.this) {
if (journalWriter == null) { if (journalWriter == null) {
return null; // Closed. return; // Closed.
} }
try {
trimToSize(); trimToSize();
if (journalRebuildRequired()) { if (journalRebuildRequired()) {
rebuildJournal(); rebuildJournal();
redundantOpCount = 0; redundantOpCount = 0;
} }
} catch (IOException e) {
throw new RuntimeException(e);
}
} }
return null;
} }
}; };
@@ -431,7 +433,7 @@ public final class DiskLruCache implements Closeable {
redundantOpCount++; redundantOpCount++;
journalWriter.append(READ + ' ' + key + '\n'); journalWriter.append(READ + ' ' + key + '\n');
if (journalRebuildRequired()) { if (journalRebuildRequired()) {
executorService.submit(cleanupCallable); executorService.execute(cleanupRunnable);
} }
return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths); return new Snapshot(key, entry.sequenceNumber, ins, entry.lengths);
@@ -488,7 +490,7 @@ public final class DiskLruCache implements Closeable {
*/ */
public synchronized void setMaxSize(long maxSize) { public synchronized void setMaxSize(long maxSize) {
this.maxSize = maxSize; this.maxSize = maxSize;
executorService.submit(cleanupCallable); executorService.execute(cleanupRunnable);
} }
/** /**
@@ -551,7 +553,7 @@ public final class DiskLruCache implements Closeable {
journalWriter.flush(); journalWriter.flush();
if (size > maxSize || journalRebuildRequired()) { if (size > maxSize || journalRebuildRequired()) {
executorService.submit(cleanupCallable); executorService.execute(cleanupRunnable);
} }
} }
@@ -593,7 +595,7 @@ public final class DiskLruCache implements Closeable {
lruEntries.remove(key); lruEntries.remove(key);
if (journalRebuildRequired()) { if (journalRebuildRequired()) {
executorService.submit(cleanupCallable); executorService.execute(cleanupRunnable);
} }
return true; return true;

View File

@@ -18,7 +18,7 @@ public class OkHttpContributors {
new TypeToken<List<Contributor>>() { new TypeToken<List<Contributor>>() {
}; };
class Contributor { static class Contributor {
String login; String login;
int contributions; int contributions;
} }

View File

@@ -9,6 +9,7 @@ import java.io.File;
import java.io.FileInputStream; import java.io.FileInputStream;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException; import java.security.GeneralSecurityException;
import java.security.KeyStore; import java.security.KeyStore;
import java.security.SecureRandom; import java.security.SecureRandom;
@@ -116,8 +117,12 @@ public class SampleServer extends Dispatcher {
private static SSLContext sslContext(String keystoreFile, String password) private static SSLContext sslContext(String keystoreFile, String password)
throws GeneralSecurityException, IOException { throws GeneralSecurityException, IOException {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
keystore.load(new FileInputStream(keystoreFile), password.toCharArray()); InputStream in = new FileInputStream(keystoreFile);
try {
keystore.load(in, password.toCharArray());
} finally {
Util.closeQuietly(in);
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keystore, password.toCharArray()); keyManagerFactory.init(keystore, password.toCharArray());