1 31 32 package org.apache.commons.httpclient; 33 34 import java.io.FilterInputStream ; 35 import java.io.IOException ; 36 import java.io.InputStream ; 37 38 48 49 class AutoCloseInputStream extends FilterInputStream { 50 51 55 private boolean streamOpen = true; 56 57 58 private boolean selfClosed = false; 59 60 64 private ResponseConsumedWatcher watcher = null; 65 66 73 public AutoCloseInputStream( 74 final InputStream in, final ResponseConsumedWatcher watcher) { 75 super(in); 76 this.watcher = watcher; 77 } 78 79 85 public int read() throws IOException { 86 int l = -1; 87 88 if (isReadAllowed()) { 89 l = super.read(); 91 checkClose(l); 92 } 93 94 return l; 95 } 96 97 106 public int read(byte[] b, int off, int len) throws IOException { 107 int l = -1; 108 109 if (isReadAllowed()) { 110 l = super.read(b, off, len); 111 checkClose(l); 112 } 113 114 return l; 115 } 116 117 125 public int read(byte[] b) throws IOException { 126 int l = -1; 127 128 if (isReadAllowed()) { 129 l = super.read(b); 130 checkClose(l); 131 } 132 return l; 133 } 134 135 140 public void close() throws IOException { 141 if (!selfClosed) { 142 selfClosed = true; 143 notifyWatcher(); 144 } 145 } 146 147 153 private void checkClose(int readResult) throws IOException { 154 if (readResult == -1) { 155 notifyWatcher(); 156 } 157 } 158 159 166 private boolean isReadAllowed() throws IOException { 167 if (!streamOpen && selfClosed) { 168 throw new IOException ("Attempted read on closed stream."); 169 } 170 return streamOpen; 171 } 172 173 177 private void notifyWatcher() throws IOException { 178 if (streamOpen) { 179 super.close(); 180 streamOpen = false; 181 182 if (watcher != null) { 183 watcher.responseConsumed(); 184 } 185 } 186 } 187 } 188 189 | Popular Tags |