summaryrefslogtreecommitdiffstats
path: root/Dozentenmodul/src/ftp/FTPUtility.java
blob: f2c51dfc3f1a2937e2ac139c0f398099af0fc585 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
package ftp;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import java.security.NoSuchAlgorithmException;

import javax.swing.JOptionPane;

import models.Image;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;


/**
 * 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 FTPSClient ftpClient = new FTPSClient();
	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
	 * @throws NoSuchAlgorithmException 
	 */
	public void connect() throws FTPException, NoSuchAlgorithmException {
		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.execPROT("P");
				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(Image.image.getNewName());
            
            //ftpClient.rename(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;
	}
	
	

}