| 
36676
 | 
     1  | 
/*  Title:      Pure/System/download.scala
  | 
| 
34218
 | 
     2  | 
    Author:     Makarius
  | 
| 
 | 
     3  | 
  | 
| 
 | 
     4  | 
Download URLs -- with progress monitor.
  | 
| 
 | 
     5  | 
*/
  | 
| 
 | 
     6  | 
  | 
| 
 | 
     7  | 
package isabelle
  | 
| 
 | 
     8  | 
  | 
| 
 | 
     9  | 
  | 
| 
34220
 | 
    10  | 
import java.io.{BufferedInputStream, BufferedOutputStream, FileOutputStream,
 | 
| 
 | 
    11  | 
  File, InterruptedIOException}
  | 
| 
34218
 | 
    12  | 
import java.net.{URL, URLConnection}
 | 
| 
 | 
    13  | 
import java.awt.{Component, HeadlessException}
 | 
| 
 | 
    14  | 
import javax.swing.ProgressMonitorInputStream
  | 
| 
 | 
    15  | 
  | 
| 
 | 
    16  | 
  | 
| 
 | 
    17  | 
object Download
  | 
| 
 | 
    18  | 
{
 | 
| 
39703
 | 
    19  | 
  def stream(parent: Component, title: String, url: URL): (URLConnection, BufferedInputStream) =
  | 
| 
34218
 | 
    20  | 
  {
 | 
| 
 | 
    21  | 
    val connection = url.openConnection
  | 
| 
 | 
    22  | 
  | 
| 
39703
 | 
    23  | 
    val stream = new ProgressMonitorInputStream(parent, title, connection.getInputStream)
  | 
| 
34218
 | 
    24  | 
    val monitor = stream.getProgressMonitor
  | 
| 
 | 
    25  | 
    monitor.setNote(connection.getURL.toString)
  | 
| 
 | 
    26  | 
  | 
| 
 | 
    27  | 
    val length = connection.getContentLength
  | 
| 
 | 
    28  | 
    if (length != -1) monitor.setMaximum(length)
  | 
| 
 | 
    29  | 
  | 
| 
 | 
    30  | 
    (connection, new BufferedInputStream(stream))
  | 
| 
 | 
    31  | 
  }
  | 
| 
 | 
    32  | 
  | 
| 
39703
 | 
    33  | 
  def file(parent: Component, title: String, url: URL, file: File)
  | 
| 
34218
 | 
    34  | 
  {
 | 
| 
39703
 | 
    35  | 
    val (connection, instream) = stream(parent, title, url)
  | 
| 
34218
 | 
    36  | 
    val mod_time = connection.getLastModified
  | 
| 
 | 
    37  | 
  | 
| 
34220
 | 
    38  | 
    def read() =
  | 
| 
 | 
    39  | 
      try { instream.read }
 | 
| 
39703
 | 
    40  | 
      catch { case _ : InterruptedIOException => error("Canceled by user") }
 | 
| 
34220
 | 
    41  | 
    try {
 | 
| 
 | 
    42  | 
      val outstream = new BufferedOutputStream(new FileOutputStream(file))
  | 
| 
 | 
    43  | 
      try {
 | 
| 
 | 
    44  | 
        var c: Int = 0
  | 
| 
39730
 | 
    45  | 
        while ({ c = read(); c != -1 }) outstream.write(c)
 | 
| 
34220
 | 
    46  | 
      }
  | 
| 
 | 
    47  | 
      finally { outstream.close }
 | 
| 
 | 
    48  | 
      if (mod_time > 0) file.setLastModified(mod_time)
  | 
| 
 | 
    49  | 
    }
  | 
| 
 | 
    50  | 
    finally { instream.close }
 | 
| 
34218
 | 
    51  | 
  }
  | 
| 
 | 
    52  | 
}
  | 
| 
 | 
    53  | 
  |