blackberry java media file is distorted when download is resumed -


i'm developing blackberry app , having issue while resuming download. code works if download isn't interrupted, if interrupted , download re-started, media file distorted.

to allow resuming of download, request file in chunks server , persist last downloaded/written chunk. if i'm restart download, check last downloaded , written chunk, increment , use determine range request server. code listed below..:

public final class downloader extends thread {    private string remotename;   private string localname;   private string parentdir;   private string dirname;   public string filename;    private int chunksize = 512000;   public boolean completed = false;   public boolean failed = false;    public cacheobject cacheobject = null    public downloader(string remotename, string localname, string musictitle, string parentdir, string dirname) {        this.remotename = remotename;        this.parentdir = parentdir;       this.dirname = dirname;       this.localname = localname;       this.securedownload = false;       this.musictitle = musictitle;        this.cacheobject = cachedobject.getinstance().findcachedobject(musictitle);        if (this.cacheobject == null) // create new object           this.cacheobject = new cachedobject(musictitle, remotename);        this.thisobj = this;     }      public void run() {         downloadfile(localname);     }      public void downloadfile(string filename) {         try {             int chunkindex = 0; int totalsize = 0;              string tempfilename = "file:///" + fileconnect.getinstance().file_root+parentdir+ fileconnect.getinstance().file_separator;              if (!fileconnect.getinstance().fileexists(tempfilename))                 fileconnect.getinstance().createdirectory(parentdir);              if (dirname != null) {                 tempfilename = "file:///" + fileconnect.getinstance().file_root+ parentdir + "/" + dirname + fileconnect.getinstance().file_separator;                  if (!fileconnect.getinstance().fileexists(tempfilename))                    fileconnect.getinstance().createdirectory(parentdir + "/" + dirname);             }              filename = tempfilename + filename;             this.filename = filename;               file = (fileconnection) connector.open(filename, connector.read_write);              if (!file.exists()) {                file.create();             }              if(cacheobject.file_path.length() < 1)                 cacheobject.file_path = filename;              file.setwritable(true);              // trying check file size.             long fsize = (int)file.filesize();              // if greater 1 byte, open output stream @ end of file             if(fsize > 1){                 out = file.openoutputstream((fsize+1));             }             else{               out = file.openoutputstream();             }               int rangestart = 0; int rangeend = 0;              // want know total filesize on server (used updating ui..             httpconnection conn2;             conn2 = (httpconnection) util.gethttpconnection(remotename);             string totalfilesize = "" + conn2.getlength();             conn2.close();             //number of chunks            int numchunks = (int) math.ceil( integer.parseint(totalfilesize) / chunksize);             cacheobject.chunk_size = numchunks;              // set total file size..            content_length = integer.parseint(totalfilesize);            filesize = 0;            string url = remotename + httprequestdispatcher.getconnectionstring();              if(cacheobject.last_successfully_downloaded_chunk > -1){               //this resume..               if( (cacheobject.last_successfully_downloaded_chunk + 1) < numchunks ){                   chunkindex = cacheobject.last_successfully_downloaded_chunk + 1;                    filesize = cacheobject.curr_download_size;               }                         }                  while (file != null) {               try{                   conn = (httpconnection)connector.open(url);                    if(chunkindex < (numchunks-2)){                       rangestart = chunkindex * chunksize; rangeend = rangestart + chunksize - 1;                   }                   else{                       rangestart = chunkindex * chunksize;                       int remainingbytes = integer.parseint(totalfilesize) - rangestart; rangeend = rangestart + (remainingbytes - 1);                   }                    conn.setrequestproperty("user-agent", "profile/midp-2.0 configuration/cldc-1.0");                   conn.setrequestproperty("connection", "keep-alive");                     conn.setrequestproperty("range", "bytes=" + rangestart + "-" + rangeend);                   responsecode = conn.getresponsecode();                                    if (responsecode != 200 && responsecode != 206) {                           out.flush(); out.close(); file.close(); in.close(); conn.close();                       in = null; conn = null; file = null; out = null;                       thread.yield(); break;                   }                   else{                       in = conn.openinputstream(); int length = -1;                      byte[] readblock = new byte[256];                       while ((length = in.read(readblock)) != -1) {                          out.write(readblock, 0, length);                          filesize += length;                          cacheobject.curr_download_size = filesize;                      }                       totalsize += filesize;                        in.close(); conn.close(); in = null; conn = null;                        // update after byte read..                       cachemusicbox.last_successfully_downloaded_chunk = chunkindex;                       cachedobject.getinstance().savecachedobject( cacheobject);                        system.out.println("last successful chunk downloaded: " + cacheobject.last_successfully_downloaded_chunk);                        chunkindex++;                       if(chunkindex == numchunks){                           out.flush(); out.close();  file.close(); break;                       }                        thread.yield();                   }               }               // network error related               catch(exception e){                  system.out.println("download failed. kind of error - " + e.getmessage());                  system.out.println("filesize b4 closed: ." + file.filesize());                               system.out.println("last successful chunk downloaded: " + cachemusicbox.last_successfully_downloaded_chunk);                    if (out != null) {                       out.flush(); out.close();                       system.out.println("we closed outputstream");                       system.out.println("filesize when closed: ." + file.filesize());                   }                   if (file != null && file.exists()) {                       if (file.isopen()) {                                     file.close();                       }                   }                    in = null; conn = null; file = null; out = null;                   failed = true;                   system.out.println("ensuring block called " + cacheobject.last_successfully_downloaded_chunk);                    break;               }           }             system.out.println("full file downloaded: " + totalsize + " bytes");           system.out.println("wrote file local storage");           thread.sleep(3000);            if(!failed)               completed = true;         }         // other error...        catch (exception e) {           system.out.println(e.getmessage());            try{               out.flush(); out.close(); file.close();                          in = null; conn = null;   file = null; out = null;           }           catch(exception ee){               system.out.println("while closing catch belongs top guy: " + ee.getmessage());           }           failed = true;         }     }  } 

so got work. did, it'll , save them headaches..:)

if wanna resume download, follow approach:

  1. i checked filesize (according rim, filesize corresponds bytes contained in file) , open outputstream @ end of file.
  2. i start requesting file server end .. e.g filesize 500kb when link went off, start requesting @ range 500-(500+chunksize) till end of file.
  3. and process continues stated in question

Comments

Popular posts from this blog

php - Submit Form Data without Reloading page -

linux - Rails running on virtual machine in Windows -

php - $params->set Array between square bracket -