View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.vfs2.example;
18  
19  import java.io.BufferedReader;
20  import java.io.File;
21  import java.io.IOException;
22  import java.io.InputStreamReader;
23  import java.net.URL;
24  import java.nio.charset.Charset;
25  import java.text.DateFormat;
26  import java.util.ArrayList;
27  import java.util.Arrays;
28  import java.util.Collection;
29  import java.util.Date;
30  import java.util.List;
31  import java.util.StringTokenizer;
32  
33  import org.apache.commons.vfs2.Capability;
34  import org.apache.commons.vfs2.FileContent;
35  import org.apache.commons.vfs2.FileObject;
36  import org.apache.commons.vfs2.FileSystemException;
37  import org.apache.commons.vfs2.FileSystemManager;
38  import org.apache.commons.vfs2.FileType;
39  import org.apache.commons.vfs2.Selectors;
40  import org.apache.commons.vfs2.VFS;
41  import org.apache.commons.vfs2.impl.StandardFileSystemManager;
42  import org.apache.commons.vfs2.operations.FileOperationProvider;
43  import org.apache.commons.vfs2.util.FileObjectUtils;
44  
45  /**
46   * A simple command-line shell for performing file operations.
47   * <p>
48   * See <a href="https://wiki.apache.org/commons/VfsExampleShell">Commons VFS Shell Examples</a> in Apache Commons Wiki.
49   */
50  public final class Shell {
51  
52      private final FileSystemManager mgr;
53      private FileObject cwd;
54      private final BufferedReader reader;
55  
56      private Shell() throws IOException {
57          final String providers = System.getProperty("providers");
58          final URL providersUrl = (providers != null) ? Shell.class.getResource("/" + providers) : null;
59  
60          if (providersUrl != null) {
61              mgr = new StandardFileSystemManager();
62              System.out.println("Custom providers configuration used: " + providersUrl);
63              ((StandardFileSystemManager) mgr).setConfiguration(providersUrl);
64              ((StandardFileSystemManager) mgr).init();
65          } else {
66              mgr = VFS.getManager();
67          }
68  
69          cwd = mgr.toFileObject(new File(System.getProperty("user.dir")));
70          reader = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset()));
71      }
72  
73      public static void main(final String[] args) {
74          try {
75              new Shell().go();
76          } catch (final Exception e) {
77              e.printStackTrace();
78              System.exit(1);
79          }
80          System.exit(0);
81      }
82  
83      private void go() throws Exception {
84          System.out.println("VFS Shell " + getVersion(Shell.class));
85          while (true) {
86              final String[] cmd = nextCommand();
87              if (cmd == null) {
88                  return;
89              }
90              if (cmd.length == 0) {
91                  continue;
92              }
93              final String cmdName = cmd[0];
94              if (cmdName.equalsIgnoreCase("exit") || cmdName.equalsIgnoreCase("quit")) {
95                  return;
96              }
97              try {
98                  handleCommand(cmd);
99              } catch (final Exception e) {
100                 System.err.println("Command failed:");
101                 e.printStackTrace(System.err);
102             }
103         }
104     }
105 
106     /**
107      * Handles a command.
108      */
109     private void handleCommand(final String[] cmd) throws Exception {
110         final String cmdName = cmd[0];
111         if (cmdName.equalsIgnoreCase("cat")) {
112             cat(cmd);
113         } else if (cmdName.equalsIgnoreCase("cd")) {
114             cd(cmd);
115         } else if (cmdName.equalsIgnoreCase("cp")) {
116             cp(cmd);
117         } else if (cmdName.equalsIgnoreCase("help") || cmdName.equals("?")) {
118             help();
119         } else if (cmdName.equalsIgnoreCase("ls")) {
120             ls(cmd);
121         } else if (cmdName.equalsIgnoreCase("pwd")) {
122             pwd();
123         } else if (cmdName.equalsIgnoreCase("pwfs")) {
124             pwfs();
125         } else if (cmdName.equalsIgnoreCase("rm")) {
126             rm(cmd);
127         } else if (cmdName.equalsIgnoreCase("touch")) {
128             touch(cmd);
129         } else if (cmdName.equalsIgnoreCase("info")) {
130             info(cmd);
131         } else {
132             System.err.println("Unknown command \"" + cmdName + "\" (Try 'help').");
133         }
134     }
135 
136     private void info(final String[] cmd) throws Exception {
137         if (cmd.length > 1) {
138             info(cmd[1]);
139         } else {
140             System.out.println(
141                     "Default manager: \"" + mgr.getClass().getName() + "\" " + "version " + getVersion(mgr.getClass()));
142             final String[] schemes = mgr.getSchemes();
143             final List<String> virtual = new ArrayList<>();
144             final List<String> physical = new ArrayList<>();
145             for (final String scheme : schemes) {
146                 final Collection<Capability> caps = mgr.getProviderCapabilities(scheme);
147                 if (caps != null) {
148                     if (caps.contains(Capability.VIRTUAL) || caps.contains(Capability.COMPRESS)
149                             || caps.contains(Capability.DISPATCHER)) {
150                         virtual.add(scheme);
151                     } else {
152                         physical.add(scheme);
153                     }
154                 }
155             }
156             if (!physical.isEmpty()) {
157                 System.out.println("  Provider Schemes: " + physical);
158             }
159             if (!virtual.isEmpty()) {
160                 System.out.println("   Virtual Schemes: " + virtual);
161             }
162         }
163     }
164 
165     private void info(final String scheme) throws Exception {
166         System.out.println("Provider Info for scheme \"" + scheme + "\":");
167         Collection<Capability> caps;
168         caps = mgr.getProviderCapabilities(scheme);
169         if (caps != null && !caps.isEmpty()) {
170             System.out.println("  capabilities: " + caps);
171         }
172         final FileOperationProvider[] ops = mgr.getOperationProviders(scheme);
173         if (ops != null && ops.length > 0) {
174             System.out.println("  operations: " + Arrays.toString(ops));
175         }
176     }
177 
178     /**
179      * Does a 'help' command.
180      */
181     private void help() {
182         System.out.println("Commands:");
183         System.out.println("cat <file>         Displays the contents of a file.");
184         System.out.println("cd [folder]        Changes current folder.");
185         System.out.println("cp <src> <dest>    Copies a file or folder.");
186         System.out.println("help               Shows this message.");
187         System.out.println("info [scheme]      Displays information about providers.");
188         System.out.println("ls [-R] [path]     Lists contents of a file or folder.");
189         System.out.println("pwd                Displays current folder.");
190         System.out.println("pwfs               Displays current file system.");
191         System.out.println("rm <path>          Deletes a file or folder.");
192         System.out.println("touch <path>       Sets the last-modified time of a file.");
193         System.out.println("exit, quit         Exits this program.");
194     }
195 
196     /**
197      * Does an 'rm' command.
198      */
199     private void rm(final String[] cmd) throws Exception {
200         if (cmd.length < 2) {
201             throw new Exception("USAGE: rm <path>");
202         }
203 
204         final FileObject file = mgr.resolveFile(cwd, cmd[1]);
205         file.delete(Selectors.SELECT_SELF);
206     }
207 
208     /**
209      * Does a 'cp' command.
210      */
211     private void cp(final String[] cmd) throws Exception {
212         if (cmd.length < 3) {
213             throw new Exception("USAGE: cp <src> <dest>");
214         }
215 
216         final FileObject src = mgr.resolveFile(cwd, cmd[1]);
217         FileObject dest = mgr.resolveFile(cwd, cmd[2]);
218         if (dest.exists() && dest.getType() == FileType.FOLDER) {
219             dest = dest.resolveFile(src.getName().getBaseName());
220         }
221 
222         dest.copyFrom(src, Selectors.SELECT_ALL);
223     }
224 
225     /**
226      * Does a 'cat' command.
227      */
228     private void cat(final String[] cmd) throws Exception {
229         if (cmd.length < 2) {
230             throw new Exception("USAGE: cat <path>");
231         }
232 
233         // Locate the file
234         final FileObject file = mgr.resolveFile(cwd, cmd[1]);
235 
236         // Dump the contents to System.out
237         FileObjectUtils.writeContent(file, System.out);
238         System.out.println();
239     }
240 
241     /**
242      * Does a 'pwd' command.
243      */
244     private void pwd() {
245         System.out.println("Current folder is " + cwd.getName());
246     }
247 
248     /**
249      * Does a 'pwfs' command.
250      */
251     private void pwfs() {
252         System.out.println("FileSystem of current folder is " + cwd.getFileSystem() + " (root: "
253                 + cwd.getFileSystem().getRootURI() + ")");
254     }
255 
256     /**
257      * Does a 'cd' command. If the taget directory does not exist, a message is printed to {@code System.err}.
258      */
259     private void cd(final String[] cmd) throws Exception {
260         final String path;
261         if (cmd.length > 1) {
262             path = cmd[1];
263         } else {
264             path = System.getProperty("user.home");
265         }
266 
267         // Locate and validate the folder
268         final FileObject tmp = mgr.resolveFile(cwd, path);
269         if (tmp.exists()) {
270             cwd = tmp;
271         } else {
272             System.out.println("Folder does not exist: " + tmp.getName());
273         }
274         System.out.println("Current folder is " + cwd.getName());
275     }
276 
277     /**
278      * Does an 'ls' command.
279      */
280     private void ls(final String[] cmd) throws FileSystemException {
281         int pos = 1;
282         final boolean recursive;
283         if (cmd.length > pos && cmd[pos].equals("-R")) {
284             recursive = true;
285             pos++;
286         } else {
287             recursive = false;
288         }
289 
290         final FileObject file;
291         if (cmd.length > pos) {
292             file = mgr.resolveFile(cwd, cmd[pos]);
293         } else {
294             file = cwd;
295         }
296 
297         if (file.getType() == FileType.FOLDER) {
298             // List the contents
299             System.out.println("Contents of " + file.getName());
300             listChildren(file, recursive, "");
301         } else {
302             // Stat the file
303             System.out.println(file.getName());
304             final FileContent content = file.getContent();
305             System.out.println("Size: " + content.getSize() + " bytes.");
306             final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
307             final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime()));
308             System.out.println("Last modified: " + lastMod);
309         }
310     }
311 
312     /**
313      * Does a 'touch' command.
314      */
315     private void touch(final String[] cmd) throws Exception {
316         if (cmd.length < 2) {
317             throw new Exception("USAGE: touch <path>");
318         }
319         final FileObject file = mgr.resolveFile(cwd, cmd[1]);
320         if (!file.exists()) {
321             file.createFile();
322         }
323         file.getContent().setLastModifiedTime(System.currentTimeMillis());
324     }
325 
326     /**
327      * Lists the children of a folder.
328      */
329     private void listChildren(final FileObject dir, final boolean recursive, final String prefix)
330             throws FileSystemException {
331         final FileObject[] children = dir.getChildren();
332         for (final FileObject child : children) {
333             System.out.print(prefix);
334             System.out.print(child.getName().getBaseName());
335             if (child.getType() == FileType.FOLDER) {
336                 System.out.println("/");
337                 if (recursive) {
338                     listChildren(child, recursive, prefix + "    ");
339                 }
340             } else {
341                 System.out.println();
342             }
343         }
344     }
345 
346     /**
347      * Returns the next command, split into tokens.
348      */
349     private String[] nextCommand() throws IOException {
350         System.out.print("> ");
351         final String line = reader.readLine();
352         if (line == null) {
353             return null;
354         }
355         final ArrayList<String> cmd = new ArrayList<>();
356         final StringTokenizer tokens = new StringTokenizer(line);
357         while (tokens.hasMoreTokens()) {
358             cmd.add(tokens.nextToken());
359         }
360         return cmd.toArray(new String[cmd.size()]);
361     }
362 
363     private static String getVersion(final Class<?> cls) {
364         try {
365             return cls.getPackage().getImplementationVersion();
366         } catch (final Exception ignored) {
367             return "N/A";
368         }
369     }
370 }