Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



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

Have Programming Question? Ask it here!
 
 
 


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


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

Advertisement
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 Tutorials/Questions & Answers:
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
Advertisements
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
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 do I compare strings in Java?
How do I compare strings in Java?  How do I compare strings in Java
How do I decompile Java class files?
How do I decompile Java class files?  How do I decompile Java class files
How do I initialize a byte array in Java?
How do I initialize a byte array in Java?  How do I initialize a byte array in Java
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 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
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
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
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
How do I write a correct micro-benchmark in Java?
How do I write a correct micro-benchmark in Java?  How do I write a correct micro-benchmark in Java
How do I set environment variables from Java?
How do I set environment variables from Java?  How do I set environment variables from Java
How do I handle the reaction of a circle and a semi-circle colliding in java?
How do I handle the reaction of a circle and a semi-circle colliding in java?  How do I handle the reaction of a circle and a semi-circle colliding in java
How do I upgrade mysql?
How do I upgrade mysql?  How do I upgrade mysql
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
How do I throw a 404 error from within a java servlet?
How do I throw a 404 error from within a java servlet?  How you can write code in Servlet for throwing the httpd error 404? How to add the configuration for handling the not found error in the web.xml file? Thanks   
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 to disable task manager using java
How to disable task manager using java  How to disable task manager using java
how do i solve this problem?
how do i solve this problem?  Define a class named Circle with the following properties: List item An integer data field named radius with protected access modifier, and a String data field named colour with private access
how do i solve this question?
how do i solve this question?  1.Define a class named Circle with the following properties: a) An integer data field named radius with protected access modifier, and a String data field named colour with private access modifier
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
I developed a simple java web project in Struts now If I have to import the project in Eclipse Indigo how can I do it
I developed a simple java web project in Struts now If I have to import the project in Eclipse Indigo how can I do it   I developed a simple java web project in Struts now If I have to import the project in Eclipse Indigo how
how to create a php script to download file
how to create a php script to download file  php script to download file
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 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
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 do I generate random number?
How do I generate random number?  In my Java program there is a requirement of generating random numbers between two given numbers. How do I write...: Generate random numbers in Java. Thanks
How do we create session factory in hibernate?
How do we create session factory in hibernate?  Hi, How do we create session factory in hibernate? thanks
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 do I compile the registration form?
How do I compile the registration form?  How do I compile the registration form as stated at the bottom of the following page (URL is below). Do I need ANT? If so, please give instructions. I am a student. http
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..."); System.out.println("| q. Quit"); question = console.next().charAt(0
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..."); System.out.println("| q. Quit"); question = console.next().charAt(0
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..."); System.out.println("| q. Quit"); question = console.next().charAt(0
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..."); System.out.println("| q. Quit"); question = console.next().charAt(0
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 can i create a data grid - Java Beginners
how can i create a data grid  Nice to ur respose...thnks all of u plz help me i want make a datagrid but i have no idea about this how can i create datagrid. and how can i connect to the database plz help me give
how do i grab the url in php?
how do i grab the url in php?  I want to grab the 'entire' url, including any special characters like & and #, from a site. I then want... # = %23 I tried URL encoding but it only grabs the part until the #, which
I want Mini Java Project for Student Admission System. actually i want 2 know how 2 start this...please show me my way.....
I want Mini Java Project for Student Admission System. actually i want 2 know how 2 start this...please show me my way.....  I want Mini Java Project for Student Admission System. actually i want 2 know how 2 start this...please
how I do select from select in hql
how I do select from select in hql  select RN from ( select rownum RN, dbid from ( select * from profile p where type = 1912 and name like 'a%' order by globalid ) ) where db_id = 259; this is the sql The below hql
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
How to integrate IBM case Manager with Java Applicarion(JSP or core java)
How to integrate IBM case Manager with Java Applicarion(JSP or core java)  Dear All, Its really important for me to demonstrate a POC (Proof of Concept) on integrating IBM Case Manager with Java Application. Any small help
how to start a java project from scratch level
how to start a java project from scratch level   1.how to start a java project from scratch level ?can u give me small example from design to development process
How a beginner can start Java Programming?
How a beginner can start Java Programming?  I Just have programming knowledge of C & C++. Let's know how I can learn Java? Is there any Java... have programming language of C and C++ then you can learn Java programming
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
how to create a php script to download file from database mysql
how to create a php script to download file from database mysql  how to create a php script to download file from databse mysql
how to create a php script to download file from database mysql
how to create a php script to download file from database mysql  how to create a php script to download file from databse mysql
Advertisements
 

 

 

DMCA.com