forked from ALRubinger/oreilly-ejb-6thedition-book-examples
/
FileTransferBean.java
411 lines (356 loc) · 12 KB
/
FileTransferBean.java
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*
* JBoss, Home of Professional Open Source.
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.ejb3.examples.ch06.filetransfer;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remote;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.jboss.logging.Logger;
/**
* Bean Implementation class of the FileTransferEJB, modeled
* as a Stateful Session Bean
*
* @author <a href="mailto:andrew.rubinger@jboss.org">ALR</a>
*/
@Stateful(name = FileTransferBean.EJB_NAME)
@Remote(FileTransferRemoteBusiness.class)
public class FileTransferBean implements FileTransferRemoteBusiness, Serializable
{
//-------------------------------------------------------------------------------------||
// Class Members ----------------------------------------------------------------------||
//-------------------------------------------------------------------------------------||
/**
* Serial Version UID
*/
private static final long serialVersionUID = 1L;
/**
* Logger
*/
private static final Logger log = Logger.getLogger(FileTransferBean.class);
/**
* Name of the EJB, used in Global JNDI addresses
*/
public static final String EJB_NAME = "FileTransferEJB";
/**
* The name of the host to which we'll connect.
* In production systems would typically be externalized
* via configurable environment entry
*/
private static String CONNECT_HOST = "localhost";
/**
* The port to which we'll connect.
* In production systems would typically be externalized
* via configurable environment entry. IANA standard
* for FTP ports is 21, though this requires root access
* on *nix for testing, so we'll use the nonstandard 12345.
*/
private static int CONNECT_PORT = 12345;
//-------------------------------------------------------------------------------------||
// Instance Members -------------------------------------------------------------------||
//-------------------------------------------------------------------------------------||
/**
* The underlying FTP Client. We don't want its state
* getting Serialized during passivation. We'll
* reinitialize this client and its connections
* upon activation.
*/
private FTPClient client;
/**
* Name of the present working directory. In cases where
* we're passivated, if this is specified
* we'll change into this directory upon activation.
*/
private String presentWorkingDirectory;
//-------------------------------------------------------------------------------------||
// Lifecycle Callbacks ----------------------------------------------------------------||
//-------------------------------------------------------------------------------------||
/**
* Called by the container when the instance is about to be passivated or brought
* out of service entirely.
*
* @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#disconnect()
*/
@PrePassivate
@PreDestroy
@Override
public void disconnect()
{
// Obtain FTP Client
final FTPClient client = this.getClient();
// If exists
if (client != null)
{
// If connected
if (client.isConnected())
{
// Logout
try
{
client.logout();
log.info("Logged out of: " + client);
}
catch (final IOException ioe)
{
log.warn("Exception encountered in logging out of the FTP client", ioe);
}
// Disconnect
try
{
log.debug("Disconnecting: " + client);
client.disconnect();
log.info("Disconnected: " + client);
}
catch (final IOException ioe)
{
log.warn("Exception encountered in disconnecting the FTP client", ioe);
}
// Null out the client so it's not serialized
this.client = null;
}
}
}
/**
* Called by the container when the instance has been created or re-activated
* (brought out of passivated state). Will construct the underlying FTP Client
* and open all appropriate connections.
*
* @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#connect()
*/
@PostConstruct
@PostActivate
@Override
public void connect() throws IllegalStateException, FileTransferException
{
/*
* Precondition checks
*/
final FTPClient clientBefore = this.getClient();
if (clientBefore != null && clientBefore.isConnected())
{
throw new IllegalStateException("FTP Client is already initialized");
}
// Get the connection properties
final String connectHost = this.getConnectHost();
final int connectPort = this.getConnectPort();
// Create the client
final FTPClient client = new FTPClient();
final String canonicalServerName = connectHost + ":" + connectPort;
log.debug("Connecting to FTP Server at " + canonicalServerName);
try
{
client.connect(connectHost, connectPort);
}
catch (final IOException ioe)
{
throw new FileTransferException("Error in connecting to " + canonicalServerName, ioe);
}
// Set
log.info("Connected to FTP Server at: " + canonicalServerName);
this.setClient(client);
// Check that the last operation succeeded
this.checkLastOperation();
try
{
// Login
client.login("user", "password");
// Check that the last operation succeeded
this.checkLastOperation();
}
catch (final Exception e)
{
throw new FileTransferException("Could not log in", e);
}
// If there's a pwd defined, cd into it.
final String pwd = this.getPresentWorkingDirectory();
if (pwd != null)
{
this.cd(pwd);
}
}
//-------------------------------------------------------------------------------------||
// Required Implementations -----------------------------------------------------------||
//-------------------------------------------------------------------------------------||
/* (non-Javadoc)
* @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#cd(java.lang.String)
*/
@Override
public void cd(final String directory)
{
// Get the client
final FTPClient client = this.getClient();
// Exec cd
try
{
// Exec cd
client.changeWorkingDirectory(directory);
// Check reply for success
this.checkLastOperation();
}
catch (final Exception e)
{
throw new FileTransferException("Could not change working directory to \"" + directory + "\"", e);
}
// Set the pwd (used upon activation)
log.info("cd > " + directory);
this.setPresentWorkingDirectory(directory);
}
/* (non-Javadoc)
* @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#mkdir(java.lang.String)
*/
@Override
public void mkdir(final String directory)
{
// Get the client
final FTPClient client = this.getClient();
// Exec cd
try
{
// Exec mkdir
client.makeDirectory(directory);
// Check reply for success
this.checkLastOperation();
}
catch (final Exception e)
{
throw new FileTransferException("Could not make directory \"" + directory + "\"", e);
}
}
/* (non-Javadoc)
* @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#pwd()
*/
@Override
public String pwd()
{
// Get the client
final FTPClient client = this.getClient();
// Exec pwd
try
{
final FTPFile[] files = client.listFiles();
for (final FTPFile file : files)
{
log.info(file);
}
// Exec pwd
String dir = client.printWorkingDirectory();
String separator = File.separator;
if ("\\".equals(separator)) {
// reformat to use for windows
if (dir.startsWith("/")) {
dir = dir.substring(1);
}
dir = dir.replaceAll("/", "\\" + separator);
}
return dir;
}
catch (final IOException ioe)
{
throw new FileTransferException("Could not print working directory", ioe);
}
}
//-------------------------------------------------------------------------------------||
// Internal Helper Methods ------------------------------------------------------------||
//-------------------------------------------------------------------------------------||
/**
* Ensures that the last operation succeeded with a positive
* reply code. Otherwise a {@link FileTransferException}
* is raised, noting the reply code denoting the error.
*
* @throws FileTransferException
*/
protected void checkLastOperation() throws FileTransferException
{
// Get the client
final FTPClient client = this.getClient();
// Obtain and check the reply from the connection
final int connectReply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(connectReply))
{
// Indicate the problem
throw new FileTransferException("Did not receive positive completion code from server, instead code was: "
+ connectReply);
}
}
/* (non-Javadoc)
* @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferRemoteBusiness#endSession()
*/
@Remove
@Override
public void endSession()
{
log.info("Session Ending...");
}
//-------------------------------------------------------------------------------------||
// Accessors / Mutators ---------------------------------------------------------------||
//-------------------------------------------------------------------------------------||
/**
* @return the connectHost
*/
public String getConnectHost()
{
return CONNECT_HOST;
}
/**
* @return the connectPort
*/
public int getConnectPort()
{
return CONNECT_PORT;
}
/**
* @return the client
*/
protected final FTPClient getClient()
{
return client;
}
/**
* @param client the client to set
*/
private void setClient(final FTPClient client)
{
this.client = client;
}
/**
* @return the presentWorkingDirectory
*/
private String getPresentWorkingDirectory()
{
return presentWorkingDirectory;
}
/**
* @param presentWorkingDirectory the presentWorkingDirectory to set
*/
private void setPresentWorkingDirectory(String presentWorkingDirectory)
{
this.presentWorkingDirectory = presentWorkingDirectory;
}
}