KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > oddjob > dummy > DummyFtpTask


1 /*
2  * Copyright (c) 2005, Rob Gordon.
3  */

4 package org.oddjob.dummy;
5
6 import java.io.File JavaDoc;
7 import java.util.Enumeration JavaDoc;
8 import java.util.Locale JavaDoc;
9 import java.util.Vector JavaDoc;
10
11 import org.apache.tools.ant.BuildException;
12 import org.apache.tools.ant.Project;
13 import org.apache.tools.ant.Task;
14 import org.apache.tools.ant.types.DummyFileSet;
15 import org.apache.tools.ant.types.EnumeratedAttribute;
16 import org.apache.tools.ant.types.FileSet;
17 import org.apache.tools.ant.types.selectors.FileSelector;
18
19 /**
20  *
21  * @author Rob Gordon.
22  */

23 public class DummyFtpTask extends Task {
24
25     protected static final int SEND_FILES = 0;
26
27     protected static final int GET_FILES = 1;
28
29     protected static final int DEL_FILES = 2;
30
31     protected static final int LIST_FILES = 3;
32
33     protected static final int MK_DIR = 4;
34
35     protected static final int CHMOD = 5;
36
37     protected static final int RM_DIR = 6;
38
39     /** return code of ftp - not implemented in commons-net version 1.0 */
40     private static final int CODE_521 = 521;
41
42     /** Default port for FTP */
43     public static final int DEFAULT_FTP_PORT = 21;
44
45     private String JavaDoc remotedir;
46
47     private String JavaDoc server;
48
49     private String JavaDoc userid;
50
51     private String JavaDoc password;
52
53     private File JavaDoc listing;
54
55     private boolean binary = true;
56
57     private boolean passive = false;
58
59     private boolean verbose = false;
60
61     private boolean newerOnly = false;
62
63     private boolean timeDiffAuto = false;
64
65     private long timeDiffMillis = 0;
66
67     private int action;
68
69     private Vector JavaDoc filesets = new Vector JavaDoc();
70
71     private Vector JavaDoc dirCache = new Vector JavaDoc();
72
73     private int transferred = 0;
74
75     private String JavaDoc remoteFileSep = "/";
76
77     private int port = DEFAULT_FTP_PORT;
78
79     private boolean skipFailedTransfers = false;
80
81     private int skipped = 0;
82
83     private boolean ignoreNoncriticalErrors = false;
84
85     private boolean preserveLastModified = false;
86
87     private String JavaDoc chmod = null;
88
89     private String JavaDoc umask = null;
90
91     protected static final String JavaDoc[] ACTION_STRS = { "sending", "getting",
92             "deleting", "listing", "making directory", "chmod", "removing" };
93
94     protected static final String JavaDoc[] COMPLETED_ACTION_STRS = { "sent",
95             "retrieved", "deleted", "listed", "created directory",
96             "mode changed", "removed" };
97
98     protected static final String JavaDoc[] ACTION_TARGET_STRS = { "files", "files",
99             "files", "files", "directory", "files", "directories" };
100
101     /**
102      * Sets the remote directory where files will be placed. This may be a
103      * relative or absolute path, and must be in the path syntax expected by the
104      * remote server. No correction of path syntax will be performed.
105      *
106      * @param dir
107      * the remote directory name.
108      */

109     public void setRemotedir(String JavaDoc dir) {
110         this.remotedir = dir;
111     }
112
113     /**
114      * Sets the FTP server to send files to.
115      *
116      * @param server
117      * the remote server name.
118      */

119     public void setServer(String JavaDoc server) {
120         this.server = server;
121     }
122
123     /**
124      * Sets the FTP port used by the remote server.
125      *
126      * @param port
127      * the port on which the remote server is listening.
128      */

129     public void setPort(int port) {
130         this.port = port;
131     }
132
133     /**
134      * Sets the login user id to use on the specified server.
135      *
136      * @param userid
137      * remote system userid.
138      */

139     public void setUserid(String JavaDoc userid) {
140         this.userid = userid;
141     }
142
143     /**
144      * Sets the login password for the given user id.
145      *
146      * @param password
147      * the password on the remote system.
148      */

149     public void setPassword(String JavaDoc password) {
150         this.password = password;
151     }
152
153     /**
154      * If true, uses binary mode, otherwise text mode (default is binary).
155      *
156      * @param binary
157      * if true use binary mode in transfers.
158      */

159     public void setBinary(boolean binary) {
160         this.binary = binary;
161     }
162
163     /**
164      * Specifies whether to use passive mode. Set to true if you are behind a
165      * firewall and cannot connect without it. Passive mode is disabled by
166      * default.
167      *
168      * @param passive
169      * true is passive mode should be used.
170      */

171     public void setPassive(boolean passive) {
172         this.passive = passive;
173     }
174
175     /**
176      * Set to true to receive notification about each file as it is transferred.
177      *
178      * @param verbose
179      * true if verbose notifications are required.
180      */

181     public void setVerbose(boolean verbose) {
182         this.verbose = verbose;
183     }
184
185     /**
186      * A synonym for <tt>depends</tt>. Set to true to transmit only new or
187      * changed files.
188      *
189      * See the related attributes timediffmillis and timediffauto.
190      *
191      * @param newer
192      * if true only transfer newer files.
193      */

194     public void setNewer(boolean newer) {
195         this.newerOnly = newer;
196     }
197
198     /**
199      * number of milliseconds to add to the time on the remote machine to get
200      * the time on the local machine.
201      *
202      * use in conjunction with <code>newer</code>
203      *
204      * @param timeDiffMillis
205      * number of milliseconds
206      *
207      * @since ant 1.6
208      */

209     public void setTimeDiffMillis(long timeDiffMillis) {
210         this.timeDiffMillis = timeDiffMillis;
211     }
212
213     /**
214      * &quot;true&quot; to find out automatically the time difference between
215      * local and remote machine.
216      *
217      * This requires right to create and delete a temporary file in the remote
218      * directory.
219      *
220      * @param timeDiffAuto
221      * true = find automatically the time diff
222      *
223      * @since ant 1.6
224      */

225     public void setTimeDiffAuto(boolean timeDiffAuto) {
226         this.timeDiffAuto = timeDiffAuto;
227     }
228
229     /**
230      * Set to true to preserve modification times for "gotten" files.
231      *
232      * @param preserveLastModified
233      * if true preserver modification times.
234      */

235     public void setPreserveLastModified(boolean preserveLastModified) {
236         this.preserveLastModified = preserveLastModified;
237     }
238
239     /**
240      * Set to true to transmit only files that are new or changed from their
241      * remote counterparts. The default is to transmit all files.
242      *
243      * @param depends
244      * if true only transfer newer files.
245      */

246     public void setDepends(boolean depends) {
247         this.newerOnly = depends;
248     }
249
250     /**
251      * Sets the remote file separator character. This normally defaults to the
252      * Unix standard forward slash, but can be manually overridden using this
253      * call if the remote server requires some other separator. Only the first
254      * character of the string is used.
255      *
256      * @param separator
257      * the file separator on the remote system.
258      */

259     public void setSeparator(String JavaDoc separator) {
260         remoteFileSep = separator;
261     }
262
263     /**
264      * Sets the file permission mode (Unix only) for files sent to the server.
265      *
266      * @param theMode
267      * unix style file mode for the files sent to the remote system.
268      */

269     public void setChmod(String JavaDoc theMode) {
270         this.chmod = theMode;
271     }
272
273     /**
274      * Sets the default mask for file creation on a unix server.
275      *
276      * @param theUmask
277      * unix style umask for files created on the remote server.
278      */

279     public void setUmask(String JavaDoc theUmask) {
280         this.umask = theUmask;
281     }
282
283     /**
284      * A set of files to upload or download
285      *
286      * @param set
287      * the set of files to be added to the list of files to be
288      * transferred.
289      */

290     public void addFileset(DummyFileSet set) {
291         filesets.addElement(set);
292     }
293
294     /**
295      * Sets the FTP action to be taken. Currently accepts "put", "get", "del",
296      * "mkdir" and "list".
297      *
298      * @deprecated setAction(String) is deprecated and is replaced with
299      * setAction(FTP.Action) to make Ant's Introspection mechanism
300      * do the work and also to encapsulate operations on the type in
301      * its own class.
302      * @ant.attribute ignore="true"
303      *
304      * @param action
305      * the FTP action to be performed.
306      *
307      * @throws BuildException
308      * if the action is not a valid action.
309      */

310     public void setAction(String JavaDoc action) throws BuildException {
311         log("DEPRECATED - The setAction(String) method has been deprecated."
312                 + " Use setAction(FTP.Action) instead.");
313
314         Action a = new Action();
315
316         a.setValue(action);
317         this.action = a.getAction();
318     }
319
320     /**
321      * Sets the FTP action to be taken. Currently accepts "put", "get", "del",
322      * "mkdir", "chmod" and "list".
323      *
324      * @param action
325      * the FTP action to be performed.
326      *
327      * @throws BuildException
328      * if the action is not a valid action.
329      */

330     public void setAction(Action action) throws BuildException {
331         this.action = action.getAction();
332     }
333
334     /**
335      * The output file for the "list" action. This attribute is ignored for any
336      * other actions.
337      *
338      * @param listing
339      * file in which to store the listing.
340      */

341     public void setListing(File JavaDoc listing) {
342         this.listing = listing;
343     }
344
345     /**
346      * If true, enables unsuccessful file put, delete and get operations to be
347      * skipped with a warning and the remainder of the files still transferred.
348      *
349      * @param skipFailedTransfers
350      * true if failures in transfers are ignored.
351      */

352     public void setSkipFailedTransfers(boolean skipFailedTransfers) {
353         this.skipFailedTransfers = skipFailedTransfers;
354     }
355
356     /**
357      * set the flag to skip errors on directory creation. (and maybe later other
358      * server specific errors)
359      *
360      * @param ignoreNoncriticalErrors
361      * true if non-critical errors should not cause a failure.
362      */

363     public void setIgnoreNoncriticalErrors(boolean ignoreNoncriticalErrors) {
364         this.ignoreNoncriticalErrors = ignoreNoncriticalErrors;
365     }
366
367     /**
368      * Checks to see that all required parameters are set.
369      *
370      * @throws BuildException
371      * if the configuration is not valid.
372      */

373     protected void checkConfiguration() throws BuildException {
374         if (server == null) {
375             throw new BuildException("server attribute must be set!");
376         }
377         if (userid == null) {
378             throw new BuildException("userid attribute must be set!");
379         }
380         if (password == null) {
381             throw new BuildException("password attribute must be set!");
382         }
383
384         if ((action == LIST_FILES) && (listing == null)) {
385             throw new BuildException("listing attribute must be set for list "
386                     + "action!");
387         }
388
389         if (action == MK_DIR && remotedir == null) {
390             throw new BuildException("remotedir attribute must be set for "
391                     + "mkdir action!");
392         }
393
394         if (action == CHMOD && chmod == null) {
395             throw new BuildException("chmod attribute must be set for chmod "
396                     + "action!");
397         }
398     }
399
400     /**
401      * Sends all files specified by the configured filesets to the remote
402      * server.
403      *
404      * @param ftp the FTPClient instance used to perform FTP actions
405      *
406      * @throws IOException if there is a problem reading a file
407      * @throws BuildException if there is a problem in the configuration.
408      */

409     protected void transferFiles()
410          throws BuildException {
411         transferred = 0;
412         skipped = 0;
413
414         if (filesets.size() == 0) {
415             throw new BuildException("at least one fileset must be specified.");
416         } else {
417             // get files from filesets
418
for (int i = 0; i < filesets.size(); i++) {
419                 DummyFileSet fs = (DummyFileSet) filesets.elementAt(i);
420
421                 if (fs != null) {
422                     log(fs.toString());
423                 }
424             }
425         }
426         
427         if (Math.random() > 0.8) {
428             
429             throw new BuildException("Pretending FTP Failed Exception");
430         }
431
432         log(transferred + " " + ACTION_TARGET_STRS[action] + " "
433             + COMPLETED_ACTION_STRS[action]);
434     }
435
436     /**
437      * Runs the task.
438      *
439      * @throws BuildException
440      * if the task fails or is not configured correctly.
441      */

442     public void execute() throws BuildException {
443         checkConfiguration();
444
445         try {
446             log("Opening FTP connection to " + server, Project.MSG_VERBOSE);
447             log("...pretending to connect.");
448             log("connected", Project.MSG_VERBOSE);
449             log("logging in to FTP server", Project.MSG_VERBOSE);
450             log("login succeeded", Project.MSG_VERBOSE);
451             
452             if (binary) {
453                 log("...pretending to change mode to binary");
454             } else {
455                 log("...pretending to change mode to ascii");
456             }
457             
458             if (passive) {
459                 log("entering passive mode", Project.MSG_VERBOSE);
460             }
461
462             log("...pretending to do action ["
463                     + ACTION_STRS[action] + "]");
464             // If the action is MK_DIR, then the specified remote
465
// directory is the directory to create.
466

467             if (action == MK_DIR) {
468                 log("...pretending to make remote dir [" + remotedir + "].");
469             } else {
470                 if (remotedir != null) {
471                     log("changing the remote directory", Project.MSG_VERBOSE);
472                     log("...pretending to change to remote dir [" + remotedir
473                             + "]");
474                 }
475                 log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]);
476                 transferFiles();
477             }
478
479         } finally {
480             log("disconnecting", Project.MSG_VERBOSE);
481         }
482     }
483
484     /**
485      * an action to perform, one of "send", "put", "recv", "get", "del",
486      * "delete", "list", "mkdir", "chmod", "rmdir"
487      */

488     public static class Action extends EnumeratedAttribute {
489
490         private static final String JavaDoc[] VALID_ACTIONS = { "send", "put", "recv",
491                 "get", "del", "delete", "list", "mkdir", "chmod", "rmdir" };
492
493         /**
494          * Get the valid values
495          *
496          * @return an array of the valid FTP actions.
497          */

498         public String JavaDoc[] getValues() {
499             return VALID_ACTIONS;
500         }
501
502         /**
503          * Get the symbolic equivalent of the action value.
504          *
505          * @return the SYMBOL representing the given action.
506          */

507         public int getAction() {
508             String JavaDoc actionL = getValue().toLowerCase(Locale.US);
509
510             if (actionL.equals("send") || actionL.equals("put")) {
511                 return SEND_FILES;
512             } else if (actionL.equals("recv") || actionL.equals("get")) {
513                 return GET_FILES;
514             } else if (actionL.equals("del") || actionL.equals("delete")) {
515                 return DEL_FILES;
516             } else if (actionL.equals("list")) {
517                 return LIST_FILES;
518             } else if (actionL.equals("chmod")) {
519                 return CHMOD;
520             } else if (actionL.equals("mkdir")) {
521                 return MK_DIR;
522             } else if (actionL.equals("rmdir")) {
523                 return RM_DIR;
524             }
525             return SEND_FILES;
526         }
527     }
528     
529     private void logFileSet(FileSet fs) {
530         StringBuffer JavaDoc text = new StringBuffer JavaDoc();
531         text.append("FileSelectors:");
532         Enumeration JavaDoc e = fs.selectorElements();
533         while (e.hasMoreElements()) {
534             text.append("\n");
535             FileSelector selector = (FileSelector) e.nextElement();
536             text.append(selector.toString());
537         }
538         log(text.toString());
539     }
540     
541 }
Popular Tags