PRESENTATION AND PROJECT SUBMISSION...
Tuesday, 16 July 2013
Monday, 15 July 2013
15th july
DOWNLOAD TABLE MODEL CLASS
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
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 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);
}
}
PROGRESS RENDERER CLASS
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
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;
}
}
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
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 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);
}
}
PROGRESS RENDERER CLASS
import java.awt.*;
import javax.swing.*;
import javax.swing.table.*;
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;
}
}
Friday, 12 July 2013
12 JULY
DOWNLOAD MANAGER CLASS
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class DownloadManager extends JFrame
implements Observer
{
private JTextField addTextField;
private DownloadsTableModel tableModel;
private JTable table;
private JButton pauseButton, resumeButton;
private JButton cancelButton, clearButton;
private Download selectedDownload;
private boolean clearing;
public DownloadManager()
{
setTitle("IDM");
setSize(640, 480);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
actionExit();
}
});
// add panel.
JPanel addPanel = new JPanel();
addPanel.setBackground(Color.darkGray);
addTextField = new JTextField(30);
Font font = new Font("Arial Narrow",Font.ITALIC,22);
addTextField.setFont(font);
addPanel.add(addTextField);
JButton addButton = new JButton();
ImageIcon img = new ImageIcon("C:\\j\\demo\\add.png");
addButton.setIcon(img);
addButton.setBorder(BorderFactory.createEmptyBorder());
addButton.setContentAreaFilled(false);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionAdd();
}
});
addPanel.add(addButton);
//Downloads table.
tableModel = new DownloadsTableModel();
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);
table.setDefaultRenderer(JProgressBar.class, renderer);
table.setRowHeight(
(int) renderer.getPreferredSize().getHeight());
//download panel
JPanel downloadsPanel = new JPanel();
downloadsPanel.setBackground(Color.lightGray);
downloadsPanel.setBorder(
BorderFactory.createTitledBorder("Downloads Area"));
downloadsPanel.setLayout(new BorderLayout());
downloadsPanel.add(new JScrollPane(table),
BorderLayout.CENTER);
// buttons panel.
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBackground(Color.darkGray);
pauseButton = new JButton();
ImageIcon img1 = new ImageIcon("C:\\j\\demo\\pause.png");
pauseButton.setIcon(img1);
pauseButton.setBorder(BorderFactory.createEmptyBorder());
pauseButton.setContentAreaFilled(false);
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionPause();
}
});
pauseButton.setEnabled(false);
buttonsPanel.add(pauseButton);
resumeButton = new JButton();
ImageIcon img2 = new ImageIcon("C:\\j\\demo\\play.png");
resumeButton.setIcon(img2);
resumeButton.setBorder(BorderFactory.createEmptyBorder());
resumeButton.setContentAreaFilled(false);
resumeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionResume();
}
});
resumeButton.setEnabled(false);
buttonsPanel.add(resumeButton);
cancelButton = new JButton();
ImageIcon img3 = new ImageIcon("C:\\j\\demo\\cancel.png");
cancelButton.setIcon(img3);
cancelButton.setBorder(BorderFactory.createEmptyBorder());
cancelButton.setContentAreaFilled(false);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionCancel();
}
});
cancelButton.setEnabled(false);
buttonsPanel.add(cancelButton);
clearButton = new JButton();
ImageIcon img4 = new ImageIcon("C:\\j\\demo\\clear.png");
clearButton.setIcon(img4);
clearButton.setBorder(BorderFactory.createEmptyBorder());
clearButton.setContentAreaFilled(false);
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionClear();
}
});
clearButton.setEnabled(false);
buttonsPanel.add(clearButton);
// add panels
getContentPane().setLayout(new BorderLayout());
getContentPane().add(addPanel, BorderLayout.NORTH);
getContentPane().add(downloadsPanel, BorderLayout.CENTER);
getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
}
private void actionExit() {
System.exit(0);
}
// add new download.
private void actionAdd() {
URL verifiedUrl = verifyUrl(addTextField.getText());
if (verifiedUrl != null) {
tableModel.addDownload(new Download(verifiedUrl));
addTextField.setText("");
} 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:
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) {
if (selectedDownload != null && selectedDownload.equals(o))
updateButtons();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DownloadManager manager = new DownloadManager();
manager.setVisible(true);
}
});
}
}
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
public class DownloadManager extends JFrame
implements Observer
{
private JTextField addTextField;
private DownloadsTableModel tableModel;
private JTable table;
private JButton pauseButton, resumeButton;
private JButton cancelButton, clearButton;
private Download selectedDownload;
private boolean clearing;
public DownloadManager()
{
setTitle("IDM");
setSize(640, 480);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
actionExit();
}
});
// add panel.
JPanel addPanel = new JPanel();
addPanel.setBackground(Color.darkGray);
addTextField = new JTextField(30);
Font font = new Font("Arial Narrow",Font.ITALIC,22);
addTextField.setFont(font);
addPanel.add(addTextField);
JButton addButton = new JButton();
ImageIcon img = new ImageIcon("C:\\j\\demo\\add.png");
addButton.setIcon(img);
addButton.setBorder(BorderFactory.createEmptyBorder());
addButton.setContentAreaFilled(false);
addButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionAdd();
}
});
addPanel.add(addButton);
//Downloads table.
tableModel = new DownloadsTableModel();
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);
table.setDefaultRenderer(JProgressBar.class, renderer);
table.setRowHeight(
(int) renderer.getPreferredSize().getHeight());
//download panel
JPanel downloadsPanel = new JPanel();
downloadsPanel.setBackground(Color.lightGray);
downloadsPanel.setBorder(
BorderFactory.createTitledBorder("Downloads Area"));
downloadsPanel.setLayout(new BorderLayout());
downloadsPanel.add(new JScrollPane(table),
BorderLayout.CENTER);
// buttons panel.
JPanel buttonsPanel = new JPanel();
buttonsPanel.setBackground(Color.darkGray);
pauseButton = new JButton();
ImageIcon img1 = new ImageIcon("C:\\j\\demo\\pause.png");
pauseButton.setIcon(img1);
pauseButton.setBorder(BorderFactory.createEmptyBorder());
pauseButton.setContentAreaFilled(false);
pauseButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionPause();
}
});
pauseButton.setEnabled(false);
buttonsPanel.add(pauseButton);
resumeButton = new JButton();
ImageIcon img2 = new ImageIcon("C:\\j\\demo\\play.png");
resumeButton.setIcon(img2);
resumeButton.setBorder(BorderFactory.createEmptyBorder());
resumeButton.setContentAreaFilled(false);
resumeButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionResume();
}
});
resumeButton.setEnabled(false);
buttonsPanel.add(resumeButton);
cancelButton = new JButton();
ImageIcon img3 = new ImageIcon("C:\\j\\demo\\cancel.png");
cancelButton.setIcon(img3);
cancelButton.setBorder(BorderFactory.createEmptyBorder());
cancelButton.setContentAreaFilled(false);
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionCancel();
}
});
cancelButton.setEnabled(false);
buttonsPanel.add(cancelButton);
clearButton = new JButton();
ImageIcon img4 = new ImageIcon("C:\\j\\demo\\clear.png");
clearButton.setIcon(img4);
clearButton.setBorder(BorderFactory.createEmptyBorder());
clearButton.setContentAreaFilled(false);
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
actionClear();
}
});
clearButton.setEnabled(false);
buttonsPanel.add(clearButton);
// add panels
getContentPane().setLayout(new BorderLayout());
getContentPane().add(addPanel, BorderLayout.NORTH);
getContentPane().add(downloadsPanel, BorderLayout.CENTER);
getContentPane().add(buttonsPanel, BorderLayout.SOUTH);
}
private void actionExit() {
System.exit(0);
}
// add new download.
private void actionAdd() {
URL verifiedUrl = verifyUrl(addTextField.getText());
if (verifiedUrl != null) {
tableModel.addDownload(new Download(verifiedUrl));
addTextField.setText("");
} 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:
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) {
if (selectedDownload != null && selectedDownload.equals(o))
updateButtons();
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
DownloadManager manager = new DownloadManager();
manager.setVisible(true);
}
});
}
}
Thursday, 11 July 2013
11 july
DOWNLOAD CLASS
import java.io.*;
import java.net.*;
import java.util.*;
class Download extends Observable implements Runnable {
private static final int MAX_BUFFER_SIZE = 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;
private int size;
private int downloaded;
private int status;
public Download(URL url) {
this.url = url;
size = -1;
downloaded = 0;
status = DOWNLOADING;
download();
}
public String getUrl() {
return url.toString();
}
public int getSize() {
return size;
}
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();
}
private String getFileName(URL url) {
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range","bytes=" + downloaded + "-");
connection.connect();
if (connection.getResponseCode() / 100 != 2) {
error();
}
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
if (size == -1) {
size = contentLength;
stateChanged();
}
file = new RandomAccessFile(getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
int read = stream.read(buffer);
if (read == -1)
break;
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}
private void stateChanged() {
setChanged();
notifyObservers();
}
}
import java.io.*;
import java.net.*;
import java.util.*;
class Download extends Observable implements Runnable {
private static final int MAX_BUFFER_SIZE = 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;
private int size;
private int downloaded;
private int status;
public Download(URL url) {
this.url = url;
size = -1;
downloaded = 0;
status = DOWNLOADING;
download();
}
public String getUrl() {
return url.toString();
}
public int getSize() {
return size;
}
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();
}
private String getFileName(URL url) {
String fileName = url.getFile();
return fileName.substring(fileName.lastIndexOf('/') + 1);
}
public void run() {
RandomAccessFile file = null;
InputStream stream = null;
try {
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
connection.setRequestProperty("Range","bytes=" + downloaded + "-");
connection.connect();
if (connection.getResponseCode() / 100 != 2) {
error();
}
int contentLength = connection.getContentLength();
if (contentLength < 1) {
error();
}
if (size == -1) {
size = contentLength;
stateChanged();
}
file = new RandomAccessFile(getFileName(url), "rw");
file.seek(downloaded);
stream = connection.getInputStream();
while (status == DOWNLOADING) {
byte buffer[];
if (size - downloaded > MAX_BUFFER_SIZE) {
buffer = new byte[MAX_BUFFER_SIZE];
} else {
buffer = new byte[size - downloaded];
}
int read = stream.read(buffer);
if (read == -1)
break;
file.write(buffer, 0, read);
downloaded += read;
stateChanged();
}
if (status == DOWNLOADING) {
status = COMPLETE;
stateChanged();
}
} catch (Exception e) {
error();
} finally {
if (file != null) {
try {
file.close();
} catch (Exception e) {}
}
if (stream != null) {
try {
stream.close();
} catch (Exception e) {}
}
}
}
private void stateChanged() {
setChanged();
notifyObservers();
}
}
Wednesday, 10 July 2013
10th july
The
DownloadManager Class
The DownloadManager
class
is responsible for creating and running the Download Manager’s GUI. This class
has a main( ) method declared, so on execution it will be invoked
first. The main( ) method instantiates a new DownloadManager class instance and then calls its show( ) method, which causes it
to be displayed.
The DownloadManager Variables- DownloadManager starts off by declaring several instance variables, most of which hold references to the GUI controls. The selectedDownload variable holds a reference to the Download object represented by the selected row in the table.
Finally, the clearing instance variable
is a boolean flag that tracks whether or not a download is
currently being cleared from the Downloads
table.
The DownloadManager Constructor- When the DownloadManager is instantiated, all of the GUI’s controls are initialized inside its
constructor. First, the window’s
title is set with a call to setTitle( ). Next, the setSize( ) call establishes the window’s width and height in pixels. After that,
a window listener is added by calling addWindowListener( ), passing aWindowAdapter object that overrides the windowClosing( ) event handler. This
handler calls the actionExit( ) method when the application’s
window is closed. Then the “Add” panel, which has the Add Text field and button,
is set up. An ActionListener is added to
the “Add Download” button so that the actionAdd( ) method is called each
time the button is clicked.
The downloads table is constructed
next. A ListSelectionListener is added to the table so that each
time a row is selected in the table, the tableSelectionChanged( ) method is invoked. The
table’s selection mode is also updated to ListSelectionModel.SINGLE_SELECTION
so
that only one row at a time can be selected in the table. Limiting row selection
to only one row at a time simplifies the logic for determining which buttons
should be enabled in the GUI when a row in the download table is selected.
Next, a ProgressRenderer class is instantiated and registered with the table
to handle the “Progress” column. The table’s row height is updated to the ProgressRenderer’s height by calling table.setRowHeight( ). After the table has
been assembled and tweaked, it is wrapped in a JScrollPane
to
make it scrollable
and then added to a panel. Finally,
the buttons panel is created. The buttons panel has Pause, Resume, Cancel, and Clear
buttons. Each of the buttons adds an ActionListener that invokes its
respective action method when it is clicked. After creating the buttons panel,
all of the panels that have been created are added to the window
.
The verifyUrl( ) Method-
The verifyUrl(
) method
is called by the actionAdd( ) method each time a download is
added to the Download Manager. This method first verifies that the URL entered
is an HTTP URL since only HTTP is supported.
Next, the URL being verified is
used to construct a new URL class instance. If the URL is malformed, the URL class
constructor will throw an exception. Finally, this method verifies that a file
is actually specified in the URL.
The tableSelectionChanged(
) Method-This method starts by seeing if there is already a row currently
selected by checking if the selectedDownload variable
is null. If the selectedDownload variable is not null, DownloadManager
removes itself as an observer of the download so that it no longer receives
change notifications.
The updateButtons( ) Method-
The updateButtons(
) method
updates the state of all the buttons on the button panel basedon the state of
the selected download.
Compiling and Running the Download Manager
Compile DownloadManager like this:
javac DownloadManager.java
DownloadsTableModel.java ProgressRenderer.java Download.java
Run DownloadManager like this:
java DownloadManager
Tuesday, 9 July 2013
9th july
The ProgressRenderer Class
The ProgressRenderer
class
is a small utility class that is used to render the current progress of a
download listed in the GUI’s “Downloads” JTable instance. In the
Download Manager’s case, we want to render each of the table’s Progress column
cells as progress bars.
javax.swing.JProgressBar
JProgressBar uses a BoundedRangeModel as its data model, with the value property representing the "current" state
of the task, and the minimum and maximum properties representing the beginning and end points, respectively.
public interface TableCellRenderer
javax.swing.table
This interface defines the method required by any object that would like
to be a renderer for cells in a JTable.
Component
getTableCellRendererComponent(JTable table,
Object value, boolean isSelected,
boolean hasFocus, int row,int column)
Returns the component used
for drawing the cell. This method is used to configure the renderer
appropriately before drawing.
Parameters:
table - the
JTable that is asking the renderer to draw; can be null
value - the
value of the cell to be rendered. It is up to the specific renderer to
interpret and draw the value. For example, if value is the string
"true", it could be rendered as a string or it could be rendered as a
check box that is checked. null is a valid value
isSelected -
true if the cell is to be rendered with the selection highlighted; otherwise
false
hasFocus - if
true, render cell appropriately. For example, put a special border on the cell,
if the cell can be edited, render in the color used to indicate editing
row - the
row index of the cell being drawn. When drawing the header, the value of row is
-1
column - the
column index of the cell being drawn.
The DownloadsTableModel Class
The DownloadsTableModel
class
houses the Download Manager’s list of downloads
and is the backing data
source for the GUI’s “Downloads” JTable instance.
The addDownload( ) Method -This
method first registers itself with the new Download as an Observer interested in receiving change notifications. Next, the Download is added to the internal list of downloads being
managed. Finally, a table row insertion event notification is fired to alert
the table that a new row has been added.
The clearDownload(
) Method -After removing the Download from the internal list, a table row deleted event
notification is fired to alert the table that a row has been deleted.
The getColumnClass(
) Method- All columns are displayed as text (that is, String objects)
except for the Progress column, which is displayed as a progress bar (which is an
object of type JProgressBar).
The getValueAt( )
Method -This method first looks up the Download corresponding to the
row specified. Next, the column specified is used to determine which one of
the Download’s property values to return.
The update( )
Method -This method is passed a reference to the Download that has changed, in
the form of an Observable object. Next, an index to that
download is looked up in the list of downloads, and that index is then
used to fire a table row update event notification, which alerts the table
that the given row has been updated. The table will then renderer the row with the given
index, reflecting its new values.
javax.swing.table
Class AbstractTableModel -
This abstract class provides default implementations
for most of the methods in the TableModel interface. It takes care of the management of
listeners and provides some conveniences for generating TableMonmnmmmmdelEvents and dispatching them to the listeners. To create a
concrete TableModel as a subclass of AbstractTableModel you need only provide implementations for the
following three methods: public int getRowCount();
public int getColumnCount();
public Object getValueAt(int row, int column);
Ø fireTableRowsInserted
public void fireTableRowsInserted(int firstRow, int lastRow)
Notifies all listeners that rows in the range
[firstRow, lastRow], inclusive,
have been inserted.
Ø fireTableRowsUpdated
public void fireTableRowsUpdated(int firstRow, int lastRow)
Notifies all listeners that rows in the range
[firstRow, lastRow], inclusive,
have been updated.
Ø fireTableRowsDeleted
public void fireTableRowsDeleted(int firstRow,int lastRow)
Notifies all listeners that rows
in the range
[firstRow, lastRow], inclusive, have been deleted. Monday, 8 July 2013
8th july
The Download Class
The Download class is the workhorse of the Download Manager. Its
primary purpose is to download a file and save that file’s contents to disk. Each
time a new download is added to the Download Manager, a new Download object is instantiated to handle
the download. The Download Manager has the ability to download multiple files
at once.
The Download Variables
Download begins by declaring several static final variables that specify
the various constants used by the class. Next, four instance variables are
declared. The url variable holds the
Internet URL for the file being downloaded; the size variable holds the size of the download file in bytes; the downloaded variable holds the number of bytes
that have been downloaded thus far; and the status variable indicates the download’s current status.
The Download Constructor
Download’s constructor is passed a reference to the URL to
download in the form of a URL object, which is assigned
to the url instance variable. It
then sets the remaining instance variables
to their initial states and calls the download( ) method. Notice that size is set to –1 to indicate there is no size yet.
The download( ) Method
The download( ) method creates a new Thread object, passing it a reference to the invoking Download instance. To use threads, the Download class simply implements the Runnable interface by overriding the run( ) method. After the download( ) method has instantiated a new Thread instance, passing its constructor the Runnable Download class, it calls the thread’s start( ) method. Invoking the start( ) method causes the Runnable instance’s (the Download class’) run( ) method to be executed.
The run( ) Method
run( ) sets up variables for the network stream that the
download’s contents will
be read from and sets up the file
that the download’s contents will be written to. Next, a
connection to the download’s URL is
opened by calling url.openConnection(
).
Since we know that the Download Manager supports only HTTP downloads, the
connection is cast to the HttpURLConnection
type. After the HttpURLConnection has been created, the
connection request property is set by calling connection. setRequestProperty( ).
Class
URLConnection
The abstract class
URLConnection is the superclass of all classes that represent a communications link
between the application and a URL. Instances of this class can be used both to
read from and to write to the resource referenced by the URL. In general,
creating a connection to a URL is a multistep process:- The
connection object is created by invoking the openConnection method on a
URL.
- The
setup parameters and general request properties are manipulated.
- The
actual connection to the remote object is made, using the connect method.
- The
remote object becomes available. The header fields and the contents of the
remote object can be accessed.
Ø setRequestProperty
public void setRequestProperty(String key,String value)
Sets the general request property. If a property with the key already
exists, overwrite its value with the new value.
Ø getContentLength
public int getContentLength()
Returns the value of the
content-length header field.
RandomAccessFile
public RandomAccessFile(File file,String mode)
|
"rw"
|
Open for reading and writing.
If the file does not already exist then an attempt will be made to create it.
|
The
stateChanged( ) Method
Each time the Download class needs to notify its registered Observers of a change, the stateChanged( ) method is invoked. The stateChanged( ) method first calls the Observable class’ setChanged( ) method to flag the class as having
been changed. Next, the stateChanged( ) method calls Observable’s notifyObservers( ) method, which broadcasts the change
notification to the registered Observers.
Friday, 5 July 2013
5th july
IDM
In this
project a tool called Download Manager is developed that manages Internet
downloads for you and makes simple work of resuming interrupted downloads. It
also lets you pause and then resume a download, and manage multiple downloads,
simultaneously.
At the core
of the Download Manager’s usefulness is its ability to take advantage of
downloading
only specific portions of a file. In a classic download scenario, a whole file
is
downloaded from beginning to end. If the transmission of the file is
interrupted for
any reason,
the progress made toward completing the downloading of the file is lost. The Download
Manager, however, can pick up from where an interruption occurs and then download only
the file’s remaining fragment. Not all downloads are created equal, though, and
there are some that simply cannot be restarted.
Understanding Internet Downloads
To understand and
appreciate the Download Manager, it’s necessary to shed some light on how Internet
downloads really work. Internet downloads in their simplest form are merely client/server
transactions. The client, your browser, requests to download a file from a
server on the Internet. The server then responds by sending the requested file
to your browser. In order for clients to communicate with servers, they must
have an established protocol for doing so. The most common protocols for
downloading files are File Transfer Protocol (FTP) and Hypertext Transfer
Protocol (HTTP).
FTP is usually
associated generically with exchanging files between computers, whereas HTTP is
usually associated specifically with transferring web pages and their related
files (that is, graphics, sounds, and so on). Over time, as the World Wide Web
has grown in popularity, HTTP has become the dominant protocol for downloading
files from the Internet. FTP is definitely not extinct, though. The Download Manager
developed in this project will only support HTTP downloads. HTTP downloads come in two forms: resumable
(HTTP 1.1) and non resumable (HTTP 1.0). The difference between these two forms
lies in the way files can be requested from servers. With the antiquated HTTP
1.0, a client can only request that a server send it a file, whereas with HTTP
1.1, a client can request that a server send it a complete file or only a
specific portion of a file. This is the feature the Download Manager is
built on.
An Overview of the Download Manager
The Download Manager uses a simple
yet effective GUI interface built with Java’s Swing libraries. The use of Swing
gives the interface a crisp, modern look and feel.
The GUI maintains a list of
downloads that are currently being managed. Each download in the list reports
its URL, size of the file in bytes, progress as a percentage toward completion,
and current status. The downloads can each be in one of the following different
states:
Downloading, Paused, Complete,
Error, or Cancelled. The GUI also has controls for adding downloads to the list
and for changing the state of each download in the list. When a download in the
list is selected, depending on its current state, it can be paused, resumed,
cancelled, or removed from the list altogether.
The Download Manager is broken into
a few classes for natural separation of functional
components. These are the Download, DownloadsTableModel, ProgressRenderer, and DownloadManager classes, respectively.
The DownloadManager class is responsible
for the GUI interface and makes use of the DownloadsTableModel and ProgressRenderer classes for displaying
the current list of downloads. The Download class represents a “managed” download and is responsible for performing
the actual downloading of a file.
Thursday, 4 July 2013
Wednesday, 3 July 2013
3rd july
You can rename a table or a column temporarily by giving another name known as alias.
The use of table aliases means to rename a table in a particular SQL statement. The renaming is a temporary change and the actual table name does not change in the database.
The column aliases are used to rename a table's columns for the purpose of a particular SQL query.
Syntax:
The basic syntax of table alias is as follows:
SELECT column1, column2.... FROM table_name AS alias_name WHERE [condition];
The basic syntax of column alias is as follows:
SELECT column_name AS alias_name FROM table_name WHERE [condition];
Example:
Consider the following two tables, (a) CUSTOMERS table is as follows:
+----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+
(b) Another table is ORDERS as follows:
+-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+
Now, following is the usage of table alias:
SQL> SELECT C.ID, C.NAME, C.AGE, O.AMOUNT FROM CUSTOMERS AS C, ORDERS AS O WHERE C.ID = O.CUSTOMER_ID;
This would produce the following result:
+----+----------+-----+--------+ | ID | NAME | AGE | AMOUNT | +----+----------+-----+--------+ | 3 | kaushik | 23 | 3000 | | 3 | kaushik | 23 | 1500 | | 2 | Khilan | 25 | 1560 | | 4 | Chaitali | 25 | 2060 | +----+----------+-----+--------+
Following is the usage of column alias:
SQL> SELECT ID AS CUSTOMER_ID, NAME AS CUSTOMER_NAME FROM CUSTOMERS WHERE SALARY IS NOT NULL;
This would produce the following result:
+-------------+---------------+ | CUSTOMER_ID | CUSTOMER_NAME | +-------------+---------------+ | 1 | Ramesh | | 2 | Khilan | | 3 | kaushik | | 4 | Chaitali | | 5 | Hardik | | 6 | Komal | | 7 | Muffy | +-------------+---------------+
The SQL ORDER BY clause is used to sort the data in ascending or descending order, based on one or more columns. Some database sorts query results in ascending order by default.
Syntax:
The basic syntax of ORDER BY clause is as follows:
SELECT column-list
FROM table_name
[WHERE condition]
[ORDER BY column1, column2, .. columnN] [ASC | DESC];
You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort, that column should be in column-list.
Example:
Consider the CUSTOMERS table having the following records:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would sort the result in ascending order by NAME and SALARY:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME, SALARY;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
+----+----------+-----+-----------+----------+
Following is an example, which would sort the result in descending order by NAME:
SQL> SELECT * FROM CUSTOMERS
ORDER BY NAME DESC;
This would produce the following result:
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
+----+----------+-----+-----------+----------+
Subscribe to:
Comments (Atom)