Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  package com.webimageloader.loader;
  
  import java.io.Closeable;
  import java.net.URL;
 import java.util.Map;
 
 
 
 public class NetworkLoader implements LoaderCloseable {
     private static final String TAG = "NetworkLoader";
 
     private static final int TAG_REGULAR = 0x7eb00000;
     private static final int TAG_CONDITIONAL = 0x7eb0000c;
 
     private int connectionTimeout;
     private int readTimeout;
     private long defaultMaxAge;
     private long forcedMaxAge;
 
     private BackgroundLoader regularLoader;
 
     public NetworkLoader(Builder builder) {
         this. = Collections.unmodifiableMap(builder.streamHandlers);
         this. = builder.connectionFactory;
         this. = builder.connectionHandler;
         this. = builder.connectionTimeout;
         this. = builder.readTimeout;
         this. = builder.defaultMaxAge;
         this. = builder.forcedMaxAge;
 
          = new NetworkLoaderImpl("Network".builder.threadCount);
          = new NetworkLoaderImpl("Network, cache check"., 1);
     }
 
     @Override
     public void load(LoaderWork.Manager managerLoaderRequest request) {
         if (request.getMetadata() != null) {
             .load(managerrequest);
         } else {
             .load(managerrequest);
         }
     }
 
     @Override
     public void close() throws IOException {
         .close();
         .close();
     }
 
     private class NetworkLoaderImpl extends SimpleBackgroundLoader {
         public NetworkLoaderImpl(String nameint priorityint threadCount) {
             super(nameprioritythreadCount);
         }
 
         @Override
         protected void loadInBackground(LoaderWork.Manager managerLoaderRequest requestthrows Exception {
             String url = request.getUrl();
 
             String protocol = getProtocol(url);
             URLStreamHandler streamHandler = getURLStreamHandler(protocol);
 
             URLConnection urlConnection = openConnection(new URL(nullurlstreamHandler));
 
             Metadata metadata = request.getMetadata();
             if (metadata != null) {
                 tag();
 
                 // We have some information available
                 long modifiedSince = metadata.getLastModified();
                 if (modifiedSince != 0) {
                     urlConnection.setIfModifiedSince(modifiedSince);
                 }
 
                 String etag = metadata.getEtag();
                 if (!TextUtils.isEmpty(etag)) {
                    urlConnection.addRequestProperty("If-None-Match"etag);
                }
            } else {
                tag();
            }
            String contentType = urlConnection.getContentType();
            long lastModified = urlConnection.getLastModified();
            long expires = getExpires(urlConnection);
            String etag = urlConnection.getHeaderField("ETag");
            // Update metadata
            metadata = new Metadata(contentTypelastModifiedexpiresetag);
            if (getResponseCode(urlConnection) == .) {
                if (.) Log.v(request + " was not modified since last fetch");
                manager.deliverNotMotified(metadata);
            } else {
                if (.) Log.v("Loaded " + request + " from network");
                manager.deliverStream(new NetworkInputSupplier(urlConnection), metadata);
            }
        }
    }
    private int getResponseCode(URLConnection urlConnectionthrows IOException {
        // We can't assume we have a HttpUrlConnection as resources uses a custom subclass
        if (urlConnection instanceof HttpURLConnection) {
            return ((HttpURLConnectionurlConnection).getResponseCode();
        } else {
            return -1;
        }
    }
    private long getExpires(URLConnection urlConnection) {
        if ( > 0) {
            return System.currentTimeMillis() + ;
        } else if ( == .) {
            return .;
        }
        // Prefer "max-age" before "expires"
        long maxAge = HeaderParser.getMaxAge(urlConnection);
        if (maxAge > 0) {
            return System.currentTimeMillis() + maxAge * 1000;
        }
        long expires = urlConnection.getExpiration();
        if (expires > 0) {
            return expires;
        }
        // Use default
        return System.currentTimeMillis() + ;
    }
    private URLConnection openConnection(URL urlthrows IOException {
        final URLConnection urlConnection;
        if ( != null && isHttp(url.getProtocol())) {
            // For http(s) URLs, give the user a chance to set their own connection implementation
            urlConnection = .openConnection(url);
        } else {
            urlConnection = url.openConnection();
        }
        if ( > 0) {
            urlConnection.setConnectTimeout();
        }
        if ( > 0) {
            urlConnection.setReadTimeout();
        }
        if ( != null && urlConnection instanceof HttpURLConnection) {
            // Only let the connection handler handle http requests
            .handleConnection((HttpURLConnectionurlConnection);
        }
        return urlConnection;
    }
    private boolean isHttp(String protocol) {
        return protocol.equals("http") || protocol.equals("https");
    }
    @TargetApi(14)
    private void tag(int tag) {
        if (Android.isAPI(14)) {
            TrafficStats.setThreadStatsTag(tag);
        }
    }

    
Workaround for bug pre-Froyo, see here for more info: http://android-developers.blogspot.com/2011/09/androids-http-clients.html
    private static void disableConnectionReuseIfNecessary() {
        // HTTP connection reuse which was buggy pre-froyo
        if (!Android.isAPI(8)) {
            System.setProperty("http.keepAlive""false");
        }
    }
    private static String getProtocol(String url) {
        int i = url.indexOf(':');
        return i == -1 ? null : url.substring(0, i);
    }
    private URLStreamHandler getURLStreamHandler(String protocol) {
        return .get(protocol);
    }
    private class NetworkInputSupplier implements InputSupplier {
        private URLConnection connection;
        private URL url;
        private long length;
        public NetworkInputSupplier(URLConnection connection) {
            this. = connection;
             = connection.getURL();
            // XXX: This returns a int which could be too small
             = connection.getContentLength();
        }
        @Override
        public long getLength() throws IOException {
            return ;
        }
        @Override
        public InputStream getInput() throws IOException {
            if ( != null) {
                InputStream is = .getInputStream();
                 = null;
                // Handle a bug in older versions of Android, see
                // http://android-developers.blogspot.se/2010/07/multithreading-for-performance.html
                if (!Android.isAPI(9)) {
                    is = new FlushedInputStream(is);
                }
                return is;
            } else {
                return openConnection().getInputStream();
            }
        }
    }
    public static class Builder {
        private HashMap<StringURLStreamHandlerstreamHandlers;
        private ConnectionFactory connectionFactory;
        private ConnectionHandler connectionHandler;
        private int threadCount = .;
        private int connectionTimeout = .;
        private int readTimeout = .;
        private long defaultMaxAge = .;
        private long forcedMaxAge = .;
        public Builder() {
             = new HashMap<StringURLStreamHandler>();
        }
        public Builder addURLSchemeHandler(String schemeURLStreamHandler handler) {
            .put(schemehandler);
            return this;
        }
        public Builder setConnectionFactory(ConnectionFactory factory) {
             = factory;
            return this;
        }
        public Builder setConnectionHandler(ConnectionHandler handler) {
             = handler;
            return this;
        }
        public Builder setThreadCount(int count) {
            this. = count;
            return this;
        }
        public Builder setConnectionTimeout(int connectionTimeout) {
            this. = connectionTimeout;
            return this;
        }
        public Builder setReadTimeout(int readTimeout) {
            this. = readTimeout;
            return this;
        }
        public Builder setDefaultCacheMaxAge(long maxAge) {
            this. = maxAge;
            return this;
        }
        public Builder setCacheMaxAge(long maxAge) {
            this. = maxAge;
            return this;
        }
    }
New to GrepCode? Check out our FAQ X