KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > vfs > example > Shell


1 /*
2  * Copyright 2002-2005 The Apache Software Foundation.
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  */

16 package org.apache.commons.vfs.example;
17
18 import org.apache.commons.vfs.FileContent;
19 import org.apache.commons.vfs.FileObject;
20 import org.apache.commons.vfs.FileSystemException;
21 import org.apache.commons.vfs.FileSystemManager;
22 import org.apache.commons.vfs.FileType;
23 import org.apache.commons.vfs.FileUtil;
24 import org.apache.commons.vfs.Selectors;
25 import org.apache.commons.vfs.VFS;
26
27 import java.io.BufferedReader JavaDoc;
28 import java.io.IOException JavaDoc;
29 import java.io.InputStreamReader JavaDoc;
30 import java.text.DateFormat JavaDoc;
31 import java.util.ArrayList JavaDoc;
32 import java.util.Date JavaDoc;
33 import java.util.StringTokenizer JavaDoc;
34
35 /**
36  * A simple command-line shell for performing file operations.
37  *
38  * @author <a HREF="mailto:adammurdoch@apache.org">Adam Murdoch</a>
39  * @author Gary D. Gregory
40  */

41 public class Shell
42 {
43     private static final String JavaDoc CVS_ID = "$Id: Shell.java,v 1.2 2006/09/07 09:27:08 james Exp $";
44     private final FileSystemManager mgr;
45     private FileObject cwd;
46     private BufferedReader JavaDoc reader;
47
48     public static void main(final String JavaDoc[] args)
49     {
50         try
51         {
52             (new Shell()).go();
53         }
54         catch (Exception JavaDoc e)
55         {
56             e.printStackTrace();
57             System.exit(1);
58         }
59         System.exit(0);
60     }
61
62     private Shell() throws FileSystemException
63     {
64         mgr = VFS.getManager();
65         cwd = mgr.resolveFile(System.getProperty("user.dir"));
66         reader = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(System.in));
67     }
68
69     private void go() throws Exception JavaDoc
70     {
71         System.out.println("VFS Shell [" + CVS_ID + "]");
72         while (true)
73         {
74             final String JavaDoc[] cmd = nextCommand();
75             if (cmd == null)
76             {
77                 return;
78             }
79             if (cmd.length == 0)
80             {
81                 continue;
82             }
83             final String JavaDoc cmdName = cmd[0];
84             if (cmdName.equalsIgnoreCase("exit") || cmdName.equalsIgnoreCase("quit"))
85             {
86                 return;
87             }
88             try
89             {
90                 handleCommand(cmd);
91             }
92             catch (final Exception JavaDoc e)
93             {
94                 System.err.println("Command failed:");
95                 e.printStackTrace(System.err);
96             }
97         }
98     }
99
100     /**
101      * Handles a command.
102      */

103     private void handleCommand(final String JavaDoc[] cmd) throws Exception JavaDoc
104     {
105         final String JavaDoc cmdName = cmd[0];
106         if (cmdName.equalsIgnoreCase("cat"))
107         {
108             cat(cmd);
109         }
110         else if (cmdName.equalsIgnoreCase("cd"))
111         {
112             cd(cmd);
113         }
114         else if (cmdName.equalsIgnoreCase("cp"))
115         {
116             cp(cmd);
117         }
118         else if (cmdName.equalsIgnoreCase("help"))
119         {
120             help();
121         }
122         else if (cmdName.equalsIgnoreCase("ls"))
123         {
124             ls(cmd);
125         }
126         else if (cmdName.equalsIgnoreCase("pwd"))
127         {
128             pwd();
129         }
130         else if (cmdName.equalsIgnoreCase("rm"))
131         {
132             rm(cmd);
133         }
134         else if (cmdName.equalsIgnoreCase("touch"))
135         {
136             touch(cmd);
137         }
138         else
139         {
140             System.err.println("Unknown command \"" + cmdName + "\".");
141         }
142     }
143
144     /**
145      * Does a 'help' command.
146      */

147     private void help()
148     {
149         System.out.println("Commands:");
150         System.out.println("cat <file> Displays the contents of a file.");
151         System.out.println("cd [folder] Changes current folder.");
152         System.out.println("cp <src> <dest> Copies a file or folder.");
153         System.out.println("help Shows this message.");
154         System.out.println("ls [-R] [path] Lists contents of a file or folder.");
155         System.out.println("pwd Displays current folder.");
156         System.out.println("rm <path> Deletes a file or folder.");
157         System.out.println("touch <path> Sets the last-modified time of a file.");
158         System.out.println("exit Exits this program.");
159         System.out.println("quit Exits this program.");
160     }
161
162     /**
163      * Does an 'rm' command.
164      */

165     private void rm(final String JavaDoc[] cmd) throws Exception JavaDoc
166     {
167         if (cmd.length < 2)
168         {
169             throw new Exception JavaDoc("USAGE: rm <path>");
170         }
171
172         final FileObject file = mgr.resolveFile(cwd, cmd[1]);
173         file.delete(Selectors.SELECT_SELF);
174     }
175
176     /**
177      * Does a 'cp' command.
178      */

179     private void cp(final String JavaDoc[] cmd) throws Exception JavaDoc
180     {
181         if (cmd.length < 3)
182         {
183             throw new Exception JavaDoc("USAGE: cp <src> <dest>");
184         }
185
186         final FileObject src = mgr.resolveFile(cwd, cmd[1]);
187         FileObject dest = mgr.resolveFile(cwd, cmd[2]);
188         if (dest.exists() && dest.getType() == FileType.FOLDER)
189         {
190             dest = dest.resolveFile(src.getName().getBaseName());
191         }
192
193         dest.copyFrom(src, Selectors.SELECT_ALL);
194     }
195
196     /**
197      * Does a 'cat' command.
198      */

199     private void cat(final String JavaDoc[] cmd) throws Exception JavaDoc
200     {
201         if (cmd.length < 2)
202         {
203             throw new Exception JavaDoc("USAGE: cat <path>");
204         }
205
206         // Locate the file
207
final FileObject file = mgr.resolveFile(cwd, cmd[1]);
208
209         // Dump the contents to System.out
210
FileUtil.writeContent(file, System.out);
211         System.out.println();
212     }
213
214     /**
215      * Does a 'pwd' command.
216      */

217     private void pwd()
218     {
219         System.out.println("Current folder is " + cwd.getName());
220     }
221
222     /**
223      * Does a 'cd' command.
224      * If the taget directory does not exist, a message is printed to <code>System.err</code>.
225      */

226    private void cd(final String JavaDoc[] cmd) throws Exception JavaDoc
227     {
228         final String JavaDoc path;
229         if (cmd.length > 1)
230         {
231             path = cmd[1];
232         }
233         else
234         {
235             path = System.getProperty("user.home");
236         }
237
238         // Locate and validate the folder
239
FileObject tmp = mgr.resolveFile(cwd, path);
240         if (tmp.exists())
241         {
242             cwd = tmp;
243         }
244         else
245         {
246             System.out.println("Folder does not exist: " + tmp.getName());
247         }
248         System.out.println("Current folder is " + cwd.getName());
249     }
250
251     /**
252      * Does an 'ls' command.
253      */

254     private void ls(final String JavaDoc[] cmd) throws FileSystemException
255     {
256         int pos = 1;
257         final boolean recursive;
258         if (cmd.length > pos && cmd[pos].equals("-R"))
259         {
260             recursive = true;
261             pos++;
262         }
263         else
264         {
265             recursive = false;
266         }
267
268         final FileObject file;
269         if (cmd.length > pos)
270         {
271             file = mgr.resolveFile(cwd, cmd[pos]);
272         }
273         else
274         {
275             file = cwd;
276         }
277
278         if (file.getType() == FileType.FOLDER)
279         {
280             // List the contents
281
System.out.println("Contents of " + file.getName());
282             listChildren(file, recursive, "");
283         }
284         else
285         {
286             // Stat the file
287
System.out.println(file.getName());
288             final FileContent content = file.getContent();
289             System.out.println("Size: " + content.getSize() + " bytes.");
290             final DateFormat JavaDoc dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
291             final String JavaDoc lastMod = dateFormat.format(new Date JavaDoc(content.getLastModifiedTime()));
292             System.out.println("Last modified: " + lastMod);
293         }
294     }
295
296     /**
297      * Does a 'touch' command.
298      */

299     private void touch(final String JavaDoc[] cmd) throws Exception JavaDoc
300     {
301         if (cmd.length < 2)
302         {
303             throw new Exception JavaDoc("USAGE: touch <path>");
304         }
305         final FileObject file = mgr.resolveFile(cwd, cmd[1]);
306         if (!file.exists())
307         {
308             file.createFile();
309         }
310         file.getContent().setLastModifiedTime(System.currentTimeMillis());
311     }
312
313     /**
314      * Lists the children of a folder.
315      */

316     private void listChildren(final FileObject dir,
317                               final boolean recursive,
318                               final String JavaDoc prefix)
319         throws FileSystemException
320     {
321         final FileObject[] children = dir.getChildren();
322         for (int i = 0; i < children.length; i++)
323         {
324             final FileObject child = children[i];
325             System.out.print(prefix);
326             System.out.println(child.getName().getBaseName() + " [" + child.getURL().toExternalForm() + "]");
327             if (recursive)
328             {
329               if (child.getType() == FileType.FOLDER) {
330                 System.out.println("/");
331
332                 listChildren(child, recursive, prefix + " ");
333               }
334             }
335
336         }
337
338         System.out.println();
339     }
340
341     /**
342      * Returns the next command, split into tokens.
343      */

344     private String JavaDoc[] nextCommand() throws IOException JavaDoc
345     {
346         System.out.print("> ");
347         final String JavaDoc line = reader.readLine();
348         if (line == null)
349         {
350             return null;
351         }
352         final ArrayList JavaDoc cmd = new ArrayList JavaDoc();
353         final StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc(line);
354         while (tokens.hasMoreTokens())
355         {
356             cmd.add(tokens.nextToken());
357         }
358         return (String JavaDoc[]) cmd.toArray(new String JavaDoc[cmd.size()]);
359     }
360 }
361
Popular Tags