Chapter 33: Creating a Download Manager in Java 987
// Verify download URL.
private URL verifyUrl(String url) {
// Only allow HTTP URLs.
if (!url.toLowerCase().startsWith("http://"))
return null;
// Verify format of URL.
URL verifiedUrl = null;
try {
verifiedUrl = new URL(url);
} catch (Exception e) {
return null;
}
// Make sure URL specifies a file.
if (verifiedUrl.getFile().length() < 2)
return null;
return verifiedUrl;
}
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 newURLclass instance. If the URL is
malformed, theURLclass constructor will throw an exception. Finally, this method verifies
that a file is actually specified in the URL.
The tableSelectionChanged( ) Method
ThetableSelectionChanged( )method, shown here, is called each time a row is selected
in the downloads table:
// Called when table row selection changes.
private void tableSelectionChanged() {
/ Unregister from receiving notifications
from the last selected download. /
if (selectedDownload != null)
selectedDownload.deleteObserver(DownloadManager.this);
/ If not in the middle of clearing a download,
set the selected download and register to
receive notifications from it. /
if (!clearing && table.getSelectedRow() > -1) {
selectedDownload =
tableModel.getDownload(table.getSelectedRow());
selectedDownload.addObserver(DownloadManager.this);
updateButtons();
}
}
This method starts by seeing if there is already a row currently selected by checking if
theselectedDownloadvariable isnull.IftheselectedDownloadvariable is notnull,
DownloadManagerremoves itself as an observer of the download so that it no longer
receives change notifications. Next theclearingflag is checked. If the table is not empty
and theclearingflag isfalse, then first theselectedDownloadvariable is updated with the
Downloadcorresponding to the row selected. Second, theDownloadManageris registered