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))
);
stream.writeHeaders(responseHeaders, true);
Source source = Okio.source(file);
try {
BufferedSink out = Okio.buffer(stream.getSink());
out.writeAll(source);
out.close();
} finally {
Util.closeQuietly(source);
try (Source source = Okio.source(file); BufferedSink sink = Okio.buffer(stream.getSink())) {
sink.writeAll(source);
}
}

View File

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

View File

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

View File

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

View File

@@ -26,7 +26,6 @@ public class TestTls13Request {
private static final ConnectionSpec TLS_13 = new ConnectionSpec.Builder(true)
.cipherSuites(TLS13_CIPHER_SUITES)
.tlsVersions(TlsVersion.TLS_1_3)
.supportsTlsExtensions(true)
.build();
@@ -87,10 +86,7 @@ public class TestTls13Request {
Request request = new Request.Builder().url(url).build();
Response response = null;
try {
response = client.newCall(request).execute();
try (Response response = client.newCall(request).execute()) {
Handshake handshake = response.handshake();
System.out.println(handshake.tlsVersion()
+ " "
@@ -104,10 +100,6 @@ public class TestTls13Request {
+ "b");
} catch (IOException ioe) {
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.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
@@ -523,7 +524,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.secure()
.build();
assertEquals(true, cookie.secure());
assertTrue(cookie.secure());
}
@Test public void builderHttpOnly() throws Exception {
@@ -533,7 +534,7 @@ public final class CookieTest {
.hostOnlyDomain("example.com")
.httpOnly()
.build();
assertEquals(true, cookie.httpOnly());
assertTrue(cookie.httpOnly());
}
@Test public void builderIpv6() throws Exception {
@@ -563,11 +564,11 @@ public final class CookieTest {
assertEquals(cookieA.hashCode(), cookieB.hashCode());
assertEquals(cookieA, cookieB);
} else {
assertFalse(cookieA.hashCode() == cookieB.hashCode());
assertFalse(cookieA.equals(cookieB));
assertNotEquals(cookieA.hashCode(), cookieB.hashCode());
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!
while (delegate.hasNext()) {
DiskLruCache.Snapshot snapshot = delegate.next();
try {
try (DiskLruCache.Snapshot snapshot = delegate.next()) {
BufferedSource metadata = Okio.buffer(snapshot.getSource(ENTRY_METADATA));
nextUrl = metadata.readUtf8LineStrict();
return true;
} catch (IOException ignored) {
// We couldn't read the metadata for this snapshot; possibly because the host filesystem
// 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 {
Source source = null;
try {
source = Okio.source(file);
try (Source source = Okio.source(file)) {
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);
}
BufferedSource source = source();
byte[] bytes;
try {
try (BufferedSource source = source()) {
bytes = source.readByteArray();
} finally {
Util.closeQuietly(source);
}
if (contentLength != -1 && contentLength != bytes.length) {
throw new IOException("Content-Length ("
@@ -180,12 +177,9 @@ public abstract class ResponseBody implements Closeable {
* possibility for your response.
*/
public final String string() throws IOException {
BufferedSource source = source();
try {
try (BufferedSource source = source()) {
Charset charset = Util.bomAwareCharset(source, 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 {
BufferedSource source = Okio.buffer(fileSystem.source(journalFile));
try {
try (BufferedSource source = Okio.buffer(fileSystem.source(journalFile))) {
String magic = source.readUtf8LineStrict();
String version = source.readUtf8LineStrict();
String appVersionString = source.readUtf8LineStrict();
@@ -306,8 +305,6 @@ public final class DiskLruCache implements Closeable, Flushable {
} else {
journalWriter = newJournalWriter();
}
} finally {
Util.closeQuietly(source);
}
}
@@ -393,8 +390,7 @@ public final class DiskLruCache implements Closeable, Flushable {
journalWriter.close();
}
BufferedSink writer = Okio.buffer(fileSystem.sink(journalFileTmp));
try {
try (BufferedSink writer = Okio.buffer(fileSystem.sink(journalFileTmp))) {
writer.writeUtf8(MAGIC).writeByte('\n');
writer.writeUtf8(VERSION_1).writeByte('\n');
writer.writeDecimalLong(appVersion).writeByte('\n');
@@ -413,8 +409,6 @@ public final class DiskLruCache implements Closeable, Flushable {
writer.writeByte('\n');
}
}
} finally {
writer.close();
}
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!
// 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.
if (!source.buffer().exhausted() || !sink.buffer().exhausted()) {
if (!source.getBuffer().exhausted() || !sink.buffer().exhausted()) {
throw new IOException("TLS tunnel buffered too many bytes!");
}
return null;

View File

@@ -35,7 +35,6 @@ import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import okhttp3.Headers;
import okhttp3.Protocol;
import okhttp3.internal.NamedRunnable;
import okhttp3.internal.Util;
import okhttp3.internal.platform.Platform;
@@ -175,11 +174,6 @@ public final class Http2Connection implements Closeable {
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.
*/

View File

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

View File

@@ -11,7 +11,6 @@ import java.security.SecureRandom;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
import okhttp3.internal.Util;
import okhttp3.mockwebserver.Dispatcher;
import okhttp3.mockwebserver.MockResponse;
import okhttp3.mockwebserver.MockWebServer;
@@ -119,11 +118,8 @@ public class SampleServer extends Dispatcher {
private static SSLContext sslContext(String keystoreFile, String password)
throws GeneralSecurityException, IOException {
KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream in = new FileInputStream(keystoreFile);
try {
try (InputStream in = new FileInputStream(keystoreFile)) {
keystore.load(in, password.toCharArray());
} finally {
Util.closeQuietly(in);
}
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());