1/*
2 * Copyright 2007 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.mockftpserver.stub;
17
18import org.apache.commons.net.ftp.FTP;
19import org.apache.commons.net.ftp.FTPClient;
20import org.apache.commons.net.ftp.FTPFile;
21import org.apache.log4j.Logger;
22import org.mockftpserver.core.command.CommandHandler;
23import org.mockftpserver.core.command.CommandNames;
24import org.mockftpserver.core.command.InvocationRecord;
25import org.mockftpserver.core.command.SimpleCompositeCommandHandler;
26import org.mockftpserver.core.command.StaticReplyCommandHandler;
27import org.mockftpserver.stub.command.*;
28import org.mockftpserver.test.AbstractTest;
29import org.mockftpserver.test.IntegrationTest;
30import org.mockftpserver.test.PortTestUtil;
31
32import java.io.ByteArrayInputStream;
33import java.io.ByteArrayOutputStream;
34import java.io.IOException;
35
36/**
37 * Tests for StubFtpServer using the Apache Jakarta Commons Net FTP client.
38 *
39 * @author Chris Mair
40 * @version $Revision$ - $Date$
41 */
42public final class StubFtpServerIntegrationTest extends AbstractTest implements IntegrationTest {
43
44    private static final Logger LOG = Logger.getLogger(StubFtpServerIntegrationTest.class);
45    private static final String SERVER = "localhost";
46    private static final String USERNAME = "user123";
47    private static final String PASSWORD = "password";
48    private static final String FILENAME = "abc.txt";
49    private static final String ASCII_CONTENTS = "abcdef\tghijklmnopqr";
50    private static final byte[] BINARY_CONTENTS = new byte[256];
51
52    private StubFtpServer stubFtpServer;
53    private FTPClient ftpClient;
54    private RetrCommandHandler retrCommandHandler;
55    private StorCommandHandler storCommandHandler;
56
57    //-------------------------------------------------------------------------
58    // Tests
59    //-------------------------------------------------------------------------
60
61    public void testLogin() throws Exception {
62        // Connect
63        LOG.info("Conecting to " + SERVER);
64        ftpClientConnect();
65        verifyReplyCode("connect", 220);
66
67        // Login
68        String userAndPassword = USERNAME + "/" + PASSWORD;
69        LOG.info("Logging in as " + userAndPassword);
70        boolean success = ftpClient.login(USERNAME, PASSWORD);
71        assertTrue("Unable to login with " + userAndPassword, success);
72        verifyReplyCode("login with " + userAndPassword, 230);
73
74        assertTrue("isStarted", stubFtpServer.isStarted());
75        assertFalse("isShutdown", stubFtpServer.isShutdown());
76
77        // Quit
78        LOG.info("Quit");
79        ftpClient.quit();
80        verifyReplyCode("quit", 221);
81    }
82
83    public void testAcct() throws Exception {
84        ftpClientConnect();
85
86        // ACCT
87        int replyCode = ftpClient.acct("123456");
88        assertEquals("acct", 230, replyCode);
89    }
90
91    /**
92     * Test the stop() method when no session has ever been started
93     */
94    public void testStop_NoSessionEverStarted() throws Exception {
95        LOG.info("Testing a stop() when no session has ever been started");
96    }
97
98    public void testHelp() throws Exception {
99        // Modify HELP CommandHandler to return a predefined help message
100        final String HELP = "help message";
101        HelpCommandHandler helpCommandHandler = (HelpCommandHandler) stubFtpServer.getCommandHandler(CommandNames.HELP);
102        helpCommandHandler.setHelpMessage(HELP);
103
104        ftpClientConnect();
105
106        // HELP
107        String help = ftpClient.listHelp();
108        assertTrue("Wrong response", help.indexOf(HELP) != -1);
109        verifyReplyCode("listHelp", 214);
110    }
111
112    /**
113     * Test the LIST and SYST commands.
114     */
115    public void testList() throws Exception {
116        ftpClientConnect();
117
118        // Set directory listing
119        ListCommandHandler listCommandHandler = (ListCommandHandler) stubFtpServer.getCommandHandler(CommandNames.LIST);
120        listCommandHandler.setDirectoryListing("11-09-01 12:30PM  406348 File2350.log\n"
121                + "11-01-01 1:30PM <DIR> 0 archive");
122
123        // LIST
124        FTPFile[] files = ftpClient.listFiles();
125        assertEquals("number of files", 2, files.length);
126        verifyFTPFile(files[0], FTPFile.FILE_TYPE, "File2350.log", 406348L);
127        verifyFTPFile(files[1], FTPFile.DIRECTORY_TYPE, "archive", 0L);
128        verifyReplyCode("list", 226);
129    }
130
131    /**
132     * Test the LIST, PASV and SYST commands, transferring a directory listing in passive mode
133     */
134    public void testList_PassiveMode() throws Exception {
135        ftpClientConnect();
136
137        ftpClient.enterLocalPassiveMode();
138
139        // Set directory listing
140        ListCommandHandler listCommandHandler = (ListCommandHandler) stubFtpServer.getCommandHandler(CommandNames.LIST);
141        listCommandHandler.setDirectoryListing("11-09-01 12:30PM  406348 File2350.log");
142
143        // LIST
144        FTPFile[] files = ftpClient.listFiles();
145        assertEquals("number of files", 1, files.length);
146        verifyReplyCode("list", 226);
147    }
148
149    public void testNlst() throws Exception {
150        ftpClientConnect();
151
152        // Set directory listing
153        NlstCommandHandler nlstCommandHandler = (NlstCommandHandler) stubFtpServer.getCommandHandler(CommandNames.NLST);
154        nlstCommandHandler.setDirectoryListing("File1.txt\nfile2.data");
155
156        // NLST
157        String[] filenames = ftpClient.listNames();
158        assertEquals("number of files", 2, filenames.length);
159        assertEquals(filenames[0], "File1.txt");
160        assertEquals(filenames[1], "file2.data");
161        verifyReplyCode("listNames", 226);
162    }
163
164    /**
165     * Test printing the current working directory (PWD)
166     */
167    public void testPwd() throws Exception {
168        // Modify PWD CommandHandler to return a predefined directory
169        final String DIR = "some/dir";
170        PwdCommandHandler pwdCommandHandler = (PwdCommandHandler) stubFtpServer.getCommandHandler(CommandNames.PWD);
171        pwdCommandHandler.setDirectory(DIR);
172
173        ftpClientConnect();
174
175        // PWD
176        String dir = ftpClient.printWorkingDirectory();
177        assertEquals("Unable to PWD", DIR, dir);
178        verifyReplyCode("printWorkingDirectory", 257);
179    }
180
181    public void testStat() throws Exception {
182        // Modify Stat CommandHandler to return predefined text
183        final String STATUS = "some information 123";
184        StatCommandHandler statCommandHandler = (StatCommandHandler) stubFtpServer.getCommandHandler(CommandNames.STAT);
185        statCommandHandler.setStatus(STATUS);
186
187        ftpClientConnect();
188
189        // STAT
190        String status = ftpClient.getStatus();
191        assertEquals("STAT reply", "211 " + STATUS + ".", status.trim());
192        verifyReplyCode("getStatus", 211);
193    }
194
195    /**
196     * Test getting the status (STAT), when the reply text contains multiple lines
197     */
198    public void testStat_MultilineReplyText() throws Exception {
199        // Modify Stat CommandHandler to return predefined text
200        final String STATUS = "System name: abc.def\nVersion 3.5.7\nNumber of failed logins: 2";
201        final String FORMATTED_REPLY_STATUS = "211-System name: abc.def\r\nVersion 3.5.7\r\n211 Number of failed logins: 2.";
202        StatCommandHandler statCommandHandler = (StatCommandHandler) stubFtpServer.getCommandHandler(CommandNames.STAT);
203        statCommandHandler.setStatus(STATUS);
204
205        ftpClientConnect();
206
207        // STAT
208        String status = ftpClient.getStatus();
209        assertEquals("STAT reply", FORMATTED_REPLY_STATUS, status.trim());
210        verifyReplyCode("getStatus", 211);
211    }
212
213    public void testSyst() throws Exception {
214        ftpClientConnect();
215
216        // SYST
217        assertEquals("getSystemName()", "\"WINDOWS\" system type.", ftpClient.getSystemName());
218        verifyReplyCode("syst", 215);
219    }
220
221    public void testCwd() throws Exception {
222        // Connect
223        LOG.info("Conecting to " + SERVER);
224        ftpClientConnect();
225        verifyReplyCode("connect", 220);
226
227        // CWD
228        boolean success = ftpClient.changeWorkingDirectory("dir1/dir2");
229        assertTrue("Unable to CWD", success);
230        verifyReplyCode("changeWorkingDirectory", 250);
231    }
232
233    /**
234     * Test changing the current working directory (CWD), when it causes a remote error
235     */
236    public void testCwd_Error() throws Exception {
237        // Override CWD CommandHandler to return error reply code
238        final int REPLY_CODE = 500;
239        StaticReplyCommandHandler cwdCommandHandler = new StaticReplyCommandHandler(REPLY_CODE);
240        stubFtpServer.setCommandHandler("CWD", cwdCommandHandler);
241
242        ftpClientConnect();
243
244        // CWD
245        boolean success = ftpClient.changeWorkingDirectory("dir1/dir2");
246        assertFalse("Expected failure", success);
247        verifyReplyCode("changeWorkingDirectory", REPLY_CODE);
248    }
249
250    public void testCdup() throws Exception {
251        ftpClientConnect();
252
253        // CDUP
254        boolean success = ftpClient.changeToParentDirectory();
255        assertTrue("Unable to CDUP", success);
256        verifyReplyCode("changeToParentDirectory", 200);
257    }
258
259    public void testDele() throws Exception {
260        ftpClientConnect();
261
262        // DELE
263        boolean success = ftpClient.deleteFile(FILENAME);
264        assertTrue("Unable to DELE", success);
265        verifyReplyCode("deleteFile", 250);
266    }
267
268    public void testFeat_UseStaticReplyCommandHandler() throws IOException {
269        // The FEAT command is not supported out of the box
270        final String FEAT_TEXT = "Extensions supported:\n" +
271                "MLST size*;create;modify*;perm;media-type\n" +
272                "SIZE\n" +
273                "COMPRESSION\n" +
274                "END";
275        StaticReplyCommandHandler featCommandHandler = new StaticReplyCommandHandler(211, FEAT_TEXT);
276        stubFtpServer.setCommandHandler("FEAT", featCommandHandler);
277
278        ftpClientConnect();
279        assertEquals(ftpClient.sendCommand("FEAT"), 211);
280        LOG.info(ftpClient.getReplyString());
281    }
282
283    public void testMkd() throws Exception {
284        ftpClientConnect();
285
286        // MKD
287        boolean success = ftpClient.makeDirectory("dir1/dir2");
288        assertTrue("Unable to CWD", success);
289        verifyReplyCode("makeDirectory", 257);
290    }
291
292    public void testNoop() throws Exception {
293        ftpClientConnect();
294
295        // NOOP
296        boolean success = ftpClient.sendNoOp();
297        assertTrue("Unable to NOOP", success);
298        verifyReplyCode("NOOP", 200);
299    }
300
301    public void testRest() throws Exception {
302        ftpClientConnect();
303
304        // REST
305        int replyCode = ftpClient.rest("marker");
306        assertEquals("Unable to REST", 350, replyCode);
307    }
308
309    public void testRmd() throws Exception {
310        ftpClientConnect();
311
312        // RMD
313        boolean success = ftpClient.removeDirectory("dir1/dir2");
314        assertTrue("Unable to RMD", success);
315        verifyReplyCode("removeDirectory", 250);
316    }
317
318    public void testRename() throws Exception {
319        ftpClientConnect();
320
321        // Rename (RNFR, RNTO)
322        boolean success = ftpClient.rename(FILENAME, "new_" + FILENAME);
323        assertTrue("Unable to RENAME", success);
324        verifyReplyCode("rename", 250);
325    }
326
327    public void testAllo() throws Exception {
328        ftpClientConnect();
329
330        // ALLO
331        assertTrue("ALLO", ftpClient.allocate(1024));
332        assertTrue("ALLO with recordSize", ftpClient.allocate(1024, 64));
333    }
334
335    /**
336     * Test GET and PUT of ASCII files
337     */
338    public void testTransferAsciiFile() throws Exception {
339        retrCommandHandler.setFileContents(ASCII_CONTENTS);
340
341        ftpClientConnect();
342
343        // Get File
344        LOG.info("Get File for remotePath [" + FILENAME + "]");
345        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
346        assertTrue(ftpClient.retrieveFile(FILENAME, outputStream));
347        LOG.info("File contents=[" + outputStream.toString());
348        assertEquals("File contents", ASCII_CONTENTS, outputStream.toString());
349
350        // Put File
351        LOG.info("Put File for local path [" + FILENAME + "]");
352        ByteArrayInputStream inputStream = new ByteArrayInputStream(ASCII_CONTENTS.getBytes());
353        assertTrue(ftpClient.storeFile(FILENAME, inputStream));
354        InvocationRecord invocationRecord = storCommandHandler.getInvocation(0);
355        byte[] contents = (byte[]) invocationRecord.getObject(StorCommandHandler.FILE_CONTENTS_KEY);
356        LOG.info("File contents=[" + contents + "]");
357        assertEquals("File contents", ASCII_CONTENTS.getBytes(), contents);
358    }
359
360    /**
361     * Test GET and PUT of binary files
362     */
363    public void testTransferBinaryFiles() throws Exception {
364        retrCommandHandler.setFileContents(BINARY_CONTENTS);
365
366        ftpClientConnect();
367        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
368
369        // Get File
370        LOG.info("Get File for remotePath [" + FILENAME + "]");
371        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
372        assertTrue("GET", ftpClient.retrieveFile(FILENAME, outputStream));
373        LOG.info("GET File length=" + outputStream.size());
374        assertEquals("File contents", BINARY_CONTENTS, outputStream.toByteArray());
375
376        // Put File
377        LOG.info("Put File for local path [" + FILENAME + "]");
378        ByteArrayInputStream inputStream = new ByteArrayInputStream(BINARY_CONTENTS);
379        assertTrue("PUT", ftpClient.storeFile(FILENAME, inputStream));
380        InvocationRecord invocationRecord = storCommandHandler.getInvocation(0);
381        byte[] contents = (byte[]) invocationRecord.getObject(StorCommandHandler.FILE_CONTENTS_KEY);
382        LOG.info("PUT File length=" + contents.length);
383        assertEquals("File contents", BINARY_CONTENTS, contents);
384    }
385
386    public void testStou() throws Exception {
387        StouCommandHandler stouCommandHandler = (StouCommandHandler) stubFtpServer.getCommandHandler(CommandNames.STOU);
388        stouCommandHandler.setFilename(FILENAME);
389
390        ftpClientConnect();
391
392        // Stor a File (STOU)
393        ByteArrayInputStream inputStream = new ByteArrayInputStream(ASCII_CONTENTS.getBytes());
394        assertTrue(ftpClient.storeUniqueFile(FILENAME, inputStream));
395        InvocationRecord invocationRecord = stouCommandHandler.getInvocation(0);
396        byte[] contents = (byte[]) invocationRecord.getObject(StorCommandHandler.FILE_CONTENTS_KEY);
397        LOG.info("File contents=[" + contents + "]");
398        assertEquals("File contents", ASCII_CONTENTS.getBytes(), contents);
399    }
400
401    public void testAppe() throws Exception {
402        AppeCommandHandler appeCommandHandler = (AppeCommandHandler) stubFtpServer.getCommandHandler(CommandNames.APPE);
403
404        ftpClientConnect();
405
406        // Append a File (APPE)
407        ByteArrayInputStream inputStream = new ByteArrayInputStream(ASCII_CONTENTS.getBytes());
408        assertTrue(ftpClient.appendFile(FILENAME, inputStream));
409        InvocationRecord invocationRecord = appeCommandHandler.getInvocation(0);
410        byte[] contents = (byte[]) invocationRecord.getObject(AppeCommandHandler.FILE_CONTENTS_KEY);
411        LOG.info("File contents=[" + contents + "]");
412        assertEquals("File contents", ASCII_CONTENTS.getBytes(), contents);
413    }
414
415    public void testAbor() throws Exception {
416        ftpClientConnect();
417
418        // ABOR
419        assertTrue("ABOR", ftpClient.abort());
420    }
421
422    public void testPasv() throws Exception {
423        ftpClientConnect();
424
425        // PASV
426        ftpClient.enterLocalPassiveMode();
427        // no reply code; the PASV command is sent only when the data connection is opened
428    }
429
430    public void testMode() throws Exception {
431        ftpClientConnect();
432
433        // MODE
434        boolean success = ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
435        assertTrue("Unable to MODE", success);
436        verifyReplyCode("setFileTransferMode", 200);
437    }
438
439    public void testStru() throws Exception {
440        ftpClientConnect();
441
442        // STRU
443        boolean success = ftpClient.setFileStructure(FTP.FILE_STRUCTURE);
444        assertTrue("Unable to STRU", success);
445        verifyReplyCode("setFileStructure", 200);
446    }
447
448    public void testSimpleCompositeCommandHandler() throws Exception {
449        // Replace CWD CommandHandler with a SimpleCompositeCommandHandler
450        CommandHandler commandHandler1 = new StaticReplyCommandHandler(500);
451        CommandHandler commandHandler2 = new CwdCommandHandler();
452        SimpleCompositeCommandHandler simpleCompositeCommandHandler = new SimpleCompositeCommandHandler();
453        simpleCompositeCommandHandler.addCommandHandler(commandHandler1);
454        simpleCompositeCommandHandler.addCommandHandler(commandHandler2);
455        stubFtpServer.setCommandHandler("CWD", simpleCompositeCommandHandler);
456
457        // Connect
458        ftpClientConnect();
459
460        // CWD
461        assertFalse("first", ftpClient.changeWorkingDirectory("dir1/dir2"));
462        assertTrue("first", ftpClient.changeWorkingDirectory("dir1/dir2"));
463    }
464
465    public void testSite() throws Exception {
466        ftpClientConnect();
467
468        // SITE
469        int replyCode = ftpClient.site("parameters,1,2,3");
470        assertEquals("SITE", 200, replyCode);
471    }
472
473    public void testSmnt() throws Exception {
474        ftpClientConnect();
475
476        // SMNT
477        assertTrue("SMNT", ftpClient.structureMount("dir1/dir2"));
478        verifyReplyCode("structureMount", 250);
479    }
480
481    public void testRein() throws Exception {
482        ftpClientConnect();
483
484        // REIN
485        assertEquals("REIN", 220, ftpClient.rein());
486    }
487
488    /**
489     * Test that command names in lowercase or mixed upper/lower case are accepted
490     */
491    public void testCommandNamesInLowerOrMixedCase() throws Exception {
492        ftpClientConnect();
493
494        assertEquals("rein", 220, ftpClient.sendCommand("rein"));
495        assertEquals("rEIn", 220, ftpClient.sendCommand("rEIn"));
496        assertEquals("reiN", 220, ftpClient.sendCommand("reiN"));
497        assertEquals("Rein", 220, ftpClient.sendCommand("Rein"));
498    }
499
500    public void testUnrecognizedCommand() throws Exception {
501        ftpClientConnect();
502
503        assertEquals("Unrecognized:XXXX", 502, ftpClient.sendCommand("XXXX"));
504    }
505
506    // -------------------------------------------------------------------------
507    // Test setup and tear-down
508    // -------------------------------------------------------------------------
509
510    /**
511     * Perform initialization before each test
512     *
513     * @see org.mockftpserver.test.AbstractTest#setUp()
514     */
515    protected void setUp() throws Exception {
516        super.setUp();
517
518        for (int i = 0; i < BINARY_CONTENTS.length; i++) {
519            BINARY_CONTENTS[i] = (byte) i;
520        }
521
522        stubFtpServer = new StubFtpServer();
523        stubFtpServer.setServerControlPort(PortTestUtil.getFtpServerControlPort());
524        stubFtpServer.start();
525        ftpClient = new FTPClient();
526        retrCommandHandler = (RetrCommandHandler) stubFtpServer.getCommandHandler(CommandNames.RETR);
527        storCommandHandler = (StorCommandHandler) stubFtpServer.getCommandHandler(CommandNames.STOR);
528    }
529
530    /**
531     * Perform cleanup after each test
532     *
533     * @see org.mockftpserver.test.AbstractTest#tearDown()
534     */
535    protected void tearDown() throws Exception {
536        super.tearDown();
537        stubFtpServer.stop();
538    }
539
540    // -------------------------------------------------------------------------
541    // Internal Helper Methods
542    // -------------------------------------------------------------------------
543
544    /**
545     * Connect to the server from the FTPClient
546     */
547    private void ftpClientConnect() throws IOException {
548        ftpClient.connect(SERVER, PortTestUtil.getFtpServerControlPort());
549    }
550
551    /**
552     * Assert that the FtpClient reply code is equal to the expected value
553     *
554     * @param operation         - the description of the operation performed; used in the error message
555     * @param expectedReplyCode - the expected FtpClient reply code
556     */
557    private void verifyReplyCode(String operation, int expectedReplyCode) {
558        int replyCode = ftpClient.getReplyCode();
559        LOG.info("Reply: operation=\"" + operation + "\" replyCode=" + replyCode);
560        assertEquals("Unexpected replyCode for " + operation, expectedReplyCode, replyCode);
561    }
562
563    /**
564     * Verify that the FTPFile has the specified properties
565     *
566     * @param ftpFile - the FTPFile to verify
567     * @param type    - the expected file type
568     * @param name    - the expected file name
569     * @param size    - the expected file size (will be zero for a directory)
570     */
571    private void verifyFTPFile(FTPFile ftpFile, int type, String name, long size) {
572        LOG.info(ftpFile);
573        assertEquals("type: " + ftpFile, type, ftpFile.getType());
574        assertEquals("name: " + ftpFile, name, ftpFile.getName());
575        assertEquals("size: " + ftpFile, size, ftpFile.getSize());
576    }
577
578}
579