Home Answers Viewqa JSP-Servlet How do i start to create Download Manager in Java

 
 


chaitanya
How do i start to create Download Manager in Java
1 Answer(s)      2 years and 9 months ago
Posted in : JSP-Servlet

Can you tell me from where do i start to develop Download manager in java.
View Answers

July 12, 2011 at 6:11 PM


import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.Observable; import java.util.Observer; import java.util.Properties; import javax.swing.BorderFactory; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JProgressBar; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.AbstractTableModel; import javax.swing.table.TableCellRenderer;

public class DownloadManager extends JFrame implements Observer { private JTextField addTextField = new JTextField(30);

private DownloadsTableModel tableModel = new DownloadsTableModel();

private JTable table;

private JButton pauseButton = new JButton("Pause");

private JButton resumeButton = new JButton("Resume");

private JButton cancelButton, clearButton;

private JLabel saveFileLabel = new JLabel();

private Download selectedDownload;

private boolean clearing;

public DownloadManager() { setTitle("Marvin's Download Manager"); setSize(640, 480); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); JMenuBar menuBar = new JMenuBar(); JMenu fileMenu = new JMenu("File"); fileMenu.setMnemonic(KeyEvent.VK_F); JMenuItem fileExitMenuItem = new JMenuItem("Exit", KeyEvent.VK_X); fileExitMenuItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { System.exit(0); } }); fileMenu.add(fileExitMenuItem); menuBar.add(fileMenu); setJMenuBar(menuBar);

// Set up add panel. JPanel addPanel = new JPanel(new BorderLayout());

JPanel targetPanel = new JPanel(new BorderLayout()); targetPanel.add(addTextField, BorderLayout.WEST); JButton addButton = new JButton("Add Download"); addButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { actionAdd(); } });

targetPanel.add(addButton, BorderLayout.EAST);

JPanel destinationPanel = new JPanel(new BorderLayout()); saveFileLabel.setText("File:"); destinationPanel.add(saveFileLabel, BorderLayout.WEST);

JButton saveFileButton = new JButton("Download To"); saveFileButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { actionSaveTo(); } }); destinationPanel.add(saveFileButton, BorderLayout.EAST); addPanel.add(destinationPanel, BorderLayout.NORTH); addPanel.add(targetPanel, BorderLayout.SOUTH);

// Set up Downloads table.

table = new JTable(tableModel); table.getSelectionModel().addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { tableSelectionChanged(); } }); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

ProgressRenderer renderer = new ProgressRenderer(0, 100); renderer.setStringPainted(true); // show progress text table.setDefaultRenderer(JProgressBar.class, renderer);

table.setRowHeight((int) renderer.getPreferredSize().getHeight());

JPanel downloadsPanel = new JPanel(); downloadsPanel.setBorder(BorderFactory.createTitledBorder("Downloads")); downloadsPanel.setLayout(new BorderLayout()); downloadsPanel.add(new JScrollPane(table), BorderLayout.CENTER);

JPanel buttonsPanel = new JPanel();

pauseButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { actionPause(); } }); pauseButton.setEnabled(false); buttonsPanel.add(pauseButton);

resumeButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { actionResume(); } }); resumeButton.setEnabled(false); buttonsPanel.add(resumeButton); cancelButton = new JButton("Cancel"); cancelButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { actionCancel(); } }); cancelButton.setEnabled(false); buttonsPanel.add(cancelButton); clearButton = new JButton("Clear"); clearButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { actionClear(); } }); clearButton.setEnabled(false); buttonsPanel.add(clearButton);

getContentPane().setLayout(new BorderLayout()); getContentPane().add(addPanel, BorderLayout.NORTH); getContentPane().add(downloadsPanel, BorderLayout.CENTER); getContentPane().add(buttonsPanel, BorderLayout.SOUTH); }

private void actionSaveTo() {

JFileChooser jfchooser = new JFileChooser();

jfchooser.setApproveButtonText("OK"); jfchooser.setDialogTitle("Save To"); jfchooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);

int result = jfchooser.showOpenDialog(this); File newZipFile = jfchooser.getSelectedFile(); System.out.println("importProfile:" + newZipFile); this.saveFileLabel.setText(newZipFile.getPath());

}

private void actionAdd() { URL verifiedUrl = verifyUrl(addTextField.getText()); if (verifiedUrl != null) { tableModel.addDownload(new Download(verifiedUrl, saveFileLabel.getText())); addTextField.setText(""); // reset add text field } else { JOptionPane.showMessageDialog(this, "Invalid Download URL", "Error", JOptionPane.ERROR_MESSAGE); } }

private URL verifyUrl(String url) { if (!url.toLowerCase().startsWith("http://")) return null;

URL verifiedUrl = null; try { verifiedUrl = new URL(url); } catch (Exception e) { return null; }

if (verifiedUrl.getFile().length() < 2) return null;

return verifiedUrl; }

private void tableSelectionChanged() { if (selectedDownload != null) selectedDownload.deleteObserver(DownloadManager.this);

if (!clearing && table.getSelectedRow() > -1) { selectedDownload = tableModel.getDownload(table.getSelectedRow()); selectedDownload.addObserver(DownloadManager.this); updateButtons(); } }

private void actionPause() { selectedDownload.pause(); updateButtons(); }

private void actionResume() { selectedDownload.resume(); updateButtons(); }

private void actionCancel() { selectedDownload.cancel(); updateButtons(); }

private void actionClear() { clearing = true; tableModel.clearDownload(table.getSelectedRow()); clearing = false; selectedDownload = null; updateButtons(); }

private void updateButtons() { if (selectedDownload != null) { int status = selectedDownload.getStatus(); switch (status) { case Download.DOWNLOADING: pauseButton.setEnabled(true); resumeButton.setEnabled(false); cancelButton.setEnabled(true); clearButton.setEnabled(false); break; case Download.PAUSED: pauseButton.setEnabled(false); resumeButton.setEnabled(true); cancelButton.setEnabled(true); clearButton.setEnabled(false); break; case Download.ERROR: pauseButton.setEnabled(false); resumeButton.setEnabled(true); cancelButton.setEnabled(false); clearButton.setEnabled(true); break; default: // COMPLETE or CANCELLED pauseButton.setEnabled(false); resumeButton.setEnabled(false); cancelButton.setEnabled(false); clearButton.setEnabled(true); } } else { pauseButton.setEnabled(false); resumeButton.setEnabled(false); cancelButton.setEnabled(false); clearButton.setEnabled(false); } }

public void update(Observable o, Object arg) { // Update buttons if the selected download has changed. if (selectedDownload != null && selectedDownload.equals(o)) updateButtons(); }

// Run the Download Manager. public static void main(String[] args) { DownloadManager manager = new DownloadManager(); manager.setVisible(true); } }

class Download extends Observable implements Runnable { private static final int MAXBUFFERSIZE = 1024;

public static final String STATUSES[] = { "Downloading", "Paused", "Complete", "Cancelled", "Error" };

public static final int DOWNLOADING = 0;

public static final int PAUSED = 1;

public static final int COMPLETE = 2;

public static final int CANCELLED = 3;

public static final int ERROR = 4;

private URL url; // download URL

private String saveDir; // dir to save

private int size; // size of download in bytes

private int downloaded; // number of bytes downloaded

private int status; // current status of download

// Proxy information public static final boolean proxyRequired = true; // Change for your settings public static final String proxyIP = "127.0.0.1"; public static final String proxyPort = "8080"; public static final String proxyUsername = "proxyUser"; public static final String proxyPassword = "proxyPassword";

// Constructor for Download. public Download(URL url, String saveDir) { this.url = url; this.saveDir = saveDir; size = -1; downloaded = 0; status = DOWNLOADING;

// Begin the download. download(); }

// Get this download's URL. public String getUrl() { return url.toString(); }

// Get this download's size. public int getSize() { return size; }

// Get this download's progress. public float getProgress() { return ((float) downloaded / size) * 100; }

public int getStatus() { return status; }

public void pause() { status = PAUSED; stateChanged(); }

public void resume() { status = DOWNLOADING; stateChanged(); download(); }

public void cancel() { status = CANCELLED; stateChanged(); }

private void error() { status = ERROR; stateChanged(); }

private void download() { Thread thread = new Thread(this); thread.start(); }

// Get file name portion of URL. public String getFileName(URL url) { String fileName = url.getFile(); return fileName.substring(fileName.lastIndexOf('/') + 1); }

// Download file. public void run() { RandomAccessFile file = null; InputStream stream = null; FileOutputStream out = null;

try {

if (proxyRequired){ // This can be put in a menu, updated via interface System.out.println("Setting proxy"); Properties systemSettings = System.getProperties(); systemSettings.put("http.proxyHost", proxyIP); systemSettings.put("http.proxyPort", proxyPort); System.setProperties(systemSettings); }

// Open connection to URL. HttpURLConnection connection = (HttpURLConnection) url.openConnection();

// Specify what portion of file to download. connection.setRequestProperty("Range", "bytes=" + downloaded + "-");

if (proxyRequired){ String encoded = new String(new sun.misc.BASE64Encoder().encode(new String( proxyUsername + ":" + proxyPassword).getBytes())); connection.setRequestProperty("Proxy-Authorization", "Basic " + encoded); }

System.out.println("Going to make connection"); // Connect to server. connection.connect(); System.out.println("Connected!");

int responseCode = connection.getResponseCode(); System.out.println("Response code from server=" + responseCode);

// Make sure response code is in the 200 range. // 200 - no partial download // 206 - supports resume //if (responseCode / 100 != 2) { if (responseCode == 200 || responseCode == 206) { error(); }

// Check for valid content length. System.out.println("Content length=" + connection.getContentLength()); int contentLength = connection.getContentLength(); if (contentLength < 1) { error(); }

/* * Set the size for this download if it hasn't been already set. */ if (size == -1) { size = contentLength; stateChanged(); }

// Open file and seek to the end of it. file = new RandomAccessFile(getFileName(url), "rw"); file.seek(downloaded);

System.out.println("Get InputStream"); stream = connection.getInputStream(); status = DOWNLOADING; out = new FileOutputStream(saveDir + File.separator + this.getFileName(url)); while (status == DOWNLOADING) { /* * Size buffer according to how much of the file is left to download. */ byte buffer[]; if (size - downloaded > MAXBUFFERSIZE) { buffer = new byte[MAXBUFFERSIZE]; } else { buffer = new byte[size - downloaded]; }

// Read from server into buffer. int read = stream.read(buffer); if (read == -1) break;

// Write buffer to file. //file.write(buffer, 0, read); out.write(buffer, 0, read); downloaded += read; stateChanged(); }

/* * Change status to complete if this point was reached because downloading * has finished. */ if (status == DOWNLOADING) { status = COMPLETE;

stateChanged(); } } catch (Exception e) { System.out.println("Error=" + e); e.printStackTrace(); error(); } finally {

// Close file. if (file != null) { try { // Complete the file out.close(); file.close(); } catch (Exception e) { e.printStackTrace(); } }

// Close connection to server. if (stream != null) { try { stream.close(); } catch (Exception e) { e.printStackTrace(); } } } }

private void stateChanged() { setChanged(); notifyObservers(); } }

class DownloadsTableModel extends AbstractTableModel implements Observer { private static final String[] columnNames = { "URL", "Size", "Progress", "Status" };

private static final Class[] columnClasses = { String.class, String.class, JProgressBar.class, String.class };

private ArrayList<Download> downloadList = new ArrayList<Download>();

public void addDownload(Download download) { download.addObserver(this); downloadList.add(download); fireTableRowsInserted(getRowCount() - 1, getRowCount() - 1); }

public Download getDownload(int row) { return (Download) downloadList.get(row); }

public void clearDownload(int row) { downloadList.remove(row); fireTableRowsDeleted(row, row); }

public int getColumnCount() { return columnNames.length; }

public String getColumnName(int col) { return columnNames[col]; }

public Class getColumnClass(int col) { return columnClasses[col]; }

public int getRowCount() { return downloadList.size(); }

public Object getValueAt(int row, int col) { Download download = downloadList.get(row); switch (col) { case 0: // URL return download.getUrl(); case 1: // Size int size = download.getSize(); return (size == -1) ? "" : Integer.toString(size); case 2: // Progress return new Float(download.getProgress()); case 3: // Status return Download.STATUSES[download.getStatus()]; } return ""; }

public void update(Observable o, Object arg) { int index = downloadList.indexOf(o); fireTableRowsUpdated(index, index); } }

class ProgressRenderer extends JProgressBar implements TableCellRenderer { public ProgressRenderer(int min, int max) { super(min, max); }

public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { setValue((int) ((Float) value).floatValue()); return this; }

}

To Run

Copy the code above, and paste into a DownloadManager.java file
If you?re behind a proxy, change the proxy settings.
If you?re not behind a proxy, set the proxyRequired = false;
Compile and run

To Download Files

Select the folder you want to save the file
Copy the URL of the file you want to download
Paste to the textbox
Click ?Add to Download?
File will automatically be downloaded
You can click ?Pause? to temporary stop download

Enhancement

Persists directly the file downloaded even if not 100% completed 
File splitting, download a single file with multiple threads

Other useful references

http://www.intel.com/cd/ids/developer/asmo-na/eng/20188.htm?page=1

http://www.intel.com/cd/ids/developer/asmo-na/eng/20187.htm









Related Pages:
How do i start to create Download Manager in Java - JSP-Servlet
How do i start to create Download Manager in Java  Can you tell me from where do i start to develop Download manager in java
How do i create the node for target SMO in java..???
How do i create the node for target SMO in java..???  How do i create the node for target SMO in java..??? or else whats the method for accessing the target SMO
how to upload and download images in java?
how to upload and download images in java?  what is the code for uploading and downloading images in java? how do I make a photo gallery through JSP? I want to create a photo gallery for each user which can be viewed by all users
how do i allow users to download a xls file in html?
how do i allow users to download a xls file in html?  can anyone help me to allow users to download a xls file in html? i tried with href="path...;i tried with href="path/filename.xls click here but it works only in chrome
Java Web Start and Java Plug-in
Java Web Start should check for updates on the web, and what to do when.... In Jnlp file Java Web Start will use the <description> element to create... Java Web Start Enhancements in version 6  
Configuring Struts DataSource Manager on Tomcat 5
Configuring Struts DataSource Manager on Tomcat 5       This tutorial shows you how you can configure Struts DataSource Manager on the Tomcat 5.5.9 server. We will use
how do i begin a two dimensional array?
how do i begin a two dimensional array?  I'm new to java programming and need to create a two dimensional array that enters exactly what is entered in the first dimension and then the first non-white space character of what
How do I use JGraph to create a MST(minimum spanning tree) using java?
How do I use JGraph to create a MST(minimum spanning tree) using java?  How do I use JGraph to create a MST(minimum spanning tree) using java? thanks for the help
How can i download these java related materials from rose india
How can i download these java related materials from rose india  How can i download these java related materials from rose india   Hello... tutorial do you want to download from the site? Please specify it. Thanks
what is java and why do i need it?
what is java and why do i need it?  Hi, Please tell me what is Java and why do i need it? Is it free to download? Also explain me how to write and test my first Java Application? What is the configuration or system requirement
How to create function download in web services with java? - WebSevices
How to create function download in web services with java?  I am a student in Viet Nam, I am coding a project j2me access web services to download a file.xml, anybody please help me how to creates function download in web
Which java can i download?
Which java can i download?  Hello, i'm a beginner on java. Which java can i download for to exercise with my codes? Thanks in advance.   nobody.   And i download Eclipse java. But when i want to install
Programming: Hammurabi I - Project start
Java: Programming: Hammurabi I - Project start Copy these files to start your project The Hammurabi I program may require a number of things that you... that must be extended are marked with "TODO" (ie, things remaining "to do
Java Kick Start - Java Beginners
Java Kick Start  Hello Sir, i like to become a good developer in Java. Im good in JAVA basics. So how to get started with any kind of application development in Java. Please do help me with this as im not finding any kind of good
Struts Quick Start
Struts Quick Start Struts Quick Start to Struts technology In this post I will show you how you can quick start the development of you struts based project... applications in Java technology. Struts is one of the most used framework
How do i do the coding for 'leaving a comment' in java
How do i do the coding for 'leaving a comment' in java  i am designing a webpage.In my webpage i want to add the option of adding a comment by the readers of the page.how do i do
how to start with java - Java Beginners
how to start with java  sir i am new to java and i need the guidence how to start with it . i am doing my MCA final semester project . the project.... framework - struts database - postgreSQL and java and jsp is used
How to download Java
How to download Java  Hi, My windows 7 computer is ready. Now I want to download and install Java. Can anyone tell me How to download Java and then install on my computer. Thanks
how do i write a java program for this??
how do i write a java program for this??  â??Ask the user if they have a dog. If â??yesâ??, ask the user how old is and compute the dogâ??s age in human years. Display the output. If â??noâ?? ask the user their age and compute
Open Source Download Manager
Open Source Download Manager Open source Download manager A download manager is a computer program designed to download files from the Internet... and regularly updating them.    Free Download CFile Manager Open source
How do I do this program? I'm new to Java programming...
How do I do this program? I'm new to Java programming...  Suppose you want to print out numbers in brackets, formatted as follows: [1] [2] [3] and so on. Write a method that takes two parameters: howMany and lineLength
Download Java
process of downloading and Installing Java  Hi, How easy is the process of downloading and Installing Java? I have windows 7 machines. Can anyone tell me how to download and install Java? Thanks
layout manager
layout manager  how to use Absolute Layout manager in java form
Explain about threads:how to start program in threads?
Explain about threads:how to start program in threads?  import...() { for(int i=1;i<=26;i++) { System.out.println((char)i); } } public void run() { print
How do we create custom component
How do we create custom component  How do we create custom component in JSF. I couldnot find any category for JSF questions
how to download file
how to download file  How do I let people download a file from my page
how to launch a web application using java web start in netbeans ide?
web start in Netbeans IDE, Please can anyone help me how to do this...I knw...how to launch a web application using java web start in netbeans ide? ... but i dont knw how to do with web application, Please can anyone help me or send
PureStack question---i dont know how to do this
PureStack question---i dont know how to do this  Write a stack class... will look like after perform each of the following sequence of events: a. start... the queue g. H and I join the queue h. G leaves the queue i. H and I leave
PureStack question---i dont know how to do this
PureStack question---i dont know how to do this  Write a stack class... will look like after perform each of the following sequence of events: a. start... the queue g. H and I join the queue h. G leaves the queue i. H and I leave
How to create a class in java
How to create a class in java  I am a beginner in programming and tried to learn how to do programming in Java. Friends please explain how can I create a class in Java
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO FOR THIS CODING
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO.... Print the list"); System.out.println("| i. Print the list from...': PrintList(); case 'i': PrintListSpecific(); case 'j
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO FOR THIS CODING
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO.... Print the list"); System.out.println("| i. Print the list from...': PrintList(); case 'i': PrintListSpecific(); case 'j
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO FOR THIS CODING
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO.... Print the list"); System.out.println("| i. Print the list from...': PrintList(); case 'i': PrintListSpecific(); case 'j
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO FOR THIS CODING
HOW TO I CHANGE THE SWITCH TO IF ELSE OR DO WHILE OR WHILE DO.... Print the list"); System.out.println("| i. Print the list from...': PrintList(); case 'i': PrintListSpecific(); case 'j
download excel
download excel  hi i create an excel file but i don't i know how to give download link to that excel file please give me any code or steps to give download link
java how to create visual swing editor
java how to create visual swing editor   How do I create a visual swing designer in java ?Meaning that I can "draw" a button,a JTextArea from within my designer program . I just need some basics . I've got no idea how to start
could not start server. - EJB
comes ---sun java server could not start. so what should I do to start this server...could not start server.  Dear All I have installed netbeans 5.5.1 and sun java Application server 9.2 to run ejb program. But when I start
HOW TO DO WEBSITE INTERFACE FOR JAVA MODULE
HOW TO DO WEBSITE INTERFACE FOR JAVA MODULE  Hi , Greetings. I... information etc. All these modules work fine in browser. I use JCreator. How to place... , student regis. modules is displayed and so on. What need to do to create
Photo upload, Download
from server side. I want to save the photo with a given name. How can i do... application for java(Swings). And i am using MySQL as backend database. My... dont know whether this code proper) . My question is how can i load
Task manager enable and disable thru java
Task manager enable and disable thru java  I would like to know, how to enable and disable task manager using java. Kindly, please Let me know
May I know how to create a web page?
May I know how to create a web page?  can u suggest me how to start
what should i do next?? - Java Beginners
what should i do next??  I know java basics.actully i passed the SCJP exam.Then now i have no idea about what should i do next.I like to come... if u don't know how to install the software of java also u can from him.He
Java Web Start Enhancements in version 6
supported. It describes the applications preferences for how Java Web Start... Java Web Start Enhancements in version 6  ...; Prior to Java SE 6, In Java Web Start <offline-allowed> element
Download Eclipse Helios And Add The Tomcat7 For Java EE6
Download Eclipse Helios And Add The Tomcat7 For Java EE6 In this tutorial you will learn how to download the Eclipse Helios IDE and how to add the tomcat7 application server in Eclipse. You can download the Eclipse Helios IDE for Java
Download Hibernate 4
Download Hibernate 4 In this tutorial you will learn about how to download... that which format you are selecting to download. In this tutorial I have...-core-4.0.0.Final.jar" is available. Now when you will start to go to create
How can I start programming with Java
How can I start programming with Java       How can I Start programming with Java? Before getting... the flexible application. To start programming with Java first, download and install
How do i enable java1.5 in netbeans5.5 - IDE Questions
How do i enable java1.5 in netbeans5.5  what is the steps to enable Java 1.5 in netbeans 5.5
How can I do it? .click();
How can I do it? .click();  I have a very unusual problem. I want...("a"); x.click(); </script> So it's click on an element witch one Id's is "a", but I want that it make mouseup in this element. How can I do it, because if I write
how do i upload a file by using servlet or jsp?
how do i upload a file by using servlet or jsp?  hi plz tell me the write java code
start and deploy
start and deploy  how to deployee java web application in glassfish by using netbeans6.7

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.