Merge "Fix stream flushing when SYNC_FLUSH is set."
diff --git a/luni/src/main/java/java/util/zip/DeflaterOutputStream.java b/luni/src/main/java/java/util/zip/DeflaterOutputStream.java
index 6cce5a5..3377afd 100644
--- a/luni/src/main/java/java/util/zip/DeflaterOutputStream.java
+++ b/luni/src/main/java/java/util/zip/DeflaterOutputStream.java
@@ -188,7 +188,10 @@
      * Doing so may degrade compression but improve interactive behavior.
      */
     @Override public void flush() throws IOException {
-        if (syncFlush) {
+        // Though not documented, it's illegal to call deflate with any flush param
+        // other than Z_FINISH after the deflater has finished. See the error checking
+        // at the start of the deflate function in deflate.c.
+        if (syncFlush && !done) {
             int byteCount;
             while ((byteCount = def.deflate(buf, 0, buf.length, Deflater.SYNC_FLUSH)) != 0) {
                 out.write(buf, 0, byteCount);
diff --git a/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java b/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java
index 55e45bc..3b785c9 100644
--- a/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java
+++ b/luni/src/test/java/libcore/java/util/zip/GZIPOutputStreamTest.java
@@ -16,17 +16,14 @@
 
 package libcore.java.util.zip;
 
-import java.io.ByteArrayInputStream;
+import junit.framework.TestCase;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.Arrays;
 import java.util.Random;
-import java.util.zip.GZIPInputStream;
 import java.util.zip.GZIPOutputStream;
-import java.util.zip.InflaterInputStream;
-import junit.framework.TestCase;
 
 public final class GZIPOutputStreamTest extends TestCase {
   public void testShortMessage() throws IOException {
@@ -67,4 +64,15 @@
     in.close();
   }
 
+  // https://code.google.com/p/android/issues/detail?id=62589
+  public void testFlushAfterFinish() throws Exception {
+    byte[] responseBytes = "Some data to gzip".getBytes();
+    ByteArrayOutputStream output = new ByteArrayOutputStream(responseBytes.length);
+    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(output, true);
+    gzipOutputStream.write(responseBytes);
+    gzipOutputStream.finish();
+    // Calling flush() after finish() shouldn't throw.
+    gzipOutputStream.flush();
+    gzipOutputStream.close();
+  }
 }