Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
blueBill Core - open source birding Copyright (C) 2009-2011 by Tidalwave s.a.s. (http://www.tidalwave.it) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. WWW: http://bluebill.tidalwave.it SCM: https://java.net/hg/bluebill~core-src /
 
 package it.tidalwave.mobile.util;
 
 import  javax.annotation.Nonnull;
 import  javax.inject.Provider;
 import java.io.File;
 import java.net.URL;
 import  it.tidalwave.netbeans.util.Locator;
 import  it.tidalwave.role.Removable;
 import lombok.Cleanup;

Author(s):
Fabrizio Giudici
Version:
$Id$ /
 
 public class DefaultDownloadable extends Downloadable implements Removable
   {
     private final static Logger log = LoggerFactory.getLogger(DefaultDownloadable.class);
 
     @Nonnull
     public final URL url// FIXME
 
     @Nonnull
     public final URL proxiedUrl;
     
     /* package */ File cachedFile;
             
     /* package */ File downloadFile;
             
     /* package */ File timestampFile;
             
     /* package */ final Provider<MasterFileSystemmasterFileSystem = Locator.createProviderFor(MasterFileSystem.class);
 
     /* package */ int contentLength = 0;

    
/
 
     public DefaultDownloadable (final @Nonnull URL url)
       throws MalformedURLException
       {
         String x = url.toExternalForm().replaceAll(" ""%20");
         
         this. = new URL(x);
         this. = new URL(x); // FIXME: can be eventually different, inject a proxy configurator
         
         .info("        URL: {}"url);
         .info("proxied URL: {}");
         computeCachedFile();
       }

    
/
 
     @Override
     public void download()
       {
         download(false);
       }

    
/
    @Override
    public void refresh()
      {
        download(true);
      }

    
/
    public void remove() 
      throws IOException
      {
        .info("Deleting {}");
        safeDelete();
      }

    
/
    @Override @Nonnull
    public File getFile()
      {
        return ;
      }

    
Can be overridden for testing (URLs are not mockable). /
    @Nonnull
    protected InputStream createInputStream()
      throws IOException
      {
        final URLConnection connection = .openConnection();
        connection.connect();
         = connection.getContentLength(); // TODO: handle the case in which it's unknown size
        return connection.getInputStream();
      }

    
/
    private synchronized void download (final boolean always)
      {
        .info("download() - {}");
        computeCachedFile();
        .info(">>>> will save to {}");
        if (always || ( == .))
          {
            setStatus(.);
            new Thread() // TODO: use a pool, with QUEUED state
              {
                @Override
                public void run()
                  {
                    try
                      {
                        load();
                      }
                    catch (Exception e)
                      {
                        setStatus(.);
                        .error("While loading {}: {}"e);
                        .error("download()"e);
                      }
                  }
              }.start();
          }
      }

    
/
    private void load()
      throws IOException
      {
        .info("load() - into {}");
        final byte[] buffer = new byte[64 * 1024];
        .getParentFile().mkdirs();
        
        if (.exists())
          {
            safeDelete();  
          }
        
        .debug(">>>> writing temporary file {}");
        @Cleanup final InputStream is = createInputStream();
        @Cleanup final OutputStream os = new FileOutputStream();
//        final OutputStream os = fileSystem.get().openFileOutput(getCachedFile());
        // FIXME: first download in cache, at the end copy to the real resource.
        int loaded = 0;
        for (;;)
          {
            final int n = is.read(buffer);
            if (n < 0)
              {
                break;
              }
            os.write(buffer, 0, n);
            loaded += n;
            if ( > 0)
              {
                setDownloadProgress((1.0f * loaded) / );
                .trace("Loaded {} bytes, so far: {} bytes, progress: {}"new Object[]{ nloaded });
              }
          }
        if (.exists())
          {
            safeDelete();  
          }
        
        .debug(">>>> moving {} to {}");
        final @Cleanup FileWriter w = new FileWriter();
        .debug(">>>> creating {}");
        w.write("downloaded: " + System.currentTimeMillis() + "\n");
        
        setStatus(.);
      }

    
/
    @Nonnull
    /* package */ static String normalized (final @Nonnull URL url)
      {
        return url.toExternalForm().replaceAll("://""/").replaceAll("[:;#$?&=]""_");
//        return url.toExternalForm().replaceAll("[:/;#@\\$\\?\\&]", "_").replaceAll("_*", "_");
      }

    
/
    private void computeCachedFile()
      {
        Status newStatus = null;
        synchronized (this)
          {
            if ( == null)
              {
                try
                  {
                    final FileSystem externalFileSystem = .get().getExternalFileSystem();
                    final String prefix = "/Media/" + normalized();
                     = externalFileSystem.getFile(prefix);
                     = externalFileSystem.getFile(prefix + ".download");
                     = externalFileSystem.getFile(prefix + ".timestamp");
                    if (.exists())
                      {
                        newStatus = .;
                      }
                    else
                      {
                        newStatus = .;
                      }
                  }
                catch (IOException e)
                  {
                    newStatus = .;
                    .error("Cannot map to external storage: {}"e);
                    .error("<ctor>"e);
                  }
              }
          }
        if (newStatus != null)
          {
            setStatus(newStatus);
          }
      }
    
    
/
    private static void safeDelete (final @Nonnull File file)
      throws IOException 
      {
        if (!file.delete())
          {
            throw new IOException("Not deleted: " + file); // Java 5 / Android compatibility
          }
      }
  }
New to GrepCode? Check out our FAQ X