aboutsummaryrefslogtreecommitdiffstats
path: root/framework/src/ant/apache-ant-1.9.6/src/tests/junit/org/apache/tools/ant/taskdefs/optional/net/FTPTest.java
blob: 1a22115edac18943b540da81fa315e337132e134 (plain)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package org.apache.tools.ant.taskdefs.optional.net;

import static org.apache.tools.ant.AntAssert.assertContains;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Vector;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.BuildFileRule;
import org.apache.tools.ant.DefaultLogger;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.condition.Os;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.util.RetryHandler;
import org.apache.tools.ant.util.Retryable;
import org.apache.tools.ant.util.regexp.RegexpMatcher;
import org.apache.tools.ant.util.regexp.RegexpMatcherFactory;
import org.junit.After;
import org.junit.Assume;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;

//FIXME these tests are more integration than unit tests and report errors badly
public class FTPTest {
	
	@Rule
	public BuildFileRule buildRule = new BuildFileRule();
	
    // keep track of what operating systems are supported here.
    private boolean supportsSymlinks = Os.isFamily("unix");

    private FTPClient ftp;
    
    private boolean loginSuceeded = false;
    
    private String loginFailureMessage;
    
    private String tmpDir = null;
    private String remoteTmpDir = null;
    private String ftpFileSep = null;
    private myFTP myFTPTask = new myFTP();


    @Before
    public void setUp() {
        buildRule.configureProject("src/etc/testcases/taskdefs/optional/net/ftp.xml");
        Project project = buildRule.getProject();
        project.executeTarget("setup");
        tmpDir = project.getProperty("tmp.dir");
        ftp = new FTPClient();
        ftpFileSep = project.getProperty("ftp.filesep");
        myFTPTask.setSeparator(ftpFileSep);
        myFTPTask.setProject(project);
        remoteTmpDir = myFTPTask.resolveFile(tmpDir);
        String remoteHost = project.getProperty("ftp.host");
        int port = Integer.parseInt(project.getProperty("ftp.port"));
        String remoteUser = project.getProperty("ftp.user");
        String password = project.getProperty("ftp.password");
        boolean connectionSucceeded = false;
        try {
            ftp.connect(remoteHost, port);
            connectionSucceeded = true;
        } catch (Exception ex) {
            loginFailureMessage = "could not connect to host " + remoteHost + " on port " + port;
        }
        if (connectionSucceeded) {
            try {
                ftp.login(remoteUser, password);
                loginSuceeded = true;
            } catch (IOException ioe) {
                loginFailureMessage = "could not log on to " + remoteHost + " as user " + remoteUser;
            }
        }
    }

    @After
    public void tearDown() {
        try {
            if (ftp!= null) {
            	ftp.disconnect();
            }
        } catch (IOException ioe) {
            // do nothing
        }
        buildRule.getProject().executeTarget("cleanup");
    }
    
    private boolean changeRemoteDir(String remoteDir) {
        boolean result = true;
        try {
            ftp.cwd(remoteDir);
        }
        catch (Exception ex) {
            System.out.println("could not change directory to " + remoteTmpDir);
            result = false;
        }
        return result;
    }
    
    @Test
    public void test1() {
    	Assume.assumeTrue(loginFailureMessage, loginSuceeded);
    	Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        
    	FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha"});
        ds.scan();
        compareFiles(ds, new String[] {} ,new String[] {"alpha"});
    }

    @Test
    public void test2() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/"});
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml"},
            new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
    }

    @Test
    public void test3() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml"},
            new String[] {"alpha", "alpha/beta",
                          "alpha/beta/gamma"});
    }

    @Test
    public void testFullPathMatchesCaseSensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
        ds.scan();
        compareFiles(ds, new String[] {}, new String[] {});
    }

    @Test
    public void testFullPathMatchesCaseInsensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setCaseSensitive(false);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/beta/gamma/GAMMA.XML"});
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
            new String[] {});
    }

    @Test
    public void test2ButCaseInsensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"ALPHA/"});
        ds.setCaseSensitive(false);
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml"},
            new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
    }
    
    @Test
    public void test2bisButCaseInsensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
	    FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
	    ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
	    ds.setIncludes(new String[] {"alpha/BETA/gamma/"});
	    ds.setCaseSensitive(false);
	    ds.scan();
	    compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
	        new String[] {"alpha/beta/gamma"});
    }
    
    @Test
    public void testGetWithSelector() {
    	buildRule.executeTarget("ftp-get-with-selector");
    	assertContains("selectors are not supported in remote filesets", buildRule.getLog());
        FileSet fsDestination = (FileSet) buildRule.getProject().getReference("fileset-destination-without-selector");
        DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(buildRule.getProject());
        dsDestination.scan();
        String [] sortedDestinationDirectories = dsDestination.getIncludedDirectories();
        String [] sortedDestinationFiles = dsDestination.getIncludedFiles();
        for (int counter = 0; counter < sortedDestinationDirectories.length; counter++) {
            sortedDestinationDirectories[counter] =
                sortedDestinationDirectories[counter].replace(File.separatorChar, '/');
        }
        for (int counter = 0; counter < sortedDestinationFiles.length; counter++) {
            sortedDestinationFiles[counter] =
                sortedDestinationFiles[counter].replace(File.separatorChar, '/');
        }
        FileSet fsSource =  (FileSet) buildRule.getProject().getReference("fileset-source-without-selector");
        DirectoryScanner dsSource = fsSource.getDirectoryScanner(buildRule.getProject());
        dsSource.scan();
        compareFiles(dsSource, sortedDestinationFiles, sortedDestinationDirectories);
    }
    
    @Test
    public void testGetFollowSymlinksTrue() {
        Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        buildRule.getProject().executeTarget("ftp-get-directory-symbolic-link");
        FileSet fsDestination = (FileSet) buildRule.getProject().getReference("fileset-destination-without-selector");
        DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(buildRule.getProject());
        dsDestination.scan();
        compareFiles(dsDestination, new String[] {"alpha/beta/gamma/gamma.xml"},
            new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
    }
    
    @Test
    public void testGetFollowSymlinksFalse() {
        Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        buildRule.getProject().executeTarget("ftp-get-directory-no-symbolic-link");
        FileSet fsDestination = (FileSet) buildRule.getProject().getReference("fileset-destination-without-selector");
        DirectoryScanner dsDestination = fsDestination.getDirectoryScanner(buildRule.getProject());
        dsDestination.scan();
        compareFiles(dsDestination, new String[] {},
            new String[] {});
    }
    
    @Test
    public void testAllowSymlinks() {
        Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        buildRule.getProject().executeTarget("symlink-setup");
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/beta/gamma/"});
        ds.setFollowSymlinks(true);
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
                     new String[] {"alpha/beta/gamma"});
    }

    @Test
    public void testProhibitSymlinks() {
        Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        buildRule.getProject().executeTarget("symlink-setup");
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/beta/gamma/"});
        ds.setFollowSymlinks(false);
        ds.scan();
        compareFiles(ds, new String[] {}, new String[] {});
    }
    
    @Test
    public void testFileSymlink() {
        Assume.assumeTrue("System does not support Symlinks", supportsSymlinks);
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        buildRule.getProject().executeTarget("symlink-file-setup");
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/beta/gamma/"});
        ds.setFollowSymlinks(true);
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
                     new String[] {"alpha/beta/gamma"});
    }
    
    // father and child pattern test
    @Test
    public void testOrderOfIncludePatternsIrrelevant() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        String [] expectedFiles = {"alpha/beta/beta.xml",
                                   "alpha/beta/gamma/gamma.xml"};
        String [] expectedDirectories = {"alpha/beta", "alpha/beta/gamma" };
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/be?a/**", "alpha/beta/gamma/"});
        ds.scan();
        compareFiles(ds, expectedFiles, expectedDirectories);
        // redo the test, but the 2 include patterns are inverted
        ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/beta/gamma/", "alpha/be?a/**"});
        ds.scan();
        compareFiles(ds, expectedFiles, expectedDirectories);
    }

    @Test
    public void testPatternsDifferInCaseScanningSensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml"},
                     new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
    }

    @Test
    public void testPatternsDifferInCaseScanningInsensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/", "ALPHA/"});
        ds.setCaseSensitive(false);
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml"},
                     new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
    }

    @Test
    public void testFullpathDiffersInCaseScanningSensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {
            "alpha/beta/gamma/gamma.xml",
            "alpha/beta/gamma/GAMMA.XML"
        });
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
                     new String[] {});
    }

    @Test
    public void testFullpathDiffersInCaseScanningInsensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {
            "alpha/beta/gamma/gamma.xml",
            "alpha/beta/gamma/GAMMA.XML"
        });
        ds.setCaseSensitive(false);
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
                     new String[] {});
    }

    @Test
    public void testParentDiffersInCaseScanningSensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml"},
                     new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
    }

    @Test
    public void testParentDiffersInCaseScanningInsensitive() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {"alpha/", "ALPHA/beta/"});
        ds.setCaseSensitive(false);
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml"},
                     new String[] {"alpha", "alpha/beta", "alpha/beta/gamma"});
    }

    @Test
    public void testExcludeOneFile() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {
            "**/*.xml"
        });
        ds.setExcludes(new String[] {
            "alpha/beta/b*xml"
        });
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/gamma/gamma.xml"},
                     new String[] {});
    }
    
    @Test
    public void testExcludeHasPrecedence() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {
            "alpha/**"
        });
        ds.setExcludes(new String[] {
            "alpha/**"
        });
        ds.scan();
        compareFiles(ds, new String[] {},
                     new String[] {});

    }
    
    @Test
    public void testAlternateIncludeExclude() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setIncludes(new String[] {
            "alpha/**",
            "alpha/beta/gamma/**"
        });
        ds.setExcludes(new String[] {
            "alpha/beta/**"
        });
        ds.scan();
        compareFiles(ds, new String[] {},
                     new String[] {"alpha"});

    }
    
    @Test
    public void testAlternateExcludeInclude() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setExcludes(new String[] {
            "alpha/**",
            "alpha/beta/gamma/**"
        });
        ds.setIncludes(new String[] {
            "alpha/beta/**"
        });
        ds.scan();
        compareFiles(ds, new String[] {},
                     new String[] {});

    }
    
    /**
     * Test inspired by Bug#1415.
     */
    @Test
    public void testChildrenOfExcludedDirectory() {
        Assume.assumeTrue(loginFailureMessage, loginSuceeded);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        buildRule.getProject().executeTarget("children-of-excluded-dir-setup");
        FTP.FTPDirectoryScanner ds = myFTPTask.newScanner(ftp);
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setExcludes(new String[] {"alpha/**"});
        ds.scan();
        compareFiles(ds, new String[] {"delta/delta.xml"},
                    new String[] {"delta"});

        ds = myFTPTask.newScanner(ftp);
        Assume.assumeTrue("Could not change remote directory", changeRemoteDir(remoteTmpDir));
        ds.setBasedir(new File(buildRule.getProject().getBaseDir(), "tmp"));
        ds.setExcludes(new String[] {"alpha"});
        ds.scan();
        compareFiles(ds, new String[] {"alpha/beta/beta.xml",
                                       "alpha/beta/gamma/gamma.xml",
                                        "delta/delta.xml"},
                     new String[] {"alpha/beta", "alpha/beta/gamma", "delta"});

    }
    
    /**
     * This class enables the use of the log messages as a way of testing 
     * the number of files actually transferred.
     * It uses the ant regular expression mechanism to get a regex parser
     * to parse the log output.
     */
    private class CountLogListener extends DefaultLogger {
        private Vector lastMatchGroups = null;
        private RegexpMatcher matcher = new RegexpMatcherFactory().newRegexpMatcher();

        /**
         * The only constructor for a CountLogListener
         * @param pattern a regular expression pattern.  It should have 
         * one parenthesized group and that group should contain the
         * number desired.
         */
        public CountLogListener(String pattern) {
            super();
            this.matcher.setPattern(pattern);
        }
        
        
        /* 
         * @param event the build event that is being logged.
         */
        public void messageLogged(BuildEvent event) {
            String message = event.getMessage();
            if (this.matcher.matches(message)) {
                lastMatchGroups = this.matcher.getGroups(message);
            }
            super.messageLogged(event);
        }
        
        /**
         * returns the desired number that results from parsing the log
         * message
         * @return the number of files indicated in the desired message or -1
         * if a matching log message was never found.
         */
        public int getCount() {
            if (this.lastMatchGroups == null) {
                return -1;
            }
            return Integer.parseInt((String) this.lastMatchGroups.get(1));
        }
    }
    
    /**
     * This class enables the use of the log to count the number
     * of times a message has been emitted.
     */
    private class LogCounter extends DefaultLogger {
        private Map searchMap = new HashMap();
        private int matchCount;

        public void addLogMessageToSearch(String message) {
            searchMap.put(message, new Integer(0));
        }
        
        /* 
         * @param event the build event that is being logged.
         */
        public void messageLogged(BuildEvent event) {
            String message = event.getMessage();
            Integer mcnt = (Integer) searchMap.get(message);
            if (null != mcnt) {
                searchMap.put(message, new Integer(mcnt.intValue() + 1));
            }
            super.messageLogged(event);
        }
        
        /**
         * @return the number of times that the looked for message was sent 
         * to the log
         */
        public int getMatchCount(String message) {
            Integer mcnt = (Integer) searchMap.get(message);
            if (null != mcnt) {
                return mcnt.intValue();
            }
            return 0;
        }
    }
    /**
     * Tests the combination of the newer parameter and the 
     * serverTimezoneConfig  parameter in the PUT action.  The default 
     * configuration is an ftp server on localhost which formats 
     * timestamps as GMT.
     */
    @Test
    public void testTimezonePut() {
        CountLogListener log = new CountLogListener("(\\d+) files? sent");
        buildRule.getProject().executeTarget("timed.test.setup");
        buildRule.getProject().addBuildListener(log);
        buildRule.getProject().executeTarget("timed.test.put.older");
        assertEquals(1, log.getCount());
    }

    /**
     * Tests the combination of the newer parameter and the 
     * serverTimezoneConfig  parameter in the GET action.  The default 
     * configuration is an ftp server on localhost which formats 
     * timestamps as GMT.
     */
    @Test
    public void testTimezoneGet() {
        CountLogListener log = new CountLogListener("(\\d+) files? retrieved");
        buildRule.getProject().executeTarget("timed.test.setup");
        buildRule.getProject().addBuildListener(log);
        buildRule.getProject().executeTarget("timed.test.get.older");
        assertEquals(3, log.getCount());
    }
   
    
    /**
     * Tests that the presence of one of the server config params forces
     * the system type to Unix if not specified.
     */
    @Test
    public void testConfiguration1() {
        int[] expectedCounts = {
                1,1,0,1,0,0,0
        };
        performConfigTest("configuration.1", expectedCounts);
        
    }

    /**
     * Tests the systemTypeKey attribute.
     */
    @Test
    public void testConfiguration2() {
        int[] expectedCounts = {
                1,0,0,1,1,0,0
        };
        performConfigTest("configuration.2", expectedCounts);
        
    }

    /**
     * Tests the systemTypeKey attribute with UNIX specified.
     */
    @Test
    public void testConfiguration3() {
        int[] expectedCounts = {
                1,0,1,0,0,1,0
        };
        performConfigTest("configuration.3", expectedCounts);
        
    }
    
    @Test
    public void testConfigurationLang() {
        int[] expectedCounts = {
                1,1,0,0,0,0,1
        };
        performConfigTest("configuration.lang.good", expectedCounts);
        
        try {
            performConfigTest("configuration.lang.bad", expectedCounts);
            fail("BuildException Expected");
        } catch (Exception bx) {
            assertTrue(bx instanceof BuildException); 
        }
    }
    /**
     * Tests the systemTypeKey attribute.
     */
    @Test
    public void testConfigurationNone() {
        int[] expectedCounts = {
                0,0,0,0,0,0,0
        };
        performConfigTest("configuration.none", expectedCounts);
 
    }
    
    private void performConfigTest(String target, int[] expectedCounts) {
        String[] messages = new String[]{
                "custom configuration",
                "custom config: system key = default (UNIX)",
                "custom config: system key = UNIX",
                "custom config: server time zone ID = " + buildRule.getProject().getProperty("ftp.server.timezone"),
                "custom config: system key = WINDOWS",
                "custom config: default date format = yyyy/MM/dd HH:mm",
                "custom config: server language code = de" 

        };
        LogCounter counter = new LogCounter();
        for (int i=0; i < messages.length; i++) {
            counter.addLogMessageToSearch(messages[i]);
        }
            
        buildRule.getProject().addBuildListener(counter);
        buildRule.getProject().executeTarget(target);
        for (int i=0; i < messages.length; i++) {
            assertEquals("target "+target+":message "+ i, expectedCounts[i], counter.getMatchCount(messages[i]));
        }
        
    }

    
    /**
     *  this test is inspired by a user reporting that deletions of directories with the ftp task do not work
     */
    @Test
    public void testFTPDelete() {
        buildRule.getProject().executeTarget("ftp-delete");
    }
    
    private void compareFiles(DirectoryScanner ds, String[] expectedFiles,
                              String[] expectedDirectories) {
        String includedFiles[] = ds.getIncludedFiles();
        String includedDirectories[] = ds.getIncludedDirectories();
        assertEquals("file present: ", expectedFiles.length,
                     includedFiles.length);
        assertEquals("directories present: ", expectedDirectories.length,
                     includedDirectories.length);

        for (int counter=0; counter < includedFiles.length; counter++) {
            includedFiles[counter] = includedFiles[counter].replace(File.separatorChar, '/');
        }
        Arrays.sort(includedFiles);
        for (int counter=0; counter < includedDirectories.length; counter++) {
            includedDirectories[counter] = includedDirectories[counter]
                            .replace(File.separatorChar, '/');
        }
        Arrays.sort(includedDirectories);
        for (int counter=0; counter < includedFiles.length; counter++) {
            assertEquals(expectedFiles[counter], includedFiles[counter]);
        }
        for (int counter=0; counter < includedDirectories.length; counter++) {
            assertEquals(expectedDirectories[counter], includedDirectories[counter]);
            counter++;
        }
    }
    private static class myFTP extends FTP {
        public FTP.FTPDirectoryScanner newScanner(FTPClient client) {
            return new FTP.FTPDirectoryScanner(client);
        }
        // provide public visibility
        public String resolveFile(String file) {
            return super.resolveFile(file);
        }
    }


    public abstract static class myRetryableFTP extends FTP {
        private final int numberOfFailuresToSimulate;
        private int simulatedFailuresLeft;
        
        protected myRetryableFTP(int numberOfFailuresToSimulate) {
            this.numberOfFailuresToSimulate = numberOfFailuresToSimulate;
            this.simulatedFailuresLeft = numberOfFailuresToSimulate;
        }

        protected void getFile(FTPClient ftp, String dir, String filename)
                throws IOException, BuildException 
        {
            if (this.simulatedFailuresLeft > 0) {
                this.simulatedFailuresLeft--;
                throw new IOException("Simulated failure for testing");
            }
           super.getFile(ftp, dir, filename);
        }
        protected void executeRetryable(RetryHandler h, Retryable r,
                String filename) throws IOException 
        {
            this.simulatedFailuresLeft = this.numberOfFailuresToSimulate;    
            super.executeRetryable(h, r, filename);
        }
    }
    public static class oneFailureFTP extends myRetryableFTP {
        public oneFailureFTP() {
            super(1);
        }
    }
    public static class twoFailureFTP extends myRetryableFTP {
        public twoFailureFTP() {
            super(2);
        }
    }
    public static class threeFailureFTP extends myRetryableFTP {
        public threeFailureFTP() {
            super(3);
        }
    }
    
    public static class randomFailureFTP extends myRetryableFTP {
        public randomFailureFTP() {
            super(new Random().nextInt(Short.MAX_VALUE));
        }
    }
    public void testGetWithSelectorRetryable1() {
        buildRule.getProject().addTaskDefinition("ftp", oneFailureFTP.class);
        try {
            buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
        } catch (BuildException bx) {
            fail("Two retries expected, failed after one.");
        }
    }
    
    @Test
    public void testGetWithSelectorRetryable2() {
        buildRule.getProject().addTaskDefinition("ftp", twoFailureFTP.class);
        try {
            buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
        } catch (BuildException bx) {
            fail("Two retries expected, failed after two.");
        }
    }
    
    @Test
    public void testGetWithSelectorRetryable3() {
        buildRule.getProject().addTaskDefinition("ftp", threeFailureFTP.class);
        try {
            buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
            fail("Two retries expected, continued after two.");
        } catch (BuildException bx) {
        }
    }
    
    @Test
    public void testGetWithSelectorRetryableRandom() {
        buildRule.getProject().addTaskDefinition("ftp", randomFailureFTP.class);
        try {
            buildRule.getProject().setProperty("ftp.retries", "forever");
            buildRule.getProject().executeTarget("ftp-get-with-selector-retryable");
        } catch (BuildException bx) {
            fail("Retry forever specified, but failed.");
        }
    }
    
    @Test
    public void testInitialCommand() {
        performCommandTest("test-initial-command", new int[] { 1,0 });
    }
    
    @Test
    public void testSiteAction() {
        performCommandTest("test-site-action", new int[] { 1,0 });
    }
    
    private void performCommandTest(String target, int[] expectedCounts) {
        String[] messages = new String[]{
                "Doing Site Command: umask 222",
                "Failed to issue Site Command: umask 222",

        };
        LogCounter counter = new LogCounter();
        for (int i=0; i < messages.length; i++) {
            counter.addLogMessageToSearch(messages[i]);
        }
            
        buildRule.getProject().addBuildListener(counter);
        buildRule.getProject().executeTarget(target);
        for (int i=0; i < messages.length; i++) {
            assertEquals("target "+target+":message "+ i, expectedCounts[i], counter.getMatchCount(messages[i]));
        }

    }
    
}