1
0
mirror of https://github.com/square/okhttp.git synced 2025-08-08 23:42:08 +03:00

Use automatic-resource-management blocks.

This commit is contained in:
Jesse Wilson
2019-01-01 21:50:44 -05:00
parent 0f5a7499e3
commit 5f4a2642c0
14 changed files with 26 additions and 77 deletions

View File

@@ -158,13 +158,8 @@ public final class Http2Server extends Http2Connection.Listener {
new Header("content-type", contentType(file)) new Header("content-type", contentType(file))
); );
stream.writeHeaders(responseHeaders, true); stream.writeHeaders(responseHeaders, true);
Source source = Okio.source(file); try (Source source = Okio.source(file); BufferedSink sink = Okio.buffer(stream.getSink())) {
try { sink.writeAll(source);
BufferedSink out = Okio.buffer(stream.getSink());
out.writeAll(source);
out.close();
} finally {
Util.closeQuietly(source);
} }
} }

View File

@@ -169,7 +169,7 @@ public class Main extends HelpOption implements Runnable {
Sink out = Okio.sink(System.out); Sink out = Okio.sink(System.out);
BufferedSource source = response.body().source(); BufferedSource source = response.body().source();
while (!source.exhausted()) { while (!source.exhausted()) {
out.write(source.buffer(), source.buffer().size()); out.write(source.getBuffer(), source.getBuffer().size());
out.flush(); out.flush();
} }

View File

@@ -251,20 +251,14 @@ public final class HttpLoggingInterceptor implements Interceptor {
} else { } else {
BufferedSource source = responseBody.source(); BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body. source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer(); Buffer buffer = source.getBuffer();
Long gzippedLength = null; Long gzippedLength = null;
if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) { if ("gzip".equalsIgnoreCase(headers.get("Content-Encoding"))) {
gzippedLength = buffer.size(); gzippedLength = buffer.size();
GzipSource gzippedResponseBody = null; try (GzipSource gzippedResponseBody = new GzipSource(buffer.clone())) {
try {
gzippedResponseBody = new GzipSource(buffer.clone());
buffer = new Buffer(); buffer = new Buffer();
buffer.writeAll(gzippedResponseBody); buffer.writeAll(gzippedResponseBody);
} finally {
if (gzippedResponseBody != null) {
gzippedResponseBody.close();
}
} }
} }

View File

@@ -63,7 +63,7 @@ public final class ServerSentEventReader {
return false; return false;
} }
switch (source.buffer().getByte(0)) { switch (source.getBuffer().getByte(0)) {
case '\r': case '\r':
case '\n': case '\n':
completeEvent(id, type, data); completeEvent(id, type, data);
@@ -162,7 +162,7 @@ public final class ServerSentEventReader {
*/ */
private boolean isKey(ByteString key) throws IOException { private boolean isKey(ByteString key) throws IOException {
if (source.rangeEquals(0, key)) { if (source.rangeEquals(0, key)) {
byte nextByte = source.buffer().getByte(key.size()); byte nextByte = source.getBuffer().getByte(key.size());
return nextByte == ':' return nextByte == ':'
|| nextByte == '\r' || nextByte == '\r'
|| nextByte == '\n'; || nextByte == '\n';
@@ -174,7 +174,7 @@ public final class ServerSentEventReader {
private void skipCrAndOrLf() throws IOException { private void skipCrAndOrLf() throws IOException {
if ((source.readByte() & 0xff) == '\r' if ((source.readByte() & 0xff) == '\r'
&& source.request(1) && source.request(1)
&& source.buffer().getByte(0) == '\n') { && source.getBuffer().getByte(0) == '\n') {
source.skip(1); source.skip(1);
} }
} }
@@ -186,11 +186,11 @@ public final class ServerSentEventReader {
private long skipNameAndDivider(long length) throws IOException { private long skipNameAndDivider(long length) throws IOException {
source.skip(length); source.skip(length);
if (source.buffer().getByte(0) == ':') { if (source.getBuffer().getByte(0) == ':') {
source.skip(1L); source.skip(1L);
length++; length++;
if (source.buffer().getByte(0) == ' ') { if (source.getBuffer().getByte(0) == ' ') {
source.skip(1); source.skip(1);
length++; length++;
} }

View File

@@ -26,7 +26,6 @@ public class TestTls13Request {
private static final ConnectionSpec TLS_13 = new ConnectionSpec.Builder(true) private static final ConnectionSpec TLS_13 = new ConnectionSpec.Builder(true)
.cipherSuites(TLS13_CIPHER_SUITES) .cipherSuites(TLS13_CIPHER_SUITES)
.tlsVersions(TlsVersion.TLS_1_3) .tlsVersions(TlsVersion.TLS_1_3)
.supportsTlsExtensions(true)
.build(); .build();
@@ -87,10 +86,7 @@ public class TestTls13Request {
Request request = new Request.Builder().url(url).build(); Request request = new Request.Builder().url(url).build();
Response response = null; try (Response response = client.newCall(request).execute()) {
try {
response = client.newCall(request).execute();
Handshake handshake = response.handshake(); Handshake handshake = response.handshake();
System.out.println(handshake.tlsVersion() System.out.println(handshake.tlsVersion()
+ " " + " "
@@ -104,10 +100,6 @@ public class TestTls13Request {
+ "b"); + "b");
} catch (IOException ioe) { } catch (IOException ioe) {
System.out.println(ioe.toString()); System.out.println(ioe.toString());
} finally {
if (response != null) {
response.close();
}
} }
} }
} }

View File

@@ -27,6 +27,7 @@ import org.junit.Test;
import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertTrue;
@@ -523,7 +524,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.secure() .secure()
.build(); .build();
assertEquals(true, cookie.secure()); assertTrue(cookie.secure());
} }
@Test public void builderHttpOnly() throws Exception { @Test public void builderHttpOnly() throws Exception {
@@ -533,7 +534,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com") .hostOnlyDomain("example.com")
.httpOnly() .httpOnly()
.build(); .build();
assertEquals(true, cookie.httpOnly()); assertTrue(cookie.httpOnly());
} }
@Test public void builderIpv6() throws Exception { @Test public void builderIpv6() throws Exception {
@@ -563,11 +564,11 @@ public final class CookieTest {
assertEquals(cookieA.hashCode(), cookieB.hashCode()); assertEquals(cookieA.hashCode(), cookieB.hashCode());
assertEquals(cookieA, cookieB); assertEquals(cookieA, cookieB);
} else { } else {
assertFalse(cookieA.hashCode() == cookieB.hashCode()); assertNotEquals(cookieA.hashCode(), cookieB.hashCode());
assertFalse(cookieA.equals(cookieB)); assertNotEquals(cookieA, cookieB);
} }
} }
assertFalse(cookieA.equals(null)); assertNotEquals(null, cookieA);
} }
} }

View File

@@ -339,16 +339,13 @@ public final class Cache implements Closeable, Flushable {
canRemove = false; // Prevent delegate.remove() on the wrong item! canRemove = false; // Prevent delegate.remove() on the wrong item!
while (delegate.hasNext()) { while (delegate.hasNext()) {
DiskLruCache.Snapshot snapshot = delegate.next(); try (DiskLruCache.Snapshot snapshot = delegate.next()) {
try {
BufferedSource metadata = Okio.buffer(snapshot.getSource(ENTRY_METADATA)); BufferedSource metadata = Okio.buffer(snapshot.getSource(ENTRY_METADATA));
nextUrl = metadata.readUtf8LineStrict(); nextUrl = metadata.readUtf8LineStrict();
return true; return true;
} catch (IOException ignored) { } catch (IOException ignored) {
// We couldn't read the metadata for this snapshot; possibly because the host filesystem // We couldn't read the metadata for this snapshot; possibly because the host filesystem
// has disappeared! Skip it. // has disappeared! Skip it.
} finally {
snapshot.close();
} }
} }

View File

@@ -116,12 +116,8 @@ public abstract class RequestBody {
} }
@Override public void writeTo(BufferedSink sink) throws IOException { @Override public void writeTo(BufferedSink sink) throws IOException {
Source source = null; try (Source source = Okio.source(file)) {
try {
source = Okio.source(file);
sink.writeAll(source); sink.writeAll(source);
} finally {
Util.closeQuietly(source);
} }
} }
}; };

View File

@@ -131,12 +131,9 @@ public abstract class ResponseBody implements Closeable {
throw new IOException("Cannot buffer entire body for content length: " + contentLength); throw new IOException("Cannot buffer entire body for content length: " + contentLength);
} }
BufferedSource source = source();
byte[] bytes; byte[] bytes;
try { try (BufferedSource source = source()) {
bytes = source.readByteArray(); bytes = source.readByteArray();
} finally {
Util.closeQuietly(source);
} }
if (contentLength != -1 && contentLength != bytes.length) { if (contentLength != -1 && contentLength != bytes.length) {
throw new IOException("Content-Length (" throw new IOException("Content-Length ("
@@ -180,12 +177,9 @@ public abstract class ResponseBody implements Closeable {
* possibility for your response. * possibility for your response.
*/ */
public final String string() throws IOException { public final String string() throws IOException {
BufferedSource source = source(); try (BufferedSource source = source()) {
try {
Charset charset = Util.bomAwareCharset(source, charset()); Charset charset = Util.bomAwareCharset(source, charset());
return source.readString(charset); return source.readString(charset);
} finally {
Util.closeQuietly(source);
} }
} }

View File

@@ -273,8 +273,7 @@ public final class DiskLruCache implements Closeable, Flushable {
} }
private void readJournal() throws IOException { private void readJournal() throws IOException {
BufferedSource source = Okio.buffer(fileSystem.source(journalFile)); try (BufferedSource source = Okio.buffer(fileSystem.source(journalFile))) {
try {
String magic = source.readUtf8LineStrict(); String magic = source.readUtf8LineStrict();
String version = source.readUtf8LineStrict(); String version = source.readUtf8LineStrict();
String appVersionString = source.readUtf8LineStrict(); String appVersionString = source.readUtf8LineStrict();
@@ -306,8 +305,6 @@ public final class DiskLruCache implements Closeable, Flushable {
} else { } else {
journalWriter = newJournalWriter(); journalWriter = newJournalWriter();
} }
} finally {
Util.closeQuietly(source);
} }
} }
@@ -393,8 +390,7 @@ public final class DiskLruCache implements Closeable, Flushable {
journalWriter.close(); journalWriter.close();
} }
BufferedSink writer = Okio.buffer(fileSystem.sink(journalFileTmp)); try (BufferedSink writer = Okio.buffer(fileSystem.sink(journalFileTmp))) {
try {
writer.writeUtf8(MAGIC).writeByte('\n'); writer.writeUtf8(MAGIC).writeByte('\n');
writer.writeUtf8(VERSION_1).writeByte('\n'); writer.writeUtf8(VERSION_1).writeByte('\n');
writer.writeDecimalLong(appVersion).writeByte('\n'); writer.writeDecimalLong(appVersion).writeByte('\n');
@@ -413,8 +409,6 @@ public final class DiskLruCache implements Closeable, Flushable {
writer.writeByte('\n'); writer.writeByte('\n');
} }
} }
} finally {
writer.close();
} }
if (fileSystem.exists(journalFile)) { if (fileSystem.exists(journalFile)) {

View File

@@ -400,7 +400,7 @@ public final class RealConnection extends Http2Connection.Listener implements Co
// that happens, then we will have buffered bytes that are needed by the SSLSocket! // that happens, then we will have buffered bytes that are needed by the SSLSocket!
// This check is imperfect: it doesn't tell us whether a handshake will succeed, just // This check is imperfect: it doesn't tell us whether a handshake will succeed, just
// that it will almost certainly fail because the proxy has sent unexpected data. // that it will almost certainly fail because the proxy has sent unexpected data.
if (!source.buffer().exhausted() || !sink.buffer().exhausted()) { if (!source.getBuffer().exhausted() || !sink.buffer().exhausted()) {
throw new IOException("TLS tunnel buffered too many bytes!"); throw new IOException("TLS tunnel buffered too many bytes!");
} }
return null; return null;

View File

@@ -35,7 +35,6 @@ import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import okhttp3.Headers; import okhttp3.Headers;
import okhttp3.Protocol;
import okhttp3.internal.NamedRunnable; import okhttp3.internal.NamedRunnable;
import okhttp3.internal.Util; import okhttp3.internal.Util;
import okhttp3.internal.platform.Platform; import okhttp3.internal.platform.Platform;
@@ -175,11 +174,6 @@ public final class Http2Connection implements Closeable {
readerRunnable = new ReaderRunnable(new Http2Reader(builder.source, client)); readerRunnable = new ReaderRunnable(new Http2Reader(builder.source, client));
} }
/** The protocol as selected using ALPN. */
public Protocol getProtocol() {
return Protocol.HTTP_2;
}
/** /**
* Returns the number of {@link Http2Stream#isOpen() open streams} on this connection. * Returns the number of {@link Http2Stream#isOpen() open streams} on this connection.
*/ */

View File

@@ -27,7 +27,6 @@ import okio.GzipSource;
import okio.Okio; import okio.Okio;
import static java.nio.charset.StandardCharsets.UTF_8; import static java.nio.charset.StandardCharsets.UTF_8;
import static okhttp3.internal.Util.closeQuietly;
/** /**
* A database of public suffixes provided by * A database of public suffixes provided by
@@ -313,8 +312,7 @@ public final class PublicSuffixDatabase {
InputStream resource = PublicSuffixDatabase.class.getResourceAsStream(PUBLIC_SUFFIX_RESOURCE); InputStream resource = PublicSuffixDatabase.class.getResourceAsStream(PUBLIC_SUFFIX_RESOURCE);
if (resource == null) return; if (resource == null) return;
BufferedSource bufferedSource = Okio.buffer(new GzipSource(Okio.source(resource))); try (BufferedSource bufferedSource = Okio.buffer(new GzipSource(Okio.source(resource)))) {
try {
int totalBytes = bufferedSource.readInt(); int totalBytes = bufferedSource.readInt();
publicSuffixListBytes = new byte[totalBytes]; publicSuffixListBytes = new byte[totalBytes];
bufferedSource.readFully(publicSuffixListBytes); bufferedSource.readFully(publicSuffixListBytes);
@@ -322,8 +320,6 @@ public final class PublicSuffixDatabase {
int totalExceptionBytes = bufferedSource.readInt(); int totalExceptionBytes = bufferedSource.readInt();
publicSuffixExceptionListBytes = new byte[totalExceptionBytes]; publicSuffixExceptionListBytes = new byte[totalExceptionBytes];
bufferedSource.readFully(publicSuffixExceptionListBytes); bufferedSource.readFully(publicSuffixExceptionListBytes);
} finally {
closeQuietly(bufferedSource);
} }
synchronized (this) { synchronized (this) {

View File

@@ -11,7 +11,6 @@ import java.security.SecureRandom;
import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext; import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.TrustManagerFactory;
import okhttp3.internal.Util;
import okhttp3.mockwebserver.Dispatcher; import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse; import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer; import okhttp3.mockwebserver.MockWebServer;
@@ -119,11 +118,8 @@ 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());
InputStream in = new FileInputStream(keystoreFile); try (InputStream in = new FileInputStream(keystoreFile)) {
try {
keystore.load(in, password.toCharArray()); keystore.load(in, password.toCharArray());
} finally {
Util.closeQuietly(in);
} }
KeyManagerFactory keyManagerFactory = KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());