diff options
| author | tspitzer | 2013-09-17 15:38:08 +0200 |
|---|---|---|
| committer | tspitzer | 2013-09-17 15:38:08 +0200 |
| commit | 205f059ec5df1a24daa87f8563d2bbb99344ecf9 (patch) | |
| tree | 4f37a93f4224a5f37adb6e6477e65ce9e983febe /Dozentenmodul/src/downloader | |
| parent | neue Version (diff) | |
| download | tutor-module-205f059ec5df1a24daa87f8563d2bbb99344ecf9.tar.gz tutor-module-205f059ec5df1a24daa87f8563d2bbb99344ecf9.tar.xz tutor-module-205f059ec5df1a24daa87f8563d2bbb99344ecf9.zip | |
g
Diffstat (limited to 'Dozentenmodul/src/downloader')
| -rw-r--r-- | Dozentenmodul/src/downloader/DownloadTask.java | 105 | ||||
| -rw-r--r-- | Dozentenmodul/src/downloader/FTPException.java | 8 | ||||
| -rw-r--r-- | Dozentenmodul/src/downloader/FTPUtility.java | 187 | ||||
| -rw-r--r-- | Dozentenmodul/src/downloader/UploadTask.java | 91 | ||||
| -rw-r--r-- | Dozentenmodul/src/downloader/jschtest.java | 84 |
5 files changed, 475 insertions, 0 deletions
diff --git a/Dozentenmodul/src/downloader/DownloadTask.java b/Dozentenmodul/src/downloader/DownloadTask.java new file mode 100644 index 00000000..cf04f387 --- /dev/null +++ b/Dozentenmodul/src/downloader/DownloadTask.java @@ -0,0 +1,105 @@ +package downloader;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.InputStream;
+
+import javax.swing.JOptionPane;
+import javax.swing.SwingWorker;
+import GUI.FTPDownloader;
+
+/**
+ * Execute file download in a background thread and update the progress.
+ * @author www.codejava.net
+ *
+ */
+public class DownloadTask extends SwingWorker<Void, Void> {
+
+ private static final int BUFFER_SIZE = 4096;
+
+ private String host;
+ private int port;
+ private String username;
+ private String password;
+
+ private String downloadPath;
+ private String saveDir;
+
+ @SuppressWarnings("unused")
+ private FTPDownloader gui;
+
+ public DownloadTask(String host, int port, String username,
+ String password, String downloadPath, String saveDir,
+ FTPDownloader gui) {
+ this.host = host;
+ this.port = port;
+ this.username = username;
+ this.password = password;
+ this.downloadPath = downloadPath;
+ this.saveDir = saveDir;
+ this.gui = gui;
+
+ }
+
+ /**
+ * Executed in background thread
+ */
+ @Override
+ protected Void doInBackground() throws Exception {
+ FTPUtility util = new FTPUtility(host, port, username, password);
+ try {
+ util.connect();
+
+ byte[] buffer = new byte[BUFFER_SIZE];
+ int bytesRead = -1;
+ long totalBytesRead = 0;
+ int percentCompleted = 0;
+
+ long fileSize = util.getFileSize(downloadPath);
+ //gui.setFileSize(fileSize);
+
+ String fileName = new File(downloadPath).getName();
+
+ File downloadFile = new File(saveDir + File.separator + fileName);
+ FileOutputStream outputStream = new FileOutputStream(downloadFile);
+
+ util.downloadFile(downloadPath);
+ InputStream inputStream = util.getInputStream();
+
+ while ((bytesRead = inputStream.read(buffer)) != -1) {
+ outputStream.write(buffer, 0, bytesRead);
+ totalBytesRead += bytesRead;
+ //System.out.println(totalBytesRead);
+ percentCompleted = (int) (totalBytesRead * 100 / fileSize);
+ setProgress(percentCompleted);
+
+ }
+
+ outputStream.close();
+
+ util.finish();
+ } catch (FTPException ex) {
+ JOptionPane.showMessageDialog(null, "Error downloading file: " + ex.getMessage(),
+ "Error", JOptionPane.ERROR_MESSAGE);
+ ex.printStackTrace();
+ setProgress(0);
+ cancel(true);
+ } finally {
+ util.disconnect();
+ }
+
+ return null;
+ }
+
+ /**
+ * Executed in Swing's event dispatching thread
+ */
+ @Override
+ protected void done() {
+ if (!isCancelled()) {
+ JOptionPane.showMessageDialog(null,
+ "File has been downloaded successfully!", "Message",
+ JOptionPane.INFORMATION_MESSAGE);
+ }
+ }
+}
\ No newline at end of file diff --git a/Dozentenmodul/src/downloader/FTPException.java b/Dozentenmodul/src/downloader/FTPException.java new file mode 100644 index 00000000..33ba32be --- /dev/null +++ b/Dozentenmodul/src/downloader/FTPException.java @@ -0,0 +1,8 @@ +package downloader;
+
+@SuppressWarnings("serial")
+public class FTPException extends Exception {
+ public FTPException(String message) {
+ super(message);
+ }
+}
\ No newline at end of file diff --git a/Dozentenmodul/src/downloader/FTPUtility.java b/Dozentenmodul/src/downloader/FTPUtility.java new file mode 100644 index 00000000..dd0bd9ed --- /dev/null +++ b/Dozentenmodul/src/downloader/FTPUtility.java @@ -0,0 +1,187 @@ +package downloader;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.commons.net.ftp.FTP;
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.commons.net.ftp.FTPReply;
+
+/**
+ * A utility class that provides functionality for downloading files from a FTP
+ * server.
+ *
+ * @author www.codejava.net
+ *
+ */
+public class FTPUtility {
+
+ // FTP server information
+ private String host;
+ private int port;
+ private String username;
+ private String password;
+
+ private FTPClient ftpClient = new FTPClient();
+ private int replyCode;
+
+ private InputStream inputStream;
+ private OutputStream outputStream;
+
+ public FTPUtility(String host, int port, String user, String pass) {
+ this.host = host;
+ this.port = port;
+ this.username = user;
+ this.password = pass;
+ }
+
+ /**
+ * Connect and login to the server.
+ *
+ * @throws FTPException
+ */
+ public void connect() throws FTPException {
+ try {
+ ftpClient.connect(host, port);
+ replyCode = ftpClient.getReplyCode();
+ if (!FTPReply.isPositiveCompletion(replyCode)) {
+ throw new FTPException("FTP serve refused connection.");
+ }
+
+ boolean logged = ftpClient.login(username, password);
+ if (!logged) {
+ // failed to login
+ ftpClient.disconnect();
+ throw new FTPException("Could not login to the server.");
+ }
+
+ ftpClient.enterLocalPassiveMode();
+
+ } catch (IOException ex) {
+ throw new FTPException("I/O error: " + ex.getMessage());
+ }
+ }
+
+ /**
+ * Gets size (in bytes) of the file on the server.
+ *
+ * @param filePath
+ * Path of the file on server
+ * @return file size in bytes
+ * @throws FTPException
+ */
+ public long getFileSize(String filePath) throws FTPException {
+ try {
+ FTPFile file = ftpClient.mlistFile(filePath);
+ if (file == null) {
+ throw new FTPException("The file may not exist on the server!");
+ }
+ return file.getSize();
+ } catch (IOException ex) {
+ throw new FTPException("Could not determine size of the file: "
+ + ex.getMessage());
+ }
+ }
+
+ /**
+ * Start downloading a file from the server
+ *
+ * @param downloadPath
+ * Full path of the file on the server
+ * @throws FTPException
+ * if client-server communication error occurred
+ */
+ public void downloadFile(String downloadPath) throws FTPException {
+ try {
+
+ boolean success = ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
+ if (!success) {
+ throw new FTPException("Could not set binary file type.");
+ }
+
+ inputStream = ftpClient.retrieveFileStream(downloadPath);
+
+ if (inputStream == null) {
+ throw new FTPException(
+ "Could not open input stream. The file may not exist on the server.");
+ }
+ } catch (IOException ex) {
+ throw new FTPException("Error downloading file: " + ex.getMessage());
+ }
+ }
+
+
+ /**
+ * Start uploading a file to the server
+ * @param uploadFile the file to be uploaded
+ * @param destDir destination directory on the server
+ * where the file is stored
+ * @throws FTPException if client-server communication error occurred
+ */
+ public void uploadFile(File uploadFile, String destDir) throws FTPException {
+ try {
+ boolean success = ftpClient.changeWorkingDirectory(destDir);
+ if (!success) {
+ throw new FTPException("Could not change working directory to "
+ + destDir + ". The directory may not exist.");
+ }
+
+ success = ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
+ if (!success) {
+ throw new FTPException("Could not set binary file type.");
+ }
+
+ outputStream = ftpClient.storeFileStream(uploadFile.getName());
+
+ } catch (IOException ex) {
+ throw new FTPException("Error uploading file: " + ex.getMessage());
+ }
+ }
+
+ /**
+ * Write an array of bytes to the output stream.
+ */
+ public void writeFileBytes(byte[] bytes, int offset, int length)
+ throws IOException {
+ outputStream.write(bytes, offset, length);
+ }
+
+ /**
+ * Complete the download operation.
+ */
+ public void finish() throws IOException {
+ inputStream.close();
+ ftpClient.completePendingCommand();
+ }
+
+ /**
+ * Log out and disconnect from the server
+ */
+ public void disconnect() throws FTPException {
+ if (ftpClient.isConnected()) {
+ try {
+ if (!ftpClient.logout()) {
+ throw new FTPException("Could not log out from the server");
+ }
+ ftpClient.disconnect();
+ } catch (IOException ex) {
+ throw new FTPException("Error disconnect from the server: "
+ + ex.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Return InputStream of the remote file on the server.
+ */
+ public InputStream getInputStream() {
+ return inputStream;
+ }
+
+ public OutputStream getOutputStream() {
+ return outputStream;
+ }
+}
\ No newline at end of file diff --git a/Dozentenmodul/src/downloader/UploadTask.java b/Dozentenmodul/src/downloader/UploadTask.java new file mode 100644 index 00000000..691a31bb --- /dev/null +++ b/Dozentenmodul/src/downloader/UploadTask.java @@ -0,0 +1,91 @@ +package downloader;
+
+import java.io.File;
+import java.io.FileInputStream;
+
+import javax.swing.JOptionPane;
+import javax.swing.SwingWorker;
+
+/**
+ * Executes the file upload in a background thread and updates progress to
+ * listeners that implement the java.beans.PropertyChangeListener interface.
+ * @author www.codejava.net
+ *
+ */
+public class UploadTask extends SwingWorker<Void, Void> {
+ private static final int BUFFER_SIZE = 4096;
+
+ private String host;
+ private int port;
+ private String username;
+ private String password;
+
+ private String destDir;
+ private File uploadFile;
+
+ public UploadTask(String host, int port, String username, String password,
+ String destDir, File uploadFile) {
+ this.host = host;
+ this.port = port;
+ this.username = username;
+ this.password = password;
+ this.destDir = destDir;
+ this.uploadFile = uploadFile;
+ }
+
+ /**
+ * Executed in background thread
+ */
+ @Override
+ protected Void doInBackground() throws Exception {
+ FTPUtility util = new FTPUtility(host, port, username, password);
+ try {
+ util.connect();
+ util.uploadFile(uploadFile, destDir);
+
+ FileInputStream inputStream = new FileInputStream(uploadFile);
+ byte[] buffer = new byte[BUFFER_SIZE];
+ int bytesRead = -1;
+ long totalBytesRead = 0;
+ int percentCompleted = 0;
+ long fileSize = uploadFile.length();
+ long start=System.nanoTime();
+ final double NANOS_PER_SECOND = 1000000000.0;
+ final double BYTES_PER_MIB = 1024*1024;
+ while ((bytesRead = inputStream.read(buffer)) != -1) {
+ util.writeFileBytes(buffer, 0, bytesRead);
+ totalBytesRead += bytesRead;
+ percentCompleted = (int) (totalBytesRead * 100 / fileSize);
+ double speed = NANOS_PER_SECOND / BYTES_PER_MIB * totalBytesRead / (System.nanoTime() - start + 1);
+ setProgress(percentCompleted);
+ firePropertyChange("speed", 0, speed);
+ }
+
+ inputStream.close();
+
+ util.finish();
+ } catch (FTPException ex) {
+ JOptionPane.showMessageDialog(null, "Error uploading file: " + ex.getMessage(),
+ "Error", JOptionPane.ERROR_MESSAGE);
+ ex.printStackTrace();
+ setProgress(0);
+ cancel(true);
+ } finally {
+ util.disconnect();
+ }
+
+ return null;
+ }
+
+ /**
+ * Executed in Swing's event dispatching thread
+ */
+ @Override
+ protected void done() {
+ if (!isCancelled()) {
+ JOptionPane.showMessageDialog(null,
+ "File has been uploaded successfully!", "Message",
+ JOptionPane.INFORMATION_MESSAGE);
+ }
+ }
+}
\ No newline at end of file diff --git a/Dozentenmodul/src/downloader/jschtest.java b/Dozentenmodul/src/downloader/jschtest.java new file mode 100644 index 00000000..83be7e03 --- /dev/null +++ b/Dozentenmodul/src/downloader/jschtest.java @@ -0,0 +1,84 @@ +package downloader;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.util.Properties;
+
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
+import com.jcraft.jsch.SftpException;
+import com.jcraft.jsch.UserInfo;
+
+public class jschtest {
+
+ /**
+ * @param args
+ */
+ public static void main(String[] args) {
+ File testfile=new File("C:\\Users\\tspitzer\\Documents\\201301_ws_win7_OPT_Apps_NC_Off2010.zip");
+ try {
+ sftpFile(testfile, "fr-bwlehrpool-rw-admin" , "fefobu36", "bwsonas.lsdf.kit.edu", "/.mounts/bwlehrpool");
+ } catch (FileNotFoundException | JSchException | SftpException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ System.out.println("Fertig");
+
+ }
+
+ private static void sftpFile(File localFile, String username, String password, String hostname, String remoteDirectory)
+ throws JSchException, SftpException, FileNotFoundException {
+
+ JSch jsch = new JSch();
+ String filename = localFile.getName();
+ Session session = jsch.getSession(username, hostname, 22);
+ session.setUserInfo(new HardcodedUserInfo(password));
+ Properties config = new Properties();
+ config.setProperty("StrictHostKeyChecking", "no");
+ session.setConfig(config);
+ session.connect();
+ ChannelSftp channel = (ChannelSftp)session.openChannel("sftp");
+ channel.connect();
+ channel.cd(remoteDirectory);
+ channel.put(new FileInputStream(localFile), filename);
+ channel.disconnect();
+ session.disconnect();
+ }
+
+ private static class HardcodedUserInfo implements UserInfo {
+
+ private final String password;
+
+ private HardcodedUserInfo(String password) {
+ this.password = password;
+ }
+
+ public String getPassphrase() {
+ return null;
+ }
+
+ public String getPassword() {
+ return password;
+ }
+
+ public boolean promptPassword(String s) {
+ return true;
+ }
+
+ public boolean promptPassphrase(String s) {
+ return true;
+ }
+
+ public boolean promptYesNo(String s) {
+ return true;
+ }
+
+ public void showMessage(String s) {
+ System.out.println("message = " + s);
+ }
+ }
+
+}
|
