Home | History | Annotate | Download | only in plugins
      1 package com.jme3.asset.plugins;
      2 
      3 import com.jme3.asset.AssetInfo;
      4 import com.jme3.asset.AssetKey;
      5 import com.jme3.asset.AssetLoadException;
      6 import com.jme3.asset.AssetManager;
      7 import java.io.IOException;
      8 import java.io.InputStream;
      9 import java.net.URL;
     10 import java.net.URLConnection;
     11 
     12 /**
     13  * Handles loading of assets from a URL
     14  *
     15  * @author Kirill Vainer
     16  */
     17 public class UrlAssetInfo extends AssetInfo {
     18 
     19     private URL url;
     20     private InputStream in;
     21 
     22     public static UrlAssetInfo create(AssetManager assetManager, AssetKey key, URL url) throws IOException {
     23         // Check if URL can be reached. This will throw
     24         // IOException which calling code will handle.
     25         URLConnection conn = url.openConnection();
     26         conn.setUseCaches(false);
     27         InputStream in = conn.getInputStream();
     28 
     29         // For some reason url cannot be reached?
     30         if (in == null){
     31             return null;
     32         }else{
     33             return new UrlAssetInfo(assetManager, key, url, in);
     34         }
     35     }
     36 
     37     private UrlAssetInfo(AssetManager assetManager, AssetKey key, URL url, InputStream in) throws IOException {
     38         super(assetManager, key);
     39         this.url = url;
     40         this.in = in;
     41     }
     42 
     43     public boolean hasInitialConnection(){
     44         return in != null;
     45     }
     46 
     47     @Override
     48     public InputStream openStream() {
     49         if (in != null){
     50             // Reuse the already existing stream (only once)
     51             InputStream in2 = in;
     52             in = null;
     53             return in2;
     54         }else{
     55             // Create a new stream for subsequent invocations.
     56             try {
     57                 URLConnection conn = url.openConnection();
     58                 conn.setUseCaches(false);
     59                 return conn.getInputStream();
     60             } catch (IOException ex) {
     61                 throw new AssetLoadException("Failed to read URL " + url, ex);
     62             }
     63         }
     64     }
     65 }
     66