KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > neu > ccs > jmk > FileOperator


1 // $Id: FileOperator.java,v 1.2 2001/12/07 11:41:24 ramsdell Exp $
2

3 // Executes a file operation on file operands.
4

5 /*
6  * Copyright 1997 by John D. Ramsdell
7  *
8  * This program is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21  */

22
23 package edu.neu.ccs.jmk;
24
25 import java.io.*;
26 import java.util.Vector JavaDoc;
27
28 /**
29  * This operator is used to implement file commands.
30  * To be useful, subclasses must implement
31  * <code>getName(String)</code> and <code>exec(File, PrintWriter)</code>.
32  * @version November 1997
33  * @author John D. Ramsdell
34  */

35 abstract class FileOperator
36 implements Operator
37 {
38   private final static char wildCard = '*';
39
40   /**
41    * The actual method implemented by a particular file operator
42    * is given by defining this method.
43    * @return true if the file operation completed successfully;
44    * false otherwise
45    */

46   abstract boolean exec(File arg, PrintWriter out);
47
48   /**
49    * Applies the file operator to each argument.
50    * If an argument contains the wild card character '*',
51    * the argument is expanded, and the file operator is applied
52    * to each element in the expansion.
53    * @param args operands given to the file operator
54    * @param out place to write messages
55    * @exception CommandFailedException if operation failed
56    */

57   public void exec(String JavaDoc[] args, PrintWriter out)
58        throws CommandFailedException
59   {
60     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(); // For error messages
61
exec(args, out, sb);
62     if (sb.length() != 0) { // Errors occurred
63
sb.insert(0, getName());
64       throw new CommandFailedException(sb.toString());
65     }
66   }
67
68   private void exec(String JavaDoc[] args, PrintWriter out, StringBuffer JavaDoc sb) {
69     for (int i = 0; i < args.length; i++) {
70       String JavaDoc fileName = args[i];
71       if (fileName.indexOf(wildCard) < 0) { // If no wild card exec
72
if (!exec(new File(fileName), out)) {
73       sb.append(' ');
74       sb.append(fileName);
75     }
76       }
77       else { // else glob and then exec
78
try {
79       exec(glob(fileName), out, sb);
80     }
81     catch (CommandFailedException ex) {
82       sb.append(' ');
83       sb.append(fileName);
84     }
85       }
86     }
87   }
88
89   /**
90    * This method expands a localized file name that may contain wild
91    * cards to an array of file names without the wild cards.
92    * All file separators in the file name must preceed any wild card.
93    * @exception CommandFailedException if wild card is misused
94    */

95   static String JavaDoc[] glob(String JavaDoc fileName)
96        throws CommandFailedException
97   {
98     int wildCardIndex = fileName.indexOf(wildCard);
99     if (wildCardIndex < 0) // No wild card
100
return new String JavaDoc[] { fileName };
101     else {
102       int separatorIndex = fileName.lastIndexOf(File.separatorChar);
103       if (separatorIndex > wildCardIndex) {
104     String JavaDoc msg = "Cannot expand " + fileName;
105     throw new CommandFailedException(msg);
106       }
107       String JavaDoc pattern;
108       String JavaDoc dirName;
109       File dir;
110       if (separatorIndex >= 0) {
111     pattern = fileName.substring(separatorIndex + 1);
112     dirName = fileName.substring(0, separatorIndex + 1);
113     dir = new File(dirName);
114       }
115       else {
116     pattern = fileName;
117     dirName = "";
118     dir = new File(System.getProperty("user.dir"));
119       }
120       String JavaDoc[] list = dir.list(new WildCardFilter(pattern, wildCard));
121       if (list == null)
122     return new String JavaDoc[0];
123       Vector JavaDoc v = new Vector JavaDoc();
124       for (int i = 0; i < list.length; i++)
125     list[i] = dirName + list[i];
126       return list;
127     }
128   }
129
130   /**
131    * This method expands an array of localized file names that may
132    * contain wild cards to an array of file names without wild cards.
133    * Wild cards must conform to the rules given above.
134    */

135   static String JavaDoc[] glob(String JavaDoc[] args)
136        throws CommandFailedException
137   {
138     for (int i = 0; i < args.length; i++) {
139       if (args[i].indexOf(wildCard) >= 0) { // If wild card
140
Vector JavaDoc v = new Vector JavaDoc();
141     for (int j = 0; j < i; j++) // Add previous strings
142
v.addElement(args[j]);
143     addStrings(v, glob(args[i])); // Add this arg
144
for (int j = i + 1; j < args.length; j++) // Add remaining args
145
if (args[j].indexOf(wildCard) >= 0)
146         addStrings(v, glob(args[j]));
147       else
148         v.addElement(args[j]);
149     String JavaDoc[] result = new String JavaDoc[v.size()];
150     v.copyInto(result);
151     return result; // Wild cards found
152
}
153     }
154     return args; // No wild cards found
155
}
156
157   private static void addStrings(Vector JavaDoc v, String JavaDoc[] s) {
158     for (int i = 0; i < s.length; i++)
159       v.addElement(s[i]);
160   }
161
162   /**
163    * This method expands a localized file name into a list of all
164    * directories in that file.
165    */

166   static String JavaDoc[] dirs(String JavaDoc fileName) {
167     Vector JavaDoc v = new Vector JavaDoc();
168     findDirs(new File(fileName), v);
169     String JavaDoc[] result = new String JavaDoc[v.size()];
170     v.copyInto(result);
171     return result;
172   }
173
174   private static void findDirs(File f, Vector JavaDoc v) {
175     if (f.isDirectory()) {
176       v.addElement(f.getPath());
177       String JavaDoc[] l = f.list();
178       for (int i = 0; i < l.length; i++)
179     findDirs(new File(f, l[i]), v);
180     }
181   }
182
183   /**
184    * An entry point for testing exec commands.
185    * It simply passes the arguments to the exec operation.
186    * @param args operands for the command
187    */

188   public static void main(String JavaDoc[] args) {
189     PrintWriter out = new PrintWriter(System.out, true);
190     FileOperator operator = new FileOperator() {
191       boolean exec(File arg, PrintWriter out) {
192     return arg.delete();
193       }
194       public String JavaDoc getName() {
195     return "delete";
196       }
197     };
198     try {
199       operator.exec(args, out);
200     }
201     catch (Throwable JavaDoc t) {
202       System.err.println("Internal error: " + t.getMessage());
203       t.printStackTrace();
204     }
205     out.println("File command " + operator.getName() + " completed");
206   }
207 }
208
Popular Tags