id
int64 0
10.2k
| text_id
stringlengths 17
67
| repo_owner
stringclasses 232
values | repo_name
stringclasses 295
values | issue_url
stringlengths 39
89
| pull_url
stringlengths 37
87
| comment_url
stringlengths 37
94
| links_count
int64 1
2
| link_keyword
stringclasses 12
values | issue_title
stringlengths 7
197
| issue_body
stringlengths 45
21.3k
| base_sha
stringlengths 40
40
| head_sha
stringlengths 40
40
| diff_url
stringlengths 120
170
| diff
stringlengths 478
132k
| changed_files
stringlengths 47
2.6k
| changed_files_exts
stringclasses 22
values | changed_files_count
int64 1
22
| java_changed_files_count
int64 1
22
| kt_changed_files_count
int64 0
0
| py_changed_files_count
int64 0
0
| code_changed_files_count
int64 1
22
| repo_symbols_count
int64 32.6k
242M
| repo_tokens_count
int64 6.59k
49.2M
| repo_lines_count
int64 992
6.2M
| repo_files_without_tests_count
int64 12
28.1k
| changed_symbols_count
int64 0
36.1k
| changed_tokens_count
int64 0
6.5k
| changed_lines_count
int64 0
561
| changed_files_without_tests_count
int64 1
17
| issue_symbols_count
int64 45
21.3k
| issue_words_count
int64 2
1.39k
| issue_tokens_count
int64 13
4.47k
| issue_lines_count
int64 1
325
| issue_links_count
int64 0
19
| issue_code_blocks_count
int64 0
31
| pull_create_at
timestamp[s] | stars
int64 10
44.3k
| language
stringclasses 8
values | languages
stringclasses 296
values | license
stringclasses 2
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
162 | square/okhttp/1085/1034 | square | okhttp | https://github.com/square/okhttp/issues/1034 | https://github.com/square/okhttp/pull/1085 | https://github.com/square/okhttp/pull/1085 | 1 | closes | SpdyConnection.pushExecutor has zero keep-alive time | https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java#L158
Because of the 0ms keep-alive time, the pushExecutor creates (and destroys) a new thread on every callback. This seems unnecessarily expensive, compared to reusing the thread, particularly in settings where push callbacks are invoked frequently.
Is there a reason why you'd want the threads created for this executor to be effectively single-use?
| 9aa1268899524f0f750ab35fa363f2ed3cec29cf | 712e56de25c8c212d8c85c6b316faeb8789d731c | https://github.com/square/okhttp/compare/9aa1268899524f0f750ab35fa363f2ed3cec29cf...712e56de25c8c212d8c85c6b316faeb8789d731c | diff --git a/okhttp/src/main/java/com/squareup/okhttp/Connection.java b/okhttp/src/main/java/com/squareup/okhttp/Connection.java
index 11bf1f217..0806c7954 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/Connection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/Connection.java
@@ -85,7 +85,7 @@ public final class Connection {
"TLS_DHE_RSA_WITH_AES_128_CBC_SHA", // 0x00,0x33 Android 2.3
"TLS_DHE_DSS_WITH_AES_128_CBC_SHA", // 0x00,0x32 Android 2.3
"TLS_DHE_RSA_WITH_AES_256_CBC_SHA", // 0x00,0x39 Android 2.3
- "TLS_RSA_WITH_AES_128_GCM_SHA256", // 0x00,0x9C
+ "TLS_RSA_WITH_AES_128_GCM_SHA256", // 0x00,0x9C Android L
"TLS_RSA_WITH_AES_128_CBC_SHA", // 0x00,0x2F Android 2.3
"TLS_RSA_WITH_AES_256_CBC_SHA", // 0x00,0x35 Android 2.3
"SSL_RSA_WITH_3DES_EDE_CBC_SHA", // 0x00,0x0A Android 2.3 (Deprecated in L)
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
index 31719ff07..0b6fa2d5f 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
@@ -153,8 +153,7 @@ public final class SpdyConnection implements Closeable {
if (protocol == Protocol.HTTP_2) {
variant = new Http20Draft14();
// Like newSingleThreadExecutor, except lazy creates the thread.
- pushExecutor = new ThreadPoolExecutor(0, 1,
- 0L, TimeUnit.MILLISECONDS,
+ pushExecutor = new ThreadPoolExecutor(0, 1, 60, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(),
Util.threadFactory(String.format("OkHttp %s Push Observer", hostName), true));
// 1 less than SPDY http://tools.ietf.org/html/draft-ietf-httpbis-http2-14#section-6.9.2 | ['okhttp/src/main/java/com/squareup/okhttp/Connection.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 736,645 | 166,586 | 21,524 | 114 | 297 | 93 | 5 | 2 | 475 | 53 | 105 | 6 | 1 | 0 | 2014-10-11T14:11:59 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
161 | square/okhttp/1106/938 | square | okhttp | https://github.com/square/okhttp/issues/938 | https://github.com/square/okhttp/pull/1106 | https://github.com/square/okhttp/pull/1106 | 1 | closes | SpdyConnection synchronization problem in goAway | We call SpdyStream.receiveRstStream (synchronizes on the stream) while holding the lock on SpdyConnection.this. We should release the SpdyConnection lock before acquiring the SpdyStream lock.
| 125df557fbeb9c77eb17872acac2eb156428d2ed | 8f1bc30cd1e821b8b3745502a0f442f54cdebce8 | https://github.com/square/okhttp/compare/125df557fbeb9c77eb17872acac2eb156428d2ed...8f1bc30cd1e821b8b3745502a0f442f54cdebce8 | diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
index 0b6fa2d5f..d3ebee2e3 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
@@ -24,7 +24,6 @@ import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
@@ -734,18 +733,19 @@ public final class SpdyConnection implements Closeable {
@Override public void goAway(int lastGoodStreamId, ErrorCode errorCode, ByteString debugData) {
if (debugData.size() > 0) { // TODO: log the debugData
}
+
+ // Copy the streams first. We don't want to hold a lock when we call receiveRstStream().
+ SpdyStream[] streamsCopy;
synchronized (SpdyConnection.this) {
+ streamsCopy = streams.values().toArray(new SpdyStream[streams.size()]);
shutdown = true;
+ }
- // Fail all streams created after the last good stream ID.
- for (Iterator<Map.Entry<Integer, SpdyStream>> i = streams.entrySet().iterator();
- i.hasNext(); ) {
- Map.Entry<Integer, SpdyStream> entry = i.next();
- int streamId = entry.getKey();
- if (streamId > lastGoodStreamId && entry.getValue().isLocallyInitiated()) {
- entry.getValue().receiveRstStream(ErrorCode.REFUSED_STREAM);
- i.remove();
- }
+ // Fail all streams created after the last good stream ID.
+ for (SpdyStream spdyStream : streamsCopy) {
+ if (spdyStream.getId() > lastGoodStreamId && spdyStream.isLocallyInitiated()) {
+ spdyStream.receiveRstStream(ErrorCode.REFUSED_STREAM);
+ removeStream(spdyStream.getId());
}
}
} | ['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 755,423 | 170,699 | 21,981 | 117 | 1,054 | 232 | 20 | 1 | 192 | 24 | 43 | 2 | 0 | 0 | 2014-10-26T14:28:50 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
170 | square/okhttp/518/184 | square | okhttp | https://github.com/square/okhttp/issues/184 | https://github.com/square/okhttp/pull/518 | https://github.com/square/okhttp/pull/518 | 1 | closes | OkHttp changes the global SSL context, breaks other HTTP clients | We're enabling SPDY for the shared SSL context, and other HTTP clients like HttpURLConnection don't anticipate this, causing them to freak out and crash the app.
@skyisle's original report...
Here is backtrace.
DEBUG I backtrace:
DEBUG I #00 pc 00022430 /system/lib/libssl.so (SSL_select_next_proto+25)
DEBUG I #01 pc 000222ef /system/lib/libjavacore.so
DEBUG I #02 pc 0002905f /system/lib/libssl.so (ssl_parse_serverhello_tlsext+458)
DEBUG I #03 pc 00015957 /system/lib/libssl.so (ssl3_get_server_hello+894)
DEBUG I #04 pc 00018193 /system/lib/libssl.so (ssl3_connect+618)
DEBUG I #05 pc 000235d7 /system/lib/libssl.so (SSL_connect+18)
DEBUG I #06 pc 0001126b /system/lib/libssl.so (ssl23_connect+1970)
DEBUG I #07 pc 0002350f /system/lib/libssl.so (SSL_do_handshake+66)
DEBUG I #08 pc 00024bc5 /system/lib/libjavacore.so
DEBUG I #09 pc 0001e490 /system/lib/libdvm.so (dvmPlatformInvoke+112)
DEBUG I #10 pc 0004d2b1 /system/lib/libdvm.so (dvmCallJNIMethod(unsigned int const_, JValue_, Method const_, Thread_)+396)
DEBUG I #11 pc 000278a0 /system/lib/libdvm.so
DEBUG I #12 pc 0002b77c /system/lib/libdvm.so (dvmInterpret(Thread_, Method const_, JValue_)+176)
DEBUG I #13 pc 0005fae5 /system/lib/libdvm.so (dvmCallMethodV(Thread_, Method const_, Object_, bool, JValue_, std::__va_list)+272)
DEBUG I #14 pc 0005fb0f /system/lib/libdvm.so (dvmCallMethod(Thread_, Method const_, Object_, JValue*, ...)+20)
DEBUG I #15 pc 0005466f /system/lib/libdvm.so
DEBUG I #16 pc 0000e418 /system/lib/libc.so (__thread_entry+72)
DEBUG I #17 pc 0000db0c /system/lib/libc.so (pthread_create+168)
DEBUG I #18 pc 00052f34 <unknown>
| de6d505c03419a53e0387802a6cc2196572dd99e | 5d7fdbaf30a411c56666462bd032d86e8eb4ddf7 | https://github.com/square/okhttp/compare/de6d505c03419a53e0387802a6cc2196572dd99e...5d7fdbaf30a411c56666462bd032d86e8eb4ddf7 | diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
index 68e1cfadb..b76b5cd45 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
@@ -15,8 +15,8 @@
*/
package com.squareup.okhttp;
-import com.squareup.okhttp.internal.bytes.ByteString;
import com.squareup.okhttp.internal.Util;
+import com.squareup.okhttp.internal.bytes.ByteString;
import com.squareup.okhttp.internal.http.HttpAuthenticator;
import com.squareup.okhttp.internal.http.HttpURLConnectionImpl;
import com.squareup.okhttp.internal.http.HttpsURLConnectionImpl;
@@ -31,11 +31,12 @@ import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
+import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.HostnameVerifier;
-import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
/** Configures and creates HTTP connections. */
@@ -202,8 +203,7 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
/**
* Sets the socket factory used to secure HTTPS connections.
*
- * <p>If unset, the {@link HttpsURLConnection#getDefaultSSLSocketFactory()
- * system-wide default} SSL socket factory will be used.
+ * <p>If unset, a lazily created SSL socket factory will be used.
*/
public OkHttpClient setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
@@ -218,7 +218,8 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
* Sets the verifier used to confirm that response certificates apply to
* requested hostnames for HTTPS connections.
*
- * <p>If unset, the {@link HttpsURLConnection#getDefaultHostnameVerifier()
+ * <p>If unset, the
+ * {@link javax.net.ssl.HttpsURLConnection#getDefaultHostnameVerifier()
* system-wide default} hostname verifier will be used.
*/
public OkHttpClient setHostnameVerifier(HostnameVerifier hostnameVerifier) {
@@ -422,7 +423,7 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
result.responseCache = toOkResponseCacheOrNull(ResponseCache.getDefault());
}
if (result.sslSocketFactory == null) {
- result.sslSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
+ result.sslSocketFactory = getDefaultSSLSocketFactory();
}
if (result.hostnameVerifier == null) {
result.hostnameVerifier = OkHostnameVerifier.INSTANCE;
@@ -439,6 +440,30 @@ public final class OkHttpClient implements URLStreamHandlerFactory, Cloneable {
return result;
}
+ /**
+ * Java and Android programs default to using a single global SSL context,
+ * accessible to HTTP clients as {@link SSLSocketFactory#getDefault()}. If we
+ * used the shared SSL context, when OkHttp enables NPN for its SPDY-related
+ * stuff, it would also enable NPN for other usages, which might crash them
+ * because NPN is enabled when it isn't expected to be.
+ * <p>
+ * This code avoids that by defaulting to an OkHttp created SSL context. The
+ * significant drawback of this approach is that apps that customize the
+ * global SSL context will lose these customizations.
+ */
+ private synchronized SSLSocketFactory getDefaultSSLSocketFactory() {
+ if (sslSocketFactory == null) {
+ try {
+ SSLContext sslContext = SSLContext.getInstance("TLS");
+ sslContext.init(null, null, null);
+ sslSocketFactory = sslContext.getSocketFactory();
+ } catch (GeneralSecurityException e) {
+ throw new AssertionError(); // The system has no TLS. Just give up.
+ }
+ }
+ return sslSocketFactory;
+ }
+
/** Returns a shallow copy of this OkHttpClient. */
@Override public OkHttpClient clone() {
try { | ['okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 688,744 | 159,125 | 20,229 | 100 | 1,840 | 403 | 37 | 1 | 1,769 | 183 | 605 | 27 | 0 | 0 | 2014-02-09T00:24:27 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
169 | square/okhttp/628/627 | square | okhttp | https://github.com/square/okhttp/issues/627 | https://github.com/square/okhttp/pull/628 | https://github.com/square/okhttp/pull/628 | 1 | fix | SpdyConnection clears the old settings without merging with the new server settings causing the window size always set as -1 | When debugging an issue with client requests hanging on SpdyStream.waitUntilWritable(), we found that the window size is set as -1 in SpdyStream.java at line:
this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize();
After tracing down the issue, the problem turned out to be line 662 of https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java, where peerSettings is cleared without merging with the new settings. This has caused any later SpdyStream always uses an –1 as the initial window size, and the bug has also caused the new window size settings not get propagated to existing SpdySteam(s).
| 945619c3f451bba092f772adbd62cd0a6fd7ec3b | 12ba9103d825b776d6cf4f74704332f4118ec1be | https://github.com/square/okhttp/compare/945619c3f451bba092f772adbd62cd0a6fd7ec3b...12ba9103d825b776d6cf4f74704332f4118ec1be | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java
index 44459b8c9..294684f1b 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java
@@ -17,6 +17,7 @@ package com.squareup.okhttp.internal.spdy;
import org.junit.Test;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_BANDWIDTH;
import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_RETRANS_RATE;
import static com.squareup.okhttp.internal.spdy.Settings.MAX_CONCURRENT_STREAMS;
@@ -68,9 +69,10 @@ public final class SettingsTest {
settings.set(DOWNLOAD_RETRANS_RATE, 0, 97);
assertEquals(97, settings.getDownloadRetransRate(-3));
- assertEquals(-1, settings.getInitialWindowSize());
+ assertEquals(DEFAULT_INITIAL_WINDOW_SIZE,
+ settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
settings.set(Settings.INITIAL_WINDOW_SIZE, 0, 108);
- assertEquals(108, settings.getInitialWindowSize());
+ assertEquals(108, settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
assertEquals(-3, settings.getClientCertificateVectorSize(-3));
settings.set(Settings.CLIENT_CERTIFICATE_VECTOR_SIZE, 0, 117);
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java
index 64b81ced1..2ef127e99 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java
@@ -39,6 +39,7 @@ import static com.squareup.okhttp.internal.spdy.ErrorCode.INVALID_STREAM;
import static com.squareup.okhttp.internal.spdy.ErrorCode.PROTOCOL_ERROR;
import static com.squareup.okhttp.internal.spdy.ErrorCode.REFUSED_STREAM;
import static com.squareup.okhttp.internal.spdy.ErrorCode.STREAM_IN_USE;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
import static com.squareup.okhttp.internal.spdy.Settings.PERSIST_VALUE;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_DATA;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_GOAWAY;
@@ -47,7 +48,6 @@ import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_PING;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_RST_STREAM;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_SETTINGS;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_WINDOW_UPDATE;
-import static com.squareup.okhttp.internal.spdy.SpdyConnection.INITIAL_WINDOW_SIZE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -301,7 +301,7 @@ public final class SpdyConnectionTest {
// This stream was created *after* the connection settings were adjusted.
SpdyStream stream = connection.newStream(headerEntries("a", "android"), false, true);
- assertEquals(3368, connection.peerSettings.getInitialWindowSize());
+ assertEquals(3368, connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
assertEquals(1684, connection.bytesLeftInWriteWindow); // initial wasn't affected.
// New Stream is has the most recent initial window size.
assertEquals(3368, stream.bytesLeftInWriteWindow);
@@ -405,6 +405,35 @@ public final class SpdyConnectionTest {
}
}
+ @Test public void clearSettingsBeforeMerge() throws Exception {
+ // write the mocking script
+ Settings settings1 = new Settings();
+ settings1.set(Settings.UPLOAD_BANDWIDTH, PERSIST_VALUE, 100);
+ settings1.set(Settings.DOWNLOAD_BANDWIDTH, PERSIST_VALUE, 200);
+ settings1.set(Settings.DOWNLOAD_RETRANS_RATE, 0, 300);
+ peer.sendFrame().settings(settings1);
+ peer.sendFrame().ping(false, 2, 0);
+ peer.acceptFrame();
+ peer.play();
+
+ // play it back
+ SpdyConnection connection = connection(peer, SPDY3);
+
+ peer.takeFrame(); // Guarantees that the Settings frame has been processed.
+
+ // fake a settings frame with clear flag set.
+ Settings settings2 = new Settings();
+ settings2.set(Settings.MAX_CONCURRENT_STREAMS, PERSIST_VALUE, 600);
+ connection.readerRunnable.settings(true, settings2);
+
+ synchronized (connection) {
+ assertEquals(-1, connection.peerSettings.getUploadBandwidth(-1));
+ assertEquals(-1, connection.peerSettings.getDownloadBandwidth(-1));
+ assertEquals(-1, connection.peerSettings.getDownloadRetransRate(-1));
+ assertEquals(600, connection.peerSettings.getMaxConcurrentStreams(-1));
+ }
+ }
+
@Test public void bogusDataFrameDoesNotDisruptConnection() throws Exception {
// write the mocking script
peer.sendFrame().data(true, 41, new OkBuffer().writeUtf8("bogus"));
@@ -1042,7 +1071,7 @@ public final class SpdyConnectionTest {
throws IOException, InterruptedException {
peer.setVariantAndClient(variant, false);
- int windowUpdateThreshold = INITIAL_WINDOW_SIZE / 2;
+ int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2;
// Write the mocking script.
peer.acceptFrame(); // SYN_STREAM
@@ -1152,7 +1181,7 @@ public final class SpdyConnectionTest {
}
@Test public void writeAwaitsWindowUpdate() throws Exception {
- int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
+ int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
// Write the mocking script. This accepts more data frames than necessary!
peer.acceptFrame(); // SYN_STREAM
@@ -1166,7 +1195,7 @@ public final class SpdyConnectionTest {
SpdyConnection connection = connection(peer, SPDY3);
SpdyStream stream = connection.newStream(headerEntries("b", "banana"), true, true);
BufferedSink out = Okio.buffer(stream.getSink());
- out.write(new byte[INITIAL_WINDOW_SIZE]);
+ out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]);
out.flush();
// Check that we've filled the window for both the stream and also the connection.
@@ -1194,7 +1223,7 @@ public final class SpdyConnectionTest {
}
@Test public void initialSettingsWithWindowSizeAdjustsConnection() throws Exception {
- int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
+ int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
// Write the mocking script. This accepts more data frames than necessary!
peer.acceptFrame(); // SYN_STREAM
@@ -1208,7 +1237,7 @@ public final class SpdyConnectionTest {
SpdyConnection connection = connection(peer, SPDY3);
SpdyStream stream = connection.newStream(headerEntries("a", "apple"), true, true);
BufferedSink out = Okio.buffer(stream.getSink());
- out.write(new byte[INITIAL_WINDOW_SIZE]);
+ out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]);
out.flush();
// write 1 more than the window size
@@ -1221,7 +1250,7 @@ public final class SpdyConnectionTest {
// Receiving a Settings with a larger window size will unblock the streams.
Settings initial = new Settings();
- initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 1);
+ initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 1);
connection.readerRunnable.settings(false, initial);
assertEquals(1, connection.bytesLeftInWriteWindow);
@@ -1235,7 +1264,7 @@ public final class SpdyConnectionTest {
// Settings after the initial do not affect the connection window size.
Settings next = new Settings();
- next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 2);
+ next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 2);
connection.readerRunnable.settings(false, next);
assertEquals(0, connection.bytesLeftInWriteWindow); // connection wasn't affected.
@@ -1263,7 +1292,7 @@ public final class SpdyConnectionTest {
}
@Test public void blockedStreamDoesntStarveNewStream() throws Exception {
- int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize());
+ int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize());
// Write the mocking script. This accepts more data frames than necessary!
peer.acceptFrame(); // SYN_STREAM on stream 1
@@ -1278,7 +1307,7 @@ public final class SpdyConnectionTest {
SpdyConnection connection = connection(peer, SPDY3);
SpdyStream stream1 = connection.newStream(headerEntries("a", "apple"), true, true);
BufferedSink out1 = Okio.buffer(stream1.getSink());
- out1.write(new byte[INITIAL_WINDOW_SIZE]);
+ out1.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]);
out1.flush();
// Check that we've filled the window for both the stream and also the connection.
@@ -1299,7 +1328,7 @@ public final class SpdyConnectionTest {
assertEquals(0, connection.bytesLeftInWriteWindow);
assertEquals(0, connection.getStream(1).bytesLeftInWriteWindow);
- assertEquals(INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow);
+ assertEquals(DEFAULT_INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow);
}
@Test public void maxFrameSizeHonored() throws Exception {
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java
index c05d6b174..bf430882e 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java
@@ -22,6 +22,12 @@ import java.util.Arrays;
* Settings are {@link com.squareup.okhttp.internal.spdy.SpdyConnection connection} scoped.
*/
final class Settings {
+ /**
+ * From the SPDY/3 and HTTP/2 specs, the default initial window size for all
+ * streams is 64 KiB. (Chrome 25 uses 10 MiB).
+ */
+ static final int DEFAULT_INITIAL_WINDOW_SIZE = 64 * 1024;
+
/** Peer request to clear durable settings. */
static final int FLAG_CLEAR_PREVIOUSLY_PERSISTED_SETTINGS = 0x1;
@@ -171,11 +177,9 @@ final class Settings {
return (bit & set) != 0 ? values[DOWNLOAD_RETRANS_RATE] : defaultValue;
}
- // TODO: honor this setting in http/2.
- /** Returns -1 if unset. */
- int getInitialWindowSize() {
+ int getInitialWindowSize(int defaultValue) {
int bit = 1 << INITIAL_WINDOW_SIZE;
- return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : -1;
+ return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : defaultValue;
}
/** spdy/3 only. */
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
index fab8698a2..4cd8d32c8 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
@@ -38,6 +38,8 @@ import okio.ByteString;
import okio.OkBuffer;
import okio.Okio;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
+
/**
* A socket connection to a remote peer. A connection hosts streams which can
* send and receive data.
@@ -89,8 +91,6 @@ public final class SpdyConnection implements Closeable {
private final PushObserver pushObserver;
private int nextPingId;
- static final int INITIAL_WINDOW_SIZE = 65535;
-
/**
* The total number of bytes consumed by the application, but not yet
* acknowledged by sending a {@code WINDOW_UPDATE} frame on this connection.
@@ -107,15 +107,12 @@ public final class SpdyConnection implements Closeable {
/** Settings we communicate to the peer. */
// TODO: Do we want to dynamically adjust settings, or KISS and only set once?
- final Settings okHttpSettings = new Settings()
- .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE);
- // TODO: implement stream limit
+ final Settings okHttpSettings = new Settings();
// okHttpSettings.set(Settings.MAX_CONCURRENT_STREAMS, 0, max);
/** Settings we receive from the peer. */
// TODO: MWS will need to guard on this setting before attempting to push.
- final Settings peerSettings = new Settings()
- .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE);
+ final Settings peerSettings = new Settings();
private boolean receivedInitialPeerSettings = false;
final FrameReader frameReader;
@@ -151,7 +148,7 @@ public final class SpdyConnection implements Closeable {
} else {
throw new AssertionError(protocol);
}
- bytesLeftInWriteWindow = peerSettings.getInitialWindowSize();
+ bytesLeftInWriteWindow = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
frameReader = variant.newReader(builder.source, client);
frameWriter = variant.newWriter(builder.sink, client);
maxFrameSize = variant.maxFrameSize();
@@ -657,16 +654,13 @@ public final class SpdyConnection implements Closeable {
long delta = 0;
SpdyStream[] streamsToNotify = null;
synchronized (SpdyConnection.this) {
- int priorWriteWindowSize = peerSettings.getInitialWindowSize();
- if (clearPrevious) {
- peerSettings.clear();
- } else {
- peerSettings.merge(newSettings);
- }
+ int priorWriteWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
+ if (clearPrevious) peerSettings.clear();
+ peerSettings.merge(newSettings);
if (getProtocol() == Protocol.HTTP_2) {
ackSettingsLater();
}
- int peerInitialWindowSize = peerSettings.getInitialWindowSize();
+ int peerInitialWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
if (peerInitialWindowSize != -1 && peerInitialWindowSize != priorWriteWindowSize) {
delta = peerInitialWindowSize - priorWriteWindowSize;
if (!receivedInitialPeerSettings) {
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
index 4fea5e8d3..0fcde2dbb 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
@@ -28,6 +28,8 @@ import okio.OkBuffer;
import okio.Sink;
import okio.Source;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
+
/** A logical bidirectional stream. */
public final class SpdyStream {
// Internal state is guarded by this. No long-running or potentially
@@ -76,8 +78,10 @@ public final class SpdyStream {
if (requestHeaders == null) throw new NullPointerException("requestHeaders == null");
this.id = id;
this.connection = connection;
- this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize();
- this.source = new SpdyDataSource(connection.okHttpSettings.getInitialWindowSize());
+ this.bytesLeftInWriteWindow =
+ connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
+ this.source = new SpdyDataSource(
+ connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
this.sink = new SpdyDataSink();
this.source.finished = inFinished;
this.sink.finished = outFinished;
@@ -370,7 +374,8 @@ public final class SpdyStream {
// Flow control: notify the peer that we're ready for more data!
unacknowledgedBytesRead += read;
- if (unacknowledgedBytesRead >= connection.peerSettings.getInitialWindowSize() / 2) {
+ if (unacknowledgedBytesRead
+ >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
connection.writeWindowUpdateLater(id, unacknowledgedBytesRead);
unacknowledgedBytesRead = 0;
}
@@ -380,7 +385,7 @@ public final class SpdyStream {
synchronized (connection) { // Multiple application threads may hit this section.
connection.unacknowledgedBytesRead += read;
if (connection.unacknowledgedBytesRead
- >= connection.peerSettings.getInitialWindowSize() / 2) {
+ >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
connection.writeWindowUpdateLater(0, connection.unacknowledgedBytesRead);
connection.unacknowledgedBytesRead = 0;
} | ['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 735,611 | 170,055 | 21,803 | 106 | 2,646 | 547 | 49 | 3 | 687 | 84 | 152 | 6 | 1 | 0 | 2014-03-10T21:05:36 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
168 | square/okhttp/631/627 | square | okhttp | https://github.com/square/okhttp/issues/627 | https://github.com/square/okhttp/pull/631 | https://github.com/square/okhttp/pull/631 | 1 | fix | SpdyConnection clears the old settings without merging with the new server settings causing the window size always set as -1 | When debugging an issue with client requests hanging on SpdyStream.waitUntilWritable(), we found that the window size is set as -1 in SpdyStream.java at line:
this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize();
After tracing down the issue, the problem turned out to be line 662 of https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java, where peerSettings is cleared without merging with the new settings. This has caused any later SpdyStream always uses an –1 as the initial window size, and the bug has also caused the new window size settings not get propagated to existing SpdySteam(s).
| 0d774185b616c7d471822f22f57f947412ef593d | 83156632582465e93f462f311c0e6b340393c896 | https://github.com/square/okhttp/compare/0d774185b616c7d471822f22f57f947412ef593d...83156632582465e93f462f311c0e6b340393c896 | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java
index 44459b8c9..294684f1b 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java
@@ -17,6 +17,7 @@ package com.squareup.okhttp.internal.spdy;
import org.junit.Test;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_BANDWIDTH;
import static com.squareup.okhttp.internal.spdy.Settings.DOWNLOAD_RETRANS_RATE;
import static com.squareup.okhttp.internal.spdy.Settings.MAX_CONCURRENT_STREAMS;
@@ -68,9 +69,10 @@ public final class SettingsTest {
settings.set(DOWNLOAD_RETRANS_RATE, 0, 97);
assertEquals(97, settings.getDownloadRetransRate(-3));
- assertEquals(-1, settings.getInitialWindowSize());
+ assertEquals(DEFAULT_INITIAL_WINDOW_SIZE,
+ settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
settings.set(Settings.INITIAL_WINDOW_SIZE, 0, 108);
- assertEquals(108, settings.getInitialWindowSize());
+ assertEquals(108, settings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
assertEquals(-3, settings.getClientCertificateVectorSize(-3));
settings.set(Settings.CLIENT_CERTIFICATE_VECTOR_SIZE, 0, 117);
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java
index 8b934fa16..b73d6f930 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java
@@ -39,6 +39,7 @@ import static com.squareup.okhttp.internal.spdy.ErrorCode.INVALID_STREAM;
import static com.squareup.okhttp.internal.spdy.ErrorCode.PROTOCOL_ERROR;
import static com.squareup.okhttp.internal.spdy.ErrorCode.REFUSED_STREAM;
import static com.squareup.okhttp.internal.spdy.ErrorCode.STREAM_IN_USE;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
import static com.squareup.okhttp.internal.spdy.Settings.PERSIST_VALUE;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_DATA;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_GOAWAY;
@@ -47,7 +48,6 @@ import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_PING;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_RST_STREAM;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_SETTINGS;
import static com.squareup.okhttp.internal.spdy.Spdy3.TYPE_WINDOW_UPDATE;
-import static com.squareup.okhttp.internal.spdy.SpdyConnection.INITIAL_WINDOW_SIZE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
@@ -301,7 +301,7 @@ public final class SpdyConnectionTest {
// This stream was created *after* the connection settings were adjusted.
SpdyStream stream = connection.newStream(headerEntries("a", "android"), false, true);
- assertEquals(3368, connection.peerSettings.getInitialWindowSize());
+ assertEquals(3368, connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
assertEquals(1684, connection.bytesLeftInWriteWindow); // initial wasn't affected.
// New Stream is has the most recent initial window size.
assertEquals(3368, stream.bytesLeftInWriteWindow);
@@ -405,6 +405,35 @@ public final class SpdyConnectionTest {
}
}
+ @Test public void clearSettingsBeforeMerge() throws Exception {
+ // write the mocking script
+ Settings settings1 = new Settings();
+ settings1.set(Settings.UPLOAD_BANDWIDTH, PERSIST_VALUE, 100);
+ settings1.set(Settings.DOWNLOAD_BANDWIDTH, PERSIST_VALUE, 200);
+ settings1.set(Settings.DOWNLOAD_RETRANS_RATE, 0, 300);
+ peer.sendFrame().settings(settings1);
+ peer.sendFrame().ping(false, 2, 0);
+ peer.acceptFrame();
+ peer.play();
+
+ // play it back
+ SpdyConnection connection = connection(peer, SPDY3);
+
+ peer.takeFrame(); // Guarantees that the Settings frame has been processed.
+
+ // fake a settings frame with clear flag set.
+ Settings settings2 = new Settings();
+ settings2.set(Settings.MAX_CONCURRENT_STREAMS, PERSIST_VALUE, 600);
+ connection.readerRunnable.settings(true, settings2);
+
+ synchronized (connection) {
+ assertEquals(-1, connection.peerSettings.getUploadBandwidth(-1));
+ assertEquals(-1, connection.peerSettings.getDownloadBandwidth(-1));
+ assertEquals(-1, connection.peerSettings.getDownloadRetransRate(-1));
+ assertEquals(600, connection.peerSettings.getMaxConcurrentStreams(-1));
+ }
+ }
+
@Test public void bogusDataFrameDoesNotDisruptConnection() throws Exception {
// write the mocking script
peer.sendFrame().data(true, 41, new OkBuffer().writeUtf8("bogus"));
@@ -1042,7 +1071,7 @@ public final class SpdyConnectionTest {
throws IOException, InterruptedException {
peer.setVariantAndClient(variant, false);
- int windowUpdateThreshold = INITIAL_WINDOW_SIZE / 2;
+ int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2;
// Write the mocking script.
peer.acceptFrame(); // SYN_STREAM
@@ -1152,7 +1181,7 @@ public final class SpdyConnectionTest {
}
@Test public void writeAwaitsWindowUpdate() throws Exception {
- int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
+ int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
// Write the mocking script. This accepts more data frames than necessary!
peer.acceptFrame(); // SYN_STREAM
@@ -1166,7 +1195,7 @@ public final class SpdyConnectionTest {
SpdyConnection connection = connection(peer, SPDY3);
SpdyStream stream = connection.newStream(headerEntries("b", "banana"), true, true);
BufferedSink out = Okio.buffer(stream.getSink());
- out.write(new byte[INITIAL_WINDOW_SIZE]);
+ out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]);
out.flush();
// Check that we've filled the window for both the stream and also the connection.
@@ -1194,7 +1223,7 @@ public final class SpdyConnectionTest {
}
@Test public void initialSettingsWithWindowSizeAdjustsConnection() throws Exception {
- int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
+ int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, HTTP_20_DRAFT_09.maxFrameSize());
// Write the mocking script. This accepts more data frames than necessary!
peer.acceptFrame(); // SYN_STREAM
@@ -1208,7 +1237,7 @@ public final class SpdyConnectionTest {
SpdyConnection connection = connection(peer, SPDY3);
SpdyStream stream = connection.newStream(headerEntries("a", "apple"), true, true);
BufferedSink out = Okio.buffer(stream.getSink());
- out.write(new byte[INITIAL_WINDOW_SIZE]);
+ out.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]);
out.flush();
// write 1 more than the window size
@@ -1221,7 +1250,7 @@ public final class SpdyConnectionTest {
// Receiving a Settings with a larger window size will unblock the streams.
Settings initial = new Settings();
- initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 1);
+ initial.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 1);
connection.readerRunnable.settings(false, initial);
assertEquals(1, connection.bytesLeftInWriteWindow);
@@ -1235,7 +1264,7 @@ public final class SpdyConnectionTest {
// Settings after the initial do not affect the connection window size.
Settings next = new Settings();
- next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, INITIAL_WINDOW_SIZE + 2);
+ next.set(Settings.INITIAL_WINDOW_SIZE, PERSIST_VALUE, DEFAULT_INITIAL_WINDOW_SIZE + 2);
connection.readerRunnable.settings(false, next);
assertEquals(0, connection.bytesLeftInWriteWindow); // connection wasn't affected.
@@ -1263,7 +1292,7 @@ public final class SpdyConnectionTest {
}
@Test public void blockedStreamDoesntStarveNewStream() throws Exception {
- int framesThatFillWindow = roundUp(INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize());
+ int framesThatFillWindow = roundUp(DEFAULT_INITIAL_WINDOW_SIZE, SPDY3.maxFrameSize());
// Write the mocking script. This accepts more data frames than necessary!
peer.acceptFrame(); // SYN_STREAM on stream 1
@@ -1278,7 +1307,7 @@ public final class SpdyConnectionTest {
SpdyConnection connection = connection(peer, SPDY3);
SpdyStream stream1 = connection.newStream(headerEntries("a", "apple"), true, true);
BufferedSink out1 = Okio.buffer(stream1.getSink());
- out1.write(new byte[INITIAL_WINDOW_SIZE]);
+ out1.write(new byte[DEFAULT_INITIAL_WINDOW_SIZE]);
out1.flush();
// Check that we've filled the window for both the stream and also the connection.
@@ -1299,7 +1328,7 @@ public final class SpdyConnectionTest {
assertEquals(0, connection.bytesLeftInWriteWindow);
assertEquals(0, connection.getStream(1).bytesLeftInWriteWindow);
- assertEquals(INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow);
+ assertEquals(DEFAULT_INITIAL_WINDOW_SIZE - 3, connection.getStream(3).bytesLeftInWriteWindow);
}
@Test public void maxFrameSizeHonored() throws Exception {
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java
index c05d6b174..bf430882e 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java
@@ -22,6 +22,12 @@ import java.util.Arrays;
* Settings are {@link com.squareup.okhttp.internal.spdy.SpdyConnection connection} scoped.
*/
final class Settings {
+ /**
+ * From the SPDY/3 and HTTP/2 specs, the default initial window size for all
+ * streams is 64 KiB. (Chrome 25 uses 10 MiB).
+ */
+ static final int DEFAULT_INITIAL_WINDOW_SIZE = 64 * 1024;
+
/** Peer request to clear durable settings. */
static final int FLAG_CLEAR_PREVIOUSLY_PERSISTED_SETTINGS = 0x1;
@@ -171,11 +177,9 @@ final class Settings {
return (bit & set) != 0 ? values[DOWNLOAD_RETRANS_RATE] : defaultValue;
}
- // TODO: honor this setting in http/2.
- /** Returns -1 if unset. */
- int getInitialWindowSize() {
+ int getInitialWindowSize(int defaultValue) {
int bit = 1 << INITIAL_WINDOW_SIZE;
- return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : -1;
+ return (bit & set) != 0 ? values[INITIAL_WINDOW_SIZE] : defaultValue;
}
/** spdy/3 only. */
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
index 1ab4ab531..5c10db157 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
@@ -38,6 +38,8 @@ import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
+
/**
* A socket connection to a remote peer. A connection hosts streams which can
* send and receive data.
@@ -89,8 +91,6 @@ public final class SpdyConnection implements Closeable {
private final PushObserver pushObserver;
private int nextPingId;
- static final int INITIAL_WINDOW_SIZE = 65535;
-
/**
* The total number of bytes consumed by the application, but not yet
* acknowledged by sending a {@code WINDOW_UPDATE} frame on this connection.
@@ -107,15 +107,12 @@ public final class SpdyConnection implements Closeable {
/** Settings we communicate to the peer. */
// TODO: Do we want to dynamically adjust settings, or KISS and only set once?
- final Settings okHttpSettings = new Settings()
- .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE);
- // TODO: implement stream limit
+ final Settings okHttpSettings = new Settings();
// okHttpSettings.set(Settings.MAX_CONCURRENT_STREAMS, 0, max);
/** Settings we receive from the peer. */
// TODO: MWS will need to guard on this setting before attempting to push.
- final Settings peerSettings = new Settings()
- .set(Settings.INITIAL_WINDOW_SIZE, 0, INITIAL_WINDOW_SIZE);
+ final Settings peerSettings = new Settings();
private boolean receivedInitialPeerSettings = false;
final FrameReader frameReader;
@@ -151,7 +148,7 @@ public final class SpdyConnection implements Closeable {
} else {
throw new AssertionError(protocol);
}
- bytesLeftInWriteWindow = peerSettings.getInitialWindowSize();
+ bytesLeftInWriteWindow = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
frameReader = variant.newReader(builder.source, client);
frameWriter = variant.newWriter(builder.sink, client);
maxFrameSize = variant.maxFrameSize();
@@ -657,16 +654,13 @@ public final class SpdyConnection implements Closeable {
long delta = 0;
SpdyStream[] streamsToNotify = null;
synchronized (SpdyConnection.this) {
- int priorWriteWindowSize = peerSettings.getInitialWindowSize();
- if (clearPrevious) {
- peerSettings.clear();
- } else {
- peerSettings.merge(newSettings);
- }
+ int priorWriteWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
+ if (clearPrevious) peerSettings.clear();
+ peerSettings.merge(newSettings);
if (getProtocol() == Protocol.HTTP_2) {
ackSettingsLater();
}
- int peerInitialWindowSize = peerSettings.getInitialWindowSize();
+ int peerInitialWindowSize = peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
if (peerInitialWindowSize != -1 && peerInitialWindowSize != priorWriteWindowSize) {
delta = peerInitialWindowSize - priorWriteWindowSize;
if (!receivedInitialPeerSettings) {
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
index d0d2972aa..58d116fec 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
@@ -28,6 +28,8 @@ import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
+import static com.squareup.okhttp.internal.spdy.Settings.DEFAULT_INITIAL_WINDOW_SIZE;
+
/** A logical bidirectional stream. */
public final class SpdyStream {
// Internal state is guarded by this. No long-running or potentially
@@ -76,8 +78,10 @@ public final class SpdyStream {
if (requestHeaders == null) throw new NullPointerException("requestHeaders == null");
this.id = id;
this.connection = connection;
- this.bytesLeftInWriteWindow = connection.peerSettings.getInitialWindowSize();
- this.source = new SpdyDataSource(connection.okHttpSettings.getInitialWindowSize());
+ this.bytesLeftInWriteWindow =
+ connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE);
+ this.source = new SpdyDataSource(
+ connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE));
this.sink = new SpdyDataSink();
this.source.finished = inFinished;
this.sink.finished = outFinished;
@@ -370,7 +374,8 @@ public final class SpdyStream {
// Flow control: notify the peer that we're ready for more data!
unacknowledgedBytesRead += read;
- if (unacknowledgedBytesRead >= connection.peerSettings.getInitialWindowSize() / 2) {
+ if (unacknowledgedBytesRead
+ >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
connection.writeWindowUpdateLater(id, unacknowledgedBytesRead);
unacknowledgedBytesRead = 0;
}
@@ -380,7 +385,7 @@ public final class SpdyStream {
synchronized (connection) { // Multiple application threads may hit this section.
connection.unacknowledgedBytesRead += read;
if (connection.unacknowledgedBytesRead
- >= connection.peerSettings.getInitialWindowSize() / 2) {
+ >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
connection.writeWindowUpdateLater(0, connection.unacknowledgedBytesRead);
connection.unacknowledgedBytesRead = 0;
} | ['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/Settings.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SettingsTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/SpdyConnectionTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java'] | {'.java': 5} | 5 | 5 | 0 | 0 | 5 | 707,538 | 163,749 | 20,895 | 102 | 2,646 | 547 | 49 | 3 | 687 | 84 | 152 | 6 | 1 | 0 | 2014-03-11T04:15:42 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
167 | square/okhttp/737/215 | square | okhttp | https://github.com/square/okhttp/issues/215 | https://github.com/square/okhttp/pull/737 | https://github.com/square/okhttp/pull/737 | 1 | closes | Creating HttpResponseCache causes StrictMode violation | When cache is created I'm having this violation:
06-18 11:19:42.607: E/StrictMode(4300): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
06-18 11:19:42.607: E/StrictMode(4300): java.lang.Throwable: Explicit termination method 'close' not called
06-18 11:19:42.607: E/StrictMode(4300): at dalvik.system.CloseGuard.open(CloseGuard.java:184)
06-18 11:19:42.607: E/StrictMode(4300): at java.io.FileOutputStream.<init>(FileOutputStream.java:90)
06-18 11:19:42.607: E/StrictMode(4300): at com.squareup.okhttp.internal.DiskLruCache.open(DiskLruCache.java:226)
06-18 11:19:42.607: E/StrictMode(4300): at com.squareup.okhttp.HttpResponseCache.<init>(HttpResponseCache.java:171)
| 6486179b9d9c888a818c85384eed88fa0a8768a6 | c51382a430a2adb8a29cb59976af76b2cb48e386 | https://github.com/square/okhttp/compare/6486179b9d9c888a818c85384eed88fa0a8768a6...c51382a430a2adb8a29cb59976af76b2cb48e386 | diff --git a/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java b/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java
index e299d5721..2b701c335 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java
@@ -169,12 +169,18 @@ public final class HttpResponseCache extends ResponseCache implements OkResponse
if (snapshot == null) {
return null;
}
- entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
} catch (IOException e) {
// Give up because the cache cannot be read.
return null;
}
+ try {
+ entry = new Entry(snapshot.getInputStream(ENTRY_METADATA));
+ } catch (IOException e) {
+ Util.closeQuietly(snapshot);
+ return null;
+ }
+
Response response = entry.response(request, snapshot);
if (!entry.matches(request, response)) { | ['okhttp/src/main/java/com/squareup/okhttp/HttpResponseCache.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 663,416 | 150,136 | 19,555 | 92 | 240 | 46 | 8 | 1 | 772 | 60 | 237 | 9 | 0 | 0 | 2014-04-20T08:00:05 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
166 | square/okhttp/769/745 | square | okhttp | https://github.com/square/okhttp/issues/745 | https://github.com/square/okhttp/pull/769 | https://github.com/square/okhttp/pull/769 | 1 | fixes | Can't execute DELETE without body. | I'm trying to create Request just as:
```
Request.Builder builder = new Request.Builder().url("URL");
builder.method("DELETE", null);
```
(because there are no `.delete()` method)
When I'm trying to execute such request it crashes, with error message:
`java.lang.IllegalStateException: Cannot stream a request body without chunked encoding or a known content length!`
As I get it, it happens because DELETE can "has request body" (`hasRequestBody` returns `true` for DELETE) and when we are trying to create request body it blows up, because neither `contentLength` info provided nor `Transfer-Encoding` is set to `chunked` because no body provided.
So, there is workaround: just add `Content-Length: 0` header.
Looks like it is somekind related to #605.
| 04aee71eb5007c87d857c4c2690689e89722f092 | 520d9fc2bc6b251a998b58794070f8bebee9d682 | https://github.com/square/okhttp/compare/04aee71eb5007c87d857c4c2690689e89722f092...520d9fc2bc6b251a998b58794070f8bebee9d682 | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
index d5851488f..c44f386b8 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
@@ -65,6 +65,148 @@ public final class CallTest {
cache.delete();
}
+ @Test public void get() throws Exception {
+ server.enqueue(new MockResponse().setBody("abc").addHeader("Content-Type: text/plain"));
+ server.play();
+
+ Request request = new Request.Builder()
+ .url(server.getUrl("/"))
+ .header("User-Agent", "SyncApiTest")
+ .build();
+
+ executeSynchronously(request)
+ .assertCode(200)
+ .assertContainsHeaders("Content-Type: text/plain")
+ .assertBody("abc");
+
+ RecordedRequest recordedRequest = server.takeRequest();
+ assertEquals("GET", recordedRequest.getMethod());
+ assertEquals("SyncApiTest", recordedRequest.getHeader("User-Agent"));
+ assertEquals(0, recordedRequest.getBody().length);
+ assertNull(recordedRequest.getHeader("Content-Length"));
+ }
+
+ @Test public void head() throws Exception {
+ server.enqueue(new MockResponse().addHeader("Content-Type: text/plain"));
+ server.play();
+
+ Request request = new Request.Builder()
+ .url(server.getUrl("/"))
+ .head()
+ .header("User-Agent", "SyncApiTest")
+ .build();
+
+ executeSynchronously(request)
+ .assertCode(200)
+ .assertContainsHeaders("Content-Type: text/plain");
+
+ RecordedRequest recordedRequest = server.takeRequest();
+ assertEquals("HEAD", recordedRequest.getMethod());
+ assertEquals("SyncApiTest", recordedRequest.getHeader("User-Agent"));
+ assertEquals(0, recordedRequest.getBody().length);
+ assertNull(recordedRequest.getHeader("Content-Length"));
+ }
+
+ @Test public void post() throws Exception {
+ server.enqueue(new MockResponse().setBody("abc"));
+ server.play();
+
+ Request request = new Request.Builder()
+ .url(server.getUrl("/"))
+ .post(Request.Body.create(MediaType.parse("text/plain"), "def"))
+ .build();
+
+ executeSynchronously(request)
+ .assertCode(200)
+ .assertBody("abc");
+
+ RecordedRequest recordedRequest = server.takeRequest();
+ assertEquals("POST", recordedRequest.getMethod());
+ assertEquals("def", recordedRequest.getUtf8Body());
+ assertEquals("3", recordedRequest.getHeader("Content-Length"));
+ assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
+ }
+
+ @Test public void postZeroLength() throws Exception {
+ server.enqueue(new MockResponse().setBody("abc"));
+ server.play();
+
+ Request request = new Request.Builder()
+ .url(server.getUrl("/"))
+ .method("POST", null)
+ .build();
+
+ executeSynchronously(request)
+ .assertCode(200)
+ .assertBody("abc");
+
+ RecordedRequest recordedRequest = server.takeRequest();
+ assertEquals("POST", recordedRequest.getMethod());
+ assertEquals(0, recordedRequest.getBody().length);
+ assertEquals("0", recordedRequest.getHeader("Content-Length"));
+ assertEquals(null, recordedRequest.getHeader("Content-Type"));
+ }
+
+ @Test public void delete() throws Exception {
+ server.enqueue(new MockResponse().setBody("abc"));
+ server.play();
+
+ Request request = new Request.Builder()
+ .url(server.getUrl("/"))
+ .delete()
+ .build();
+
+ executeSynchronously(request)
+ .assertCode(200)
+ .assertBody("abc");
+
+ RecordedRequest recordedRequest = server.takeRequest();
+ assertEquals("DELETE", recordedRequest.getMethod());
+ assertEquals(0, recordedRequest.getBody().length);
+ assertEquals("0", recordedRequest.getHeader("Content-Length"));
+ assertEquals(null, recordedRequest.getHeader("Content-Type"));
+ }
+
+ @Test public void put() throws Exception {
+ server.enqueue(new MockResponse().setBody("abc"));
+ server.play();
+
+ Request request = new Request.Builder()
+ .url(server.getUrl("/"))
+ .put(Request.Body.create(MediaType.parse("text/plain"), "def"))
+ .build();
+
+ executeSynchronously(request)
+ .assertCode(200)
+ .assertBody("abc");
+
+ RecordedRequest recordedRequest = server.takeRequest();
+ assertEquals("PUT", recordedRequest.getMethod());
+ assertEquals("def", recordedRequest.getUtf8Body());
+ assertEquals("3", recordedRequest.getHeader("Content-Length"));
+ assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
+ }
+
+ @Test public void patch() throws Exception {
+ server.enqueue(new MockResponse().setBody("abc"));
+ server.play();
+
+ Request request = new Request.Builder()
+ .url(server.getUrl("/"))
+ .patch(Request.Body.create(MediaType.parse("text/plain"), "def"))
+ .build();
+
+ executeSynchronously(request)
+ .assertCode(200)
+ .assertBody("abc");
+
+ RecordedRequest recordedRequest = server.takeRequest();
+ assertEquals("PATCH", recordedRequest.getMethod());
+ assertEquals("def", recordedRequest.getUtf8Body());
+ assertEquals("3", recordedRequest.getHeader("Content-Length"));
+ assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
+ }
+
@Test public void illegalToExecuteTwice() throws Exception {
server.enqueue(new MockResponse()
.setBody("abc")
@@ -127,25 +269,6 @@ public final class CallTest {
assertTrue(server.takeRequest().getHeaders().contains("User-Agent: SyncApiTest"));
}
- @Test public void get() throws Exception {
- server.enqueue(new MockResponse()
- .setBody("abc")
- .addHeader("Content-Type: text/plain"));
- server.play();
-
- Request request = new Request.Builder()
- .url(server.getUrl("/"))
- .header("User-Agent", "SyncApiTest")
- .build();
-
- executeSynchronously(request)
- .assertCode(200)
- .assertContainsHeaders("Content-Type: text/plain")
- .assertBody("abc");
-
- assertTrue(server.takeRequest().getHeaders().contains("User-Agent: SyncApiTest"));
- }
-
@Test public void get_Async() throws Exception {
server.enqueue(new MockResponse()
.setBody("abc")
@@ -340,25 +463,6 @@ public final class CallTest {
assertEquals(301, response.code());
}
- @Test public void post() throws Exception {
- server.enqueue(new MockResponse().setBody("abc"));
- server.play();
-
- Request request = new Request.Builder()
- .url(server.getUrl("/"))
- .post(Request.Body.create(MediaType.parse("text/plain"), "def"))
- .build();
-
- executeSynchronously(request)
- .assertCode(200)
- .assertBody("abc");
-
- RecordedRequest recordedRequest = server.takeRequest();
- assertEquals("def", recordedRequest.getUtf8Body());
- assertEquals("3", recordedRequest.getHeader("Content-Length"));
- assertEquals("text/plain; charset=utf-8", recordedRequest.getHeader("Content-Type"));
- }
-
@Test public void post_Async() throws Exception {
server.enqueue(new MockResponse().setBody("abc"));
server.play();
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java
index fcb26b1fa..1878da5cf 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java
@@ -23,6 +23,7 @@ import okio.Buffer;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
public final class RequestTest {
@Test public void string() throws Exception {
@@ -73,6 +74,36 @@ public final class RequestTest {
assertEquals("Retransmit body", "616263", bodyToHex(body));
}
+ /** Common verbs used for apis such as GitHub, AWS, and Google Cloud. */
+ @Test public void crudVerbs() {
+ MediaType contentType = MediaType.parse("application/json");
+ Request.Body body = Request.Body.create(contentType, "{}");
+
+ Request get = new Request.Builder().url("http://localhost/api").get().build();
+ assertEquals("GET", get.method());
+ assertNull(get.body());
+
+ Request head = new Request.Builder().url("http://localhost/api").head().build();
+ assertEquals("HEAD", head.method());
+ assertNull(head.body());
+
+ Request delete = new Request.Builder().url("http://localhost/api").delete().build();
+ assertEquals("DELETE", delete.method());
+ assertNull(delete.body());
+
+ Request post = new Request.Builder().url("http://localhost/api").post(body).build();
+ assertEquals("POST", post.method());
+ assertEquals(body, post.body());
+
+ Request put = new Request.Builder().url("http://localhost/api").put(body).build();
+ assertEquals("PUT", put.method());
+ assertEquals(body, put.body());
+
+ Request patch = new Request.Builder().url("http://localhost/api").patch(body).build();
+ assertEquals("PATCH", patch.method());
+ assertEquals(body, patch.body());
+ }
+
private String bodyToHex(Request.Body body) throws IOException {
Buffer buffer = new Buffer();
body.writeTo(buffer);
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java
index ac9b48fa8..060b11a95 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java
@@ -209,7 +209,7 @@ public class JavaApiConverterTest {
@Test public void createOkResponse_fromCacheResponse() throws Exception {
final String statusLine = "HTTP/1.1 200 Fantastic";
URI uri = new URI("http://foo/bar");
- Request request = new Request.Builder().url(uri.toURL()).method("GET", null).build();
+ Request request = new Request.Builder().url(uri.toURL()).build();
CacheResponse cacheResponse = new CacheResponse() {
@Override
public Map<String, List<String>> getHeaders() throws IOException {
@@ -244,7 +244,7 @@ public class JavaApiConverterTest {
final Principal serverPrincipal = SERVER_CERT.getSubjectX500Principal();
final List<Certificate> serverCertificates = Arrays.<Certificate>asList(SERVER_CERT);
URI uri = new URI("https://foo/bar");
- Request request = new Request.Builder().url(uri.toURL()).method("GET", null).build();
+ Request request = new Request.Builder().url(uri.toURL()).build();
SecureCacheResponse cacheResponse = new SecureCacheResponse() {
@Override
public Map<String, List<String>> getHeaders() throws IOException {
@@ -517,7 +517,7 @@ public class JavaApiConverterTest {
@Test public void createJavaUrlConnection_accessibleRequestInfo_GET() throws Exception {
Request okRequest = createArbitraryOkRequest().newBuilder()
- .method("GET", null)
+ .get()
.build();
Response okResponse = createArbitraryOkResponse(okRequest);
HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse);
@@ -529,7 +529,7 @@ public class JavaApiConverterTest {
@Test public void createJavaUrlConnection_accessibleRequestInfo_POST() throws Exception {
Request okRequest = createArbitraryOkRequest().newBuilder()
- .method("POST", createRequestBody("PostBody"))
+ .post(createRequestBody("PostBody"))
.build();
Response okResponse = createArbitraryOkResponse(okRequest);
HttpURLConnection httpUrlConnection = JavaApiConverter.createJavaUrlConnection(okResponse);
@@ -541,7 +541,7 @@ public class JavaApiConverterTest {
@Test public void createJavaUrlConnection_https_extraHttpsMethods() throws Exception {
Request okRequest = createArbitraryOkRequest().newBuilder()
- .method("GET", null)
+ .get()
.url("https://secure/request")
.build();
Handshake handshake = Handshake.get("SecureCipher", Arrays.<Certificate>asList(SERVER_CERT),
@@ -584,7 +584,7 @@ public class JavaApiConverterTest {
Request okRequest =
createArbitraryOkRequest().newBuilder()
.url("http://insecure/request")
- .method("GET", null)
+ .get()
.build();
Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
.protocol(Protocol.HTTP_1_1)
@@ -607,7 +607,7 @@ public class JavaApiConverterTest {
Request okRequest =
createArbitraryOkRequest().newBuilder()
.url("http://insecure/request")
- .method("POST", createRequestBody("RequestBody"))
+ .post(createRequestBody("RequestBody"))
.build();
Response.Body responseBody = createResponseBody("ResponseBody");
Response okResponse = createArbitraryOkResponse(okRequest).newBuilder()
@@ -631,7 +631,7 @@ public class JavaApiConverterTest {
Request okRequest =
createArbitraryOkRequest().newBuilder()
.url("https://secure/request")
- .method("POST", createRequestBody("RequestBody") )
+ .post(createRequestBody("RequestBody") )
.build();
Response.Body responseBody = createResponseBody("ResponseBody");
Handshake handshake = Handshake.get("SecureCipher", Arrays.<Certificate>asList(SERVER_CERT),
@@ -754,10 +754,7 @@ public class JavaApiConverterTest {
}
private static Request createArbitraryOkRequest() {
- return new Request.Builder()
- .url("http://arbitrary/url")
- .method("GET", null)
- .build();
+ return new Request.Builder().url("http://arbitrary/url").build();
}
private static Response createArbitraryOkResponse(Request request) {
diff --git a/okhttp/src/main/java/com/squareup/okhttp/Call.java b/okhttp/src/main/java/com/squareup/okhttp/Call.java
index 069a04440..3eba08ff1 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/Call.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/Call.java
@@ -16,8 +16,11 @@
package com.squareup.okhttp;
import com.squareup.okhttp.internal.NamedRunnable;
+import com.squareup.okhttp.internal.Util;
import com.squareup.okhttp.internal.http.HttpEngine;
+import com.squareup.okhttp.internal.http.HttpMethod;
import com.squareup.okhttp.internal.http.OkHeaders;
+import com.squareup.okhttp.internal.http.RetryableSink;
import java.io.IOException;
import java.net.ProtocolException;
import okio.BufferedSink;
@@ -170,6 +173,7 @@ public final class Call {
// Copy body metadata to the appropriate request headers.
Request.Body body = request.body();
+ RetryableSink requestBodyOut = null;
if (body != null) {
MediaType contentType = body.contentType();
if (contentType == null) throw new IllegalStateException("contentType == null");
@@ -187,10 +191,12 @@ public final class Call {
}
request = requestBuilder.build();
+ } else if (HttpMethod.hasRequestBody(request.method())) {
+ requestBodyOut = Util.emptySink();
}
// Create the initial HTTP engine. Retries and redirects need new engine for each attempt.
- engine = new HttpEngine(client, request, false, null, null, null);
+ engine = new HttpEngine(client, request, false, null, null, requestBodyOut);
while (true) {
if (canceled) return null;
diff --git a/okhttp/src/main/java/com/squareup/okhttp/Request.java b/okhttp/src/main/java/com/squareup/okhttp/Request.java
index 937f3e39b..a6108e18f 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/Request.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/Request.java
@@ -276,10 +276,18 @@ public final class Request {
return method("POST", body);
}
+ public Builder delete() {
+ return method("DELETE", null);
+ }
+
public Builder put(Body body) {
return method("PUT", body);
}
+ public Builder patch(Body body) {
+ return method("PATCH", body);
+ }
+
public Builder method(String method, Body body) {
if (method == null || method.length() == 0) {
throw new IllegalArgumentException("method == null || method.length() == 0");
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java b/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java
index c481ee274..1b86147d1 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/Util.java
@@ -16,6 +16,7 @@
package com.squareup.okhttp.internal;
+import com.squareup.okhttp.internal.http.RetryableSink;
import com.squareup.okhttp.internal.spdy.Header;
import java.io.Closeable;
import java.io.File;
@@ -222,4 +223,10 @@ public final class Util {
}
return result;
}
+
+ public static RetryableSink emptySink() {
+ return EMPTY_SINK;
+ }
+
+ private static final RetryableSink EMPTY_SINK = new RetryableSink(0);
}
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java
index 5647f0b73..f5579b3dc 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java
@@ -28,6 +28,7 @@ import com.squareup.okhttp.Response;
import com.squareup.okhttp.ResponseSource;
import com.squareup.okhttp.Route;
import com.squareup.okhttp.internal.Dns;
+import com.squareup.okhttp.internal.Util;
import java.io.IOException;
import java.io.InputStream;
import java.net.CacheRequest;
@@ -283,7 +284,7 @@ public final class HttpEngine {
}
boolean hasRequestBody() {
- return HttpMethod.hasRequestBody(request.method());
+ return HttpMethod.hasRequestBody(request.method()) && !Util.emptySink().equals(requestBodyOut);
}
/** Returns the request body or null if this request doesn't have a body. */
diff --git a/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java b/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java
index 68ac4e043..313e82744 100644
--- a/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java
+++ b/samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java
@@ -12,10 +12,7 @@ public class PostExample {
void run() throws IOException {
String json = bowlingJson("Jesse", "Jake");
Request.Body body = Request.Body.create(MediaType.parse("application/json"), json);
- Request request = new Request.Builder()
- .url("http://www.roundsapp.com/post")
- .method("POST", body)
- .build();
+ Request request = new Request.Builder().url("http://www.roundsapp.com/post").post(body).build();
Response response = client.newCall(request).execute();
System.out.println(response.body().string()); | ['okhttp-tests/src/test/java/com/squareup/okhttp/internal/huc/JavaApiConverterTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java', 'okhttp/src/main/java/com/squareup/okhttp/Call.java', 'okhttp/src/main/java/com/squareup/okhttp/Request.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/Util.java', 'samples/guide/src/main/java/com/squareup/okhttp/guide/PostExample.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/RequestTest.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java'] | {'.java': 8} | 8 | 8 | 0 | 0 | 8 | 665,782 | 150,731 | 19,663 | 94 | 1,266 | 272 | 31 | 5 | 761 | 109 | 172 | 18 | 0 | 1 | 2014-04-26T15:57:33 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
165 | square/okhttp/939/933 | square | okhttp | https://github.com/square/okhttp/issues/933 | https://github.com/square/okhttp/pull/939 | https://github.com/square/okhttp/pull/939 | 1 | closes | Certain SPDY requests always timeout | This simple request to fetch a .mp3 always timeouts. Some requests to the same domain work though. Other clients (Browsers, curl, etc) have no problem.
``` java
String url = "https://s.auspiel.de/sounds/effects/mischen-1.mp3";
OkHttpClient httpClient = new OkHttpClient();
httpClient.setReadTimeout(10, TimeUnit.SECONDS);
Call call = httpClient.newCall(new Request.Builder().
url(url). tag(url). get().build());
call.enqueue(new com.squareup.okhttp.Callback() {
@Override public void onFailure(Request request, Throwable throwable) {
System.out.println("Failure");
}
@Override public void onResponse(Response response) throws IOException {
System.out.println("GOT RESPONSE");
byte[] responseData = response.body().bytes();
System.out.println("READ BODY"); // this is never reached
}
});
```
Example repo: https://github.com/MSch/okhttp-spdy-timeout
https://github.com/MSch/okhttp-spdy-timeout/blob/master/app/src/main/java/msch/okhttpbug/MyActivity.java#L25-L40
I also tried with OkHttp 2.0.0-RC2 and OkIo master. Same issue.
e.g. https://s.auspiel.de/sounds/male/bayerisch/greeting/begruessung-1.mp3 works.
Tested devices: Samsung Galaxy Nexus with Android 4.2.2 and Asus Nexus 7 with Android 4.4.2
```
E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher
java.lang.RuntimeException: java.io.InterruptedIOException: timeout
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:153)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.io.InterruptedIOException: timeout
at com.squareup.okhttp.internal.spdy.SpdyStream$SpdyTimeout.exitAndThrowIfTimedOut(SpdyStream.java:573)
at com.squareup.okhttp.internal.spdy.SpdyStream$SpdyDataSource.waitUntilReadable(SpdyStream.java:380)
at com.squareup.okhttp.internal.spdy.SpdyStream$SpdyDataSource.read(SpdyStream.java:343)
at com.squareup.okhttp.internal.http.SpdyTransport$SpdySource.read(SpdyTransport.java:273)
at okio.Buffer.writeAll(Buffer.java:574)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:87)
at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:56)
at msch.okhttpbug.MyActivity$1.onResponse(MyActivity.java:37)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:150)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
```
| 7213e9b6b9e1508c349ccd6b13b894bd5d8bf96d | 6171f554512ce314d5b7008fc660a1697887581c | https://github.com/square/okhttp/compare/7213e9b6b9e1508c349ccd6b13b894bd5d8bf96d...6171f554512ce314d5b7008fc660a1697887581c | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java
index 5bcb09e38..e700dd6c6 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java
@@ -211,17 +211,17 @@ public final class Http2ConnectionTest {
@Test public void readSendsWindowUpdateHttp2() throws Exception {
peer.setVariantAndClient(HTTP_2, false);
- int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2;
+ int windowSize = 100;
+ int windowUpdateThreshold = 50;
// Write the mocking script.
peer.acceptFrame(); // SYN_STREAM
peer.sendFrame().synReply(false, 3, headerEntries("a", "android"));
for (int i = 0; i < 3; i++) {
- // Send frames summing to windowUpdateThreshold.
- for (int sent = 0, count; sent < windowUpdateThreshold; sent += count) {
- count = Math.min(HTTP_2.maxFrameSize(), windowUpdateThreshold - sent);
- peer.sendFrame().data(false, 3, data(count));
- }
+ // Send frames of summing to size 50, which is windowUpdateThreshold.
+ peer.sendFrame().data(false, 3, data(24));
+ peer.sendFrame().data(false, 3, data(25));
+ peer.sendFrame().data(false, 3, data(1));
peer.acceptFrame(); // connection WINDOW UPDATE
peer.acceptFrame(); // stream WINDOW UPDATE
}
@@ -230,15 +230,15 @@ public final class Http2ConnectionTest {
// Play it back.
SpdyConnection connection = connection(peer, HTTP_2);
+ connection.okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, windowSize);
SpdyStream stream = connection.newStream(headerEntries("b", "banana"), false, true);
assertEquals(0, stream.unacknowledgedBytesRead);
assertEquals(headerEntries("a", "android"), stream.getResponseHeaders());
Source in = stream.getSource();
Buffer buffer = new Buffer();
- while (in.read(buffer, 1024) != -1) {
- if (buffer.size() == 3 * windowUpdateThreshold) break;
- }
+ buffer.writeAll(in);
assertEquals(-1, in.read(buffer, 1));
+ assertEquals(150, buffer.size());
MockSpdyPeer.InFrame synStream = peer.takeFrame();
assertEquals(TYPE_HEADERS, synStream.type);
diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java
index 862e2f34a..a6c970362 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java
@@ -1013,17 +1013,17 @@ public final class Spdy3ConnectionTest {
@Test public void readSendsWindowUpdate() throws Exception {
peer.setVariantAndClient(SPDY3, false);
- int windowUpdateThreshold = DEFAULT_INITIAL_WINDOW_SIZE / 2;
+ int windowSize = 100;
+ int windowUpdateThreshold = 50;
// Write the mocking script.
peer.acceptFrame(); // SYN_STREAM
peer.sendFrame().synReply(false, 1, headerEntries("a", "android"));
for (int i = 0; i < 3; i++) {
- // Send frames summing to windowUpdateThreshold.
- for (int sent = 0, count; sent < windowUpdateThreshold; sent += count) {
- count = Math.min(SPDY3.maxFrameSize(), windowUpdateThreshold - sent);
- peer.sendFrame().data(false, 1, data(count));
- }
+ // Send frames of summing to size 50, which is windowUpdateThreshold.
+ peer.sendFrame().data(false, 1, data(24));
+ peer.sendFrame().data(false, 1, data(25));
+ peer.sendFrame().data(false, 1, data(1));
peer.acceptFrame(); // connection WINDOW UPDATE
peer.acceptFrame(); // stream WINDOW UPDATE
}
@@ -1032,15 +1032,15 @@ public final class Spdy3ConnectionTest {
// Play it back.
SpdyConnection connection = connection(peer, SPDY3);
+ connection.okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, windowSize);
SpdyStream stream = connection.newStream(headerEntries("b", "banana"), false, true);
assertEquals(0, stream.unacknowledgedBytesRead);
assertEquals(headerEntries("a", "android"), stream.getResponseHeaders());
Source in = stream.getSource();
Buffer buffer = new Buffer();
- while (in.read(buffer, 1024) != -1) {
- if (buffer.size() == 3 * windowUpdateThreshold) break;
- }
+ buffer.writeAll(in);
assertEquals(-1, in.read(buffer, 1));
+ assertEquals(150, buffer.size());
MockSpdyPeer.InFrame synStream = peer.takeFrame();
assertEquals(TYPE_HEADERS, synStream.type);
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
index bceb25784..8e22f702c 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
@@ -113,6 +113,7 @@ public final class SpdyConnection implements Closeable {
// TODO: Do we want to dynamically adjust settings, or KISS and only set once?
final Settings okHttpSettings = new Settings();
// okHttpSettings.set(Settings.MAX_CONCURRENT_STREAMS, 0, max);
+ private static final int OKHTTP_CLIENT_WINDOW_SIZE = 16 * 1024 * 1024;
/** Settings we receive from the peer. */
// TODO: MWS will need to guard on this setting before attempting to push.
@@ -145,7 +146,7 @@ public final class SpdyConnection implements Closeable {
// thrashing window updates every 64KiB, yet small enough to avoid blowing
// up the heap.
if (builder.client) {
- okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, 16 * 1024 * 1024);
+ okHttpSettings.set(Settings.INITIAL_WINDOW_SIZE, 0, OKHTTP_CLIENT_WINDOW_SIZE);
}
hostName = builder.hostName;
@@ -503,6 +504,10 @@ public final class SpdyConnection implements Closeable {
public void sendConnectionPreface() throws IOException {
frameWriter.connectionPreface();
frameWriter.settings(okHttpSettings);
+ int windowSize = okHttpSettings.getInitialWindowSize(Settings.DEFAULT_INITIAL_WINDOW_SIZE);
+ if (windowSize != Settings.DEFAULT_INITIAL_WINDOW_SIZE) {
+ frameWriter.windowUpdate(0, windowSize - Settings.DEFAULT_INITIAL_WINDOW_SIZE);
+ }
}
public static class Builder {
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
index 7eb78cbef..331536d37 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java
@@ -350,7 +350,7 @@ public final class SpdyStream {
// Flow control: notify the peer that we're ready for more data!
unacknowledgedBytesRead += read;
if (unacknowledgedBytesRead
- >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
+ >= connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
connection.writeWindowUpdateLater(id, unacknowledgedBytesRead);
unacknowledgedBytesRead = 0;
}
@@ -360,7 +360,7 @@ public final class SpdyStream {
synchronized (connection) { // Multiple application threads may hit this section.
connection.unacknowledgedBytesRead += read;
if (connection.unacknowledgedBytesRead
- >= connection.peerSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
+ >= connection.okHttpSettings.getInitialWindowSize(DEFAULT_INITIAL_WINDOW_SIZE) / 2) {
connection.writeWindowUpdateLater(0, connection.unacknowledgedBytesRead);
connection.unacknowledgedBytesRead = 0;
} | ['okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Http2ConnectionTest.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/spdy/Spdy3ConnectionTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyStream.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 723,492 | 163,303 | 21,251 | 113 | 883 | 192 | 11 | 2 | 2,973 | 166 | 700 | 55 | 4 | 2 | 2014-06-18T02:26:03 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
164 | square/okhttp/948/947 | square | okhttp | https://github.com/square/okhttp/issues/947 | https://github.com/square/okhttp/pull/948 | https://github.com/square/okhttp/pull/948 | 1 | closes | Caching broken by transparent gzip header mismatch | Following the technique described in the Cache javadoc (http://square.github.io/okhttp/javadoc/com/squareup/okhttp/Cache.html) we added the Cache-Control max-stale header to ensure we get a cached response when offline. We're doing this through Retrofit's RequestInterceptor, like so:
```
requestFacade.addHeader("Cache-Control", "max-stale=" + maxStale);
```
This works great in okhttp 1.6: we get a response when offline. However, it no longer works in 2.0RC2 (or master). After some debugging, it turns out there _is_ a cache Response, but it's not returned after this test in Cache.get(Request):
```
if (!entry.matches(request, response))
```
which in turn is caused by OkHeaders.varyMatches(), which returns false for the Accept-Encoding field: cachedField [], actualField: [gzip].
This issue can be worked around by performing the gzip "by hand" by adding our own gzip header and decompressing the resulting response when necessary (this was not necessary in 1.6), as I described here, after an unrelated transparent gzip issue in an earlier version of okhttp: http://stackoverflow.com/questions/21585347/retrofit-okhttp-retrieve-gzipinputstream/22537697#22537697
| eb40f47753ce1a7d45bb3fbcf7eb28ac6e7e2479 | 94f9a1719cc420be061b16e2da03258552c5060b | https://github.com/square/okhttp/compare/eb40f47753ce1a7d45bb3fbcf7eb28ac6e7e2479...94f9a1719cc420be061b16e2da03258552c5060b | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
index 93163450b..b78a68e92 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
@@ -920,6 +920,19 @@ public final class CacheTest {
assertEquals("DEFDEFDEF", readAscii(client.open(server.getUrl("/"))));
}
+ /** https://github.com/square/okhttp/issues/947 */
+ @Test public void gzipAndVaryOnAcceptEncoding() throws Exception {
+ server.enqueue(new MockResponse()
+ .setBody(gzip("ABCABCABC"))
+ .addHeader("Content-Encoding: gzip")
+ .addHeader("Vary: Accept-Encoding")
+ .addHeader("Cache-Control: max-age=60"));
+ server.enqueue(new MockResponse().setBody("FAIL"));
+
+ assertEquals("ABCABCABC", readAscii(client.open(server.getUrl("/"))));
+ assertEquals("ABCABCABC", readAscii(client.open(server.getUrl("/"))));
+ }
+
@Test public void conditionalCacheHitIsNotDoublePooled() throws Exception {
server.enqueue(new MockResponse().addHeader("ETag: v1").setBody("A"));
server.enqueue(new MockResponse()
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java
index 6736801fe..b09801b48 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java
@@ -174,8 +174,12 @@ public final class OkHeaders {
Set<String> varyFields = varyFields(response);
if (varyFields.isEmpty()) return new Headers.Builder().build();
+ // Use the request headers sent over the network, since that's what the
+ // response varies on. Otherwise OkHttp-supplied headers like
+ // "Accept-Encoding: gzip" may be lost.
+ Headers requestHeaders = response.networkResponse().request().headers();
+
Headers.Builder result = new Headers.Builder();
- Headers requestHeaders = response.request().headers();
for (int i = 0; i < requestHeaders.size(); i++) {
String fieldName = requestHeaders.name(i);
if (varyFields.contains(fieldName)) { | ['okhttp/src/main/java/com/squareup/okhttp/internal/http/OkHeaders.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 724,213 | 163,458 | 21,264 | 113 | 328 | 66 | 6 | 1 | 1,178 | 150 | 280 | 16 | 2 | 2 | 2014-06-19T12:32:28 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
155 | square/okhttp/1065/1036 | square | okhttp | https://github.com/square/okhttp/issues/1036 | https://github.com/square/okhttp/pull/1065 | https://github.com/square/okhttp/pull/1065#issuecomment-57098303 | 1 | fixes | okhttp 2.0.0 OkHttpClient.cancel(tag) doesn't work | The Recipes [Canceling a Call](https://github.com/square/okhttp/wiki/Recipes#canceling-a-call) worked, but after I used `OkHttpClient.cancel(tag)` instead, it didn't work.
My code:
``` java
import java.io.IOException;
import java.util.concurrent.*;
import com.squareup.okhttp.*;
public class Test {
private final ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Request request = new Request.Builder()
.url("http://httpbin.org/delay/2") // This URL is served with a 2 second delay.
.tag("asdf")
.build();
final long startNanos = System.nanoTime();
final Call call = client.newCall(request);
// Schedule a job to cancel the call in 1 second.
executor.schedule(new Runnable() {
@Override public void run() {
System.out.printf("%.2f Canceling call.%n", (System.nanoTime() - startNanos) / 1e9f);
client.cancel("asdf");
System.out.printf("%.2f Canceled call.%n", (System.nanoTime() - startNanos) / 1e9f);
}
}, 1, TimeUnit.SECONDS);
try {
System.out.printf("%.2f Executing call.%n", (System.nanoTime() - startNanos) / 1e9f);
Response response = call.execute();
System.out.printf("%.2f Call was expected to fail, but completed: %s%n",
(System.nanoTime() - startNanos) / 1e9f, response);
} catch (IOException e) {
System.out.printf("%.2f Call failed as expected: %s%n",
(System.nanoTime() - startNanos) / 1e9f, e);
}
}
public static void main(String[] args) throws Exception {
new Test().run();
}
}
```
Result:
```
0.25 Executing call.
1.25 Canceling call.
1.25 Canceled call.
3.46 Call was expected to fail, but completed: Response{protocol=http/1.1, code=200, message=OK, url=http://httpbin.org/delay/2}
```
| 4cdf0a90b3643d198014a56bf619dd9587820fca | 38d57953ee7a22a6f87d97ed15e69f17abb2c16f | https://github.com/square/okhttp/compare/4cdf0a90b3643d198014a56bf619dd9587820fca...38d57953ee7a22a6f87d97ed15e69f17abb2c16f | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
index 40519c61d..cefb681be 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
@@ -1172,6 +1172,33 @@ public final class CallTest {
assertEquals(1, server.getRequestCount());
}
+ @Test public void cancelInFlightBeforeResponseReadThrowsIOE() throws Exception {
+ server.setDispatcher(new Dispatcher() {
+ @Override public MockResponse dispatch(RecordedRequest request) {
+ client.cancel("request");
+ return new MockResponse().setBody("A");
+ }
+ });
+ server.play();
+
+ Request request = new Request.Builder().url(server.getUrl("/a")).tag("request").build();
+ try {
+ client.newCall(request).execute();
+ fail();
+ } catch (IOException e) {
+ }
+ }
+
+ @Test public void cancelInFlightBeforeResponseReadThrowsIOE_HTTP_2() throws Exception {
+ enableProtocol(Protocol.HTTP_2);
+ cancelInFlightBeforeResponseReadThrowsIOE();
+ }
+
+ @Test public void cancelInFlightBeforeResponseReadThrowsIOE_SPDY_3() throws Exception {
+ enableProtocol(Protocol.SPDY_3);
+ cancelInFlightBeforeResponseReadThrowsIOE();
+ }
+
/**
* This test puts a request in front of one that is to be canceled, so that it is canceled before
* I/O takes place.
diff --git a/okhttp/src/main/java/com/squareup/okhttp/Call.java b/okhttp/src/main/java/com/squareup/okhttp/Call.java
index db2cf6107..785a9db38 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/Call.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/Call.java
@@ -77,10 +77,20 @@ public class Call {
if (executed) throw new IllegalStateException("Already Executed");
executed = true;
}
- Response result = getResponse();
- engine.releaseConnection(); // Transfer ownership of the body to the caller.
- if (result == null) throw new IOException("Canceled");
- return result;
+ try {
+ client.getDispatcher().executed(this);
+ Response result = getResponse();
+ System.out.println("releasing");
+ engine.releaseConnection(); // Transfer ownership of the body to the caller.
+ if (result == null) throw new IOException("Canceled");
+ return result;
+ } finally {
+ client.getDispatcher().finished(this);
+ }
+ }
+
+ Object tag() {
+ return request.tag();
}
/**
diff --git a/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java b/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java
index 0e4644d5b..21f60254a 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java
@@ -46,6 +46,9 @@ public final class Dispatcher {
/** Running calls. Includes canceled calls that haven't finished yet. */
private final Deque<AsyncCall> runningCalls = new ArrayDeque<>();
+ /** In-flight synchronous calls. Includes canceled calls that haven't finished yet. */
+ private final Deque<Call> executedCalls = new ArrayDeque<>();
+
public Dispatcher(ExecutorService executorService) {
this.executorService = executorService;
}
@@ -123,6 +126,12 @@ public final class Dispatcher {
if (engine != null) engine.disconnect();
}
}
+
+ for (Call call : executedCalls) {
+ if (Util.equal(tag, call.tag())) {
+ call.cancel();
+ }
+ }
}
/** Used by {@code AsyncCall#run} to signal completion. */
@@ -156,4 +165,14 @@ public final class Dispatcher {
}
return result;
}
+
+ /** Used by {@code Call#execute} to signal it is in-flight. */
+ synchronized void executed(Call call) {
+ executedCalls.add(call);
+ }
+
+ /** Used by {@code Call#execute} to signal completion. */
+ synchronized void finished(Call call) {
+ if (!executedCalls.remove(call)) throw new AssertionError("Call wasn't in-flight!");
+ }
}
diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
index 916062617..69029dfa4 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
@@ -467,8 +467,8 @@ public class OkHttpClient implements Cloneable {
}
/**
- * Cancels all scheduled tasks tagged with {@code tag}. Requests that are already
- * complete cannot be canceled.
+ * Cancels all scheduled or in-flight calls tagged with {@code tag}. Requests
+ * that are already complete cannot be canceled.
*/
public OkHttpClient cancel(Object tag) {
getDispatcher().cancel(tag); | ['okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java', 'okhttp/src/main/java/com/squareup/okhttp/Dispatcher.java', 'okhttp/src/main/java/com/squareup/okhttp/Call.java'] | {'.java': 4} | 4 | 4 | 0 | 0 | 4 | 725,400 | 163,726 | 21,246 | 114 | 1,504 | 317 | 41 | 3 | 2,017 | 201 | 485 | 57 | 3 | 2 | 2014-09-28T19:02:03 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
156 | square/okhttp/1259/1043 | square | okhttp | https://github.com/square/okhttp/issues/1043 | https://github.com/square/okhttp/pull/1259 | https://github.com/square/okhttp/pull/1259 | 1 | closes | Don't recover if a non-GET request fails | Currently it can silently retry requests, but now it's forbidden:
http://tools.ietf.org/html/rfc7230
A user agent MUST NOT automatically retry a request with a non-
idempotent method unless it has some means to know that the request
semantics are actually idempotent, regardless of the method, or some
means to detect that the original request was never applied.
related to https://github.com/square/okhttp/issues/258
| 24750b59c4a06e77635cec6ce6999c3db86ff7e4 | 786e3b3048b84721c73a046b02a9edcbb6927686 | https://github.com/square/okhttp/compare/24750b59c4a06e77635cec6ce6999c3db86ff7e4...786e3b3048b84721c73a046b02a9edcbb6927686 | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
index 25eb85f95..2255dd8f6 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java
@@ -704,6 +704,34 @@ public final class CallTest {
callback.await(request.url()).assertHandshake();
}
+ @Test public void recoverWhenRetryOnConnectionFailureIsTrue() throws Exception {
+ server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
+ server.enqueue(new MockResponse().setBody("retry success"));
+
+ Internal.instance.setNetwork(client, new DoubleInetAddressNetwork());
+ assertTrue(client.getRetryOnConnectionFailure());
+
+ Request request = new Request.Builder().url(server.getUrl("/")).build();
+ Response response = client.newCall(request).execute();
+ assertEquals("retry success", response.body().string());
+ }
+
+ @Test public void noRecoverWhenRetryOnConnectionFailureIsFalse() throws Exception {
+ server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_START));
+ server.enqueue(new MockResponse().setBody("unreachable!"));
+
+ Internal.instance.setNetwork(client, new DoubleInetAddressNetwork());
+ client.setRetryOnConnectionFailure(false);
+
+ Request request = new Request.Builder().url(server.getUrl("/")).build();
+ try {
+ // If this succeeds, too many requests were made.
+ client.newCall(request).execute();
+ fail();
+ } catch (IOException expected) {
+ }
+ }
+
@Test public void recoverFromTlsHandshakeFailure() throws Exception {
server.get().useHttps(sslContext.getSocketFactory(), false);
server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.FAIL_HANDSHAKE));
diff --git a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
index 09716a78b..71e646097 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java
@@ -178,6 +178,7 @@ public class OkHttpClient implements Cloneable {
private Network network;
private boolean followSslRedirects = true;
private boolean followRedirects = true;
+ private boolean retryOnConnectionFailure = true;
private int connectTimeout;
private int readTimeout;
private int writeTimeout;
@@ -208,6 +209,7 @@ public class OkHttpClient implements Cloneable {
this.network = okHttpClient.network;
this.followSslRedirects = okHttpClient.followSslRedirects;
this.followRedirects = okHttpClient.followRedirects;
+ this.retryOnConnectionFailure = okHttpClient.retryOnConnectionFailure;
this.connectTimeout = okHttpClient.connectTimeout;
this.readTimeout = okHttpClient.readTimeout;
this.writeTimeout = okHttpClient.writeTimeout;
@@ -449,6 +451,32 @@ public class OkHttpClient implements Cloneable {
return followRedirects;
}
+ /**
+ * Configure this client to retry or not when a connectivity problem is encountered. By default,
+ * this client silently recovers from the following problems:
+ *
+ * <ul>
+ * <li><strong>Unreachable IP addresses.</strong> If the URL's host has multiple IP addresses,
+ * failure to reach any individual IP address doesn't fail the overall request. This can
+ * increase availability of multi-homed services.
+ * <li><strong>Stale pooled connections.</strong> The {@link ConnectionPool} reuses sockets
+ * to decrease request latency, but these connections will occasionally time out.
+ * <li><strong>Unreachable proxy servers.</strong> A {@link ProxySelector} can be used to
+ * attempt multiple proxy servers in sequence, eventually falling back to a direct
+ * connection.
+ * </ul>
+ *
+ * Set this to false to avoid retrying requests when doing so is destructive. In this case the
+ * calling application should do its own recovery of connectivity failures.
+ */
+ public final void setRetryOnConnectionFailure(boolean retryOnConnectionFailure) {
+ this.retryOnConnectionFailure = retryOnConnectionFailure;
+ }
+
+ public final boolean getRetryOnConnectionFailure() {
+ return retryOnConnectionFailure;
+ }
+
final RouteDatabase routeDatabase() {
return routeDatabase;
}
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java
index 461f066c8..d4d9b4cb1 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java
@@ -391,6 +391,11 @@ public final class HttpEngine {
}
private boolean isRecoverable(IOException e) {
+ // If the application has opted-out of recovery, don't recover.
+ if (!client.getRetryOnConnectionFailure()) {
+ return false;
+ }
+
// If the problem was a CertificateException from the X509TrustManager,
// do not retry, we didn't have an abrupt server-initiated exception.
if (e instanceof SSLPeerUnverifiedException | ['okhttp/src/main/java/com/squareup/okhttp/OkHttpClient.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CallTest.java', 'okhttp/src/main/java/com/squareup/okhttp/internal/http/HttpEngine.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 876,114 | 202,976 | 24,677 | 132 | 1,578 | 336 | 33 | 2 | 430 | 58 | 96 | 11 | 2 | 0 | 2014-12-30T23:47:05 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
157 | square/okhttp/1254/1158 | square | okhttp | https://github.com/square/okhttp/issues/1158 | https://github.com/square/okhttp/pull/1254 | https://github.com/square/okhttp/pull/1254 | 1 | closes | Should okhttp be caching HTTP 307 (or 302) responses according to the w3 document? | I am using retrofit and okhttp in my Android app to download documents, images and music files. The files are hosted on Amazon through a CDN so the URLs change often. My backend server will try to use redirects to decrease the need to have to constantly update my content on my mobile app every time the CDN url changes. The devices should also cache responses in the case that the device is offline. For this reason, I am using 301 redirects, which I don't know is the best idea.
I was reading the description for 307 redirect at http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
---
10.3.8 307 Temporary Redirect
The requested resource resides temporarily under a different URI.
Since the redirection MAY be altered on occasion, the client SHOULD
continue to use the Request-URI for future requests.
This response is only cacheable if indicated by a Cache-Control or Expires header field.
---
At http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html,
---
13.4 - Response Cacheability
A response received with a status code of 200, 203, 206, 300, 301 or 410
MAY be stored by a cache and used in reply to a subsequent request,
subject to the expiration mechanism, unless a cache-control directive
prohibits caching. However, a cache that does not support the Range and
Content-Range headers MUST NOT cache 206 (Partial Content) responses.
A response received with any other status code
(e.g. status codes 302 and 307) MUST NOT be returned in a reply to
a subsequent request unless there are cache-control directives or another
header(s) that explicitly allow it. For example, these include the
following: an Expires header (section 14.21); a "max-age", "s-maxage",
"must- revalidate", "proxy-revalidate", "public" or "private"
cache-control directive (section 14.9).
---
It seems that the description states that caching is possible. I haven't tried this yet, but I did notice that in okhttp's CacheStrategy.java class, it has the following code:
---
public static boolean isCacheable(Response response, Request request) {
// Always go to network for uncacheable response codes (RFC 2616, 13.4),
// This implementation doesn't support caching partial content.
int responseCode = response.code();
if (responseCode != HttpURLConnection.HTTP_OK // 200
&& responseCode != HttpURLConnection.HTTP_NOT_AUTHORITATIVE // 203
&& responseCode != HttpURLConnection.HTTP_MULT_CHOICE // 300
&& responseCode != HttpURLConnection.HTTP_MOVED_PERM / 301
&& responseCode != HttpURLConnection.HTTP_GONE) { // 410
return false;
}
---
And to verify that caching isn't enabled for from 302-308, the unit tests from CacheTest.java states the following
---
for (int i = 302; i <= 308; ++i) {
assertCached(false, i);
}
---
So the okhttp code explicitly ignores caching for 307, and also 302. I just wanted clarification for this. Is the spec for 307 wrong? Or is something wrong with caching 307 that it was deliberately excluded? If I were to set my own cache headers for 307, it would seem to still be skipped.
Just another background information. I know Amazon will support caching with proper cache headers. But since I have to redirect through my own backend, if I don't have caching ability, my offline access to my redirect URL will not respond that I have a cached version from CDN locally. Of course, if I didn't redirect from my backend and go straight to Amazon, then caching wouldn't be a problem through Amazon. Could you provide some advice in this scenario?
| 64f2af812bef505b6cbc1693aa8b504d9dbbb42e | 1d6f0e75d599e2cb02f0fe182f7dbf966cd5cb2b | https://github.com/square/okhttp/compare/64f2af812bef505b6cbc1693aa8b504d9dbbb42e...1d6f0e75d599e2cb02f0fe182f7dbf966cd5cb2b | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
index 9fba4601c..0fd174648 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java
@@ -121,9 +121,12 @@ public final class CacheTest {
assertCached(false, 207);
assertCached(true, 300);
assertCached(true, 301);
- for (int i = 302; i <= 307; ++i) {
- assertCached(false, i);
- }
+ assertCached(true, 302);
+ assertCached(false, 303);
+ assertCached(false, 304);
+ assertCached(false, 305);
+ assertCached(false, 306);
+ assertCached(true, 307);
assertCached(true, 308);
for (int i = 400; i <= 406; ++i) {
assertCached(false, i);
@@ -394,6 +397,63 @@ public final class CacheTest {
assertEquals(2, cache.getHitCount());
}
+ @Test public void foundCachedWithExpiresHeader() throws Exception {
+ temporaryRedirectCachedWithCachingHeader(302, "Expires", formatDate(1, TimeUnit.HOURS));
+ }
+
+ @Test public void foundCachedWithCacheControlHeader() throws Exception {
+ temporaryRedirectCachedWithCachingHeader(302, "Cache-Control", "max-age=60");
+ }
+
+ @Test public void temporaryRedirectCachedWithExpiresHeader() throws Exception {
+ temporaryRedirectCachedWithCachingHeader(307, "Expires", formatDate(1, TimeUnit.HOURS));
+ }
+
+ @Test public void temporaryRedirectCachedWithCacheControlHeader() throws Exception {
+ temporaryRedirectCachedWithCachingHeader(307, "Cache-Control", "max-age=60");
+ }
+
+ @Test public void foundNotCachedWithoutCacheHeader() throws Exception {
+ temporaryRedirectNotCachedWithoutCachingHeader(302);
+ }
+
+ @Test public void temporaryRedirectNotCachedWithoutCacheHeader() throws Exception {
+ temporaryRedirectNotCachedWithoutCachingHeader(307);
+ }
+
+ private void temporaryRedirectCachedWithCachingHeader(
+ int responseCode, String headerName, String headerValue) throws Exception {
+ server.enqueue(new MockResponse()
+ .setResponseCode(responseCode)
+ .addHeader(headerName, headerValue)
+ .addHeader("Location", "/a"));
+ server.enqueue(new MockResponse()
+ .addHeader(headerName, headerValue)
+ .setBody("a"));
+ server.enqueue(new MockResponse()
+ .setBody("b"));
+ server.enqueue(new MockResponse()
+ .setBody("c"));
+
+ URL url = server.getUrl("/");
+ assertEquals("a", get(url).body().string());
+ assertEquals("a", get(url).body().string());
+ }
+
+ private void temporaryRedirectNotCachedWithoutCachingHeader(int responseCode) throws Exception {
+ server.enqueue(new MockResponse()
+ .setResponseCode(responseCode)
+ .addHeader("Location", "/a"));
+ server.enqueue(new MockResponse()
+ .setBody("a"));
+ server.enqueue(new MockResponse()
+ .setBody("b"));
+
+ URL url = server.getUrl("/");
+ assertEquals("a", get(url).body().string());
+ assertEquals("b", get(url).body().string());
+ }
+
@Test public void serverDisconnectsPrematurelyWithContentLengthHeader() throws IOException {
testServerPrematureDisconnect(TransferKind.FIXED_LENGTH);
}
diff --git a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java
index 800124bdf..79d73f4ee 100644
--- a/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java
+++ b/okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java
@@ -132,9 +132,12 @@ public final class UrlConnectionCacheTest {
assertCached(false, 207);
assertCached(true, 300);
assertCached(true, 301);
- for (int i = 302; i <= 307; ++i) {
- assertCached(false, i);
- }
+ assertCached(true, 302);
+ assertCached(false, 303);
+ assertCached(false, 304);
+ assertCached(false, 305);
+ assertCached(false, 306);
+ assertCached(true, 307);
assertCached(true, 308);
for (int i = 400; i <= 406; ++i) {
assertCached(false, i);
@@ -158,12 +161,12 @@ public final class UrlConnectionCacheTest {
private void assertCached(boolean shouldPut, int responseCode) throws Exception {
server = new MockWebServer();
- MockResponse response =
- new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
- .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
- .setResponseCode(responseCode)
- .setBody("ABCDE")
- .addHeader("WWW-Authenticate: challenge");
+ MockResponse response = new MockResponse()
+ .addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS))
+ .addHeader("Expires: " + formatDate(1, TimeUnit.HOURS))
+ .setResponseCode(responseCode)
+ .setBody("ABCDE")
+ .addHeader("WWW-Authenticate: challenge");
if (responseCode == HttpURLConnection.HTTP_PROXY_AUTH) {
response.addHeader("Proxy-Authenticate: Basic realm=\\"protected area\\"");
} else if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java
index 93c6d7e6d..69db3947f 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java
@@ -7,8 +7,10 @@ import com.squareup.okhttp.Response;
import java.util.Date;
import static com.squareup.okhttp.internal.http.StatusLine.HTTP_PERM_REDIRECT;
+import static com.squareup.okhttp.internal.http.StatusLine.HTTP_TEMP_REDIRECT;
import static java.net.HttpURLConnection.HTTP_GONE;
import static java.net.HttpURLConnection.HTTP_MOVED_PERM;
+import static java.net.HttpURLConnection.HTTP_MOVED_TEMP;
import static java.net.HttpURLConnection.HTTP_MULT_CHOICE;
import static java.net.HttpURLConnection.HTTP_NOT_AUTHORITATIVE;
import static java.net.HttpURLConnection.HTTP_OK;
@@ -39,26 +41,36 @@ public final class CacheStrategy {
* request.
*/
public static boolean isCacheable(Response response, Request request) {
- // Always go to network for uncacheable response codes (RFC 2616, 13.4),
+ // Always go to network for uncacheable response codes (RFC 7231 section 6.1),
// This implementation doesn't support caching partial content.
- int responseCode = response.code();
- if (responseCode != HTTP_OK
- && responseCode != HTTP_NOT_AUTHORITATIVE
- && responseCode != HTTP_MULT_CHOICE
- && responseCode != HTTP_MOVED_PERM
- && responseCode != HTTP_GONE
- && responseCode != HTTP_PERM_REDIRECT) {
- return false;
- }
+ switch (response.code()) {
+ case HTTP_OK:
+ case HTTP_NOT_AUTHORITATIVE:
+ case HTTP_MULT_CHOICE:
+ case HTTP_MOVED_PERM:
+ case HTTP_GONE:
+ case HTTP_PERM_REDIRECT:
+ // These codes can be cached unless headers forbid it.
+ break;
+
+ case HTTP_MOVED_TEMP:
+ case HTTP_TEMP_REDIRECT:
+ // These codes can only be cached with the right response headers.
+ if (response.header("Expires") != null
+ || response.cacheControl().maxAgeSeconds() != -1
+ || response.cacheControl().sMaxAgeSeconds() != -1
+ || response.cacheControl().isPublic()) {
+ break;
+ }
+ // Fall-through.
- // A 'no-store' directive on request or response prevents the response from being cached.
- CacheControl responseCaching = response.cacheControl();
- CacheControl requestCaching = request.cacheControl();
- if (responseCaching.noStore() || requestCaching.noStore()) {
- return false;
+ default:
+ // All other codes cannot be cached.
+ return false;
}
- return true;
+ // A 'no-store' directive on request or response prevents the response from being cached.
+ return !response.cacheControl().noStore() && !request.cacheControl().noStore();
}
public static class Factory { | ['okhttp/src/main/java/com/squareup/okhttp/internal/http/CacheStrategy.java', 'okhttp-urlconnection/src/test/java/com/squareup/okhttp/UrlConnectionCacheTest.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/CacheTest.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 875,001 | 202,735 | 24,643 | 132 | 1,919 | 416 | 44 | 1 | 3,541 | 539 | 802 | 69 | 2 | 0 | 2014-12-29T22:54:57 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
160 | square/okhttp/1122/1119 | square | okhttp | https://github.com/square/okhttp/issues/1119 | https://github.com/square/okhttp/pull/1122 | https://github.com/square/okhttp/pull/1122 | 1 | fixes | ConcurrentModificationException | I wouldn't deem this high priority but it did crash a device.
Android 4.4.2
OkHttp 2.0.0
``` bash
java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:806)
at java.util.HashMap$ValueIterator.next(HashMap.java:838)
at com.squareup.okhttp.internal.spdy.SpdyConnection$Reader.settings(SourceFile:698)
at com.squareup.okhttp.internal.spdy.Spdy3$Reader.readSettings$5f833cfd(SourceFile:278)
at com.squareup.okhttp.internal.spdy.Spdy3$Reader.nextFrame$64dcaf67(SourceFile:165)
at com.squareup.okhttp.internal.spdy.SpdyConnection$Reader.execute(SourceFile:574)
at com.squareup.okhttp.internal.NamedRunnable.run(SourceFile:33)
at java.lang.Thread.run(Thread.java:841)
```
[Crashlytics Link](http://crashes.to/s/fef087d43fb)
| 912d09e7da8830b831ee8f3461e0c66161fc82c8 | 3820b5c3355a0d5e48691c43481c6201a033a62c | https://github.com/square/okhttp/compare/912d09e7da8830b831ee8f3461e0c66161fc82c8...3820b5c3355a0d5e48691c43481c6201a033a62c | diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
index d3ebee2e3..458fb6db2 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java
@@ -695,7 +695,7 @@ public final class SpdyConnection implements Closeable {
}
}
if (streamsToNotify != null && delta != 0) {
- for (SpdyStream stream : streams.values()) {
+ for (SpdyStream stream : streamsToNotify) {
synchronized (stream) {
stream.addBytesToWriteWindow(delta);
} | ['okhttp/src/main/java/com/squareup/okhttp/internal/spdy/SpdyConnection.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 756,101 | 170,838 | 21,993 | 117 | 106 | 25 | 2 | 1 | 821 | 38 | 212 | 19 | 1 | 1 | 2014-11-04T02:31:17 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
159 | square/okhttp/1235/1191 | square | okhttp | https://github.com/square/okhttp/issues/1191 | https://github.com/square/okhttp/pull/1235 | https://github.com/square/okhttp/pull/1235 | 1 | closes | Crash with Facebook SDK | When I set `URL.setURLStreamHandlerFactory(new OkUrlFactory(client));` accordingly to https://github.com/square/picasso/issues/749, my app crashes because of the Facebook SDK :
```
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.squareup.okhttp.internal.spdy.SpdyStream.close(com.squareup.okhttp.internal.spdy.ErrorCode)' on a null object reference
at com.squareup.okhttp.internal.http.SpdyTransport.disconnect(SpdyTransport.java:221)
at com.squareup.okhttp.internal.http.HttpEngine.disconnect(HttpEngine.java:465)
at com.squareup.okhttp.internal.huc.HttpURLConnectionImpl.disconnect(HttpURLConnectionImpl.java:113)
at com.squareup.okhttp.internal.huc.DelegatingHttpsURLConnection.disconnect(DelegatingHttpsURLConnection.java:93)
at com.squareup.okhttp.internal.huc.HttpsURLConnectionImpl.disconnect(HttpsURLConnectionImpl.java:25)
at com.facebook.internal.Utility.disconnectQuietly(Utility.java:464)
at com.facebook.Request.executeConnectionAndWait(Request.java:1563)
at com.facebook.Request.executeBatchAndWait(Request.java:1460)
at com.facebook.Request.executeBatchAndWait(Request.java:1429)
at com.facebook.Request.executeBatchAndWait(Request.java:1411)
at com.facebook.Request.executeAndWait(Request.java:1383)
at com.facebook.Request.executeAndWait(Request.java:1269)
at com.facebook.internal.Utility.getAppSettingsQueryResponse(Utility.java:708)
at com.facebook.internal.Utility.access$000(Utility.java:57)
at com.facebook.internal.Utility$1.doInBackground(Utility.java:630)
at com.facebook.internal.Utility$1.doInBackground(Utility.java:627)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
```
Doesn't happen 100% of the time. Reproduced on Nexus 5 with Android 5.0 (LRX21O)
| e536bca6d7b2eb64054ee9845ca43dab19b020a7 | 0e199f608909793892b7883614c0d20a94c27916 | https://github.com/square/okhttp/compare/e536bca6d7b2eb64054ee9845ca43dab19b020a7...0e199f608909793892b7883614c0d20a94c27916 | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java
index 2c275e028..670361c60 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java
@@ -16,6 +16,7 @@
package com.squareup.okhttp.internal.http;
import com.squareup.okhttp.Cache;
+import com.squareup.okhttp.ConnectionPool;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.OkUrlFactory;
import com.squareup.okhttp.Protocol;
@@ -426,6 +427,26 @@ public abstract class HttpOverSpdyTest {
assertContains(requestB.getHeaders(), "cookie: c=oreo");
}
+ /** https://github.com/square/okhttp/issues/1191 */
+ @Test public void disconnectWithStreamNotEstablished() throws Exception {
+ ConnectionPool connectionPool = new ConnectionPool(5, 5000);
+ client.client().setConnectionPool(connectionPool);
+
+ server.enqueue(new MockResponse().setBody("abc"));
+ server.play();
+
+ // Disconnect before the stream is created. A connection is still established!
+ HttpURLConnection connection1 = client.open(server.getUrl("/"));
+ connection1.connect();
+ connection1.disconnect();
+
+ // That connection is pooled, and it works.
+ assertEquals(1, connectionPool.getSpdyConnectionCount());
+ HttpURLConnection connection2 = client.open(server.getUrl("/"));
+ assertContent("abc", connection2, 3);
+ assertEquals(0, server.takeRequest().getSequenceNumber());
+ }
+
<T> void assertContains(Collection<T> collection, T value) {
assertTrue(collection.toString(), collection.contains(value));
}
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java
index 0561ac38e..61b661081 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java
@@ -212,7 +212,7 @@ public final class SpdyTransport implements Transport {
}
@Override public void disconnect(HttpEngine engine) throws IOException {
- stream.close(ErrorCode.CANCEL);
+ if (stream != null) stream.close(ErrorCode.CANCEL);
}
@Override public boolean canReuseConnection() { | ['okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HttpOverSpdyTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 869,272 | 201,747 | 24,498 | 132 | 93 | 22 | 2 | 1 | 2,325 | 92 | 485 | 30 | 1 | 1 | 2014-12-26T02:05:55 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
158 | square/okhttp/1249/1239 | square | okhttp | https://github.com/square/okhttp/issues/1239 | https://github.com/square/okhttp/pull/1249 | https://github.com/square/okhttp/pull/1249 | 1 | closes | ConnectionPool is broken with MAX_CONNECTIONS_TO_CLEANUP | After merging @nfuller's recent leak fix, I noticed we have a new problem. Previously we were pretty eager to trim the idle connections down to the promised limits. An application that quickly created 100 connections would just as quickly see 95 of those connections evicted!
With the new fix, it looks like we won't evict more than once every 5 minutes, and we won't evict more than 2 connections per round. That means that we can exceed our promised limits.
We can fix this by replacing `Thread.sleep()` with `wait()` and invoke `notify()` where we're currently calling `scheduleCleanupAsRequired`. That'll cause the cleanup thread to take immediate action.
| f1a27df8f9a895f6ef7c1e718e09c65726161a26 | 98c74ace40b089f2769afb3e56c59a64eef327cb | https://github.com/square/okhttp/compare/f1a27df8f9a895f6ef7c1e718e09c65726161a26...98c74ace40b089f2769afb3e56c59a64eef327cb | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java
index 075153ddf..0bdc9f58a 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java
@@ -443,6 +443,9 @@ public final class ConnectionPoolTest {
pool.recycle(httpB);
pool.share(spdyA);
+ // Give the cleanup callable time to run and settle down.
+ Thread.sleep(100);
+
// Kill http A.
Util.closeQuietly(httpA.getSocket());
@@ -465,6 +468,31 @@ public final class ConnectionPoolTest {
assertEquals(0, pool.getConnectionCount());
}
+ @Test public void maxIdleConnectionsLimitEnforced() throws Exception {
+ ConnectionPool pool = new ConnectionPool(2, KEEP_ALIVE_DURATION_MS);
+
+ // Hit the max idle connections limit of 2.
+ pool.recycle(httpA);
+ pool.recycle(httpB);
+ Thread.sleep(100); // Give the cleanup callable time to run.
+ assertPooled(pool, httpB, httpA);
+
+ // Adding httpC bumps httpA.
+ pool.recycle(httpC);
+ Thread.sleep(100); // Give the cleanup callable time to run.
+ assertPooled(pool, httpC, httpB);
+
+ // Adding httpD bumps httpB.
+ pool.recycle(httpD);
+ Thread.sleep(100); // Give the cleanup callable time to run.
+ assertPooled(pool, httpD, httpC);
+
+ // Adding httpE bumps httpC.
+ pool.recycle(httpE);
+ Thread.sleep(100); // Give the cleanup callable time to run.
+ assertPooled(pool, httpE, httpD);
+ }
+
@Test public void evictAllConnections() throws Exception {
resetWithPoolSize(10);
pool.recycle(httpA);
diff --git a/okhttp/src/main/java/com/squareup/okhttp/Connection.java b/okhttp/src/main/java/com/squareup/okhttp/Connection.java
index 45fc5e933..8d8586ea0 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/Connection.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/Connection.java
@@ -316,14 +316,6 @@ public final class Connection {
return spdyConnection == null || spdyConnection.isIdle();
}
- /**
- * Returns true if this connection has been idle for longer than
- * {@code keepAliveDurationNs}.
- */
- boolean isExpired(long keepAliveDurationNs) {
- return getIdleStartTimeNs() < System.nanoTime() - keepAliveDurationNs;
- }
-
/**
* Returns the time in ns when this connection became idle. Undefined if
* this connection is not idle.
diff --git a/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java b/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java
index 0390917ad..16a6adbd1 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java
@@ -52,7 +52,6 @@ import java.util.concurrent.TimeUnit;
* initialized lazily.
*/
public final class ConnectionPool {
- private static final int MAX_CONNECTIONS_TO_CLEANUP = 2;
private static final long DEFAULT_KEEP_ALIVE_DURATION_MS = 5 * 60 * 1000; // 5 min
private static final ConnectionPool systemDefault;
@@ -93,36 +92,9 @@ public final class ConnectionPool {
0 /* corePoolSize */, 1 /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));
- /** {@code true} if the pool is actively draining, {@code false} if it is currently empty. */
- private boolean draining;
-
private final Runnable connectionsCleanupRunnable = new Runnable() {
- // An executing connectionsCleanupRunnable keeps a reference to the enclosing ConnectionPool,
- // preventing the ConnectionPool from being garbage collected before all held connections have
- // been explicitly closed. If this was not the case any open connections in the pool would
- // trigger StrictMode violations in Android when they were garbage collected. http://b/18369687
@Override public void run() {
- while (true) {
- performCleanup();
-
- // See whether this runnable should continue executing.
- synchronized (ConnectionPool.this) {
- if (connections.size() == 0) {
- draining = false;
- return;
- }
- }
-
- // Pause to avoid checking the pool too regularly, which would drain the battery on mobile
- // devices.
- try {
- // Use the keep alive duration as a rough indicator of a good check interval.
- long keepAliveDurationMillis = keepAliveDurationNs / (1000 * 1000);
- Thread.sleep(keepAliveDurationMillis);
- } catch (InterruptedException e) {
- // Ignored.
- }
- }
+ runCleanupUntilPoolIsEmpty();
}
};
@@ -188,7 +160,6 @@ public final class ConnectionPool {
if (foundConnection != null && foundConnection.isSpdy()) {
connections.addFirst(foundConnection); // Add it back after iteration.
- scheduleCleanupAsRequired();
}
return foundConnection;
@@ -224,10 +195,19 @@ public final class ConnectionPool {
}
synchronized (this) {
- connections.addFirst(connection);
+ addConnection(connection);
connection.incrementRecycleCount();
connection.resetIdleStartTime();
- scheduleCleanupAsRequired();
+ }
+ }
+
+ private void addConnection(Connection connection) {
+ boolean empty = connections.isEmpty();
+ connections.addFirst(connection);
+ if (empty) {
+ executor.execute(connectionsCleanupRunnable);
+ } else {
+ notifyAll();
}
}
@@ -237,71 +217,104 @@ public final class ConnectionPool {
*/
void share(Connection connection) {
if (!connection.isSpdy()) throw new IllegalArgumentException();
- if (connection.isAlive()) {
- synchronized (this) {
- connections.addFirst(connection);
- scheduleCleanupAsRequired();
- }
+ if (!connection.isAlive()) return;
+ synchronized (this) {
+ addConnection(connection);
}
}
/** Close and remove all connections in the pool. */
public void evictAll() {
- List<Connection> connections;
+ List<Connection> toEvict;
synchronized (this) {
- connections = new ArrayList<>(this.connections);
- this.connections.clear();
+ toEvict = new ArrayList<>(connections);
+ connections.clear();
}
- for (int i = 0, size = connections.size(); i < size; i++) {
- Util.closeQuietly(connections.get(i).getSocket());
+ for (int i = 0, size = toEvict.size(); i < size; i++) {
+ Util.closeQuietly(toEvict.get(i).getSocket());
}
}
- // Callers must synchronize on "this".
- private void scheduleCleanupAsRequired() {
- if (!draining) {
- // A new connection has potentially been offered up to an empty / drained pool.
- // Start the clean-up immediately.
- draining = true;
- executor.execute(connectionsCleanupRunnable);
+ private void runCleanupUntilPoolIsEmpty() {
+ while (true) {
+ if (!performCleanup()) return; // Halt cleanup.
}
}
- /** Performs a single round of pool cleanup. */
+ /**
+ * Attempts to make forward progress on connection eviction. There are three possible outcomes:
+ *
+ * <h3>The pool is empty.</h3>
+ * In this case, this method returns false and the eviction job should exit because there are no
+ * further cleanup tasks coming. (If additional connections are added to the pool, another cleanup
+ * job must be enqueued.)
+ *
+ * <h3>Connections were evicted.</h3>
+ * At least one connections was eligible for immediate eviction and was evicted. The method
+ * returns true and cleanup should continue.
+ *
+ * <h3>We waited to evict.</h3>
+ * None of the pooled connections were eligible for immediate eviction. Instead, we waited until
+ * either a connection became eligible for eviction, or the connections list changed. In either
+ * case, the method returns true and cleanup should continue.
+ */
// VisibleForTesting
- void performCleanup() {
- List<Connection> expiredConnections = new ArrayList<>(MAX_CONNECTIONS_TO_CLEANUP);
- int idleConnectionCount = 0;
+ boolean performCleanup() {
+ List<Connection> evictableConnections;
+
synchronized (this) {
+ if (connections.isEmpty()) return false; // Halt cleanup.
+
+ evictableConnections = new ArrayList<>();
+ int idleConnectionCount = 0;
+ long now = System.nanoTime();
+ long nanosUntilNextEviction = keepAliveDurationNs;
+
+ // Collect connections eligible for immediate eviction.
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious(); ) {
Connection connection = i.previous();
- if (!connection.isAlive() || connection.isExpired(keepAliveDurationNs)) {
+ long nanosUntilEviction = connection.getIdleStartTimeNs() + keepAliveDurationNs - now;
+ if (nanosUntilEviction <= 0 || !connection.isAlive()) {
i.remove();
- expiredConnections.add(connection);
- if (expiredConnections.size() == MAX_CONNECTIONS_TO_CLEANUP) {
- break;
- }
+ evictableConnections.add(connection);
} else if (connection.isIdle()) {
idleConnectionCount++;
+ nanosUntilNextEviction = Math.min(nanosUntilNextEviction, nanosUntilEviction);
}
}
+ // If the pool has too many idle connections, gather more! Oldest to newest.
for (ListIterator<Connection> i = connections.listIterator(connections.size());
i.hasPrevious() && idleConnectionCount > maxIdleConnections; ) {
Connection connection = i.previous();
if (connection.isIdle()) {
- expiredConnections.add(connection);
+ evictableConnections.add(connection);
i.remove();
--idleConnectionCount;
}
}
+
+ // If there's nothing to evict, wait. (This will be interrupted if connections are added.)
+ if (evictableConnections.isEmpty()) {
+ try {
+ long millisUntilNextEviction = nanosUntilNextEviction / (1000 * 1000);
+ long remainderNanos = nanosUntilNextEviction - millisUntilNextEviction * (1000 * 1000);
+ this.wait(millisUntilNextEviction, (int) remainderNanos);
+ return true; // Cleanup continues.
+ } catch (InterruptedException ignored) {
+ }
+ }
}
- for (Connection expiredConnection : expiredConnections) {
+ // Actually do the eviction. Note that we avoid synchronized() when closing sockets.
+ for (int i = 0, size = evictableConnections.size(); i < size; i++) {
+ Connection expiredConnection = evictableConnections.get(i);
Util.closeQuietly(expiredConnection.getSocket());
}
+
+ return true; // Cleanup continues.
}
/** | ['okhttp-tests/src/test/java/com/squareup/okhttp/ConnectionPoolTest.java', 'okhttp/src/main/java/com/squareup/okhttp/Connection.java', 'okhttp/src/main/java/com/squareup/okhttp/ConnectionPool.java'] | {'.java': 3} | 3 | 3 | 0 | 0 | 3 | 869,670 | 201,598 | 24,507 | 132 | 6,200 | 1,313 | 141 | 2 | 662 | 106 | 142 | 6 | 0 | 0 | 2014-12-29T02:33:29 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
163 | square/okhttp/980/979 | square | okhttp | https://github.com/square/okhttp/issues/979 | https://github.com/square/okhttp/pull/980 | https://github.com/square/okhttp/pull/980 | 1 | fixes | SpdyTransport sets the wrong protocol | SpdyTransport sets the response protocol according to the status line.
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/http/StatusLine.java#L41
It seems to me that it should be clarified with the transport protocol, here, right?
https://github.com/square/okhttp/blob/master/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java#L206
| 0766369844b26f64fc2e8d551ee8b5b00aa3fd87 | 9a35caf73356aa9a0142f5c5a0c50fde60d6ae02 | https://github.com/square/okhttp/compare/0766369844b26f64fc2e8d551ee8b5b00aa3fd87...9a35caf73356aa9a0142f5c5a0c50fde60d6ae02 | diff --git a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java
index 9947da037..144ec78f4 100644
--- a/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java
+++ b/okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java
@@ -41,7 +41,7 @@ public final class HeadersTest {
SpdyTransport.readNameValueBlock(headerBlock, Protocol.SPDY_3).request(request).build();
Headers headers = response.headers();
assertEquals(4, headers.size());
- assertEquals(Protocol.HTTP_1_1, response.protocol());
+ assertEquals(Protocol.SPDY_3, response.protocol());
assertEquals(200, response.code());
assertEquals("OK", response.message());
assertEquals("no-cache, no-store", headers.get("cache-control"));
diff --git a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java
index 38ad43817..14f317ba9 100644
--- a/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java
+++ b/okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java
@@ -204,7 +204,7 @@ public final class SpdyTransport implements Transport {
StatusLine statusLine = StatusLine.parse(version + " " + status);
return new Response.Builder()
- .protocol(statusLine.protocol)
+ .protocol(protocol)
.code(statusLine.code)
.message(statusLine.message)
.headers(headersBuilder.build()); | ['okhttp/src/main/java/com/squareup/okhttp/internal/http/SpdyTransport.java', 'okhttp-tests/src/test/java/com/squareup/okhttp/internal/http/HeadersTest.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 724,212 | 163,340 | 21,260 | 113 | 68 | 12 | 2 | 1 | 403 | 27 | 100 | 8 | 2 | 0 | 2014-07-02T14:29:56 | 44,252 | Kotlin | {'Kotlin': 3059143, 'Java': 744989, 'Shell': 2995} | Apache License 2.0 |
685 | dbeaver/dbeaver/12953/12943 | dbeaver | dbeaver | https://github.com/dbeaver/dbeaver/issues/12943 | https://github.com/dbeaver/dbeaver/pull/12953 | https://github.com/dbeaver/dbeaver/pull/12953 | 1 | fix | Database Navigator "Show Connected Only", "Show All" toggle no longer works | #### System information:
- Operating system (distribution) and version Windows 10 Enterprise version 1909
- DBeaver version Community 21.1.1.202106210824
- Java version
- Additional extensions
#### Connection specification:
- Database name and version postgres 13.*
- Driver name
- Do you use tunnels or proxies (SSH, SOCKS, etc)?
#### Describe the problem you're observing:
[Database Navigator], top right side, button to toggle between showing all connections and showing connected only stopped working with yesterday's upgrade to Community 21.1.1.202106210824
#### Steps to reproduce, if exist:
#### Include any warning/errors/backtraces from the logs
<none> Functionality has not worked today and there are no errors in the logs from today. | 7176cb483b61f6c3db2668dbb13df49876a4c1f0 | cb54f75baa3c1c7c1b1ba18d41e97ca82313fe53 | https://github.com/dbeaver/dbeaver/compare/7176cb483b61f6c3db2668dbb13df49876a4c1f0...cb54f75baa3c1c7c1b1ba18d41e97ca82313fe53 | diff --git a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java
index 749c8113a7..a6c2863f9a 100644
--- a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java
+++ b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java
@@ -714,6 +714,8 @@ public class DatabaseNavigatorTree extends Composite implements INavigatorListen
}
pattern = "*" + pattern;
this.matcher = new TextMatcherExt(pattern, true, false);
+ } else {
+ super.setPattern(null);
}
}
@@ -725,13 +727,10 @@ public class DatabaseNavigatorTree extends Composite implements INavigatorListen
if (matcher != null) {
return matcher.match(text);
}
- return false;
+ return super.wordMatches(text);
}
public boolean isElementVisible(Viewer viewer, Object element){
- if (matcher == null) {
- return true;
- }
if (filterShowConnected && element instanceof DBNDataSource && !((DBNDataSource) element).getDataSourceContainer().isConnected()) {
return false;
}
diff --git a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java
index 7a5d7d0710..6b4a5dffe0 100644
--- a/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java
+++ b/plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java
@@ -68,6 +68,7 @@ public class TextMatcherExt {
if (s == null || s.isEmpty()) {
continue;
}
+ s = "*" + s;
StringMatcher m = new StringMatcher(s, ignoreCase, ignoreWildCards);
m.usePrefixMatch();
matchers.add(m); | ['plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/TextMatcherExt.java', 'plugins/org.jkiss.dbeaver.ui.navigator/src/org/jkiss/dbeaver/ui/navigator/database/DatabaseNavigatorTree.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 21,355,988 | 4,380,492 | 582,549 | 4,173 | 240 | 42 | 8 | 2 | 770 | 107 | 173 | 17 | 0 | 0 | 2021-06-23T10:18:30 | 33,177 | Java | {'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202} | Apache License 2.0 |
686 | dbeaver/dbeaver/12939/12070 | dbeaver | dbeaver | https://github.com/dbeaver/dbeaver/issues/12070 | https://github.com/dbeaver/dbeaver/pull/12939 | https://github.com/dbeaver/dbeaver/pull/12939 | 1 | fix | [mysql] incorrect handling of stored procedure and function with the same name | - Operating system (distribution) and version: Debian 10
- DBeaver version: 21.0.2
- Database name and version: mysql 8.0.23
- Driver name: MySQL
If there are one stored procedure and one function with the same name, you could loose function while editing the procedure.
1) create "test" PROCEDURE
```
DELIMITER $$
$$
CREATE PROCEDURE testdb.test()
BEGIN
END$$
DELIMITER ;
```
2) create "test" FUNCTION
```
DELIMITER $$
$$
CREATE FUNCTION testdb.test()
RETURNS INT
DETERMINISTIC
BEGIN
RETURN 0;
END$$
DELIMITER ;
```
3) open the procedure, edit and save. CTRL+S generates the correct code:
```
DROP PROCEDURE IF EXISTS testdb.test;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `testdb`.`test`()
BEGIN
# test
END$$
DELIMITER ;
```
4) edit the procedure again and press CTRL+S.... boom:
DROP **FUNCTION** IF EXISTS testdb.test;
DELIMITER $$
$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `testdb`.`test`()
BEGIN
# test 1
END$$
DELIMITER ;
As you can see the second time you save, there is a DROP FUNCTION and CREATE PROCEDURE, so "test" function is deleted. | 9825b1f323d73718b7e685dea501fdbd7387410d | 9c46c6f8bd6d6b5a5db4aea769a63663699c912f | https://github.com/dbeaver/dbeaver/compare/9825b1f323d73718b7e685dea501fdbd7387410d...9c46c6f8bd6d6b5a5db4aea769a63663699c912f | diff --git a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java
index 3b2caa3e88..c6ad2fa070 100644
--- a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java
+++ b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java
@@ -923,12 +923,15 @@ public class MySQLCatalog implements
"SELECT * FROM " + MySQLConstants.META_TABLE_ROUTINES +
"\\nWHERE " + MySQLConstants.COL_ROUTINE_SCHEMA + "=?" +
(object == null && objectName == null ? "" : " AND " + MySQLConstants.COL_ROUTINE_NAME + "=?") +
- "\\nAND ROUTINE_TYPE IN ('PROCEDURE','FUNCTION')" +
+ " AND ROUTINE_TYPE" + (object == null ? " IN ('PROCEDURE','FUNCTION')" : "=?") +
"\\nORDER BY " + MySQLConstants.COL_ROUTINE_NAME
);
dbStat.setString(1, owner.getName());
if (object != null || objectName != null) {
dbStat.setString(2, object != null ? object.getName() : objectName);
+ if (object != null) {
+ dbStat.setString(3, String.valueOf(object.getProcedureType()));
+ }
}
return dbStat;
}
diff --git a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java
index bf1cf13f76..4b98d7f7e3 100644
--- a/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java
+++ b/plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java
@@ -20,10 +20,7 @@ import org.jkiss.code.NotNull;
import org.jkiss.dbeaver.DBException;
import org.jkiss.dbeaver.Log;
import org.jkiss.dbeaver.ext.mysql.MySQLConstants;
-import org.jkiss.dbeaver.model.DBPDataKind;
-import org.jkiss.dbeaver.model.DBPEvaluationContext;
-import org.jkiss.dbeaver.model.DBPRefreshableObject;
-import org.jkiss.dbeaver.model.DBUtils;
+import org.jkiss.dbeaver.model.*;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCPreparedStatement;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCResultSet;
import org.jkiss.dbeaver.model.exec.jdbc.JDBCSession;
@@ -44,7 +41,7 @@ import java.util.Map;
/**
* MySQLProcedure
*/
-public class MySQLProcedure extends AbstractProcedure<MySQLDataSource, MySQLCatalog> implements MySQLSourceObject, DBPRefreshableObject
+public class MySQLProcedure extends AbstractProcedure<MySQLDataSource, MySQLCatalog> implements MySQLSourceObject, DBPRefreshableObject, DBPUniqueObject
{
private static final Log log = Log.getLog(MySQLProcedure.class);
@@ -263,6 +260,15 @@ public class MySQLProcedure extends AbstractProcedure<MySQLDataSource, MySQLCata
return getContainer().proceduresCache.refreshObject(monitor, getContainer(), this);
}
+ @NotNull
+ @Override
+ public String getUniqueName() {
+ if (getProcedureType() == DBSProcedureType.PROCEDURE) {
+ return getName() + ' ' + getResultType();
+ }
+ return getName();
+ }
+
@Override
public String toString() {
return procedureType.name() + " " + getName(); | ['plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLCatalog.java', 'plugins/org.jkiss.dbeaver.ext.mysql/src/org/jkiss/dbeaver/ext/mysql/model/MySQLProcedure.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 21,350,073 | 4,379,299 | 582,409 | 4,172 | 1,068 | 234 | 21 | 2 | 1,144 | 163 | 306 | 59 | 0 | 3 | 2021-06-22T10:40:55 | 33,177 | Java | {'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202} | Apache License 2.0 |
688 | dbeaver/dbeaver/12766/12765 | dbeaver | dbeaver | https://github.com/dbeaver/dbeaver/issues/12765 | https://github.com/dbeaver/dbeaver/pull/12766 | https://github.com/dbeaver/dbeaver/pull/12766 | 1 | fix | SqlServer FK between two schemas doesn't show on UI | <!--
Thank you for reporting an issue.
*IMPORTANT* - *before* creating a new issue please look around:
- DBeaver documentation: https://github.com/dbeaver/dbeaver/wiki
and
- open issues in Github tracker: https://github.com/dbeaver/dbeaver/issues
If you cannot find a similar problem, then create a new issue. Short tips about new issues can be found here: https://github.com/dbeaver/dbeaver/wiki/Posting-issues
Please, do not create issue duplicates. If you find the same or similar issue, just add a comment or vote for this feature. It helps us to track the most popular requests and fix them faster.
Please fill in as much of the template as possible.
-->
#### System information:
- Operating system: **Windows 10 Version 21H1 Build 19043.1023**
- DBeaver version **21.1.0.202105300349** Community
- Additional extensions
DBeaver Git support 1.0.46.202106012023 org.jkiss.dbeaver.git.feature.feature.group DBeaver Corp
DevStyle (includes Darkest Dark Theme) 1.11.0.202105260439 com.genuitec.eclipse.theming.core.feature.feature.group Genuitec, LLC
#### Connection specification:
- Database name and version: **SqlServer Express Microsoft SQL Server 2017 (RTM-GDR) (KB4583456) - 14.0.2037.2 (X64) Nov 2 2020 19:19:59 Copyright (C) 2017 Microsoft Corporation Express Edition (64-bit) on Windows 10 Pro 10.0 <X64> (Build 19043: ) (Hypervisor)**
- Driver name **SQL Server**
- Do you use tunnels or proxies (SSH, SOCKS, etc)? **No**
#### Describe the problem you're observing:
Creating foreign keys between two tables on two different schemas via UI or SQL Script does not show it on Foreign Keys Tab/SubGroup neither on the DDL source tab.
#### Steps to reproduce, if exist:
1. Create a SQL Server database
2. Create two schemas
3. Create TableOne on schema1
4. Create TableTwo on schema2
5. Create FK from TableTwo to TableOne
6. If you create FK with UI from the Foreign Keys tab when click persist the FK disappear (but is still present on DB)
7. Execute the query `select * from sys.objects` to verify that the object is successfully created
| 63aee4269a199deb69359f4913055615619a7666 | 0e820df3b91ff92f3c37db90335d30703afde0fd | https://github.com/dbeaver/dbeaver/compare/63aee4269a199deb69359f4913055615619a7666...0e820df3b91ff92f3c37db90335d30703afde0fd | diff --git a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java
index dac1924bb9..e41e19e4ef 100644
--- a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java
+++ b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java
@@ -216,10 +216,22 @@ public class SQLServerSchema implements DBSSchema, DBPSaveableObject, DBPQualifi
return tableCache.getTypedObjects(monitor, this, SQLServerTable.class);
}
+ @Nullable
public SQLServerTableBase getTable(DBRProgressMonitor monitor, String name) throws DBException {
return tableCache.getObject(monitor, this, name);
}
+ @Nullable
+ public SQLServerTable getTable(DBRProgressMonitor monitor, long tableId) throws DBException {
+ for (SQLServerTableBase table : tableCache.getAllObjects(monitor, this)) {
+ if (table.getObjectId() == tableId && table instanceof SQLServerTable) {
+ return (SQLServerTable) table;
+ }
+ }
+ log.debug("Table '" + tableId + "' not found in schema " + getName());
+ return null;
+ }
+
@Association
public Collection<SQLServerView> getViews(DBRProgressMonitor monitor) throws DBException {
return tableCache.getTypedObjects(monitor, this, SQLServerView.class);
@@ -659,7 +671,7 @@ public class SQLServerSchema implements DBSSchema, DBPSaveableObject, DBPQualifi
return null;
}
long refTableId = JDBCUtils.safeGetLong(dbResult, "referenced_object_id");
- SQLServerTable refTable = getTable(monitor, refTableId);
+ SQLServerTable refTable = refSchema.getTable(monitor, refTableId);
if (refTable == null) {
log.debug("Ref table " + refTableId + " not found in schema " + refSchema.getName());
return null;
@@ -684,17 +696,6 @@ public class SQLServerSchema implements DBSSchema, DBPSaveableObject, DBPQualifi
return new SQLServerTableForeignKey(parent, fkName, null, refConstraint, deleteRule, updateRule, true);
}
- @Nullable
- private SQLServerTable getTable(DBRProgressMonitor monitor, long tableId) throws DBException {
- for (SQLServerTableBase table: tableCache.getAllObjects(monitor, SQLServerSchema.this)) {
- if (table.getObjectId() == tableId && table instanceof SQLServerTable) {
- return (SQLServerTable) table;
- }
- }
- log.debug("Table '" + tableId + "' not found in schema " + getName());
- return null;
- }
-
@Nullable
@Override
protected SQLServerTableForeignKeyColumn[] fetchObjectRow( | ['plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerSchema.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 21,252,088 | 4,358,670 | 579,957 | 4,152 | 1,158 | 240 | 25 | 1 | 2,113 | 299 | 550 | 39 | 3 | 0 | 2021-06-07T21:56:46 | 33,177 | Java | {'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202} | Apache License 2.0 |
689 | dbeaver/dbeaver/12577/12576 | dbeaver | dbeaver | https://github.com/dbeaver/dbeaver/issues/12576 | https://github.com/dbeaver/dbeaver/pull/12577 | https://github.com/dbeaver/dbeaver/pull/12577 | 1 | fix | Inconsistent behavior of some checkboxes on the PostgreSQL connection configuration page | On the aforementioned page, we have 3 checkboxes: a) Show all databases; b) Show template databases; c) Show databases not available for connection. If the first one is not set, the latter two are not applicable. However, if we check one of them, e.g. the second one, and then we uncheck the first one, checkbox b is still set (but grayed). We also have the same checkboxes in the global preferences, and there we can even apply checkboxes b and c without checking button a. | a4afc250c8dc2566f43c7352e4aba539db7b8e23 | 4ae933837845b1c564859b676464fe7c83b18f9a | https://github.com/dbeaver/dbeaver/compare/a4afc250c8dc2566f43c7352e4aba539db7b8e23...4ae933837845b1c564859b676464fe7c83b18f9a | diff --git a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java
index 3d86556b1b..4529685533 100644
--- a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java
+++ b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java
@@ -84,8 +84,7 @@ public class PostgreConnectionPageAdvanced extends ConnectionPageAbstract
showNonDefault.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
- showTemplates.setEnabled(showNonDefault.getSelection());
- showUnavailable.setEnabled(showNonDefault.getSelection());
+ setCheckboxesState();
}
});
showTemplates = UIUtils.createCheckbox(secureGroup, PostgreMessages.dialog_setting_connection_show_templates, PostgreMessages.dialog_setting_connection_show_templates_tip, false, 2);
@@ -125,6 +124,16 @@ public class PostgreConnectionPageAdvanced extends ConnectionPageAbstract
loadSettings();
}
+ private void setCheckboxesState() {
+ boolean enable = showNonDefault.getSelection();
+ if (!enable) {
+ showUnavailable.setSelection(false);
+ showTemplates.setSelection(false);
+ }
+ showUnavailable.setEnabled(enable);
+ showTemplates.setEnabled(enable);
+ }
+
@Override
public boolean isComplete()
{
@@ -145,11 +154,10 @@ public class PostgreConnectionPageAdvanced extends ConnectionPageAbstract
showTemplates.setSelection(
CommonUtils.getBoolean(connectionInfo.getProviderProperty(PostgreConstants.PROP_SHOW_TEMPLATES_DB),
globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_TEMPLATES_DB)));
- showTemplates.setEnabled(showNonDefault.getSelection());
showUnavailable.setSelection(
CommonUtils.getBoolean(connectionInfo.getProviderProperty(PostgreConstants.PROP_SHOW_UNAVAILABLE_DB),
globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_UNAVAILABLE_DB)));
- showUnavailable.setEnabled(showNonDefault.getSelection());
+ setCheckboxesState();
showDatabaseStatistics.setSelection(
CommonUtils.getBoolean(connectionInfo.getProviderProperty(PostgreConstants.PROP_SHOW_DATABASE_STATISTICS),
globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_DATABASE_STATISTICS)));
diff --git a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java
index 9eb6ff68de..cfb96b1b4c 100644
--- a/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java
+++ b/plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java
@@ -79,8 +79,7 @@ public class PrefPagePostgreSQL extends AbstractPrefPage implements IWorkbenchPr
showNonDefault.addSelectionListener(new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
- showTemplates.setEnabled(showNonDefault.getSelection());
- showUnavailable.setEnabled(showNonDefault.getSelection());
+ setCheckboxesState();
}
});
showTemplates = UIUtils.createCheckbox(secureGroup,
@@ -95,6 +94,7 @@ public class PrefPagePostgreSQL extends AbstractPrefPage implements IWorkbenchPr
globalPrefs.getBoolean(PostgreConstants.PROP_SHOW_UNAVAILABLE_DB),
2
);
+ setCheckboxesState();
showDatabaseStatistics = UIUtils.createCheckbox(
secureGroup,
PostgreMessages.dialog_setting_connection_database_statistics,
@@ -129,6 +129,16 @@ public class PrefPagePostgreSQL extends AbstractPrefPage implements IWorkbenchPr
return cfgGroup;
}
+ private void setCheckboxesState() {
+ boolean enable = showNonDefault.getSelection();
+ if (!enable) {
+ showUnavailable.setSelection(false);
+ showTemplates.setSelection(false);
+ }
+ showUnavailable.setEnabled(enable);
+ showTemplates.setEnabled(enable);
+ }
+
@Override
public boolean performOk() {
DBPPreferenceStore preferenceStore = DBWorkbench.getPlatform().getPreferenceStore(); | ['plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PostgreConnectionPageAdvanced.java', 'plugins/org.jkiss.dbeaver.ext.postgresql.ui/src/org/jkiss/dbeaver/ext/postgresql/ui/PrefPagePostgreSQL.java'] | {'.java': 2} | 2 | 2 | 0 | 0 | 2 | 21,216,761 | 4,351,606 | 579,212 | 4,150 | 1,256 | 182 | 30 | 2 | 474 | 85 | 108 | 1 | 0 | 0 | 2021-05-24T16:11:07 | 33,177 | Java | {'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202} | Apache License 2.0 |
690 | dbeaver/dbeaver/12571/12569 | dbeaver | dbeaver | https://github.com/dbeaver/dbeaver/issues/12569 | https://github.com/dbeaver/dbeaver/pull/12571 | https://github.com/dbeaver/dbeaver/pull/12571 | 1 | fix | Probable regression, Postgresql sequence DDL uses Cache 0 and this is not a valid value | #### System information:
- Ubuntu 18.04
- DBeaver CE 21.0.5
- Additional extensions: Non AFAIK
#### Connection specification:
- Database name and version: PostgreSQL 9.6
- Driver name: PostgreSQL JDBC Driver
- Do you use tunnels or proxies (SSH, SOCKS, etc)? No
#### Describe the problem you're observing:
The DDL suggested for a sequence sets optional attribute CACHE to 0 which is not valid in PostgreSQL.
This was reported and supposedly fixed a couple of years ago in #5156 .
#### Steps to reproduce, if exist:
Create a sequence in a PostgreSQL DB and check the DDL that DBeaver shows.
#### Include any warning/errors/backtraces from the logs
<!-- Please, find the short guide how to find logs here: https://github.com/dbeaver/dbeaver/wiki/Log-files -->
| 67d9e76022d6a32ac090e12f2e25d82ec1726fe3 | c170fae1c16ce0ef9287d3419de48541385eb1f1 | https://github.com/dbeaver/dbeaver/compare/67d9e76022d6a32ac090e12f2e25d82ec1726fe3...c170fae1c16ce0ef9287d3419de48541385eb1f1 | diff --git a/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java b/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java
index dd58352562..57c44bda18 100644
--- a/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java
+++ b/plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java
@@ -253,13 +253,29 @@ public class PostgreSequence extends PostgreTableBase implements DBSSequence, DB
AdditionalInfo info = getAdditionalInfo(monitor);
StringBuilder sql = new StringBuilder()
.append("-- DROP SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL)).append(";\\n\\n")
- .append("CREATE SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL))
- .append("\\n\\tINCREMENT BY ").append(info.getIncrementBy())
- .append("\\n\\tMINVALUE ").append(info.getMinValue())
- .append("\\n\\tMAXVALUE ").append(info.getMaxValue())
- .append("\\n\\tSTART ").append(info.getStartValue())
- .append("\\n\\tCACHE ").append(info.getCacheValue())
- .append("\\n\\t").append(info.isCycled ? "" : "NO ").append("CYCLE;");
+ .append("CREATE SEQUENCE ").append(getFullyQualifiedName(DBPEvaluationContext.DDL));
+
+ if (info.getIncrementBy() > 0) {
+ sql.append("\\n\\tINCREMENT BY ").append(info.getIncrementBy());
+ }
+ if (info.getMinValue() > 0) {
+ sql.append("\\n\\tMINVALUE ").append(info.getMinValue());
+ } else {
+ sql.append("\\n\\tNO MINVALUE");
+ }
+ if (info.getMaxValue() > 0) {
+ sql.append("\\n\\tMAXVALUE ").append(info.getMaxValue());
+ } else {
+ sql.append("\\n\\tNO MAXVALUE");
+ }
+ if (info.getStartValue() > 0) {
+ sql.append("\\n\\tSTART ").append(info.getStartValue());
+ }
+ if (info.getCacheValue() > 0) {
+ sql.append("\\n\\tCACHE ").append(info.getCacheValue());
+ sql.append("\\n\\t").append(info.isCycled ? "" : "NO ").append("CYCLE");
+ }
+ sql.append(';');
if (!CommonUtils.isEmpty(getDescription())) {
sql.append("\\nCOMMENT ON SEQUENCE ").append(DBUtils.getQuotedIdentifier(this)).append(" IS ") | ['plugins/org.jkiss.dbeaver.ext.postgresql/src/org/jkiss/dbeaver/ext/postgresql/model/PostgreSequence.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 21,193,424 | 4,346,619 | 578,586 | 4,146 | 1,449 | 331 | 30 | 1 | 782 | 120 | 186 | 20 | 1 | 0 | 2021-05-24T10:40:55 | 33,177 | Java | {'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202} | Apache License 2.0 |
684 | dbeaver/dbeaver/13321/11973 | dbeaver | dbeaver | https://github.com/dbeaver/dbeaver/issues/11973 | https://github.com/dbeaver/dbeaver/pull/13321 | https://github.com/dbeaver/dbeaver/pull/13321 | 1 | fix | Filters don't work for enum types | PostgreSQL 12, DBeaver EE 21.0.0, macOS 11.2.3.
Suppose we have a enum type and a table:
```sql
CREATE TYPE "mood" AS ENUM (
'sad',
'ok',
'happy'
);
CREATE TABLE mood_data (
id int4 NOT NULL GENERATED ALWAYS AS IDENTITY,
"time" timestamp NULL,
"mood" "mood" NULL,
CONSTRAINT mood_data_pkey PRIMARY KEY (id)
);
```
Fill the table with data. Open the data editor and try to apply a filter on the `mood` column. Possible values for filtering will be duplicated, the data editor will be closed with an error when applying the filter.
| 86adfaeec2af0cf11b43114cfb25f316830489fd | 01ddb8e9c02c212e4179295aa37381a9944d6621 | https://github.com/dbeaver/dbeaver/compare/86adfaeec2af0cf11b43114cfb25f316830489fd...01ddb8e9c02c212e4179295aa37381a9944d6621 | diff --git a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java
index 9fede8aa6a..3558b73b3c 100644
--- a/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java
+++ b/plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java
@@ -496,6 +496,12 @@ class GenericFilterValueEdit {
}
private DBDLabelValuePair findValue(Map<Object, DBDLabelValuePair> rowData, Object cellValue) {
+ final DBDLabelValuePair value = rowData.get(cellValue);
+ if (value != null) {
+ // If we managed to found something at this point - return right away
+ return value;
+ }
+ // Otherwise try to match values manually
if (cellValue instanceof Number) {
for (Map.Entry<Object, DBDLabelValuePair> pair : rowData.entrySet()) {
if (pair.getKey() instanceof Number && CommonUtils.compareNumbers((Number) pair.getKey(), (Number) cellValue) == 0) {
@@ -503,7 +509,14 @@ class GenericFilterValueEdit {
}
}
}
- return rowData.get(cellValue);
+ if (cellValue instanceof String) {
+ for (Map.Entry<Object, DBDLabelValuePair> pair : rowData.entrySet()) {
+ if (!DBUtils.isNullValue(pair.getKey()) && CommonUtils.toString(pair.getKey()).equals(cellValue)) {
+ return pair.getValue();
+ }
+ }
+ }
+ return null;
}
@Nullable | ['plugins/org.jkiss.dbeaver.ui.editors.data/src/org/jkiss/dbeaver/ui/controls/resultset/valuefilter/GenericFilterValueEdit.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 21,570,516 | 4,422,651 | 587,715 | 4,199 | 663 | 123 | 15 | 1 | 582 | 91 | 157 | 20 | 0 | 1 | 2021-07-26T15:08:20 | 33,177 | Java | {'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202} | Apache License 2.0 |
683 | dbeaver/dbeaver/14078/10955 | dbeaver | dbeaver | https://github.com/dbeaver/dbeaver/issues/10955 | https://github.com/dbeaver/dbeaver/pull/14078 | https://github.com/dbeaver/dbeaver/pull/14078 | 1 | fix | Auto-complete offers objects from the current schema only | #### System information:
- Operating system (distribution) and version Win10
- DBeaver version 7.3.3 EA
#### Steps to reproduce, if exist:
1. Open SQL Editor for MySQL sakila
2. Type `select * from a`
**Actual result**: the list for auto-complete appears with objects from the current schema only
**Expected**: the objects are offered from the whole database if they are suitable for auto-complete in the current statement.
_Note_: enabled **Use global search** option doesn't solve the issue | 19a37d839f97bb022c19ddc6fff588b230f92786 | e5219c457984fa0ef078968c11b7c835a3526142 | https://github.com/dbeaver/dbeaver/compare/19a37d839f97bb022c19ddc6fff588b230f92786...e5219c457984fa0ef078968c11b7c835a3526142 | diff --git a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java
index 68edb2d22e..9be288abeb 100644
--- a/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java
+++ b/plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java
@@ -128,7 +128,7 @@ public class SQLServerStructureAssistant implements DBSStructureAssistant<SQLSer
Collection<SQLServerDatabase> databases;
SQLServerSchema schema = null;
- if (parentObject instanceof DBPDataSourceContainer) {
+ if (parentObject instanceof DBPDataSourceContainer || parentObject instanceof SQLServerDataSource) {
if (globalSearch) {
databases = executionContext.getDataSource().getDatabases(monitor);
} else { | ['plugins/org.jkiss.dbeaver.ext.mssql/src/org/jkiss/dbeaver/ext/mssql/model/SQLServerStructureAssistant.java'] | {'.java': 1} | 1 | 1 | 0 | 0 | 1 | 22,041,779 | 4,518,554 | 599,248 | 4,274 | 172 | 31 | 2 | 1 | 508 | 77 | 114 | 12 | 0 | 0 | 2021-09-30T16:18:33 | 33,177 | Java | {'Java': 26145871, 'JavaScript': 139972, 'C++': 63113, 'ANTLR': 29768, 'CSS': 20674, 'HTML': 12246, 'XSLT': 8047, 'Batchfile': 2891, 'Shell': 202} | Apache License 2.0 |
End of preview. Expand
in Dataset Viewer.
Bug Localization
This is the data for Bug Localization benchmark.
How-to
Since the dataset is private, if you haven't used HF Hub before, add your token via
huggingface-cli
first:huggingface-cli login
List all the available configs via
datasets.get_dataset_config_names
and choose an appropriate oneLoad the data via
load_dataset
:from datasets import load_dataset # Select a configuration from ["py", "java", "kt", "mixed"] configuration = "py" # Select a split from ["dev", "train", "test"] split = "dev" # Load data dataset = load_dataset("JetBrains-Research/lca-bug-localization", configuration, split=split)
Load repos via
hf_hub_download
from huggingface_hub import hf_hub_download from datasets import load_dataset # Load json with list of repos' .tar.gz file paths paths_json = load_dataset("JetBrains-Research/lca-bug-localization", data_files="paths.json") # Load each repo in .tar.gz format, unzip, delete archive repos = paths_json["repos"][0] for i, repo_tar_path in enumerate(repos): local_repo_tars = hf_hub_download( "JetBrains-Research/lca-bug-localization", filename=repo_tar_path, repo_type="dataset", local_dir="local/dir" ) result = subprocess.run(["tar", "-xzf", local_repo_tars, "-C", os.path.join("local/dir", "repos")]) os.remove(local_repo_tars)
Dataset Structure
TODO: some overall structure or repo
Bug localization data
This section concerns configuration with full data about each commit (no -labels
suffix).
Each example has the following fields:
Field | Description |
---|---|
repo_owner |
Bug issue repository owner. |
repo_name |
Bug issue repository name. |
issue_url |
GitHub link to issue https://github.com/{repo_owner}/{repo_name}/issues/{issue_id} . |
pull_url |
GitHub link to pull request https://github.com/{repo_owner}/{repo_name}/pull/{pull_id} . |
comment_url |
GitHub link to comment with pull request to issue reference https://github.com/{repo_owner}/{repo_name}/pull/{pull_id}#issuecomment-{comment_id} . |
issue_title |
Issue title. |
issue_body |
Issue body. |
base_sha |
Pull request base sha. |
head_sha |
Pull request head sha. |
diff_url |
Pull request diff url between base and head sha https://github.com/{repo_owner}/{repo_name}/compare/{base_sha}...{head_sha} . |
diff |
Pull request diff content. |
changed_files |
List of changed files parsed from diff. |
changed_files_exts |
Dict from changed files extension to count. |
changed_files_count |
Number of changed files. |
java_changed_files_count |
Number of changed .java files. |
kt_changed_files_count |
Number of changed .kt files. |
py_changed_files_count |
Number of changed .py files. |
code_changed_files_count |
Number of changed .java , .kt or .py files. |
pull_create_at |
Data of pull request creation in format yyyy-mm-ddThh:mm:ssZ. |
stars |
Number of repo stars. |
Repos data
TODO: describe repos data as .tar.gz
archives with list of repos metadata
- Downloads last month
- 375