Skip to content

Commit

Permalink
Clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
nostra13 committed Nov 16, 2014
1 parent dae133f commit eb794c3
Showing 1 changed file with 17 additions and 10 deletions.
Expand Up @@ -69,20 +69,15 @@ public class BaseImageDownloader implements ImageDownloader {
protected final Context context;
protected final int connectTimeout;
protected final int readTimeout;
/**
* Whether read stream if server returned non-200 response
*/
protected final boolean readOnError;

public BaseImageDownloader(Context context) {
this(context.getApplicationContext(), DEFAULT_HTTP_CONNECT_TIMEOUT, DEFAULT_HTTP_READ_TIMEOUT, false);
this(context, DEFAULT_HTTP_CONNECT_TIMEOUT, DEFAULT_HTTP_READ_TIMEOUT);
}

public BaseImageDownloader(Context context, int connectTimeout, int readTimeout, boolean readOnError) {
public BaseImageDownloader(Context context, int connectTimeout, int readTimeout) {
this.context = context.getApplicationContext();
this.connectTimeout = connectTimeout;
this.readTimeout = readTimeout;
this.readOnError = readOnError;
}

@Override
Expand Down Expand Up @@ -126,18 +121,30 @@ protected InputStream getStreamFromNetwork(String imageUri, Object extra) throws

InputStream imageStream;
try {
if (conn.getResponseCode() != 200 && !readOnError) {
throw new IOException("Unable to retrieve image. Response code: " + conn.getResponseCode());
}
imageStream = conn.getInputStream();
} catch (IOException e) {
// Read all data to allow reuse connection (http://bit.ly/1ad35PY)
IoUtils.readAndCloseStream(conn.getErrorStream());
throw e;
}
if (!shouldBeProcessed(conn)) {
IoUtils.closeSilently(imageStream);
throw new IOException("Image request failed with response code " + conn.getResponseCode());
}

return new ContentLengthInputStream(new BufferedInputStream(imageStream, BUFFER_SIZE), conn.getContentLength());
}

/**
* @param conn Opened request connection (response code is available)
* @return <b>true</b> - if data from connection is correct and should be read and processed;
* <b>false</b> - if response contains irrelevant data and shouldn't be processed
* @throws IOException
*/
protected boolean shouldBeProcessed(HttpURLConnection conn) throws IOException {
return conn.getResponseCode() == 200;
}

/**
* Create {@linkplain HttpURLConnection HTTP connection} for incoming URL
*
Expand Down

0 comments on commit eb794c3

Please sign in to comment.