// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.util.*;

import javax.swing.*;

public class DownloadApplet extends JApplet implements ActionListener {
    private ArrayList urls;
    private JTextField dir;
    private JTextArea list;
    private JButton download;
    public void init() {
        setSize(500, 400);
        getContentPane().setLayout(new BorderLayout());
        // get URL's
        urls = new ArrayList();
        int n = 1;
        String urlstr;
        while((urlstr = getParameter("url" + n)) != null) {
            urls.add(urlstr);
            n++;
        }
        // setup text field
        dir = new JTextField("C:\\");
        getContentPane().add(dir, BorderLayout.NORTH);
        // setup panel
        list = new JTextArea();
        list.setText("");
        for(int i = 0; i < urls.size(); i++) {
            list.append((String)urls.get(i) + "\r\n");
        }
        getContentPane().add(new JScrollPane(list), BorderLayout.CENTER);
        //setup button
        download = new JButton("Download");
        download.addActionListener(this);
        getContentPane().add(download, BorderLayout.SOUTH);
        // done
        setVisible(true);
    }
    public void actionPerformed(ActionEvent ev) {
        for(int i = 0; i < urls.size(); i++) {
            String urlstr = (String)urls.get(i);
            String fnm = urlstr.substring(urlstr.lastIndexOf("/") + 1);
            if(dir.getText().charAt(dir.getText().length() - 1) != File.separatorChar) {
                fnm = dir.getText() + File.separator + fnm;
            } else {
                fnm = dir.getText() + fnm;
            }
            download(urlstr, fnm);
        }
    }
    private void download(String urlstr, String fnm) {
        try {
            URL url = new URL(urlstr);
            HttpURLConnection con = (HttpURLConnection)url.openConnection();
            con.connect();
            if(con.getResponseCode() == HttpURLConnection.HTTP_OK) {
               InputStream is = con.getInputStream();
               OutputStream os = new FileOutputStream(fnm);
               byte[] b = new byte[100000];
               int n;
               while((n = is.read(b)) >= 0) {
                  os.write(b,0,n);
               }
               os.close();
               is.close();
            }
            con.disconnect();
         } catch (MalformedURLException e) {
             e.printStackTrace();
         } catch (FileNotFoundException e) {
             e.printStackTrace();
         } catch (IOException e) {
             e.printStackTrace();
         }
         JOptionPane.showMessageDialog(this, fnm + " downloaded");
    }
}
