📄 downloadmanager.java
字号:
/*
* Copyright 2007 JavaAtWork All rights reserved.
* Use is subject to license terms.
*/
package com.javaatwork.mydownloader.listeners;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;
import com.javaatwork.mydownloader.DownloadFile;
import com.javaatwork.mydownloader.MyDownloader;
import com.javaatwork.mydownloader.dialog.ConfirmationDialog;
import com.javaatwork.mydownloader.dialog.ProgressDialog;
import com.javaatwork.mydownloader.dialog.TimeOutOptionPane;
import com.javaatwork.mydownloader.utils.LocaleManager;
import com.javaatwork.mydownloader.utils.Logger;
import com.javaatwork.mydownloader.utils.Parameters;
import com.javaatwork.mydownloader.utils.SwingWorker;
import com.javaatwork.mydownloader.utils.TempDirectoryManager;
import com.javaatwork.mydownloader.utils.Version;
/**
* Class who is responsible for downloading the files.
*
* @author Johannes Postma
*/
public class DownloadManager implements DestroyListener {
private boolean finished = false;
private String status = "";
private String fileInProgress = null;
private int numberOfFiles = 0;
private int fileInRow = 0;
private long totalBytesDownloaded = 0; // total bytes read of all files
private long bytesDownloaded = 0; // bytes read of one file
private long bytes = 0; // total byes of one file
private Vector localFiles = new Vector();
private long begin = 0L;
private boolean cancel = false;
private FileOutputStream out = null;
private InputStream in = null;
private ProgressDialog progressDialog = null;
private MyDownloader applet = null;
private HttpURLConnection conn = null;
// this boolean is necessary to view the correct message if an error
// if the file is already downloaded and is opened by e.g. Word
// the downloaded file cannot be written to the filesystem again.
private boolean fileExist = false;
/**
* Downloads the files from the server and stores the files in the temp
* directory (System property java.io.tmpdir).
*
* @param applet MyDownloader.
* @return The downloaded files stored in the temp (java.io.tmpdir)
* directory.
*/
public File[] downloadFiles(final MyDownloader applet) {
return downloadFiles(applet, null);
}
/**
* Downloads the files from the server and stores the files in a specific
* directory. If the directory is null the files will be stored in the temp
* (java.io.tmpdir) directory.
*
* @param applet MyDownloader.
* @param directory The directory where the files will be stored.
* @return The downloaded files.
*/
public File[] downloadFiles(final MyDownloader applet, File directory) {
this.applet = applet;
if (Version.FREE_EDITION) {
if (showFreeDialog()) {
return null;
}
}
final File downloadLocation = directory == null ? TempDirectoryManager.getTempDirectory() : directory;
final DownloadFile[] files = applet.getFilesToDownload();
if (files == null || files.length == 0) {
return null;
}
// check if files must be overwritten
if (directory != null) {
if (!overwrite(directory, files)) {
return null;
}
}
this.numberOfFiles = files.length;
begin = System.currentTimeMillis();
SwingWorker worker = new SwingWorker() {
public Object construct() {
// create a new array for the files to be download
int counter = 0;
for (int i = 0; i < files.length && !cancel; i++) {
if (files[i].isOverwrite()) {
counter++;
}
}
DownloadFile [] downFiles = new DownloadFile[counter];
counter = 0;
for (int i = 0; i < files.length && !cancel; i++) {
if (files[i].isOverwrite()) {
downFiles[counter] = files[i];
counter++;
}
}
numberOfFiles = downFiles.length;
for (int i = 0; i < downFiles.length && !cancel; i++) {
downloadFile(downloadLocation, downFiles[i].getUrl(), downFiles[i].getFileName(), applet.getCodeBase());
}
finished = true;
return null;
}
};
progressDialog = new ProgressDialog(applet, this);
worker.start();
progressDialog.start();
return (File[]) localFiles.toArray(new File[localFiles.size()]);
}
/**
* Determines if the files needs to be overwritten.
*
* @param directory The directory where the files will be stored.
* @param files The files to download.
* @return false if no file may be overwritten
*/
public boolean overwrite(File directory, DownloadFile[] files) {
for (int i = 0; i < files.length; i++) {
File existingFile = new File(directory, files[i].getFileName());
if (existingFile.exists()) {
int returnValue = 0;
if (files.length > 1) {
returnValue = applet.handleExistingFile(files[i], existingFile, true);
} else {
returnValue = applet.handleExistingFile(files[i], existingFile, false);
}
if (returnValue == ConfirmationDialog.CANCEL_OPTION) {
return false;
} else if (returnValue == ConfirmationDialog.NO_OPTION) {
files[i].setOverwrite(false);
} else if (returnValue == ConfirmationDialog.YES_TO_ALL_OPTION) {
break;
}
}
}
return true;
}
/**
* Downloads a file.
*
* @param directory The directory where the file will be stored.
* @param url The url of the file to be downloaded.
* @param fileName The name how the file will be stored.
* @param codebase The codebase of the applet.
*/
public void downloadFile(File directory, URL url, String fileName, URL codebase) {
applet.addDestroyListener(this);
File file = null;
try {
status = LocaleManager.getInstance().getString("downloading") + " ...";
fileInRow++;
// sets the file in progress
fileInProgress = fileName;
fileExist = false;
// create the file with the local path
file = new File(directory, fileName);
if (file.exists()) {
fileExist = true;
}
// retrieve the remote file
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// retrieve the cookies
// cookies will be retrieve by the use of the java plugin
// unfortunately this doesn't work in Opera.
// For Opera the Javascript solution will work.
String cookieHandler = null;
if (System.getProperty("java.specification.version").equalsIgnoreCase("1.4")) {
cookieHandler = "sun.plugin.net.cookie.PluginCookieManager";
} else {
cookieHandler = "com.sun.deploy.net.cookie.DeployCookieManager";
}
String cookie = null;
try {
Class clss = Class.forName(cookieHandler);
Class[] parameterTypes = new Class[] {URL.class};
Method meth = clss.getMethod("getCookieInfo", parameterTypes);
Object[] arguments = new Object[] {codebase};
cookie = (String)meth.invoke(clss.newInstance(), arguments);
} catch (Exception ex) {
// do nothing
// in Opera the classes cannot be found an exception will be thrown.
}
if (cookie != null && !cookie.trim().equalsIgnoreCase("")) {
Logger.log("DownloadManager", "downloadFile()", "CookieInfo: " + cookie);
conn.setRequestProperty("Cookie", cookie);
}
// cookies cannot be retrieve by the use of the java plugin
else {
cookie = Parameters.getParameter(Parameters.COOKIE, null);
if (cookie != null) {
Logger.log("DownloadManager", "downloadFile()", "CookieInfo: " + cookie);
conn.setRequestProperty("Cookie", cookie);
}
}
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
if (responseCode == 404) {
String message = LocaleManager.getInstance().getString("file_not_found");
message = message.replaceAll("<filename>", file.getName());
message += " cannot be found [response code: " + responseCode + "].";
progressDialog.showMessage(message);
} else {
String message = LocaleManager.getInstance().getString("error_occurred_during_download");
message = message.replaceAll("<filename>", file.getName());
message += " [response code: " + responseCode + "].";
progressDialog.showMessage(message);
}
return;
} else {
// log the responseCode
Logger.log("DownloadManager", "downloadFile", "File: " + fileName + " " + "[Response code: " + String.valueOf(responseCode) + "]");
}
// set the bytes downloaded for a the specific file to 0
bytesDownloaded = 0;
in = conn.getInputStream();
out = new FileOutputStream(file);
String contentLength = conn.getHeaderField("Content-Length");
// download based on the header contentlength
if (contentLength != null) {
bytes = Long.parseLong(contentLength);
int size = Integer.parseInt(contentLength);
int read = 0;
byte[] b = new byte[1024];
while ((read = in.read(b)) != -1) {
totalBytesDownloaded += read;
bytesDownloaded += read;
size = size - read;
if (size < 0) {
out.write(b, 0, read - size);
} else {
out.write(b, 0, read);
}
}
// download based on end -1
} else {
int read = 0;
byte[] b = new byte[1024];
while ((read = in.read(b)) != -1) {
totalBytesDownloaded += read;
bytesDownloaded += read;
out.write(b, 0, read);
}
}
out.flush();
in.close();
localFiles.add(file);
} catch (Exception ex) {
if (!cancel) {
if (fileExist) {
String message = LocaleManager.getInstance().getString("permission");
message = message.replaceAll("<filename>", file.getName());
progressDialog.showMessage(message);
} else {
String message = LocaleManager.getInstance().getString("error_occurred");
message = message.replaceAll("<filename>", file.getName());
progressDialog.showMessage(message);
}
Logger.log("DownloadManager", "downloadFile", "Error occurred with file: " + file.getName());
}
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// do nothing
}
}
if (conn != null) {
conn.disconnect();
}
applet.removeDestroyListener(this);
}
}
/**
* Returns the elapsed time in ms.
*
* @return The elapsed time ms.
*/
public synchronized int getElapsedTime() {
return (int) (System.currentTimeMillis() - begin);
}
/**
* Cancels the download.
*/
public void cancel() {
try {
cancel = true;
out.close();
} catch (IOException ioe) {
// do nothing
}
}
/**
* Returns the percent completed.
*
* @return The percent completed.
*/
public int getPercentCompleted() {
return (int) (((double) bytesDownloaded / (double) bytes) * 100);
}
/**
* Returns the total bytes downloaded.
*
* @return The total bytes downloaded.
*/
public synchronized long getTotalBytesDownloaded() {
return totalBytesDownloaded;
}
/**
* Returns the number of file in the row of files to be downloaded.
*
* @return The number.
*/
public synchronized int getFileInRow() {
return fileInRow;
}
/**
* Returns the total number of files to be downloaded.
*
* @return The total number of files to be downloaded.
*/
public synchronized int getNumberOfFiles() {
return numberOfFiles;
}
/**
* Returns true if the download is finished.
*
* @return True if the download is finished.
*/
public synchronized boolean isFinished() {
return finished;
}
/**
* Returns the status.
*
* @return The status.
*/
public synchronized String getStatus() {
return status;
}
/**
* Returns the filename in progress.
*
* @return The filename in progress.
*/
public synchronized String getFileInProgress() {
return fileInProgress;
}
/**
* Shows the JavaAtWork dialog.
*
* @return boolean True if the user wants to visit www.javaatwork.com
*/
private boolean showFreeDialog() {
int returnValue = TimeOutOptionPane.showTimeoutDialog(applet);
if (returnValue == TimeOutOptionPane.JAVAATWORK_OPTION) {
try {
applet.getAppletContext().showDocument(new URL("http://www.javaatwork.com"), "_blank");
return true;
} catch (MalformedURLException mue) {
Logger.log("UploadActionListener", "actionPerformed", mue.toString());
}
}
return false;
}
/**
* Closes the connections in case that the applet is destroyed.
*/
public void destroy() {
if (in != null) {
try {
in.close();
} catch (IOException e) {
// do nothing
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// do nothing
}
}
if (conn != null) {
conn.disconnect();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -